genericSymbols.py 54.9 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
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    Generic library containing the definition of top-level symbols
    that can be used to create diagrams.

    The Symbol class contains common behaviour shared by inherited
    symobols - in particular the VerticalSymbol is a class of symbols
    that can only be vertically aligned ; Horizontal symbols, on the
    other hand, can be move in both directions.

    The "Comment" class of symbols is a floating symbol that is
    connected to a parent symbol on the right.

    This library also contains the defintition of connections
    (the Connection class).

    Symbols can have an editable text area, which behaviour is
    defined in the EditableText class. This class uses the Completer
    and Highlighter class for text auto-completion and syntax
    highlighting.


    Major functionalities offered by the generic Symbol classes are
    the insersion and deletion of items (possibly recursively if there
    are child symbols), the moving and resizing, the collision
    avoidance manoeuvres (when moving a group of symbols on top
    of another group, it has the effect of "pushing" the colliders
    so that symbols never "touch" each others - keeping the diagram
    clean.

    In order to create a specific diagram editor, the user of this
    library shall create his own symbols, that inherit either from
    Horizontal- or VerticalSymbol classes. The geometry of the symbol
    has to be defined in these subclass by defining the polygon
    and other properties (colours, filling, etc.). Some methods can
    be redefined if a particular behaviour is required (e.g. resizing
    differently, holding different connections points, etc).

    For a complete example, look at the "sdlSymbols.py" module, that
    provide symbol definitions that correspond to an SDL editor.

44
    Copyright (c) 2012-2019 European Space Agency
Maxime Perrotin's avatar
Maxime Perrotin committed
45
46
47
48
49
50

    Designed and implemented by Maxime Perrotin for the TASTE project

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

Maxime Perrotin's avatar
Maxime Perrotin committed
51
__all__ = ['Symbol', 'VerticalSymbol', 'HorizontalSymbol', 'Comment']
Maxime Perrotin's avatar
Maxime Perrotin committed
52
53
import os
import logging
Maxime Perrotin's avatar
Maxime Perrotin committed
54
import traceback
Maxime Perrotin's avatar
Maxime Perrotin committed
55

Maxime Perrotin's avatar
Maxime Perrotin committed
56
57
58
59
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2.QtUiTools import QUiLoader
Maxime Perrotin's avatar
Maxime Perrotin committed
60

Maxime Perrotin's avatar
Maxime Perrotin committed
61
62
from . import undoCommands, ogAST, ogParser
from .Connectors import Connection, VerticalConnection, CommentConnection, \
Maxime Perrotin's avatar
Maxime Perrotin committed
63
                       RakeConnection, JoinConnection, Channel
Maxime Perrotin's avatar
Maxime Perrotin committed
64

Maxime Perrotin's avatar
Maxime Perrotin committed
65
from .TextInteraction import EditableText
Maxime Perrotin's avatar
Maxime Perrotin committed
66

67
LOG = logging.getLogger(__name__)
Maxime Perrotin's avatar
Maxime Perrotin committed
68
69
70


# pylint: disable=R0904, R0902
Maxime Perrotin's avatar
Maxime Perrotin committed
71
class Symbol(QObject, QGraphicsPathItem):
Maxime Perrotin's avatar
Maxime Perrotin committed
72
73
74
75
    '''
        Top-level class used to handle all SDL symbols
        Inherits from QObject to allow animations
    '''
76
77
78
    # Emit a signal when the symbol moved - can be caught by connectors to
    # adjust connection points if the symbol is not the connection parent
    moved = Signal(float, float)
79
    # when editing text, signal is emitted when the word under cursor changes
Maxime Perrotin's avatar
Maxime Perrotin committed
80
81
82
83
84
85
    # Symbols of a given type share a text-autocompletion list:
    completion_list = set()
    # Flexible lists of symbol types that can be set as child of this symbol
    _unique_followers = []  # unique : e.g. comment symbol
    _insertable_followers = []  # no limit to insert below current symbol
    _terminal_followers = []  # cannot be inserted between two symbols
86
    # List of symbols that can be connected, but without parent-child relation
87
88
    _conn_sources = []   # source types that can connect to this symbol
    _conn_targets = []   # target types that can connect to this symbol
Maxime Perrotin's avatar
Maxime Perrotin committed
89
90
    # By default a symbol is resizeable
    resizeable = True
Maxime Perrotin's avatar
Maxime Perrotin committed
91
92
    # By default symbol size may expand when inner text exceeds border
    auto_expand = True
Maxime Perrotin's avatar
Maxime Perrotin committed
93
94
    # default size: "any" or "symbol_default" - optionally used at creation
    default_size = "symbol_default"
Maxime Perrotin's avatar
Maxime Perrotin committed
95
    # By default connections between symbols are lines, not arrows
Maxime Perrotin's avatar
Maxime Perrotin committed
96
97
    arrow_head = None
    arrow_tail = None
98
99
    # Define if a symbol can be manually connected to another one by user
    user_can_connect = False
Maxime Perrotin's avatar
Maxime Perrotin committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    # Default mouse cursor
    default_cursor = Qt.SizeAllCursor
    # Decide if a symbol can be copy-pasted several times
    is_singleton = False
    # default textbox alignment: centered in the symbol
    # can differ on specific symbols (e.g. TextArea or label)
    textbox_alignment = Qt.AlignCenter
    # Common name is the name of the symbol as used in a parser or backend
    common_name = ''
    # Specify if a symbol always needs to be the child of another symbol
    # or if it can live standalone on the scene (yet can have children)
    needs_parent = True
    # nested_scene : a symbol may have content that can be visible on demand
    # (e.g. a subscene that appears when double-clicking on the item)
114
115
    _allow_nesting = False
    _nested_scene = None
116
117
    # name used to discriminate the scene context
    context_name = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
118
119
120
121
122
    # keywords for the syntax highlighter
    blackbold = ()
    redbold = ()
    # Specify if the symbol can be drawn with anti-aliasing
    _antialiasing = True
Maxime Perrotin's avatar
Maxime Perrotin committed
123
124
    # Specify if the symbol has a text area
    has_text_area = True
Maxime Perrotin's avatar
Maxime Perrotin committed
125
126
127
128
129
    # To keep track of the size of the symbol, set width and height
    # the boundingRect() function is redefined to return these values
    # this is essential because anti-aliasing or the QPen may sometimes alter
    # the size in an unwanted manner.
    width, height = 0, 0
Maxime Perrotin's avatar
Maxime Perrotin committed
130
131
132
133
134
135
136
137

    def __init__(self, parent=None):
        '''
            Create top level symbol and propagate important properties
            from parent items
        '''
        super(Symbol, self).__init__(parent)
        QGraphicsPathItem.__init__(self, parent)
138
        # Current mode, can be empty string, "Resize", or "Move"
Maxime Perrotin's avatar
Maxime Perrotin committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
        self.mode = ''
        self.comment = None
        self.text = None
        # Grabber allowing to resize the item
        self.grabber = Cornergrabber(parent=self)
        self.hyperlink_dialog = None
        self.hlink_field = None
        self.loadHyperlinkDialog()
        # hasParent compensates a Qt (or PySide) bug when calling parentItem()
        # on top-level items
        self.hasParent = False
        self.parent = None
        # Optional parser for the symbol textual representation
        self.parser = None
        # branch entry point allows working with aligned symbols
        self.branch_entrypoint = None
        # Terminal symbol can be used to identify last items of a branch
        self._terminal_symbol = False
        # and default text alignment within a textbox
        self.text_alignment = Qt.AlignLeft
        # Activate cache mode to boost rendering by calling paint less often
160
        # self.setCacheMode(QGraphicsItem.DeviceCoordinateCache)
Maxime Perrotin's avatar
Maxime Perrotin committed
161
162
163
164
165
166
        # Apply symbol default mouse cursor
        self.setCursor(self.default_cursor)
        # De-ativate cache mode otherwise paint is not properly updated
        # for the comment symbol (need to refresh on_the_right property)
        self.setCacheMode(QGraphicsItem.NoCache)
        # Initialize variables used when moving/resizing
Maxime Perrotin's avatar
Maxime Perrotin committed
167
        self.coord = self.position
Maxime Perrotin's avatar
Maxime Perrotin committed
168
        # self.height = 0 defined at subclass level
Maxime Perrotin's avatar
Maxime Perrotin committed
169
170
171
        self.old_rect = self.boundingRect()
        # List of visible connection points (that can move)
        self.movable_points = []
Maxime Perrotin's avatar
Maxime Perrotin committed
172
173
        # Flag to indicate a detected syntax error, used to force the
        # refocus of the text area to make sure user fixes it before saving
174
        self.syntax_error: bool = False
Maxime Perrotin's avatar
Maxime Perrotin committed
175

Maxime Perrotin's avatar
Maxime Perrotin committed
176
177
178
179
    def set_valid_pos(self, pos):
        ''' Hook that can be redefined by sub classes to forbid wrong
        placements on the fly, before calling the actual setPos() from Qt '''
        self.setPos(pos)
Maxime Perrotin's avatar
Maxime Perrotin committed
180

181
182
183
184
    # The "position" property cannot be defined as a standard Python
    # property because it is used in a QPropertyAnimation, which only
    # works using Qt properties. However it behaves the same way.
    position = Property(QPointF, lambda self: self.pos(),
Maxime Perrotin's avatar
Maxime Perrotin committed
185
                                 lambda self, val: self.set_valid_pos(val))
Maxime Perrotin's avatar
Maxime Perrotin committed
186

187
    pos_x = Property(float, lambda self: self.x(),
Maxime Perrotin's avatar
Maxime Perrotin committed
188
189
                            lambda self, val:
                                    self.set_valid_pos(QPointF(val, self.y())))
190
191

    pos_y = Property(float, lambda self: self.y(),
Maxime Perrotin's avatar
Maxime Perrotin committed
192
193
                            lambda self, val:
                                    self.set_valid_pos(QPointF(self.x(), val)))
Maxime Perrotin's avatar
Maxime Perrotin committed
194

Maxime Perrotin's avatar
Maxime Perrotin committed
195
196
197
    def is_composite(self):
        ''' Return True if nested scene has something in it '''
        try:
Maxime Perrotin's avatar
Maxime Perrotin committed
198
            return any(self._nested_scene.visible_symb)
Maxime Perrotin's avatar
Maxime Perrotin committed
199
200
201
        except AttributeError:
            return False

Maxime Perrotin's avatar
Maxime Perrotin committed
202
203
204
    def boundingRect(self):
        return QRectF(0, 0, self.width, self.height)

Maxime Perrotin's avatar
Maxime Perrotin committed
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    @property
    def allowed_followers(self):
        '''
            Compute dynamically the list of connectable symbols based on
            the list of current connections and authorized children
        '''
        followers = list(self._insertable_followers)
        for item_type in self._unique_followers:
            # Unique followers: can only be one of this type (e.g. comment)
            if not [child for child in self.childSymbols()
                    if isinstance(child, eval(item_type))]:
                followers.append(item_type)
        if not self.next_aligned_symbol():
            followers.extend(self._terminal_followers)
        return followers

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
    @property
    def allow_nesting(self):
        ''' Dynamically check if the scene can have a nested subscene
            May be redefined in subclasses and checked on double-click
        '''
        return self._allow_nesting

    @property
    def nested_scene(self):
        ''' Return the nested scene. Can be redefined '''
        return self._nested_scene

    @nested_scene.setter
    def nested_scene(self, value):
        ''' Set the value of the nested scene '''
        self._nested_scene = value

238
239
240
241
242
243
244
245
246
247
248
249
250
251
    # Connection zones (for start and end of connection) are lists of QRect
    # that define areas for the mouse to grab the symbol and start a connection
    # These zones depend on the shape of the symbol and must be defined in
    # sub-classes. By default there are none. Example in SDL symbol "Process".
    # Zones are defined as properties because they must be dynamically
    # computed, e.g. based on the current size of the symbol.
    @property
    def conn_start_zones(self):
        return []

    @property
    def conn_end_zones(self):
        return []

Maxime Perrotin's avatar
Maxime Perrotin committed
252
    def in_start_zone(self, point: QPoint) -> bool:
253
254
255
        ''' Return true if "point" is in one of the connection start zones '''
        return any(rect.contains(point) for rect in self.conn_start_zones)

Maxime Perrotin's avatar
Maxime Perrotin committed
256
    def in_end_zone(self, point: QPoint) -> bool:
257
258
259
        ''' Return true if "point" is in one of the connection end zones '''
        return any(rect.contains(point) for rect in self.conn_end_zones)

Maxime Perrotin's avatar
Maxime Perrotin committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
    def closest_connection_point(self, coord):
        '''
           Given a position (QPointF), expected in this symbol's
           coordinates, return the closest connection
           point on the current symbol.
           By default, return the RELATIVE POSITION of a point on the
           bounding rectangle.
        '''
        width = self.boundingRect().width()
        height = self.boundingRect().height()
        top, bottom = self.y(), self.y() + height
        left, right = self.x(), self.x() + width
        x, y = left + coord.x(), top + coord.y()
        if (x > right or x < left) and (y < top or y > bottom):
            # Coord is completely outside the rectangle area
            # in that case, return one of the angles of the bounding rect
            nearest_x = (coord.x() - width if x > right else coord.x())
            nearest_y = (coord.y() if y < top else coord.y() - height)
        elif x >= left and x <= right:
            # x is within the rectangle
            nearest_x = 0
            nearest_y = (coord.y() if abs(y - top) < abs(y - bottom)
                                   else coord.y() - height)
        elif y >= top and y <= bottom:
            # y is within the rectangle (lower priority than x)
            nearest_x = (coord.x() if abs(x - left) < abs(x - right)
                                   else coord.x() - width)
            nearest_y = 0
        return nearest_x, nearest_y

    @property
    def terminal_symbol(self):
        ''' Way to determine if a symbol is terminal (useful for branches) '''
        return self._terminal_symbol

    @terminal_symbol.setter
    def terminal_symbol(self, value):
        ''' Attribute is set per symbol '''
        self._terminal_symbol = value

    def __str__(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
301
        ''' Return the text inside the symbol '''
Maxime Perrotin's avatar
Maxime Perrotin committed
302
        return str(self.text) or u'no_name'
Maxime Perrotin's avatar
Maxime Perrotin committed
303

Maxime Perrotin's avatar
Maxime Perrotin committed
304
    def get_ast(self, pr_text):
Maxime Perrotin's avatar
Maxime Perrotin committed
305
        ''' Return the symbol in the AST form, as returned by the parser '''
Maxime Perrotin's avatar
Maxime Perrotin committed
306
307
        ast, _, _, _, terminators = \
                self.parser.parseSingleElement(self.common_name, pr_text)
Maxime Perrotin's avatar
Maxime Perrotin committed
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
        return ast, terminators

    def edit_text(self, pos=None):
        '''
            Set the focus on the text area for edition. Position is optional
            Can be called when user double clicks on an item
            Position is in scene coordinates
        '''
        _ = pos
        try:
            # Only one text area is supported for now - ignoring position
            self.text.setFocus()
        except AttributeError:
            return

Maxime Perrotin's avatar
Maxime Perrotin committed
323
    def update_completion_list(self, **kwargs):
Maxime Perrotin's avatar
Maxime Perrotin committed
324
325
326
327
328
329
330
        '''
            Update the text autocompletion list based on the symbol text
            This function is typically called when user has typed new text
            and it must be redefined per symbol
        '''
        pass

Maxime Perrotin's avatar
Maxime Perrotin committed
331
    def check_syntax(self, text, check_last_semi=True):
Maxime Perrotin's avatar
Maxime Perrotin committed
332
        ''' Check the syntax of the text inside the symbol (if any) '''
Maxime Perrotin's avatar
Maxime Perrotin committed
333
334
335
336
337
338
        # if check_last_semi=True, will raise an error if the text ends
        # with a semicolon (inserted by the user). This is the case for 
        # all symbols except the text boxes. A semi colon there would
        # prevent a COMMENT, and would only be deteted when parsing the
        # full model - without precise identication of the location.
        # By doing it here we can spot the issue immediately
Maxime Perrotin's avatar
Maxime Perrotin committed
339
        try:
Maxime Perrotin's avatar
Maxime Perrotin committed
340
341
            _, syntax_errors, _, _, _ = self.parser.parseSingleElement(
                                           self.common_name, text)
Maxime Perrotin's avatar
Maxime Perrotin committed
342
343
344
        except (AssertionError, AttributeError) as err:
            LOG.debug(self.common_name + " - error parsing - " + str(err))
            LOG.debug(str(traceback.format_exc()))
Maxime Perrotin's avatar
Maxime Perrotin committed
345
346
            LOG.error('Checker failed - no parser for this construct?')
        else:
Maxime Perrotin's avatar
Maxime Perrotin committed
347
            if check_last_semi and str(self).strip():
Maxime Perrotin's avatar
Maxime Perrotin committed
348
349
350
                if str(self).strip()[-1] == ';':
                    syntax_errors.append("Remove the semi-colon at the end"
                            " of the text.")
Maxime Perrotin's avatar
Maxime Perrotin committed
351
            return syntax_errors
Maxime Perrotin's avatar
Maxime Perrotin committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390

    def paint(self, painter, _, ___):
        ''' Apply anti-aliasing or not (symbol attribute) '''
        painter.setRenderHint(QPainter.Antialiasing, self._antialiasing)
        super(Symbol, self).paint(painter, _, ___)

    def update_position(self):
        ''' VIRTUAL - implemented in subclasses '''
        pass

    def select(self, selected=True):
        ''' When item is selected, effectively select its grabber '''
        self.grabber.setSelected(selected)

    def insert_symbol(self, parent, x, y):
        '''
            Set attributes related to the parent item when inserting the symbol
            in the scene. This method is redefined in subclasses
        '''
        if parent:
            self.hasParent = True
            self.parent = parent
            self.setParentItem(parent)

    def delete_symbol(self):
        '''
            Remove the symbol: pass ownership from parent to caller
            (undo command)
        '''
        entrypoint_parent = None
        if self.branch_entrypoint:
            # If the item is the last in a branch, make clean connections
            bep = self.branch_entrypoint
            entrypoint_parent = bep.parentItem()
            if bep.last_branch_item is self:
                # Last item of a branch, remove or reconnect the link
                # to the connection point
                for child in self.childItems():
                    # Find the connection point below
Maxime Perrotin's avatar
Maxime Perrotin committed
391
                    if isinstance(child, JoinConnection):
Maxime Perrotin's avatar
Maxime Perrotin committed
392
393
394
395
396
397
                        connection_below = child
                        break
                if bep is not self:
                    # Item is not the branch entry point itself
                    bep.last_branch_item = self.parentItem()
                    connection_below.setParentItem(self.parentItem())
Maxime Perrotin's avatar
Maxime Perrotin committed
398
                    #self.parentItem().connectionBelow = connection_below
Maxime Perrotin's avatar
Maxime Perrotin committed
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
                else:
                    # delete the link to the connection point
                    connection_below.setParentItem(None)
                    self.scene().removeItem(connection_below)
        child_below = self.next_aligned_symbol()
        if(child_below and self.hasParent and
                self.parentItem().next_aligned_symbol() is self):
            # Delete the connection to the child below if
            # it is not a full branch to be deleted
            child_below.connection.setParentItem(None)
            self.scene().removeItem(child_below.connection)
        if self.hasParent:
            if (not child_below or not self.parentItem().next_aligned_symbol()
                    or self.branch_entrypoint is self):
                # If nothing below or item is branch entry point,
                # remove the connection with the parent
                self.connection.setParentItem(None)
                self.scene().removeItem(self.connection)
            else:
                # Otherwise connect the item below with the parent
                child_below.connection = self.connection
                self.connection.child = child_below
                child_below.parent = self.parentItem()
                child_below.setParentItem(child_below.parent)
                # Update position of child - take place of deleted item
424
                child_below.pos_y = self.pos_y
Maxime Perrotin's avatar
Maxime Perrotin committed
425
                child_below.update_position()
Maxime Perrotin's avatar
Maxime Perrotin committed
426
427
            self.parentItem().cam(self.parentItem().position,
                                  self.parentItem().position)
Maxime Perrotin's avatar
Maxime Perrotin committed
428
            self.setParentItem(None)
Maxime Perrotin's avatar
Maxime Perrotin committed
429
        # Following line causes segfault on exit:
Maxime Perrotin's avatar
Maxime Perrotin committed
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
        #scene().removeItem(self)
        try:
            entrypoint_parent.updateConnectionPointPosition()
            entrypoint_parent.updateConnectionPoints()
        except AttributeError:
            pass

    def connect_to_parent(self):
        ''' Add a connection (wire) with the parent item '''
        return Connection(self.parent, self)

    def connection_to_parent(self):
        ''' Return the connection above the symbol '''
        try:
            connection, = [cnx for cnx in self.parent.connections()
Maxime Perrotin's avatar
Maxime Perrotin committed
445
                           if cnx.child == self]
Maxime Perrotin's avatar
Maxime Perrotin committed
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
            return connection
        except ValueError:
            return None

    def next_aligned_symbol(self):
        ''' Return the next symbol in the flow - implemented in subclasses '''
        return None

    def connections(self):
        ''' Return all child connections of this symbol '''
        return (c for c in self.childItems() if isinstance(c, Connection))

    def loadHyperlinkDialog(self):
        ''' Load dialog from ui file for defining hyperlink '''
        loader = QUiLoader()
461
        ui_file = QFile(':/hyperlink.ui')
Maxime Perrotin's avatar
Maxime Perrotin committed
462
463
464
465
466
467
468
469
470
471
472
473
474
        ui_file.open(QFile.ReadOnly)
        self.hyperlink_dialog = loader.load(ui_file)
        ui_file.close()
        self.hyperlink_dialog.accepted.connect(self.hyperlinkChanged)
        self.hlink_field = self.hyperlink_dialog.findChild(QLineEdit, 'hlink')

    def hyperlinkChanged(self):
        ''' Update hyperlink field '''
        if not self.text:
            return
        hlink = self.hlink_field.text()
        if hlink:
            self.text.setHtml('<a href="{hlink}">{text}</a>'.format
Maxime Perrotin's avatar
Maxime Perrotin committed
475
                  (hlink=hlink, text=str(self.text).replace('\n', '<br>')))
Maxime Perrotin's avatar
Maxime Perrotin committed
476
477
478
            self.text.hyperlink = hlink
        else:
            self.text.hyperlink = None
Maxime Perrotin's avatar
Maxime Perrotin committed
479
            self.text.setPlainText(str(self.text))
Maxime Perrotin's avatar
Maxime Perrotin committed
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514

    def contextMenuEvent(self, event):
        ''' When user right-clicks: display context menu '''
        png_action = 'Export branch to PNG, SVG or PDF'
        hl_action = 'Hyperlink'
        my_menu = QMenu(png_action)
        if not hasattr(self, '_no_hyperlink'):
            my_menu.addAction(hl_action)
        my_menu.addAction(png_action)
        action = my_menu.exec_(event.screenPos())
        if action:
            if action.text() == png_action:
                # Save a picture of the selected symbol and all its children
                filename = QFileDialog.getSaveFileName(self.window(),
                        'Export picture', '.',
                        'Picture (*.png, *.svg, *.pdf)')[0]
                if not filename:
                    return
                save_fmt = filename.split(os.extsep)[-1]
                if save_fmt not in ('png', 'svg', 'pdf'):
                    return
                self.scene().export_branch_to_picture(self, filename, save_fmt)
            elif action.text() == hl_action:
                if self.text:
                    self.hyperlink_dialog.setParent(
                            self.scene().views()[0], Qt.Dialog)
                    self.hlink_field.setText(self.text.hyperlink)
                    self.hyperlink_dialog.show()

    def childSymbols(self):
        ''' Return the list of child symbols, excluding text/connections '''
        return (item for item in self.childItems() if isinstance(item, Symbol))

    def resize_item(self, rect):
        ''' resize item, e.g. when editing text - move children accordingly '''
Maxime Perrotin's avatar
Maxime Perrotin committed
515
516
517
518
        # Call stack:
        # scene_refresh() => Text_Interaction.try_resize() => resize_item()
        LOG.debug("resize item")
        #LOG.debug(traceback.print_stack())
Maxime Perrotin's avatar
Maxime Perrotin committed
519
520
        if not self.resizeable:
            return
Maxime Perrotin's avatar
Maxime Perrotin committed
521
522
        delta_x = (self.boundingRect().width() - rect.width()) / 2.0
        delta_y = self.boundingRect().height() - rect.height()
Maxime Perrotin's avatar
Maxime Perrotin committed
523
        self.set_shape(rect.width(), rect.height())
Maxime Perrotin's avatar
Maxime Perrotin committed
524
525
526
        # Align children properly when resizing
        try:
            self.text.set_textbox_position()
Maxime Perrotin's avatar
Maxime Perrotin committed
527
        except AttributeError:
Maxime Perrotin's avatar
Maxime Perrotin committed
528
529
530
            # if called before text is initialized - or if no textbox
            pass
        for child in self.childSymbols():
531
532
            child.pos_x -= delta_x
            child.pos_y -= delta_y
533
        # X-pos must be updated when resizing
Maxime Perrotin's avatar
Maxime Perrotin committed
534
        self.pos_x += delta_x
Maxime Perrotin's avatar
Maxime Perrotin committed
535
        if self.comment:
536
537
            self.comment.pos_x -= delta_x
            self.comment.pos_y += delta_y / 2.0
Maxime Perrotin's avatar
Maxime Perrotin committed
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
        self.update_connections()

    def update_connections(self):
        '''
           When symbol moves or is resized, update the shape of all
           its connections - can be redefined in subclasses
        '''
        for cnx in self.connections():
            cnx.reshape()
        try:
            self.connection_to_parent().reshape()
        except AttributeError:
            pass
        try:
            self.branch_entrypoint.parent.update_connections()
        except AttributeError:
            pass

    def set_shape(self, width, height):
        ''' to be implemented per symbol in subclasses '''
Maxime Perrotin's avatar
Maxime Perrotin committed
558
        #LOG.debug("generic set_shape")
Maxime Perrotin's avatar
Maxime Perrotin committed
559
560
561
        #rect = self.boundingRect()
        #self.width, self.height = rect.width(), rect.height()
        self.width, self.height = width, height
Maxime Perrotin's avatar
Maxime Perrotin committed
562
        _, _ = width, height
Maxime Perrotin's avatar
Maxime Perrotin committed
563
564
565
566
567
568
569
570
571
572
573
574
575
        self.prepareGeometryChange()
        self.updateConnectionPoints()
        # Update grabber size to fit the new shape size
        self.grabber.display()
        if self.hasParent:
            self.update_position()

    def mouse_click(self, _):
        '''
            Handle resizing and moving of items when grabbing
            the lower right corner
        '''
        # Save current position to be able to revert move
Maxime Perrotin's avatar
Maxime Perrotin committed
576
        self.coord = self.position
Maxime Perrotin's avatar
Maxime Perrotin committed
577
578
579
580
581
582
583
584
        rect = self.boundingRect()
        self.height = rect.height()
        if self.grabber.resize_mode != '':
            self.mode = 'Resize'
            self.old_rect = self.boundingRect()
        else:
            self.mode = 'Move'

Maxime Perrotin's avatar
Maxime Perrotin committed
585
586
587
588
    def double_click(self):
        ''' Handle double click on symbol - redefined at symbol level '''
        pass

Maxime Perrotin's avatar
Maxime Perrotin committed
589
590
591
    def mouse_move(self, event):
        ''' Handle resizing of items - moving is handled in subclass '''
        self.updateConnectionPoints()
592
        # If any, update movable end points of connections
Maxime Perrotin's avatar
Maxime Perrotin committed
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
        for point in self.movable_points:
            point.edge.end_connection.update_position()
        if self.mode == 'Resize':
            # Define the resizing based on where item has been grabbed
            if self.grabber.resize_mode.endswith('right'):
                user_width = user_width = event.pos().x()
            elif self.grabber.resize_mode.endswith('left'):
                user_width = self.boundingRect().width() - event.pos().x()
            else:
                user_width = self.boundingRect().width()
            if self.grabber.resize_mode.startswith('bottom'):
                user_height = event.pos().y()
            else:
                user_height = self.boundingRect().height()
            # Minimum size is the size of the text inside the symbol
            try:
                height = max(user_height,
Maxime Perrotin's avatar
Maxime Perrotin committed
610
                             self.text.boundingRect().height())
Maxime Perrotin's avatar
Maxime Perrotin committed
611
                width = max(user_width,
Maxime Perrotin's avatar
Maxime Perrotin committed
612
                            self.text.boundingRect().width() + 15)
Maxime Perrotin's avatar
Maxime Perrotin committed
613
614
615
616
617
618
619
620
621
622
623
624
625
            except AttributeError:
                height = max(user_height, 15)
                width = max(user_width, 30)
            self.resize_item(QRect(0, 0, width, height))

    def mouse_release(self, _):
        ''' Default action when mouse is released: reset mode '''
        if self.mode == 'Resize' and self.old_rect != self.boundingRect():
            with undoCommands.UndoMacro(self.scene().undo_stack, 'Resize'):
                undo_cmd = undoCommands.ResizeSymbol(
                                           self, self.old_rect,
                                           self.boundingRect())
                self.scene().undo_stack.push(undo_cmd)
Maxime Perrotin's avatar
Maxime Perrotin committed
626
                self.cam(self.coord, self.position)
Maxime Perrotin's avatar
Maxime Perrotin committed
627
                self.updateConnectionPoints()
Maxime Perrotin's avatar
Maxime Perrotin committed
628
        elif self.mode == 'Move' and self.coord != self.position:
Maxime Perrotin's avatar
Maxime Perrotin committed
629
630
            with undoCommands.UndoMacro(self.scene().undo_stack, 'Move'):
                undo_cmd = undoCommands.MoveSymbol(
Maxime Perrotin's avatar
Maxime Perrotin committed
631
                                            self, self.coord, self.position)
Maxime Perrotin's avatar
Maxime Perrotin committed
632
                self.scene().undo_stack.push(undo_cmd)
Maxime Perrotin's avatar
Maxime Perrotin committed
633
                self.cam(self.coord, self.position)
634
635
636
637
                # Emit signal to indicate that the symbol moved
                # typically caught by connectors
                self.moved.emit(self.coord.x() - self.pos_x,
                                self.coord.y() - self.pos_y)
Maxime Perrotin's avatar
Maxime Perrotin committed
638
639
640
641
642
643
644
645
646
647
648
649
        self.mode = ''

    def updateConnectionPoints(self):
        ''' Recursively update connection points (decision branch lengths) '''
        if(self.branch_entrypoint and self.branch_entrypoint.hasParent):
            self.branch_entrypoint.parentItem().updateConnectionPointPosition()
            self.branch_entrypoint.parentItem().updateConnectionPoints()

    def updateConnectionPointPosition(self):
        ''' Implemented in the relevant subclass '''
        pass

650
651
652
653
654
655
656
657
658
659
660
661
662
    def top_level(self):
        ''' If the item is in a branch, return the highest level in the branch,
            e.g. the starting state. '''
        top_level = self
        while top_level.hasParent:
            # The "or top_level.parent" below is due to a Pyside/Qt bug
            # of the parentItem() function. It can happen that even when
            # the parent has explicitely been set with "setParentItem",
            # a subsequent call to parentItem returns None. Seems to happen
            # if the parent has not been added yet to the scene.
            top_level = top_level.parentItem() or top_level.parent
        return top_level

Maxime Perrotin's avatar
Maxime Perrotin committed
663
664
665
    # pylint: disable=R0914
    def cam(self, old_pos, new_pos, ignore=None):
        ''' Collision Avoidance Manoeuvre for top level symbols '''
666
667
        # Since the cam function is recursive it may be time consuming
        # Call the Qt event prcessing to avoid blocking the application
668
669
        # Removed (had bad visual side effects)
        # QApplication.processEvents()
Maxime Perrotin's avatar
Maxime Perrotin committed
670
        #print 'CAM', str(self)[slice(0, 20)]
671
        ignore = ignore or []
Maxime Perrotin's avatar
Maxime Perrotin committed
672
673
674
675
676
        if not self.scene():
            # Make sure the item is in a scene. For instance, when loading
            # a model from a file, some items may be connected together
            # and CAM called *before* the top-level item has been inserted.
            return
677
678
679

        top_level = self.top_level()
        if top_level != self:
Maxime Perrotin's avatar
Maxime Perrotin committed
680
            # Exectute CAM on top level of this item
Maxime Perrotin's avatar
Maxime Perrotin committed
681
            top_level.cam(top_level.position, top_level.position)
Maxime Perrotin's avatar
Maxime Perrotin committed
682
683
684
685
686
687
688
689
690
691
692
            return

        # In case CAM is called due to object move, go to the new position
        delta = new_pos - old_pos

        # Rectangle of current group of item in scene coordinates
        rect = (self.sceneBoundingRect() |
                self.mapRectToScene(self.childrenBoundingRect()))

        # Move the rectangle to the new position, and move the current item
        animation = False
693
        if self.position != new_pos:
Maxime Perrotin's avatar
Maxime Perrotin committed
694
695
696
697
698
            animation = True
            rect.adjust(delta.x(), delta.y(), delta.x(), delta.y())
            undo_cmd = undoCommands.MoveSymbol(
                    self, old_pos, new_pos, animate=animation)
            self.scene().undo_stack.push(undo_cmd)
699
            self.position = new_pos
Maxime Perrotin's avatar
Maxime Perrotin committed
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717

        # Get all items in the rectangle when placed at the new position
        items = self.scene().items(rect)

        # Filters: we keep only items that collide with the group
        # at the new position

        # (a) Filter out items from the current group
        items = [i for i in items
                if (not self.isAncestorOf(i) and i is not self)
                and isinstance(i, Symbol)]

        # (b) Filter out items that are in the rectangle but that do not
        #     actually collide with the current group
        items = [i for i in items if [j for j in i.collidingItems() if
            self.isAncestorOf(j) or j is self]]

        # (c) Filter out the potentially colliding items
718
719
720
        #     if they belong in the cam caller and keep only top-level items
        items = {i.top_level() for i in items if not
                any(c for c in ignore if i.commonAncestorItem(c))}
Maxime Perrotin's avatar
Maxime Perrotin committed
721
722
723
724

        # Determine how much we need to move the colliding groups and call
        # their CAM with this delta
        # Save colliders positions in case they are moved by a sub cam call
725
726
        col_pos = {i: i.position for i in items}
        for col in items:
Maxime Perrotin's avatar
Maxime Perrotin committed
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
            collider_rect = (col.sceneBoundingRect() |
                    col.mapRectToScene(col.childrenBoundingRect()))
            if old_pos.y() + rect.height() <= collider_rect.y():
                # Collision from the top: move down the collider
                delta.setX(col.x())
                delta.setY(rect.y() + rect.height() + 10)
            elif old_pos.y() >= collider_rect.y() + collider_rect.height():
                # Collision from below: move up the collider
                delta.setX(col.x())
                delta.setY(rect.y() - collider_rect.height() - 10)
            elif old_pos.x() <= col.x():
                # Collision from the left: move right
                delta.setX(rect.x() + rect.width() + 10 +
                        col.x() - collider_rect.x())
                delta.setY(col.y())
            else:
                delta.setX(col.x() - collider_rect.x() -
                        collider_rect.width() - 10 + rect.x())
                delta.setY(col.y())
Maxime Perrotin's avatar
Maxime Perrotin committed
746
            if col.position == col_pos[col]:
Maxime Perrotin's avatar
Maxime Perrotin committed
747
                #print str(self), 'collides with', str(col)
748
                col.cam(col.position, delta, ignore=ignore + [self])
Maxime Perrotin's avatar
Maxime Perrotin committed
749
750
751
                # Put it back at the new position to make sure recursive
                # CAM can happen properly with all object in new positions
                # (End of CAM reset to the old position for animation)
752
                col.position = delta
Maxime Perrotin's avatar
Maxime Perrotin committed
753
        # Place top level colliders in old position so that animation can run
754
        for col in items:
755
            col.position = col_pos[col]
Maxime Perrotin's avatar
Maxime Perrotin committed
756
757
758
759
760
        self.update_connections()
        if animation:
            # If animation is planned, it will trigger only when Qt
            # control loop runs again. Going back to original position
            # so that the animation can be done from the starting point
761
            self.position = old_pos
762
        #print 'returning from cam'
Maxime Perrotin's avatar
Maxime Perrotin committed
763
764


Maxime Perrotin's avatar
Maxime Perrotin committed
765
class Comment(Symbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
766
767
768
769
770
771
    '''
        Class used to handle right connected comments
    '''
    # Define reserved keywords for the syntax highlighter
    blackbold = ('TODO', 'FIXME', 'XXX')
    redbold = ()
772
    textbox_alignment = Qt.AlignLeft | Qt.AlignVCenter
Maxime Perrotin's avatar
Maxime Perrotin committed
773
774
775

    def __init__(self, parent=None, ast=None):
        ast = ast or ogAST.Comment()
776
        self.ast = ast
Maxime Perrotin's avatar
Maxime Perrotin committed
777
778
779
        super(Comment, self).__init__(parent)
        self.connection = None
        self.set_shape(ast.width, ast.height)
Maxime Perrotin's avatar
Maxime Perrotin committed
780
781
782
        self.text = EditableText(parent=self,
                                 text=ast.inputString,
                                 hyperlink=ast.hyperlink)
783
784
785
        if parent:
            local_pos = parent.mapFromScene(ast.pos_x or 0, ast.pos_y or 0)
            self.insert_symbol(parent, local_pos.x(), local_pos.y())
Maxime Perrotin's avatar
Maxime Perrotin committed
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
        self.common_name = 'end'
        self.parser = ogParser

    def __str__(self):
        return 'Comment'

    @property
    def on_the_right(self):
        ''' Determine if the comment symbol needs to be flipped '''
        return self.x() > self.parent.boundingRect().width() + 5

    def insert_symbol(self, parent, x, y):
        ''' Align the symbol on the right of the parent '''
        if not parent:
            return
        parent.comment = self
        super(Comment, self).insert_symbol(parent, x, y)
803
804
805
        self.pos_x = x if x is not None else parent.boundingRect().width() + 20
        self.pos_y = y if y is not None else (parent.boundingRect().height() -
                                              self.boundingRect().height()) / 2
Maxime Perrotin's avatar
Maxime Perrotin committed
806
        self.connection = self.connect_to_parent()
Maxime Perrotin's avatar
Maxime Perrotin committed
807
808
809
810
811
        try:
            self.text.set_textbox_position()
        except AttributeError:
            # if called before text is initialized
            pass
812
        #parent.cam(parent.position, parent.position)
Maxime Perrotin's avatar
Maxime Perrotin committed
813

Maxime Perrotin's avatar
Maxime Perrotin committed
814
815
816
817
    def connect_to_parent(self):
        ''' Redefinition of the function to use a comment connector '''
        return CommentConnection(self.parent, self)

Maxime Perrotin's avatar
Maxime Perrotin committed
818
819
820
821
822
823
824
825
826
827
828
829
830
    def delete_symbol(self):
        '''
            Specific delete actions for Comment:
            reset comment field in parent
        '''
        self.parentItem().comment = None
        super(Comment, self).delete_symbol()

    def resize_item(self, rect):
        '''
            Redefinition of the Resize function
            (Comment symbol only resizes in one direction)
        '''
Maxime Perrotin's avatar
Maxime Perrotin committed
831
        if not self.resizeable or self.grabber.resize_mode.endswith('left'):
Maxime Perrotin's avatar
Maxime Perrotin committed
832
833
834
835
            return
        self.set_shape(rect.width(), rect.height())
        self.update_connections()

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
864
    def set_shape(self, width, height):
        ''' Set a box - actual shape is computed in the paint function '''
        path = QPainterPath()
        path.addRect(0, 0, width, height)
        self.setPath(path)
        super(Comment, self).set_shape(width, height)

    def paint(self, painter, _, ___):
        ''' Draw the comment symbol '''
        rect = self.boundingRect()
        pen = QPen()
        pen.setStyle(Qt.DashLine)
        pen.setColor(Qt.darkGray)
        painter.setPen(pen)
        x, y, w, h = rect.x(), rect.y(), rect.width(), rect.height()
        if self.on_the_right:
            painter.drawLines([QPoint(w, y), QPoint(x, y),
                               QPoint(x, y), QPoint(x, h),
                               QPoint(x, h), QPoint(w, h)])
        else:
            painter.drawLines([QPoint(x, y), QPoint(w, y),
                               QPoint(w, y), QPoint(w, h),
                               QPoint(w, h), QPoint(x, h)])

    def mouse_move(self, event):
        ''' Handle item move '''
        super(Comment, self).mouse_move(event)
        if self.mode == 'Move':
Maxime Perrotin's avatar
Maxime Perrotin committed
865
866
            self.pos_y += event.pos().y() - event.lastPos().y()
            self.pos_x += event.pos().x() - event.lastPos().x()
Maxime Perrotin's avatar
Maxime Perrotin committed
867
868
869
870
871
872
873
874
875
876
877
878
            self.update_connections()

    def mouse_release(self, event):
        '''
            Check if the new position is valid (no collision)
            undo otherwise
        '''
        move_accepted = True
        for item in self.collidingItems():
            if isinstance(item, Symbol):
                move_accepted = False
        if not move_accepted:
879
            self.position = self.coord
Maxime Perrotin's avatar
Maxime Perrotin committed
880
881
882
883
884
885
886
887
888
889
890
            self.update_connections()
        return super(Comment, self).mouse_release(event)

    def updateConnectionPoints(self):
        '''
            Disable the update of connection points
            (comments do not influence them)
        '''
        pass


Maxime Perrotin's avatar
Maxime Perrotin committed
891
class Cornergrabber(QGraphicsPolygonItem):
Maxime Perrotin's avatar
Maxime Perrotin committed
892
893
894
895
896
897
898
899
900
    '''
        Corner grabber is used to resize an item, whatever its shape.
        Such an item is needed because when symbols have a non-rectangular
        shape, the selection area being limited to the item actual borders,
        there is no possibility to grab all items. The cornergrabber is
        a rectangle that covers the full parent bounding rect, allowing
        to resize it from any border/corner.
    '''
    hasParent = False
Maxime Perrotin's avatar
Maxime Perrotin committed
901

Maxime Perrotin's avatar
Maxime Perrotin committed
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
    def __init__(self, parent):
        ''' Create the grabber '''
        super(Cornergrabber, self).__init__(parent)
        self.setParentItem(parent)
        self.parent = parent
        self.setFlags(QGraphicsItem.ItemIsSelectable |
                QGraphicsItem.ItemIsMovable)
        self.setPos(0, 0)
        self.setPen(QColor(0, 0, 0, 0))
        # Accept hover events (when mouse passes over the item)
        self.setAcceptHoverEvents(True)
        self.show()
        # resize_mode indicates the direction when resizing
        self.resize_mode = ''

    def __repr__(self):
        ''' Pretty string for the print function '''
Maxime Perrotin's avatar
Maxime Perrotin committed
919
        return u'Cornergrabber of ' + str(self.parentItem())
Maxime Perrotin's avatar
Maxime Perrotin committed
920
921
922
923
924
925

    def display(self):
        ''' Polygon is a rectangle of the size of the parent item '''
        self.prepareGeometryChange()
        rect = self.parent.boundingRect()
        self.setPos(0, 0)
926
        self.setPolygon(QPolygonF(rect))
Maxime Perrotin's avatar
Maxime Perrotin committed
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
        self.show()

    def mousePressEvent(self, event):
        ''' Handle Qt event '''
        self.parent.mouse_click(event)
        super(Cornergrabber, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        ''' Handle Qt event '''
        self.parent.mouse_move(event)

    def mouseReleaseEvent(self, event):
        ''' Handle Qt event '''
        self.parent.mouse_release(event)

    def hoverMoveEvent(self, event):
        ''' When mouse moves inside the box, set the mouse cursor '''
        pos = event.pos()
        if self.parent.cursor().shape() != self.parent.default_cursor:
            # Parent item may have changed its cursor (e.g. when inserting
            # items). In that case, don't override the cursor for that area
            cursor = self.parent.cursor()
949
950
        elif self.parent.in_start_zone(event.pos().toPoint()):
            cursor = Qt.CrossCursor
Maxime Perrotin's avatar
Maxime Perrotin committed
951
952
953
        elif not self.parent.resizeable:
            cursor = self.parent.default_cursor
            self.resize_mode = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
        # Left side
        elif 0.0 <= pos.x() <= 10.0:
            # Top-left corner: disabled
            #if pos.y() <= 10.0:
            #    cursor = Qt.SizeFDiagCursor
            if pos.y() > self.boundingRect().height() - 10.0:
                cursor = Qt.SizeBDiagCursor
                self.resize_mode = 'bottom_left'
            else:
                cursor = Qt.SizeHorCursor
                self.resize_mode = 'left'
        # Middle of item
        elif 5.0 < pos.x() < self.boundingRect().width() - 10.0 and (
                     pos.y() > self.boundingRect().height() - 10.0):
            cursor = Qt.SizeVerCursor
            self.resize_mode = 'bottom'
        # Right side
        elif(self.boundingRect().width() - 5.0 <= pos.x()
                                <= self.boundingRect().width()):
            # Top-right corner: disabled
            #if pos.y() <= 10.0:
            #    cursor = Qt.SizeBDiagCursor
            if pos.y() > self.boundingRect().height() - 10.0:
                cursor = Qt.SizeFDiagCursor
                self.resize_mode = 'bottom_right'
            else:
                cursor = Qt.SizeHorCursor
                self.resize_mode = 'right'
        else:
            cursor = self.parent.default_cursor
            self.resize_mode = ''
        self.setCursor(cursor)


# pylint: disable=R0904
Maxime Perrotin's avatar
Maxime Perrotin committed
989
class HorizontalSymbol(Symbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
990
991
992
993
994
995
996
997
998
    '''
        Class used to handle horizontal symbols
        In case of SDL: INPUT, DECISION answers, Text Symbol, Start
    '''
    def __init__(self, parent=None, text='...',
            x=None, y=None, hyperlink=None):
        super(HorizontalSymbol, self).__init__(parent)
        self.minDistanceToSymbolAbove = 20
        self.connection = None
Maxime Perrotin's avatar
Maxime Perrotin committed
999
        if self.has_text_area:
Maxime Perrotin's avatar
Maxime Perrotin committed
1000
1001
1002
            self.text = EditableText(parent=self, text=text,
                    hyperlink=hyperlink)
        if parent:
Maxime Perrotin's avatar
Maxime Perrotin committed
1003
1004
1005
1006
1007
            if x and y:
                local_pos = parent.mapFromScene(x, y)
                self.insert_symbol(parent, local_pos.x(), local_pos.y())
            else:
                self.insert_symbol(parent, None, None)
Maxime Perrotin's avatar
Maxime Perrotin committed
1008
        else:
1009
            self.position = QPointF(x or 0, y or 0)
Maxime Perrotin's avatar
Maxime Perrotin committed
1010

Maxime Perrotin's avatar
Maxime Perrotin committed
1011
1012
1013
1014
    def connect_to_parent(self):
        ''' Redefined: connect to parent item '''
        return RakeConnection(self.parent, self)

Maxime Perrotin's avatar
Maxime Perrotin committed
1015
1016
1017
1018
1019
1020
1021
1022
1023
    def set_valid_pos(self, pos):
        ''' Redefined function - make sure symbol is below its parent '''
        if not self.hasParent:
            super(HorizontalSymbol, self).set_valid_pos(pos)
        else:
            new_y = max(pos.y(), self.parent.boundingRect().height() +
                        self.minDistanceToSymbolAbove)
            self.setPos(pos.x(), new_y)

Maxime Perrotin's avatar
Maxime Perrotin committed
1024
1025
1026
    def insert_symbol(self, parent, pos_x, pos_y):
        ''' Insert the symbol in the scene - Align below the parent '''
        if not parent:
1027
            self.position = QPointF(pos_x or 0, pos_y or 0)
Maxime Perrotin's avatar
Maxime Perrotin committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
            return
        super(HorizontalSymbol, self).insert_symbol(parent, pos_x, pos_y)
        if pos_x is None or pos_y is None:
            # Usually for first insertion when item is created:
            # compute position and (if relevant) move siblings
            first, last = None, None
            has_siblings = False
            for sibling in self.siblings():
                has_siblings = True
                first = min(first, sibling.x()) if(
                        first is not None) else sibling.x()
                last = max(last, sibling.x() +
                        sibling.boundingRect().width()) if(
                                last is not None) else(sibling.x() +
                                        sibling.boundingRect().width())
            group_width = last - first if first is not None else 0
            for sibling in self.siblings():
                sib_x = sibling.x() - (self.boundingRect().width()) / 2 - 10
Maxime Perrotin's avatar
Maxime Perrotin committed
1046
                sib_oldpos = sibling.position
1047
                sibling.pos_x = sib_x
Maxime Perrotin's avatar
Maxime Perrotin committed
1048
1049
1050
                undo_cmd = undoCommands.MoveSymbol(sibling,
                                                   sib_oldpos,
                                                   sibling.position)
Maxime Perrotin's avatar
Maxime Perrotin committed
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
                self.scene().undo_stack.push(undo_cmd)
            most_left = min([sibling.x()
                for sibling in self.siblings()] or [0])
            if has_siblings:
                pos_x = most_left + group_width + 20
            else:
                # Verical alignment (x-axis):
                pos_x = (parent.boundingRect().width() -
                        self.boundingRect().width()) / 2
            pos_y = (parent.boundingRect().height() +
                    self.minDistanceToSymbolAbove)
1062
        self.position = QPointF(pos_x, pos_y)
Maxime Perrotin's avatar
Maxime Perrotin committed
1063
1064
        self.connection = self.connect_to_parent()
        self.updateConnectionPoints()
1065
        #self.cam(self.position, self.position)
Maxime Perrotin's avatar
Maxime Perrotin committed
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083

    def update_connections(self):
        '''
           Redefined from Symbol class
           Horizontal symbols may have siblings - check their shape.
        '''
        super(HorizontalSymbol, self).update_connections()
        try:
            for sibling in self.siblings():
                for cnx in sibling.last_branch_item.connections():
                    cnx.reshape()
        except AttributeError:
            pass

    def siblings(self):
        ''' Return all the items's sibling symbols '''
        try:
            return (item for item in self.parent.childItems()
1084
1085
1086
1087
1088
                    if item is not self and isinstance(item, HorizontalSymbol))
            # Don't test only against the same type, that would exclude
            # e.g. Inputs next to Continuous signals
#                   if item is not self and (isinstance(self, type(item)) or
#                       isinstance(item, type(self))))
Maxime Perrotin's avatar
Maxime Perrotin committed
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
        except:
            return ()

    def next_aligned_symbol(self):
        ''' Return the next symbol in the flow '''
        for symbol in self.childSymbols():
            if not isinstance(symbol, (HorizontalSymbol, Comment)):
                return symbol
        return None

    def mouse_move(self, event):
1100
        ''' Will prevent move from being above the parent '''
Maxime Perrotin's avatar
Maxime Perrotin committed
1101
1102
        if self.mode == 'Move':
            event_pos = event.pos()
Maxime Perrotin's avatar
Maxime Perrotin committed
1103
1104
            new_y = self.pos_y + (event_pos.y() - event.lastPos().y())
            new_x = self.pos_x + (event_pos.x() - event.lastPos().x())
1105
            self.position = QPointF(new_x, new_y)
Maxime Perrotin's avatar
Maxime Perrotin committed
1106
1107
1108
1109
1110
1111
            self.update_connections()
        super(HorizontalSymbol, self).mouse_move(event)

    def cam(self, old_pos, new_pos, ignore=None):
        '''
            Collision avoidance manoeuvre for parallel branches
1112
            (for SDL: input, decision answers, continuous signals)
Maxime Perrotin's avatar
Maxime Perrotin committed
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
        '''
        if self.hasParent:
            # Rectangle of current group of item in scene coordinates
            try:
                # Disconnect the connection below the last item
                # (otherwise the rectangle will be too big)
                last_cnx, = (cnx for cnx in self.last_branch_item.connections()
                        if cnx.child == self.parentItem())
                last_cnx.setParentItem(None)
            except (AttributeError, ValueError):
                last_cnx = None

            rect = (self.sceneBoundingRect() |
                    self.mapRectToScene(self.childrenBoundingRect()))
            try:
                # Set back the last connection
                last_cnx.setParentItem(self.last_branch_item)
            except AttributeError:
                pass
            # Get all siblings (e.g. surrounding inputs/decision answers)
            for sibling in self.siblings():
                try:
                    # Disconnect the connection below the last item
                    last_cnx, = (cnx for cnx in
                            sibling.last_branch_item.connections()
                            if cnx.child == self.parentItem())
                    last_cnx.setParentItem(None)
                except (AttributeError, ValueError):
                    last_cnx = None
                sib_rect = (sibling.sceneBoundingRect() |
                        sibling.mapRectToScene(sibling.childrenBoundingRect()))
                try:
                    # Set back the last connection
                    last_cnx.setParentItem(sibling.last_branch_item)
                except AttributeError:
                    pass
                if rect.intersects(sib_rect):
                    width = (sib_rect & rect).width() + 10
Maxime Perrotin's avatar
Maxime Perrotin committed
1151
                    old_sib_pos = sibling.position
1152
1153
                    sibling.pos_x += width if self.pos_x <= sibling.pos_x \
                                           else -width
Maxime Perrotin's avatar
Maxime Perrotin committed
1154
1155
1156
                    undo_cmd = undoCommands.MoveSymbol(sibling,
                                                       old_sib_pos,
                                                       sibling.position)
Maxime Perrotin's avatar
Maxime Perrotin committed
1157
1158
1159
1160
1161
                    try:
                        self.scene().undo_stack.push(undo_cmd)
                    except AttributeError:
                        # If there is no scene or no undo stack
                        pass
Maxime Perrotin's avatar
Maxime Perrotin committed
1162
                    sibling.cam(sibling.position, sibling.position)
Maxime Perrotin's avatar
Maxime Perrotin committed
1163
1164
1165
        super(HorizontalSymbol, self).cam(old_pos, new_pos, ignore)
        # Recursively call the cam of the parent
        try:
Maxime Perrotin's avatar
Maxime Perrotin committed
1166
1167
            self.parentItem().cam(self.parentItem().position,
                                  self.parentItem().position)
Maxime Perrotin's avatar
Maxime Perrotin committed
1168
1169
1170
1171
1172
        except AttributeError:
            pass
        self.update_connections()


Maxime Perrotin's avatar
Maxime Perrotin committed
1173
class VerticalSymbol(Symbol):
Maxime Perrotin's avatar
Maxime Perrotin committed
1174
1175
1176
1177
1178
1179
1180
1181
    '''
        Class used to handle vertically-aligned symbols
        In case of SDL: STATE, OUTPUT, PROCEDURE, DECISION, TASK
    '''
    def __init__(self, parent=None, text='...',
            x=None, y=None, hyperlink=None):
        super(VerticalSymbol, self).__init__(parent)
        self.connection = None
Maxime Perrotin's avatar
Maxime Perrotin committed
1182
        if self.has_text_area:
1183
1184
1185
            self.text = EditableText(parent=self,
                                     text=text,
                                     hyperlink=hyperlink)
Maxime Perrotin's avatar
Maxime Perrotin committed
1186
1187
1188
1189
1190
        self.minDistanceToSymbolAbove = 15
        if parent:
            local_pos = self.mapFromScene(0, y or 0)
            self.insert_symbol(parent=parent, x=None, y=local_pos.y())
        else:
1191
            self.position = QPointF(x or 0, y or 0)
Maxime Perrotin's avatar
Maxime Perrotin committed
1192
1193
1194
1195
1196
1197
1198
1199

    def next_aligned_symbol(self):
        ''' Return the next symbol in the flow '''
        for symbol in self.childSymbols():
            if isinstance(symbol, VerticalSymbol):
                return symbol
        return None

Maxime Perrotin's avatar
Maxime Perrotin committed
1200
1201
1202
1203
    def connect_to_parent(self):
        ''' Redefined: connect to parent item with a straight line '''
        return VerticalConnection(self.parent, self)

1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
    def set_valid_pos(self, pos):
        ''' Redefined function - make sure symbol is well aligned '''
        if not self.hasParent:
            super(VerticalSymbol, self).set_valid_pos(pos)
        else:
            # 'or self.parent' because of pyside/qt bug
            parent = self.parentItem() or self.parent
            self.setX(-((self.boundingRect().width() -
                      parent.boundingRect().width()) / 2))
            # In case of collision with parent item, move down
            try:
                self.setY(max(pos.y(), parent.connectionPoint.y()))
            except AttributeError:
                self.setY(max(pos.y(), parent.boundingRect().height() + 15))

Maxime Perrotin's avatar
Maxime Perrotin committed
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
    def insert_symbol(self, parent, x, y):
        '''
            Vertical symbol: place the symbol in the scene.
            Determine the coordinates based on the position
            and size of the parent item, and make proper connections
        '''
        if not parent:
            # Place standalone item on the scene at given coordinates
            # (e.g. floating state)
            if x is not None and y is not None:
1229
                self.position = QPointF(x, y)
Maxime Perrotin's avatar
Maxime Perrotin committed
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
            return
        super(VerticalSymbol, self).insert_symbol(parent, x, y)
        # in a branch (e.g. DECISION) all items must know the first element
        # (used for computing the branch size and the connection point)
        self.branch_entrypoint = parent.branch_entrypoint
        # Check if parent has a connection point (e.g. DECISION)
        # i.e. Check if we are inserting below a decision group
        if hasattr(parent, 'connectionPoint'):
            # Move the new symbol below the connection point:
            # First, check if the parent was the last item of another branch
            for child in parent.childItems():
                if(child not in (self, parent.text, parent.grabber) and not
                        isinstance(child, HorizontalSymbol)):
                    # Insertion: change parent and position of previous child:
                    if (isinstance(child, Connection) and
                            isinstance(child.child, Comment) or
                            isinstance(child, Comment)):
                        continue
                    if not isinstance(child, Connection) or not isinstance(
                            child.child, HorizontalSymbol):
                        child.setParentItem(self)
                        child.parent = self
                        if isinstance(child, Symbol):
                            child_y_diff = (
                                    child.y() -
                                    self.parentItem().connectionPoint.y() +
                                    self.boundingRect().height() +
                                    self.minDistanceToSymbolAbove)
1258
                            child.pos_y = child_y_diff
Maxime Perrotin's avatar
Maxime Perrotin committed
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
                            if not isinstance(child, Comment):
                                child.update_position()
        else:
            # If parent already had children,
            # change their parent to the inserted symbol
            for child in parent.childItems():
                if child not in (
                            self, parent.text, parent.comment, parent.grabber):
                    if (isinstance(child, Connection) and
                            isinstance(child.child, Comment)):
                        # Don't change the parent of a comment
                        continue
                    child.parent = self
                    child.setParentItem(self)
                    # move child position down when inserting
                    if isinstance(child, Symbol):
1275
                        child.pos_y = 0.0
Maxime Perrotin's avatar
Maxime Perrotin committed
1276
1277
1278
1279
1280
1281
1282
1283
1284
                        child.update_position()

        # If inserting an symbol at the end of a branch (e.g. DECISION),
        # inform the branch entry point
        if self.branch_entrypoint and not self.next_aligned_symbol():
            self.branch_entrypoint.last_branch_item = self

        # Create the connection with the parent symbol
        self.connection = self.connect_to_parent()
Maxime Perrotin's avatar
Maxime Perrotin committed
1285
        #self.update_position()
Maxime Perrotin's avatar
Maxime Perrotin committed
1286
1287
        self.updateConnectionPoints()
        if y is not None:
1288
            self.pos_y = y
Maxime Perrotin's avatar
Maxime Perrotin committed
1289
1290
1291
1292
1293
1294
1295
        if parent and y is None:
            self.pos_y = self.parent.boundingRect().height() + 20
        try:
            self.text.set_textbox_position()
        except AttributeError:
            # if called before text is initialized - or if no textbox
            pass
Maxime Perrotin's avatar
Maxime Perrotin committed
1296
1297
1298
1299
1300

    def mouse_move(self, event):
        ''' Click and move: forbid symbol to move on the x axis '''
        super(VerticalSymbol, self).mouse_move(event)
        if self.mode == 'Move':
1301
1302
1303
            new_y = self.pos_y + event.pos().y() - event.lastPos().y()
            new_x = self.pos_x + event.pos().x() - event.lastPos().x()
            self.position = QPointF(new_x, new_y)
Maxime Perrotin's avatar
Maxime Perrotin committed
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
            self.update_connections()
            self.updateConnectionPoints()

    def cam(self, old_pos, new_pos, ignore=None):
        ''' Collision avoidance manoeuvre for vertical symbols '''
        if self.hasParent:
            branch_entry = self
            while branch_entry.hasParent and isinstance(
                    branch_entry, VerticalSymbol):
                # See cam of symbol for explanation about
                # the 'or branch_entry.parent' (pyside/qt bug)
                branch_entry = branch_entry.parentItem() or branch_entry.parent
Maxime Perrotin's avatar
Maxime Perrotin committed
1316
            branch_entry.cam(branch_entry.position, branch_entry.position)
Maxime Perrotin's avatar
Maxime Perrotin committed
1317
        else:
1318
            super(VerticalSymbol, self).cam(old_pos, new_pos, ignore)