sdlSymbols.py 44.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
from itertools import chain
Maxime Perrotin's avatar
Maxime Perrotin committed
28
29

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

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

Maxime Perrotin's avatar
Maxime Perrotin committed
35
36
37
38
39
40
import ogParser
import ogAST


LOG = logging.getLogger('sdlSymbols')

41
AST = ogAST.AST()
42
CONTEXT = ogAST.Process()
Maxime Perrotin's avatar
Maxime Perrotin committed
43
44
45
46
47
48
49
50

# 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',
51
                'SET_TIMER', 'RESET_TIMER', 'VIA', 'ENTRY', 'EXIT', 'ANY',
52
                'SYNTYPE', 'ENDSYNTYPE', 'CONSTANTS', 'ENDPROCEDURE',
53
                'COMMENT', 'SIGNAL', 'SIGNALLIST', 'USE',
Maxime Perrotin's avatar
Maxime Perrotin committed
54
                'NEWTYPE', 'ENDNEWTYPE', 'ARRAY', 'STRUCT', 'SYNONYM')]
Maxime Perrotin's avatar
Maxime Perrotin committed
55
56
57

SDL_REDBOLD = ['\\b{word}\\b'.format(word=word) for word in (
              'INPUT', 'OUTPUT', 'STATE', 'DECISION', 'NEXTSTATE',
58
              'TASK', 'PROCESS', 'LABEL', 'JOIN', 'CONNECTION', 'CONNECT')]
Maxime Perrotin's avatar
Maxime Perrotin committed
59
60


61
62
63
64
65
def variables_autocompletion(symbol, type_filter=None):
    ''' Intelligent autocompletion for variables - including struct fields
        Optional: only variables of a type listed in type_filter are kept
    '''
    res = set()
Maxime Perrotin's avatar
Maxime Perrotin committed
66
67
68
69
70
71
    if not symbol.text:
        return res
    parts = symbol.text.context.split('!')
    if len(parts) == 0:
        return res
    elif len(parts) == 1:
72
73
74
75
76
        try:
            fpar = {fp['name']: (fp['type'], None) for fp in CONTEXT.fpar}
        except AttributeError:
            # not in the context of a procedure
            fpar = {}
77
78
79
80
        # Return the list of variables, possibly filterd by type
        if not type_filter:
            res = set(CONTEXT.variables.keys()
                      + CONTEXT.global_variables.keys()
81
82
                      + AST.asn1_constants.keys()
                      + fpar.keys())
83
84
85
86
87
88
        else:
            constants = {name: (cty.type, None)
                         for name, cty in AST.asn1_constants.viewitems()}
            type_filter_names = [ogParser.type_name(ty) for ty in type_filter]
            for name, (asn1type, _) in chain(CONTEXT.variables.viewitems(),
                                          CONTEXT.global_variables.viewitems(),
89
90
                                          constants.viewitems(),
                                          fpar.viewitems()):
91
92
                if ogParser.type_name(asn1type) in type_filter_names:
                    res.add(name)
Maxime Perrotin's avatar
Maxime Perrotin committed
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
    else:
        var = parts[0].lower()
        try:
            var_t = ogParser.find_variable_type(var, CONTEXT)
            basic = ogParser.find_basic_type(var_t, AST.dataview)
            res = (field.replace('-', '_') for field in basic.Children.keys())
        except (AttributeError, TypeError):
            res = []
        else:
            for each in parts[1:-1]:
                try:
                    for child, childtype in basic.Children.viewitems():
                        if child.lower() == each.lower().replace('_', '-'):
                            basic = ogParser.find_basic_type(childtype.type,
                                                             AST.dataview)
                            break
                    else:
                        res = ()
                        break
                except (AttributeError, TypeError):
                    res = ()
                    break
            else:
                try:
                    res = (field.replace('-', '_')
                           for field in basic.Children.keys())
                except AttributeError:
                    res = ()
    return res




