sdlSymbols.py 46.3 KB
Newer Older
Maxime Perrotin's avatar
Maxime Perrotin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    OpenGEODE - A tiny SDL Editor for TASTE

    This module contains the definition of the SDL symbols,
    including geometry and specific symbol behaviour when needed.

    All symbols inherit the generic Vertical- and Horizontal-
    Symbol classes defined in the "genericSymbols.py" module.

    Copyright (c) 2012-2013 European Space Agency

    Designed and implemented by Maxime Perrotin

    Contact: maxime.perrotin@esa.int
"""

__all__ = ['Input', 'Output', 'State', 'Task', 'ProcedureCall', 'Label',
           'Decision', 'DecisionAnswer', 'Join', 'Start', 'TextSymbol',
22
           'Procedure', 'ProcedureStart', 'ProcedureStop', 'ASN1Viewer',
23
           'StateStart', 'Process']
Maxime Perrotin's avatar
Maxime Perrotin committed
24

Maxime Perrotin's avatar
Maxime Perrotin committed
25
#import traceback
26
import logging
Maxime Perrotin's avatar
Maxime Perrotin committed
27
28

from PySide.QtCore import Qt, QPoint, QRect, QRectF
29
from PySide.QtGui import(QPainterPath, QBrush, QColor, QRadialGradient, QPen)
Maxime Perrotin's avatar
Maxime Perrotin committed
30

Maxime Perrotin's avatar
Maxime Perrotin committed
31
from genericSymbols import HorizontalSymbol, VerticalSymbol, Comment
Maxime Perrotin's avatar
Maxime Perrotin committed
32
from Connectors import Connection, JoinConnection, Channel
33

Maxime Perrotin's avatar
Maxime Perrotin committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import ogParser
import ogAST


LOG = logging.getLogger('sdlSymbols')


# SDL-specific: reserved keywords, to be highlighted in textboxes
# Two kind of formatting are possible: black bold, and red bold
SDL_BLACKBOLD = ['\\b{word}\\b'.format(word=word) for word in (
                'DCL', 'CALL', 'ELSE', 'IF', 'THEN', 'MANTISSA', 'BASE',
                'EXPONENT', 'TRUE', 'FALSE', 'MOD', 'FI', 'WRITE', 'WRITELN',
                'LENGTH', 'PRESENT', 'FPAR', 'TODO', 'FIXME', 'XXX',
                'CHECKME', 'PROCEDURE', 'EXTERNAL', 'IN', 'OUT', 'TIMER',
48
49
                'SET_TIMER', 'RESET_TIMER', 'VIA', 'ENTRY', 'EXIT',
                'SYNTYPE', 'ENDSYNTYPE', 'CONSTANTS',
Maxime Perrotin's avatar
Maxime Perrotin committed
50
                'NEWTYPE', 'ENDNEWTYPE', 'ARRAY', 'STRUCT', 'SYNONYM')]
Maxime Perrotin's avatar
Maxime Perrotin committed
51
52
53
54
55
56
57

SDL_REDBOLD = ['\\b{word}\\b'.format(word=word) for word in (
              'INPUT', 'OUTPUT', 'STATE', 'DECISION', 'NEXTSTATE',
              'TASK', 'PROCESS', 'LABEL', 'JOIN', 'CONNECTION')]


# pylint: disable=R0904
58
class Input(HorizontalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
59
60
61
    ''' SDL INPUT Symbol '''
    _unique_followers = ['Comment']
    _insertable_followers = ['Task', 'ProcedureCall', 'Output', 'Decision',
62
                             'Input', 'Label', 'Connect']
Maxime Perrotin's avatar
Maxime Perrotin committed
63
64
65
66
67
68
69
70
71
72
73
74
    _terminal_followers = ['Join', 'State', 'ProcedureStop']
    completion_list = set()

    common_name = 'input_part'
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD

    def __init__(self, parent=None, ast=None):
        ''' Create the INPUT symbol '''
        ast = ast or ogAST.Input()
        self.branch_entrypoint = None
Maxime Perrotin's avatar
Maxime Perrotin committed
75
76
77
        if not ast.pos_y and parent:
            # Make sure the item is placed below its parent
            ast.pos_y = parent.y() + parent.boundingRect().height() + 10
Maxime Perrotin's avatar
Maxime Perrotin committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        super(Input, self).__init__(parent, text=ast.inputString,
                x=ast.pos_x, y=ast.pos_y, hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)
        gradient = QRadialGradient(50, 50, 50, 50, 50)
        gradient.setColorAt(0, QColor(255, 240, 170))
        gradient.setColorAt(1, Qt.white)
        self.setBrush(QBrush(gradient))
        self.terminal_symbol = False
        self.parser = ogParser
        if ast.comment:
            Comment(parent=self, ast=ast.comment)

    def check_syntax(self):
        ''' Redefined function, to check only the symbol, not recursively '''
92
93
        _, syntax_errors, _, _, _ = self.parser.parseSingleElement(
                self.common_name, '\n'.join(self.PR_SINGLE()))
Maxime Perrotin's avatar
Maxime Perrotin committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        try:
            self.scene().raise_syntax_errors(syntax_errors)
        except AttributeError:
            LOG.debug('raise_syntax_error raised an exception')

    def insert_symbol(self, parent, x, y):
        ''' Insert Input symbol - propagate branch Entry point '''
        # Make sure that parent is a state, not a sibling input
        item_parent = (parent if not isinstance(parent, Input)
                       else parent.parentItem())
        self.branch_entrypoint = item_parent.branch_entrypoint
        super(Input, self).insert_symbol(item_parent, x, y)

    def set_shape(self, width, height):
        ''' Compute the polygon to fit in width, height '''
        path = QPainterPath()
        path.lineTo(width, 0)
        path.lineTo(width - 11, height / 2)
        path.lineTo(width, height)
        path.lineTo(0, height)
        path.lineTo(0, 0)
        self.setPath(path)
        super(Input, self).set_shape(width, height)

Maxime Perrotin's avatar
Maxime Perrotin committed
118
    def PR_SINGLE(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
119
        ''' Return the PR notation of the single INPUT symbol '''
Maxime Perrotin's avatar
Maxime Perrotin committed
120
        comment = self.comment.PR() if self.comment else u';'
121
        hlink = self.text.PR()
Maxime Perrotin's avatar
Maxime Perrotin committed
122
        pos = self.scenePos()
123
        result = ['/* CIF INPUT ({x}, {y}), ({w}, {h}) */'.format(
Maxime Perrotin's avatar
Maxime Perrotin committed
124
125
                    x=int(pos.x()), y=int(pos.y()),
                    w=int(self.boundingRect().width()),
126
127
128
129
130
                    h=int(self.boundingRect().height()))]
        if hlink:
            result.append(hlink)
        result.append(u'INPUT {}{}'.format(unicode(self.text), comment))
        return result
Maxime Perrotin's avatar
Maxime Perrotin committed
131

Maxime Perrotin's avatar
Maxime Perrotin committed
132
    def PR(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
133
        ''' Return the complete Input branch in PR format '''
134
        result = self.PR_SINGLE()
Maxime Perrotin's avatar
Maxime Perrotin committed
135
136
137
        # Recursively return the complete branch below the INPUT
        next_symbol = self.next_aligned_symbol()
        while next_symbol:
Maxime Perrotin's avatar
Maxime Perrotin committed
138
            result.append(next_symbol.PR())
Maxime Perrotin's avatar
Maxime Perrotin committed
139
            next_symbol = next_symbol.next_aligned_symbol()
Maxime Perrotin's avatar
Maxime Perrotin committed
140
        return u'\n'.join(result)
Maxime Perrotin's avatar
Maxime Perrotin committed
141
142


143
144
145
class Connect(Input):
    ''' Connect point below a nested state '''
    common_name = 'connect_part'
Maxime Perrotin's avatar
Maxime Perrotin committed
146
147
148
149
    auto_expand = False
    resizeable = False
    # Symbol must not use antialiasing, otherwise the middle line is too thick
    _antialiasing = False
Maxime Perrotin's avatar
Maxime Perrotin committed
150

Maxime Perrotin's avatar
Maxime Perrotin committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    def set_shape(self, width, height):
        ''' Compute the polygon to fit in width, height '''
        self.setPen(QPen(Qt.blue))
        self.textbox_alignment = Qt.AlignLeft | Qt.AlignTop
        path = QPainterPath()
        path.moveTo(0, 0)
        path.lineTo(0, height)
        #path.moveTo(0, height / 2)
        #path.lineTo(width, height / 2)
        self.setPath(path)
        super(Input, self).set_shape(width, height)

    def resize_item(self, rect):
        ''' Symbol cannot be resized '''
        return

Maxime Perrotin's avatar
Maxime Perrotin committed
167
    def PR_SINGLE(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
168
        ''' Return the PR notation of the single CONNECT symbol '''
Maxime Perrotin's avatar
Maxime Perrotin committed
169
        comment = self.comment.PR() if self.comment else u';'
170
        hlink = self.text.PR()
Maxime Perrotin's avatar
Maxime Perrotin committed
171
        pos = self.scenePos()
172
173
174
175
176
177
178
179
        result = [u'/* CIF CONNECT ({x}, {y}), ({w}, {h}) */'.format(
                     x=int(pos.x()), y=int(pos.y()),
                     w=int(self.boundingRect().width()),
                     h=int(self.boundingRect().height()))]
        if hlink:
            result.append(hlink)
        result.append(u'CONNECT {}{}'.format(unicode(self.text), comment))
        return result
180
181


Maxime Perrotin's avatar
Maxime Perrotin committed
182
# pylint: disable=R0904
183
class Output(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
    ''' SDL OUTPUT Symbol '''
    _unique_followers = ['Comment']
    _insertable_followers = [
            'Task', 'ProcedureCall', 'Output', 'Decision', 'Label']
    _terminal_followers = ['Join', 'State', 'ProcedureStop']
    common_name = 'output'
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD
    completion_list = set()

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.Output()
        super(Output, self).__init__(parent=parent,
                text=ast.inputString, x=ast.pos_x, y=ast.pos_y,
                hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)

        self.setBrush(QBrush(QColor(255, 255, 202)))
        self.terminal_symbol = False
        self.parser = ogParser
        if ast.comment:
            Comment(parent=self, ast=ast.comment)

    def set_shape(self, width, height):
        ''' Compute the polygon to fit in width, height '''
        path = QPainterPath()
        path.lineTo(width - 11, 0)
        path.lineTo(width, height / 2)
        path.lineTo(width - 11, height)
        path.lineTo(0, height)
        path.lineTo(0, 0)
        self.setPath(path)
        super(Output, self).set_shape(width, height)

Maxime Perrotin's avatar
Maxime Perrotin committed
219
    def PR(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
220
        ''' Return the text corresponding to the SDL PR notation '''
Maxime Perrotin's avatar
Maxime Perrotin committed
221
        comment = self.comment.PR() if self.comment else u';'
Maxime Perrotin's avatar
Maxime Perrotin committed
222
        pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
223
        return (u'/* CIF OUTPUT ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
224
225
                '{hlink}'
                'OUTPUT {o}{comment}'.format(
Maxime Perrotin's avatar
Maxime Perrotin committed
226
                    hlink=self.text.PR(), o=unicode(self),
Maxime Perrotin's avatar
Maxime Perrotin committed
227
228
229
230
231
232
                    x=int(pos.x()), y=int(pos.y()),
                    w=int(self.boundingRect().width()),
                    h=int(self.boundingRect().height()), comment=comment))


# pylint: disable=R0904
233
class Decision(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
234
235
    ''' SDL DECISION Symbol '''
    _unique_followers = ['Comment']
Maxime Perrotin's avatar
Maxime Perrotin committed
236
237
    _insertable_followers = ['DecisionAnswer', 'Task', 'ProcedureCall',
                             'Output', 'Decision', 'Label']
Maxime Perrotin's avatar
Maxime Perrotin committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    _terminal_followers = ['Join', 'State', 'ProcedureStop']
    common_name = 'decision'
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD + ['\\b{}\\b'.format(word)
                                   for word in ('AND', 'OR')]
    redbold = SDL_REDBOLD
    completion_list = {'length', 'present'}

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.Decision()
        # Define the point where all branches of the decision can join again
        self.connectionPoint = QPoint(ast.width / 2, ast.height + 30)
        super(Decision, self).__init__(parent, text=ast.inputString,
                x=ast.pos_x, y=ast.pos_y, hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)
        self.setBrush(QColor(255, 255, 202))
        self.minDistanceToSymbolAbove = 0
        self.parser = ogParser
        self.text_alignment = Qt.AlignHCenter
        if ast.comment:
            Comment(parent=self, ast=ast.comment)

    @property
    def terminal_symbol(self):
        '''
            Compute dynamically if the item is terminal by checking
            if all its branches end with a terminator
        '''
        for branch in self.branches():
            if not branch.last_branch_item.terminal_symbol:
                return False
269
        return True
Maxime Perrotin's avatar
Maxime Perrotin committed
270
271
272
273
274
275
276
277

    def branches(self):
        ''' Return the list of decision answers (as a generator) '''
        return (branch for branch in self.childSymbols()
                if isinstance(branch, DecisionAnswer))

    def check_syntax(self):
        ''' Redefined function, to check only the symbol, not recursively '''
278
        _, syntax_errors, _, _, _ = self.parser.parseSingleElement(
Maxime Perrotin's avatar
Maxime Perrotin committed
279
                self.common_name, self.PR(recursive=False))
Maxime Perrotin's avatar
Maxime Perrotin committed
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
        try:
            # LOG.error('\n'.join(syntax_errors))
            self.scene().raise_syntax_errors(syntax_errors)
        except AttributeError:
            LOG.debug('raise_syntax_error raised an exception')

    def set_shape(self, width, height):
        ''' Define polygon points to draw the symbol '''
        path = QPainterPath()
        path.moveTo(width / 2, 0)
        path.lineTo(width, height / 2)
        path.lineTo(width / 2, height)
        path.lineTo(0, height / 2)
        path.lineTo(width / 2, 0)
        self.setPath(path)
        super(Decision, self).set_shape(width, height)

    def resize_item(self, rect):
        ''' On resize event, make sure connection points are updated '''
        delta_y = self.boundingRect().height() - rect.height()
        super(Decision, self).resize_item(rect)
        self.connectionPoint.setX(self.boundingRect().center().x())
        self.connectionPoint.setY(self.connectionPoint.y() - delta_y)
        self.update_connections()

    def update_connections(self):
        ''' Redefined - update arrows shape below connection point '''
        super(Decision, self).update_connections()
        for branch in self.branches():
            for cnx in branch.last_branch_item.connections():
                cnx.reshape()

    def updateConnectionPointPosition(self):
        ''' Compute the joining point of decision branches '''
        new_y = 0
        new_x = self.boundingRect().width() / 2.0
        answers = False
        for branch in self.branches():
            answers = True
            last_cnx = None
            last = branch.last_branch_item
            try:
                # To compute the branch length, we must keep only the symbols,
                # so we must remove the last connection (if any)
                last_cnx, = (c for c in last.childItems() if
                    isinstance(c, Connection) and not
                    isinstance(c.child, (Comment, HorizontalSymbol)))
327
328
                # Don't set parent item to None to avoid Qt segfault
                last_cnx.setParentItem(self)
Maxime Perrotin's avatar
Maxime Perrotin committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
            except ValueError:
                pass
            branch_len = branch.y() + (
                    branch.boundingRect() |
                    branch.childrenBoundingRect()).height()
            try:
                last_cnx.setParentItem(last)
            except AttributeError:
                pass
            # If last item was a decision, use its connection point
            # position to get the length of the branch:
            try:
                branch_len = (last.connectionPoint.y() +
                        self.mapFromScene(0, last.scenePos().y()).y())
            except AttributeError:
                pass
            # Rounded with int() -> mandatory when view scale has changed
            new_y = int(max(new_y, branch_len))
        if not answers:
            new_y = int(self.boundingRect().height())
        new_y += 15
        delta = new_y - self.connectionPoint.y()
        self.connectionPoint.setY(new_y)
        self.connectionPoint.setX(new_x)
        if delta != 0:
            child = self.next_aligned_symbol()
            try:
                child.moveBy(0, delta)
            except AttributeError:
                pass
        self.update_connections()

Maxime Perrotin's avatar
Maxime Perrotin committed
361
    def PR(self, recursive=True):
Maxime Perrotin's avatar
Maxime Perrotin committed
362
        ''' Get PR notation of a decision (possibly recursively) '''
Maxime Perrotin's avatar
Maxime Perrotin committed
363
        comment = self.comment.PR() if self.comment else u';'
Maxime Perrotin's avatar
Maxime Perrotin committed
364
        pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
365
        result = [u'/* CIF DECISION ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
366
367
                '{hlink}'
                'DECISION {d}{comment}'.format(
Maxime Perrotin's avatar
Maxime Perrotin committed
368
                    hlink=self.text.PR(), d=unicode(self),
Maxime Perrotin's avatar
Maxime Perrotin committed
369
370
371
372
373
                    x=int(pos.x()), y=int(pos.y()),
                    w=int(self.boundingRect().width()),
                    h=int(self.boundingRect().height()), comment=comment)]
        if recursive:
            for answer in self.branches():
Maxime Perrotin's avatar
Maxime Perrotin committed
374
375
                if unicode(answer).lower().strip() == 'else':
                    result.append(answer.PR())
Maxime Perrotin's avatar
Maxime Perrotin committed
376
                else:
Maxime Perrotin's avatar
Maxime Perrotin committed
377
                    result.insert(1, answer.PR())
Maxime Perrotin's avatar
Maxime Perrotin committed
378
        result.append('ENDDECISION;')
Maxime Perrotin's avatar
Maxime Perrotin committed
379
        return u'\n'.join(result)
Maxime Perrotin's avatar
Maxime Perrotin committed
380
381
382


# pylint: disable=R0904
383
class DecisionAnswer(HorizontalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
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
    ''' If Decision is a "switch", DecisionAnswer is a "case" '''
    _insertable_followers = ['DecisionAnswer', 'Task', 'ProcedureCall',
                        'Output', 'Decision', 'Label']
    _terminal_followers = ['Join', 'State', 'ProcedureStop']
    common_name = 'alternative_part'
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD
    completion_list = set()

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.Answer()
        # temp, FIXME
        self.width, self.height = ast.width, ast.height
        self.terminal_symbol = False
        # last_branch_item is used to compute branch length
        # for the connection point positionning
        self.last_branch_item = self
        super(DecisionAnswer, self).__init__(parent,
                text=ast.inputString,
                x=ast.pos_x, y=ast.pos_y, hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)
        #self.setPen(QColor(0, 0, 0, 0))
        self.branch_entrypoint = self
        self.parser = ogParser

    def check_syntax(self):
        ''' Redefined function, to check only the symbol, not recursively '''
412
        _, syntax_errors, _, _, _ = self.parser.parseSingleElement(
Maxime Perrotin's avatar
Maxime Perrotin committed
413
                self.common_name, self.PR(recursive=False))
Maxime Perrotin's avatar
Maxime Perrotin committed
414
415
416
417
418
419
420
421
422
423
424
425
426
        try:
            self.scene().raise_syntax_errors(syntax_errors)
        except:
            LOG.debug('raise_syntax_error raised an exception')

    def insert_symbol(self, parent, x, y):
        ''' ANSWER-specific insersion behaviour: link to connection point '''
        if not parent:
            return
        # Make sure that parent is a state, not a sibling input
        item_parent = (parent if not isinstance(parent, DecisionAnswer)
                       else parent.parentItem())
        super(DecisionAnswer, self).insert_symbol(item_parent, x, y)
Maxime Perrotin's avatar
Maxime Perrotin committed
427
428
        self.last_branch_item.connectionBelow = \
                JoinConnection(self.last_branch_item, item_parent)
Maxime Perrotin's avatar
Maxime Perrotin committed
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447

    def boundingRect(self):
        return QRectF(0, 0, self.width, self.height)

    def set_shape(self, width, height):
        ''' ANSWER has round, disjoint sides - does not fit in a polygon '''
        self.width, self.height = width, height
        point = width / 2.85
        path = QPainterPath()
        left = QRect(0, 0, point, height)
        right = QRect(width - point, 0, point, height)
        path.arcMoveTo(left, 125)
        path.arcTo(left, 125, 110)
        path.arcMoveTo(right, -55)
        path.arcTo(right, -55, 110)
        path.moveTo(width, height)
        self.setPath(path)
        super(DecisionAnswer, self).set_shape(width, height)

Maxime Perrotin's avatar
Maxime Perrotin committed
448
    def PR(self, recursive=True):
Maxime Perrotin's avatar
Maxime Perrotin committed
449
        ''' Return the PR string for the symbol, possibly recursively '''
Maxime Perrotin's avatar
Maxime Perrotin committed
450
451
452
        ans = unicode(self)
        if ans.lower().strip() != u'else':
            ans = u'({ans})'.format(ans=ans)
Maxime Perrotin's avatar
Maxime Perrotin committed
453
        pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
454
        result = [u'/* CIF ANSWER ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
455
                '{hlink}'
Maxime Perrotin's avatar
Maxime Perrotin committed
456
                '{a}:'.format(a=ans, hlink=self.text.PR(),
Maxime Perrotin's avatar
Maxime Perrotin committed
457
458
459
460
461
462
                    x=int(pos.x()), y=int(pos.y()),
                    w=int(self.boundingRect().width()),
                    h=int(self.boundingRect().height()))]
        if recursive:
            next_symbol = self.next_aligned_symbol()
            while next_symbol:
Maxime Perrotin's avatar
Maxime Perrotin committed
463
                result.append(next_symbol.PR())
Maxime Perrotin's avatar
Maxime Perrotin committed
464
                next_symbol = next_symbol.next_aligned_symbol()
Maxime Perrotin's avatar
Maxime Perrotin committed
465
        return u'\n'.join(result)
Maxime Perrotin's avatar
Maxime Perrotin committed
466
467
468


# pylint: disable=R0904
469
class Join(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
470
471
    ''' JOIN symbol (GOTO) '''
    auto_expand = False
Maxime Perrotin's avatar
Maxime Perrotin committed
472
    arrow_head = 'simple'
Maxime Perrotin's avatar
Maxime Perrotin committed
473
474
475
476
477
478
479
480
    common_name = 'terminator_statement'
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD
    completion_list = set()

    def __init__(self, parent=None, ast=None):
        if not ast:
481
            ast = ogAST.Terminator(defName='')
Maxime Perrotin's avatar
Maxime Perrotin committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
            ast.pos_y = 0
            ast.width = 35
            ast.height = 35
        super(Join, self).__init__(parent, text=ast.inputString,
                x=ast.pos_x, y=ast.pos_y, hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)
        self.setPen(QPen(Qt.blue))
        self.terminal_symbol = True
        self.parser = ogParser

    def resize_item(self, rect):
        ''' Redefinition of the resize item (block is a square) '''
        size = min(rect.width(), rect.height())
        rect.setWidth(size)
        rect.setHeight(size)
Maxime Perrotin's avatar
Maxime Perrotin committed
497
        super(Join, self).resize_item(rect)
Maxime Perrotin's avatar
Maxime Perrotin committed
498
499
500
501
502
503
504
505
506

    def set_shape(self, width, height):
        ''' Define the bouding rectangle of the JOIN symbol '''
        circ = min(width, height)
        path = QPainterPath()
        path.addEllipse(0, 0, circ, circ)
        self.setPath(path)
        super(Join, self).set_shape(width, height)

Maxime Perrotin's avatar
Maxime Perrotin committed
507
    def PR(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
508
509
        ''' Return the PR string for the join '''
        pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
510
        return(u'/* CIF JOIN ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
511
                '{hlink}'
Maxime Perrotin's avatar
Maxime Perrotin committed
512
513
                'JOIN {label};'.format(label=unicode(self),
                    hlink=self.text.PR(),
Maxime Perrotin's avatar
Maxime Perrotin committed
514
515
516
517
518
                    x=int(pos.x()), y=int(pos.y()),
                    w=int(self.boundingRect().width()),
                    h=int(self.boundingRect().height())))


519
class ProcedureStop(Join):
Maxime Perrotin's avatar
Maxime Perrotin committed
520
521
522
523
    ''' Procedure STOP symbol - very similar to JOIN '''
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD
Maxime Perrotin's avatar
Maxime Perrotin committed
524

Maxime Perrotin's avatar
Maxime Perrotin committed
525
526
    def __init__(self, parent=None, ast=None):
        if not ast:
527
            ast = ogAST.Terminator(defName='')
Maxime Perrotin's avatar
Maxime Perrotin committed
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
            ast.pos_y = 0
            ast.width = 35
            ast.height = 35
        super(ProcedureStop, self).__init__(parent, ast)
    completion_list = set()

    def set_shape(self, width, height):
        ''' Define the symbol shape '''
        circ = min(width, height)
        path = QPainterPath()
        path.addEllipse(0, 0, circ, circ)
        point1 = path.pointAtPercent(0.625)
        point2 = path.pointAtPercent(0.125)
        point3 = path.pointAtPercent(0.875)
        point4 = path.pointAtPercent(0.375)
        path.moveTo(point1)
        path.lineTo(point2)
        path.moveTo(point3)
546
        path.lineTo(point4)
Maxime Perrotin's avatar
Maxime Perrotin committed
547
548
549
550
        self.setPath(path)
        # call Join superclass, otherwise symbol will take Join shape
        super(Join, self).set_shape(circ, circ)

Maxime Perrotin's avatar
Maxime Perrotin committed
551
    def PR(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
552
553
        ''' Return the PR string for this symbol '''
        pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
554
        return(u'/* CIF RETURN ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
555
                '{hlink}'
556
                'RETURN {val};'.format(
Maxime Perrotin's avatar
Maxime Perrotin committed
557
                    val=unicode(self.text), hlink=self.text.PR(),
Maxime Perrotin's avatar
Maxime Perrotin committed
558
559
560
561
562
563
                    x=int(pos.x()), y=int(pos.y()),
                    w=int(self.boundingRect().width()),
                    h=int(self.boundingRect().height())))


# pylint: disable=R0904
564
class Label(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
    ''' LABEL symbol '''
    _insertable_followers = [
            'Task', 'ProcedureCall', 'Output', 'Decision', 'Label']
    _terminal_followers = ['Join', 'State', 'ProcedureStop']
    needs_parent = False
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD
    # Symbol must not use antialiasing, otherwise the middle line is too thick
    _antialiasing = False
    completion_list = set()

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.Label()
        super(Label, self).__init__(parent, text=ast.inputString,
                x=ast.pos_x, y=ast.pos_y, hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)
        self.setPen(QPen(Qt.blue))
        self.terminal_symbol = False
        self.textbox_alignment = Qt.AlignLeft | Qt.AlignTop
        self.parser = ogParser

    @property
    def common_name(self):
        return 'label' if self.hasParent else 'floating_label'

    def set_shape(self, width, height):
        ''' Define the shape of the LABEL symbol '''
        #print traceback.print_stack()
        path = QPainterPath()
        path.addEllipse(0, height / 2, width / 4, height / 2)
        path.moveTo(width / 4, height * 3 / 4)
        path.lineTo(width / 2, height * 3 / 4)
        # Add arrow head
        path.moveTo(width / 2 - 5, height * 3 / 4 - 5)
        path.lineTo(width / 2, height * 3 / 4)
        path.lineTo(width / 2 - 5, height * 3 / 4 + 5)
        # Add vertical line in the middle of the symbol
        path.moveTo(width / 2, 0)
        path.lineTo(width / 2, height)
        # Make sure the bounding rect is withing specifications
        path.moveTo(width, height)
        self.setPath(path)
        super(Label, self).set_shape(width, height)

610
    def PR_floating(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
611
612
        ''' Return the PR string for a floating label (incl. transition) '''
        pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
613
        result = [u'/* CIF LABEL ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
614
615
                    '{hlink}'
                    'CONNECTION {label}:'.format(
Maxime Perrotin's avatar
Maxime Perrotin committed
616
617
                        label=unicode(self),
                        hlink=self.text.PR(),
Maxime Perrotin's avatar
Maxime Perrotin committed
618
619
620
621
622
623
                        x=int(pos.x()), y=int(pos.y()),
                        w=int(self.boundingRect().width()),
                        h=int(self.boundingRect().height()))]
        # Recursively parse the branch
        next_symbol = self.next_aligned_symbol()
        while next_symbol:
Maxime Perrotin's avatar
Maxime Perrotin committed
624
            result.append(next_symbol.PR())
Maxime Perrotin's avatar
Maxime Perrotin committed
625
626
627
            next_symbol = next_symbol.next_aligned_symbol()
        result.append('/* CIF End Label */')
        result.append('ENDCONNECTION;')
Maxime Perrotin's avatar
Maxime Perrotin committed
628
        return u'\n'.join(result)
Maxime Perrotin's avatar
Maxime Perrotin committed
629

Maxime Perrotin's avatar
Maxime Perrotin committed
630
    def PR(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
631
632
        ''' Return the PR string for a label '''
        if self.common_name == 'floating_label':
633
            return self.PR_floating()
Maxime Perrotin's avatar
Maxime Perrotin committed
634
635
636
        else:
            # Standard label
            pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
637
            return (u'/* CIF LABEL ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
638
                    '{hlink}'
Maxime Perrotin's avatar
Maxime Perrotin committed
639
640
                    '{label}:'.format(label=unicode(self),
                        hlink=self.text.PR(),
Maxime Perrotin's avatar
Maxime Perrotin committed
641
642
643
644
645
646
                        x=int(pos.x()), y=int(pos.y()),
                        w=int(self.boundingRect().width()),
                        h=int(self.boundingRect().height())))


# pylint: disable=R0904
647
class Task(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
    ''' TASK symbol '''
    _unique_followers = ['Comment']
    _insertable_followers = [
            'Task', 'ProcedureCall', 'Output', 'Decision', 'Label']
    _terminal_followers = ['Join', 'State', 'ProcedureStop']
    common_name = 'task'
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD
    completion_list = set()

    def __init__(self, parent=None, ast=None):
        ''' Initializes the TASK symbol '''
        ast = ast or ogAST.Task()
        super(Task, self).__init__(parent, text=ast.inputString,
                x=ast.pos_x, y=ast.pos_y, hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)

        self.setBrush(QBrush(QColor(255, 255, 202)))
        self.terminal_symbol = False
        self.parser = ogParser
        if ast.comment:
            Comment(parent=self, ast=ast.comment)

    def set_shape(self, width, height):
        ''' Compute the polygon to fit in width, height '''
        path = QPainterPath()
        path.lineTo(width, 0)
        path.lineTo(width, height)
        path.lineTo(0, height)
        path.lineTo(0, 0)
        self.setPath(path)
        super(Task, self).set_shape(width, height)

Maxime Perrotin's avatar
Maxime Perrotin committed
682
    def PR(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
683
        ''' Return the text corresponding to the SDL PR notation '''
Maxime Perrotin's avatar
Maxime Perrotin committed
684
        comment = self.comment.PR() if self.comment else u';'
Maxime Perrotin's avatar
Maxime Perrotin committed
685
        pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
686
        return (u'/* CIF TASK ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
687
                '{hlink}'
Maxime Perrotin's avatar
Maxime Perrotin committed
688
689
                'TASK {t}{comment}'.format(t=unicode(self.text),
                    hlink=self.text.PR(),
Maxime Perrotin's avatar
Maxime Perrotin committed
690
691
692
693
694
695
                    x=int(pos.x()), y=int(pos.y()),
                    w=int(self.boundingRect().width()),
                    h=int(self.boundingRect().height()), comment=comment))


# pylint: disable=R0904
696
class ProcedureCall(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
697
698
699
700
701
702
703
704
705
706
707
708
709
    ''' PROCEDURE CALL symbol '''
    _unique_followers = ['Comment']
    _insertable_followers = [
            'Task', 'ProcedureCall', 'Output', 'Decision', 'Label']
    _terminal_followers = ['Join', 'State', 'ProcedureStop']
    common_name = 'procedure_call'
    # Define reserved keywords for the syntax highlighter
    blackbold = ['\\bWRITELN\\b', '\\bWRITE\\b',
                 '\\bSET_TIMER\\b', '\\bRESET_TIMER\\b']
    redbold = SDL_REDBOLD
    completion_list = {'set_timer', 'reset_timer', 'write', 'writeln'}

    def __init__(self, parent=None, ast=None):
710
        ast = ast or ogAST.Output(defName='')
Maxime Perrotin's avatar
Maxime Perrotin committed
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
        super(ProcedureCall, self).__init__(parent,
                text=ast.inputString, x=ast.pos_x, y=ast.pos_y,
                hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)
        self.setBrush(QBrush(QColor(255, 255, 202)))
        self.terminal_symbol = False
        self.parser = ogParser
        if ast.comment:
            Comment(parent=self, ast=ast.comment)

    def set_shape(self, width, height):
        ''' Compute the polygon to fit in width, height '''
        path = QPainterPath()
        path.addRect(0, 0, width, height)
        path.moveTo(7, 0)
        path.lineTo(7, height)
        path.moveTo(width - 7, 0)
        path.lineTo(width - 7, height)
        self.setPath(path)
        super(ProcedureCall, self).set_shape(width, height)

Maxime Perrotin's avatar
Maxime Perrotin committed
732
    def PR(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
733
        ''' Return the text corresponding to the SDL PR notation '''
Maxime Perrotin's avatar
Maxime Perrotin committed
734
        comment = self.comment.PR() if self.comment else u';'
Maxime Perrotin's avatar
Maxime Perrotin committed
735
        pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
736
        return (u'/* CIF PROCEDURECALL ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
737
                '{hlink}'
Maxime Perrotin's avatar
Maxime Perrotin committed
738
739
                'CALL {p}{comment}'.format(p=unicode(self.text),
                    hlink=self.text.PR(),
Maxime Perrotin's avatar
Maxime Perrotin committed
740
741
742
743
744
745
                    x=int(pos.x()), y=int(pos.y()),
                    w=int(self.boundingRect().width()),
                    h=int(self.boundingRect().height()), comment=comment))


# pylint: disable=R0904
746
class TextSymbol(HorizontalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
    ''' Text symbol - used to declare variables, etc. '''
    common_name = 'text_area'
    needs_parent = False
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD
    completion_list = set()

    def __init__(self, ast=None):
        ''' Create a Text Symbol '''
        ast = ast or ogAST.TextArea()
        super(TextSymbol, self).__init__(parent=None,
                text=ast.inputString,
                x=ast.pos_x, y=ast.pos_y, hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)
        self.setBrush(QBrush(QColor(249, 249, 249)))
        self.terminal_symbol = False
        self.setPos(ast.pos_x, ast.pos_y)
        # Disable hyperlinks for Text symbols
        self._no_hyperlink = True
        # Text is not centered in the box - change default alignment:
        self.textbox_alignment = Qt.AlignLeft | Qt.AlignTop
        self.parser = ogParser

    def update_completion_list(self):
        ''' When text was entered, update TASK completion list '''
        # Get AST for the symbol
774
        ast, _, _, _, _ = self.parser.parseSingleElement('text_area',
Maxime Perrotin's avatar
Maxime Perrotin committed
775
                                                                  self.PR())
Maxime Perrotin's avatar
Maxime Perrotin committed
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
        Task.completion_list |= {dcl for dcl in ast.variables.keys()}

    def set_shape(self, width, height):
        ''' Define the polygon of the text symbol '''
        path = QPainterPath()
        path.moveTo(width - 10, 0)
        path.lineTo(0, 0)
        path.lineTo(0, height)
        path.lineTo(width, height)
        path.lineTo(width, 10)
        path.lineTo(width - 10, 10)
        path.lineTo(width - 10, 0)
        path.lineTo(width, 10)
        self.setPath(path)
        super(TextSymbol, self).set_shape(width, height)

    def resize_item(self, rect):
        ''' Text Symbol only resizes down or right '''
        if self.grabber.resize_mode.endswith('left'):
            return
        self.prepareGeometryChange()
        self.set_shape(rect.width(), rect.height())

Maxime Perrotin's avatar
Maxime Perrotin committed
799
    def PR(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
800
801
        ''' Return the text corresponding to the SDL PR notation '''
        pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
802
        return (u'/* CIF TEXT ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
803
804
                '{hlink}'
                '{text}\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
805
806
                '/* CIF ENDTEXT */'.format(text=unicode(self.text),
                    hlink=self.text.PR(),
Maxime Perrotin's avatar
Maxime Perrotin committed
807
808
809
810
811
812
813
814
815
816
817
818
819
820
                    x=int(pos.x()), y=int(pos.y()),
                    w=int(self.boundingRect().width()),
                    h=int(self.boundingRect().height())))


class ASN1Viewer(TextSymbol):
    ''' Text symbol with dedicated text highlighting set of words for ASN.1 '''
    blackbold = ['\\b{}\\b'.format(word) for word in (
                 'DEFINITIONS', 'AUTOMATIC', 'TAGS', 'BEGIN', 'END', 'INTEGER',
                 'OCTET', 'STRING', 'BIT', 'REAL', 'SEQUENCE', 'OF', 'WITH',
                 'IMPORTS', 'FROM', 'SIZE', 'CHOICE', 'BOOLEAN')]


# pylint: disable=R0904
821
class State(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
822
823
    ''' SDL STATE Symbol '''
    _unique_followers = ['Comment']
Maxime Perrotin's avatar
Maxime Perrotin committed
824
    _insertable_followers = ['Input', 'Connect']
Maxime Perrotin's avatar
Maxime Perrotin committed
825
    arrow_head = 'simple'
Maxime Perrotin's avatar
Maxime Perrotin committed
826
827
828
829
830
831
832
833
834
    common_name = 'terminator_statement'
    needs_parent = False
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD
    completion_list = set()

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.State()
Maxime Perrotin's avatar
Maxime Perrotin committed
835
        ast.inputString = getattr(ast, 'via', None) or ast.inputString
Maxime Perrotin's avatar
Maxime Perrotin committed
836
837
838
839
840
841
842
843
844
845
        # Note: ast coordinates are in scene coordinates
        super(State, self).__init__(parent=parent,
                text=ast.inputString, x=ast.pos_x, y=ast.pos_y,
                hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)
        self.setBrush(QBrush(QColor(255, 228, 213)))
        self.terminal_symbol = True
        if parent:
            try:
                # Map AST scene coordinates to get actual position
Maxime Perrotin's avatar
Maxime Perrotin committed
846
847
                self.setPos(self.pos()
                            + self.mapFromScene(ast.pos_x, ast.pos_y))
Maxime Perrotin's avatar
Maxime Perrotin committed
848
849
850
851
852
853
854
855
856
            except TypeError:
                self.update_position()
        else:
            # Use scene coordinates to position
            self.setPos(ast.pos_x, ast.pos_y)
        self.parser = ogParser
        if ast.comment:
            Comment(parent=self, ast=ast.comment)

857
858
859
    @property
    def allow_nesting(self):
        ''' Redefinition - must be checked according to context '''
Maxime Perrotin's avatar
Maxime Perrotin committed
860
        result = not any(elem in unicode(self).lower().strip()
861
862
863
864
865
866
867
868
                       for elem in ('-', ',', '*', ' '))
        return result

    @property
    def nested_scene(self):
        ''' Redefined - nested scene per state must be unique '''
        return self._nested_scene

Maxime Perrotin's avatar
Maxime Perrotin committed
869
870
871
    def double_click(self):
        ''' Catch a double click - Set nested scene '''
        for each, value in self.scene().composite_states.viewitems():
Maxime Perrotin's avatar
Maxime Perrotin committed
872
            if unicode(self).lower() == unicode(each):
Maxime Perrotin's avatar
Maxime Perrotin committed
873
874
875
876
877
                self.nested_scene = value
                break
        else:
            self.nested_scene = None

878
879
880
881
882
    @nested_scene.setter
    def nested_scene(self, value):
        ''' Set the value of the nested scene '''
        self._nested_scene = value

Maxime Perrotin's avatar
Maxime Perrotin committed
883
884
885
    def update_completion_list(self):
        ''' When text was entered, update state completion list '''
        # Get AST for the symbol
886
887
        ast, _, _, _, _ = self.parser.parseSingleElement(
                    'state', self.PR_state(recursive=False))
Maxime Perrotin's avatar
Maxime Perrotin committed
888
889
890
891
892
893
894
        State.completion_list |= set(ast.statelist)

    def check_syntax(self):
        ''' Redefined function, to distinguish STATE and NEXTSTATE '''
        if self.hasParent:
            super(State, self).check_syntax()
        else:
895
896
            _, syntax_err, _, _, _ = self.parser.parseSingleElement(
                    'state', self.PR_state(recursive=False))
Maxime Perrotin's avatar
Maxime Perrotin committed
897
898
899
900
901
902
903
904
905
            try:
                self.scene().raise_syntax_errors(syntax_err)
            except:
                LOG.debug('raise_syntax_error raised an exception')

    def set_shape(self, width, height):
        ''' Compute the polygon to fit in width, height '''
        path = QPainterPath()
        path.addRoundedRect(0, 0, width, height, height / 4, height)
Maxime Perrotin's avatar
Maxime Perrotin committed
906
907
908
909

        if self.nested_scene and self.is_composite():
            # Distinguish composite states with dash line
            self.setPen(QPen(Qt.DashLine))
Maxime Perrotin's avatar
Maxime Perrotin committed
910
        else:
Maxime Perrotin's avatar
Maxime Perrotin committed
911
            self.setPen(QPen(Qt.SolidLine))
Maxime Perrotin's avatar
Maxime Perrotin committed
912
913
914
915
916
917
918
919
920
921
922
        self.setPath(path)
        super(State, self).set_shape(width, height)

    def get_ast(self):
        ''' Redefinition of the get_ast function for the state '''
        if self.hasParent and not [c for c in self.childSymbols()
                if not isinstance(c, Comment)]:
            # Terminator case
            return super(State, self).get_ast()
        else:
            # State case
923
924
            ast, _, _, _, terminators = self.parser.parseSingleElement(
                'state', self.PR_state())
Maxime Perrotin's avatar
Maxime Perrotin committed
925
926
            return ast, terminators

Maxime Perrotin's avatar
Maxime Perrotin committed
927
928
929
    def parse_composite_state(self):
        ''' Return PR string corresponding to the nested part of the state '''
        entry_points, exit_points = [], []
Maxime Perrotin's avatar
Maxime Perrotin committed
930
        result = [u'STATE {};'.format(unicode(self)),
Maxime Perrotin's avatar
Maxime Perrotin committed
931
932
                  'SUBSTRUCTURE']
        for each in self.nested_scene.start:
Maxime Perrotin's avatar
Maxime Perrotin committed
933
934
            if unicode(each):
                entry_points.append(unicode(each))
Maxime Perrotin's avatar
Maxime Perrotin committed
935
        for each in self.nested_scene.returns:
Maxime Perrotin's avatar
Maxime Perrotin committed
936
937
            if unicode(each) != u'no_name':
                exit_points.append(unicode(each))
Maxime Perrotin's avatar
Maxime Perrotin committed
938
939
940
941
        if entry_points:
            result.append('in ({});'.format(','.join(entry_points)))
        if exit_points:
            result.append('out ({});'.format(','.join(exit_points)))
942
        result.extend(self.nested_scene.get_pr_string())
Maxime Perrotin's avatar
Maxime Perrotin committed
943
        result.append('ENDSUBSTRUCTURE;')
Maxime Perrotin's avatar
Maxime Perrotin committed
944
        return u'\n'.join(result)
Maxime Perrotin's avatar
Maxime Perrotin committed
945

946
    def PR_state(self, recursive=True):
Maxime Perrotin's avatar
Maxime Perrotin committed
947
        ''' Parse state '''
Maxime Perrotin's avatar
Maxime Perrotin committed
948
        comment = self.comment.PR() if self.comment else u';'
Maxime Perrotin's avatar
Maxime Perrotin committed
949
950
951
952
953
        pos = self.scenePos()
        if self.hasParent and not [s for s in self.childSymbols() if
                                   not isinstance(s, Comment)]:
            # Do not generate a new STATE when there is no need
            # FIXME: check if childSymbol is a commment
Maxime Perrotin's avatar
Maxime Perrotin committed
954
955
            return u''
        result = [u'/* CIF STATE ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
956
957
                    '{hlink}'
                    'STATE {state}{comment}'.format(
Maxime Perrotin's avatar
Maxime Perrotin committed
958
959
                        state=unicode(self),
                        hlink=self.text.PR(),
Maxime Perrotin's avatar
Maxime Perrotin committed
960
961
962
963
                        x=int(pos.x()), y=int(pos.y()),
                        w=int(self.boundingRect().width()),
                        h=int(self.boundingRect().height()), comment=comment)]
        if recursive:
964
965
966
967
            for each in self.childSymbols():
                # Recursively return next symbols (inputs, connect)
                if isinstance(each, Input):
                    result.append(each.PR())
Maxime Perrotin's avatar
Maxime Perrotin committed
968
        result.append('ENDSTATE;')
Maxime Perrotin's avatar
Maxime Perrotin committed
969
        return u'\n'.join(result)
Maxime Perrotin's avatar
Maxime Perrotin committed
970

Maxime Perrotin's avatar
Maxime Perrotin committed
971
    def PR(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
972
        ''' Return the text corresponding to the SDL PR notation '''
Maxime Perrotin's avatar
Maxime Perrotin committed
973
        comment = self.comment.PR() if self.comment else u';'
Maxime Perrotin's avatar
Maxime Perrotin committed
974
        pos = self.scenePos()
Maxime Perrotin's avatar
Maxime Perrotin committed
975
        result = [u'/* CIF NEXTSTATE ({x}, {y}), ({w}, {h}) */\n'
Maxime Perrotin's avatar
Maxime Perrotin committed
976
977
                '{hlink}'
                'NEXTSTATE {state}{comment}'.format(
Maxime Perrotin's avatar
Maxime Perrotin committed
978
979
                    state=unicode(self),
                    hlink=self.text.PR(),
Maxime Perrotin's avatar
Maxime Perrotin committed
980
981
                    x=int(pos.x()), y=int(pos.y()),
                    w=int(self.boundingRect().width()),
Maxime Perrotin's avatar
Maxime Perrotin committed
982
983
984
                    h=int(self.boundingRect().height()),
                    comment=comment)]
        return u'\n'.join(result)
Maxime Perrotin's avatar
Maxime Perrotin committed
985
986


987
988
989
990
991
992
993
994
995
996
997
class Process(HorizontalSymbol):
    ''' Process symbol '''
    _unique_followers = ['Comment']
    _allow_nesting = True
    common_name = 'process_definition'
    needs_parent = False
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD
    completion_list = set()
    is_singleton = True
Maxime Perrotin's avatar
Maxime Perrotin committed
998
999
    arrow_head = 'angle'
    arrow_tail = 'angle'
1000

For faster browsing, not all history is shown. View entire blame