Maxime Perrotin's avatar
Maxime Perrotin committed
126
# pylint: disable=R0904
127
class Input(HorizontalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
128
129
130
    ''' SDL INPUT Symbol '''
    _unique_followers = ['Comment']
    _insertable_followers = ['Task', 'ProcedureCall', 'Output', 'Decision',
131
                             'Input', 'Label', 'Connect']
Maxime Perrotin's avatar
Maxime Perrotin committed
132
133
134
135
136
137
138
139
140
141
    _terminal_followers = ['Join', 'State', 'ProcedureStop']

    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()
142
        self.ast = ast
Maxime Perrotin's avatar
Maxime Perrotin committed
143
        self.branch_entrypoint = None
Maxime Perrotin's avatar
Maxime Perrotin committed
144
145
146
        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
147
        super(Input, self).__init__(parent, text=ast.inputString,
148
                x=ast.pos_x or 0, y=ast.pos_y or 0, hyperlink=ast.hyperlink)
Maxime Perrotin's avatar
Maxime Perrotin committed
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
        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 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
178
179
180
181
    @property
    def completion_list(self):
        ''' Set auto-completion list '''
        if '(' in unicode(self):
182
183
184
185
186
            # Input parameter: return the list of variables of this type
            input_name = unicode(self).split('(')[0].strip().lower()
            asn1_filter = [sig['type'] for sig in CONTEXT.input_signals if
                           sig['name'] == input_name]
            return variables_autocompletion(self, asn1_filter)
Maxime Perrotin's avatar
Maxime Perrotin committed
187
        else:
188
189
190
            # Return the list of input signals and timers
            return (set(sig['name'] for sig in CONTEXT.input_signals).union(
                    CONTEXT.global_timers + CONTEXT.timers))
Maxime Perrotin's avatar
Maxime Perrotin committed
191

Maxime Perrotin's avatar
Maxime Perrotin committed
192

193
194
195
class Connect(Input):
    ''' Connect point below a nested state '''
    common_name = 'connect_part'
196
    auto_expand = True
Maxime Perrotin's avatar
Maxime Perrotin committed
197
198
199
    resizeable = False
    # Symbol must not use antialiasing, otherwise the middle line is too thick
    _antialiasing = False
Maxime Perrotin's avatar
Maxime Perrotin committed
200

Maxime Perrotin's avatar
Maxime Perrotin committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
    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

217
218
219
220
221
222
223
224
225
226
    @property
    def completion_list(self):
        ''' Set auto-completion list: list of exit points of nested state '''
        parent_state = unicode(self.parentItem()).lower()
        for each in CONTEXT.composite_states:
            if each.statename == parent_state:
                return each.state_exitpoints
        else:
            return set()

227

Maxime Perrotin's avatar
Maxime Perrotin committed
228
# pylint: disable=R0904
229
class Output(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
230
231
232
233
234
235
236
237
238
239
240
241
    ''' 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

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.Output()
242
        self.ast = ast
Maxime Perrotin's avatar
Maxime Perrotin committed
243
        super(Output, self).__init__(parent=parent,
244
                text=ast.inputString, x=ast.pos_x or 0, y=ast.pos_y or 0,
Maxime Perrotin's avatar
Maxime Perrotin committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
                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
265
266
267
    @property
    def completion_list(self):
        ''' Set auto-completion list '''
268
269
270
271
        if '(' in unicode(self):
            # Output parameter: return the list of variables of this type
            output_name = unicode(self).split('(')[0].strip().lower()
            asn1_filter = [sig['type'] for sig in CONTEXT.output_signals if
272
                           hasattr(sig, 'type') and sig['name'] == output_name]
273
274
275
276
            return variables_autocompletion(self, asn1_filter)
        else:
            # Return the list of output signals
            return (set(sig['name'] for sig in CONTEXT.output_signals))
Maxime Perrotin's avatar
Maxime Perrotin committed
277

Maxime Perrotin's avatar
Maxime Perrotin committed
278
279

# pylint: disable=R0904
280
class Decision(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
281
282
    ''' SDL DECISION Symbol '''
    _unique_followers = ['Comment']
Maxime Perrotin's avatar
Maxime Perrotin committed
283
284
    _insertable_followers = ['DecisionAnswer', 'Task', 'ProcedureCall',
                             'Output', 'Decision', 'Label']
Maxime Perrotin's avatar
Maxime Perrotin committed
285
286
287
288
289
290
291
292
293
    _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

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.Decision()
294
        self.ast = ast
Maxime Perrotin's avatar
Maxime Perrotin committed
295
296
297
        # 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,
298
                x=ast.pos_x or 0, y=ast.pos_y or 0, hyperlink=ast.hyperlink)
Maxime Perrotin's avatar
Maxime Perrotin committed
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
        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
316
        return True
Maxime Perrotin's avatar
Maxime Perrotin committed
317

Maxime Perrotin's avatar
Maxime Perrotin committed
318
319
320
321
322
    @property
    def completion_list(self):
        ''' Set auto-completion list '''
        return chain(variables_autocompletion(self), ('length', 'present'))

Maxime Perrotin's avatar
Maxime Perrotin committed
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
    def branches(self):
        ''' Return the list of decision answers (as a generator) '''
        return (branch for branch in self.childSymbols()
                if isinstance(branch, DecisionAnswer))

    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 '''
356
        LOG.debug('UpdateConnectionPointPosition of {}'.format(unicode(self)))
Maxime Perrotin's avatar
Maxime Perrotin committed
357
358
359
360
361
362
363
364
365
366
367
368
369
        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)))
370
371
                # Don't set parent item to None to avoid Qt segfault
                last_cnx.setParentItem(self)
Maxime Perrotin's avatar
Maxime Perrotin committed
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
            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()


# pylint: disable=R0904
406
class DecisionAnswer(HorizontalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
407
408
409
410
411
412
413
414
415
416
417
    ''' 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

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.Answer()
418
        self.ast = ast
Maxime Perrotin's avatar
Maxime Perrotin committed
419
420
421
422
423
424
        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,
425
426
427
428
                                             text=ast.inputString,
                                             x=ast.pos_x or 0,
                                             y=ast.pos_y or 0,
                                             hyperlink=ast.hyperlink)
Maxime Perrotin's avatar
Maxime Perrotin committed
429
430
431
432
433
434
435
436
437
438
439
440
441
        self.set_shape(ast.width, ast.height)
        #self.setPen(QColor(0, 0, 0, 0))
        self.branch_entrypoint = self
        self.parser = ogParser

    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
442
443
        self.last_branch_item.connectionBelow = \
                JoinConnection(self.last_branch_item, item_parent)
Maxime Perrotin's avatar
Maxime Perrotin committed
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462

    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)

463
464
465
466
467
    @property
    def completion_list(self):
        ''' Set auto-completion list '''
        return ['ELSE']

Maxime Perrotin's avatar
Maxime Perrotin committed
468
469

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

    def __init__(self, parent=None, ast=None):
480
        self.ast = ast
Maxime Perrotin's avatar
Maxime Perrotin committed
481
        if not ast:
482
            ast = ogAST.Terminator(defName='')
Maxime Perrotin's avatar
Maxime Perrotin committed
483
484
485
            ast.pos_y = 0
            ast.width = 35
            ast.height = 35
486
487
488
489
490
        super(Join, self).__init__(parent,
                                   text=ast.inputString,
                                   x=ast.pos_x,
                                   y=ast.pos_y,
                                   hyperlink=ast.hyperlink)
Maxime Perrotin's avatar
Maxime Perrotin committed
491
492
493
494
495
496
497
498
499
500
        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
501
        super(Join, self).resize_item(rect)
Maxime Perrotin's avatar
Maxime Perrotin committed
502
503
504
505
506
507
508
509
510

    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)

511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
    @property
    def completion_list(self):
        ''' Set auto-completion list - list of labels '''
        return (label.inputString for label in CONTEXT.labels)

    def update_completion_list(self, pr_text):
        ''' When text was entered, update list of join terminators '''
        ast, _, _, _, _ = self.parser.parseSingleElement(self.common_name,
                                                         pr_text)
        for each in (t for t in CONTEXT.terminators if t.kind == 'join'):
            if each.inputString == unicode(self):
                # Ignore if already defined
                break
        else:
            CONTEXT.terminators.append(ast)

Maxime Perrotin's avatar
Maxime Perrotin committed
527

528
class ProcedureStop(Join):
Maxime Perrotin's avatar
Maxime Perrotin committed
529
530
531
532
    ''' 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
533

Maxime Perrotin's avatar
Maxime Perrotin committed
534
    def __init__(self, parent=None, ast=None):
535
        self.ast = ast
Maxime Perrotin's avatar
Maxime Perrotin committed
536
        if not ast:
537
            ast = ogAST.Terminator(defName='')
Maxime Perrotin's avatar
Maxime Perrotin committed
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
            ast.pos_y = 0
            ast.width = 35
            ast.height = 35
        super(ProcedureStop, self).__init__(parent, ast)

    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)
555
        path.lineTo(point4)
Maxime Perrotin's avatar
Maxime Perrotin committed
556
557
558
559
        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
560
561
562
    @property
    def completion_list(self):
        ''' Set auto-completion list '''
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
        try:
            return CONTEXT.state_exitpoints
        except AttributeError:
            # Not in a state but in a procedure
            return set()

    def update_completion_list(self, pr_text):
        ''' When text was entered, if in a nested state update exit points '''
        ast, _, _, _, _ = self.parser.parseSingleElement(self.common_name,
                                                         pr_text)
        try:
            CONTEXT.state_exitpoints = set(CONTEXT.state_exitpoints
                                           + [unicode(self)])
        except AttributeError:
            # No state exit points in a procedure
            pass
Maxime Perrotin's avatar
Maxime Perrotin committed
579

Maxime Perrotin's avatar
Maxime Perrotin committed
580
581

# pylint: disable=R0904
582
class Label(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
583
584
585
586
587
588
589
590
591
592
593
594
595
    ''' 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

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.Label()
596
597
598
599
600
601
        self.ast = ast
        super(Label, self).__init__(parent,
                                    text=ast.inputString,
                                    x=ast.pos_x or 0,
                                    y=ast.pos_y or 0,
                                    hyperlink=ast.hyperlink)
Maxime Perrotin's avatar
Maxime Perrotin committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
        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 '''
        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)

630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
    @property
    def completion_list(self):
        ''' Set auto-completion list - list of JOIN '''
        return (term.inputString
                for term in CONTEXT.terminators if term.kind == 'join')

    def update_completion_list(self, pr_text):
        ''' When text was entered, update list of labels in current context '''
        ast, _, _, _, _ = self.parser.parseSingleElement(self.common_name,
                                                         pr_text)
        for each in CONTEXT.labels:
            if each.inputString == unicode(self):
                # Ignore if already defined
                break
        else:
            CONTEXT.labels.append(ast)

Maxime Perrotin's avatar
Maxime Perrotin committed
647
648

# pylint: disable=R0904
649
class Task(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
650
651
652
653
654
655
656
657
658
659
660
661
662
    ''' 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

    def __init__(self, parent=None, ast=None):
        ''' Initializes the TASK symbol '''
        ast = ast or ogAST.Task()
663
664
665
666
667
668
        self.ast = ast
        super(Task, self).__init__(parent,
                                   text=ast.inputString,
                                   x=ast.pos_x or 0,
                                   y=ast.pos_y or 0,
                                   hyperlink=ast.hyperlink)
Maxime Perrotin's avatar
Maxime Perrotin committed
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
        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)

686
687
    @property
    def completion_list(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
688
        ''' Set auto-completion list '''
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
        elems = unicode(self).lower().strip().split()
        asn1_filter = []
        if len(elems) == 2 and elems[1] == ':=':
            # Find type of variable on the left and filter accordingly
            varname = elems[0]
            try:
                fpar = {fp['name']: (fp['type'], None) for fp in CONTEXT.fpar}
            except AttributeError:
                # not in the context of a procedure
                fpar = {}
            constants = {name: (cty.type, None)
                         for name, cty in AST.asn1_constants.viewitems()}
            for name, (asn1ty, _) in chain (CONTEXT.variables.viewitems(),
                                          CONTEXT.global_variables.viewitems(),
                                          constants.viewitems(),
                                          fpar.viewitems()):
                if name == varname:
                    asn1_filter = [asn1ty]
                    break
        return chain(variables_autocompletion(self, asn1_filter),
                     ogParser.SPECIAL_OPERATORS.viewkeys())
Maxime Perrotin's avatar
Maxime Perrotin committed
710
711

# pylint: disable=R0904
712
class ProcedureCall(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
713
714
715
716
717
718
719
720
721
722
723
724
    ''' 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

    def __init__(self, parent=None, ast=None):
725
        ast = ast or ogAST.Output(defName='')
726
        self.ast = ast
Maxime Perrotin's avatar
Maxime Perrotin committed
727
        super(ProcedureCall, self).__init__(parent,
728
729
730
731
                                            text=ast.inputString,
                                            x=ast.pos_x or 0,
                                            y=ast.pos_y or 0,
                                            hyperlink=ast.hyperlink)
Maxime Perrotin's avatar
Maxime Perrotin committed
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
        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
750
751
752
    @property
    def completion_list(self):
        ''' Set auto-completion list '''
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
        if '(' in unicode(self):
            # Get the variables of the type of the current parameter
            count = unicode(self).count(',')
            procname = unicode(self).split('(')[0].strip().lower()
            for each in (proc for proc in CONTEXT.procedures
                         if proc.inputString.lower() == procname):
                param_types = [p['type'] for p in each.fpar]
                break
            else:
                # Procedure not defined, check special operators
                if (procname == 'set_timer' and count == 1) or (
                        procname == 'reset_timer' and count == 0):
                    return chain(CONTEXT.timers, CONTEXT.global_timers)
                elif procname in ('write', 'writeln'):
                    # Could filter for OCTET STRINGS/Strings/Integer/Booleans
                    return variables_autocompletion(self)
                else:
                    return ()
            if count + 1 > len(param_types):
                # User tries to set more parameters than defined
                return ()
            else:
                # Return variables of the type of the parameter
                asn1_filter = param_types[slice(count, count + 1)]
                return variables_autocompletion(self, asn1_filter)
        else:
            return chain((proc.inputString for proc in CONTEXT.procedures),
                         ('set_timer', 'reset_timer', 'write', 'writeln'))
Maxime Perrotin's avatar
Maxime Perrotin committed
781

Maxime Perrotin's avatar
Maxime Perrotin committed
782
783

# pylint: disable=R0904
784
class TextSymbol(HorizontalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
785
786
787
788
789
790
791
792
793
794
    ''' 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

    def __init__(self, ast=None):
        ''' Create a Text Symbol '''
        ast = ast or ogAST.TextArea()
795
        self.ast = ast
Maxime Perrotin's avatar
Maxime Perrotin committed
796
        super(TextSymbol, self).__init__(parent=None,
797
798
799
800
                                         text=ast.inputString,
                                         x=ast.pos_x or 0,
                                         y=ast.pos_y or 0,
                                         hyperlink=ast.hyperlink)
Maxime Perrotin's avatar
Maxime Perrotin committed
801
802
803
        self.set_shape(ast.width, ast.height)
        self.setBrush(QBrush(QColor(249, 249, 249)))
        self.terminal_symbol = False
804
        self.setPos(ast.pos_x or 0, ast.pos_y or 0)
Maxime Perrotin's avatar
Maxime Perrotin committed
805
806
807
808
809
810
        # 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

Maxime Perrotin's avatar
Maxime Perrotin committed
811
    def update_completion_list(self, pr_text):
812
        ''' When text was entered, update list of variables/FPAR/Timers '''
Maxime Perrotin's avatar
Maxime Perrotin committed
813
        # Get AST for the symbol
Maxime Perrotin's avatar
Maxime Perrotin committed
814
        ast, _, _, _, _ = self.parser.parseSingleElement('text_area', pr_text)
815
816
817
818
        try:
            CONTEXT.variables.update(ast.variables)
            CONTEXT.timers = list(set(CONTEXT.timers + ast.timers))
        except AttributeError:
819
            # context may not have variables/timers (eg if context = block)
820
            pass
821
        CONTEXT.procedures = list(set(CONTEXT.procedures + ast.procedures))
822
823
824
825
        try:
            CONTEXT.fpar.extend(ast.fpar)
        except AttributeError:
            pass
826
827
        # Update completion list of Signalroutes
        Signalroute.completion_list |= set(sig['name'] for sig in ast.signals)
Maxime Perrotin's avatar
Maxime Perrotin committed
828

Maxime Perrotin's avatar
Maxime Perrotin committed
829
830
831
    @property
    def completion_list(self):
        ''' Set auto-completion list '''
832
        try:
833
            return set(AST.dataview.keys())
834
        except AttributeError:
835
            return [] # No Dataview
Maxime Perrotin's avatar
Maxime Perrotin committed
836

Maxime Perrotin's avatar
Maxime Perrotin committed
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
    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())


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',
864
                 'IMPORTS', 'FROM', 'SIZE', 'CHOICE', 'BOOLEAN', 'ENUMERATED')]
Maxime Perrotin's avatar
Maxime Perrotin committed
865
866
867


# pylint: disable=R0904
868
class State(VerticalSymbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
869
870
    ''' SDL STATE Symbol '''
    _unique_followers = ['Comment']
Maxime Perrotin's avatar
Maxime Perrotin committed
871
    _insertable_followers = ['Input', 'Connect']
Maxime Perrotin's avatar
Maxime Perrotin committed
872
    arrow_head = 'simple'
Maxime Perrotin's avatar
Maxime Perrotin committed
873
874
875
876
877
878
879
880
    common_name = 'terminator_statement'
    needs_parent = False
    # Define reserved keywords for the syntax highlighter
    blackbold = SDL_BLACKBOLD
    redbold = SDL_REDBOLD

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.State()
881
        self.ast = ast
Maxime Perrotin's avatar
Maxime Perrotin committed
882
        ast.inputString = getattr(ast, 'via', None) or ast.inputString
Maxime Perrotin's avatar
Maxime Perrotin committed
883
        super(State, self).__init__(parent=parent,
884
885
886
887
                                    text=ast.inputString,
                                    x=ast.pos_x or 0,
                                    y=ast.pos_y or 0,
                                    hyperlink=ast.hyperlink)
Maxime Perrotin's avatar
Maxime Perrotin committed
888
889
890
891
892
893
        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
894
895
                self.setPos(self.pos() + self.mapFromScene(ast.pos_x or 0,
                                                           ast.pos_y or 0))
Maxime Perrotin's avatar
Maxime Perrotin committed
896
897
898
899
            except TypeError:
                self.update_position()
        else:
            # Use scene coordinates to position
900
            self.setPos(ast.pos_x or 0, ast.pos_y or 0)
Maxime Perrotin's avatar
Maxime Perrotin committed
901
902
903
904
        self.parser = ogParser
        if ast.comment:
            Comment(parent=self, ast=ast.comment)

905
906
907
    @property
    def allow_nesting(self):
        ''' Redefinition - must be checked according to context '''
Maxime Perrotin's avatar
Maxime Perrotin committed
908
        result = not any(elem in unicode(self).lower().strip()
Maxime Perrotin's avatar
Maxime Perrotin committed
909
                       for elem in ('-', ',', '*'))
910
911
912
913
914
915
916
        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
917
918
919
    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
920
            if unicode(self).split()[0].lower() == unicode(each):
Maxime Perrotin's avatar
Maxime Perrotin committed
921
922
923
924
925
                self.nested_scene = value
                break
        else:
            self.nested_scene = None

926
927
928
929
930
    @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
931
    def update_completion_list(self, pr_text):
Maxime Perrotin's avatar
Maxime Perrotin committed
932
        ''' When text was entered, update state completion list '''
933
        # Get AST for the symbol and update the context dictionnary
Maxime Perrotin's avatar
Maxime Perrotin committed
934
        ast, _, _, _, _ = self.parser.parseSingleElement('state', pr_text)
935
936
        for each in ast.statelist:
            CONTEXT.mapping[each] = None
Maxime Perrotin's avatar
Maxime Perrotin committed
937

Maxime Perrotin's avatar
Maxime Perrotin committed
938
939
940
    @property
    def completion_list(self):
        ''' Set auto-completion list '''
941
942
943
944
945
946
947
948
949
        elems = unicode(self).lower().strip().split()
        if len(elems) == 2 and elems[1] == 'via':
            # Get list of entry point of the nested state
            statename = elems[0]
            for each in CONTEXT.composite_states:
                if each.statename == statename:
                    return each.state_entrypoints
        else:
            return set(state for state in CONTEXT.mapping if state != 'START')
Maxime Perrotin's avatar
Maxime Perrotin committed
950
951
952
953
954

    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
955
956
957
958

        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
959
        else:
Maxime Perrotin's avatar
Maxime Perrotin committed
960
            self.setPen(QPen(Qt.SolidLine))
Maxime Perrotin's avatar
Maxime Perrotin committed
961
962
963
        self.setPath(path)
        super(State, self).set_shape(width, height)

Maxime Perrotin's avatar
Maxime Perrotin committed
964
    def get_ast(self, pr_text):
Maxime Perrotin's avatar
Maxime Perrotin committed
965
        ''' Redefinition of the get_ast function for the state '''
Maxime Perrotin's avatar
Maxime Perrotin committed
966
967
968
        ast, _, _, _, terminators = self.parser.parseSingleElement('state',
                                                                   pr_text)
        return ast, terminators
969

970
971
972
973
974
975
    def check_syntax(self, pr_text):
        ''' Redefinition of the check syntax function for the state '''
        name = self.common_name if self.hasParent else 'state'
        _, err, _, _, _ = \
                self.parser.parseSingleElement(name, pr_text)
        return err
Maxime Perrotin's avatar
Maxime Perrotin committed
976
977


978
979
980
981
982
983
984
985
986
987
988
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
989
990
    arrow_head = 'angle'
    arrow_tail = 'angle'
991
992
993

    def __init__(self, ast=None, subscene=None):
        ast = ast or ogAST.Process()
994
        self.ast = ast
995
996
997
998
999
1000
        super(Process, self).__init__(parent=None,
                                      text=ast.processName,
                                      x=ast.pos_x,
                                      y=ast.pos_y,
                                      hyperlink=ast.hyperlink)
        self.set_shape(ast.width, ast.height)
For faster browsing, not all history is shown. View entire blame