opengeode.py 110 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# pylint: disable=C0302
"""
    OpenGEODE - A tiny, free SDL Editor for TASTE

    SDL is the Specification and Description Language (Z100 standard from ITU)

    Copyright (c) 2012-2013 European Space Agency

    Designed and implemented by Maxime Perrotin

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

import signal
import sys
import os
import argparse
import logging
import traceback
import re
import code
import pprint
26
import random
Maxime Perrotin's avatar
Maxime Perrotin committed
27
from functools import partial
Maxime Perrotin's avatar
Maxime Perrotin committed
28
from itertools import chain
Maxime Perrotin's avatar
Maxime Perrotin committed
29

Maxime Perrotin's avatar
Maxime Perrotin committed
30
31
32
# To freeze the application on Windows, all modules must be imported even
# when they are not directly used from this module (py2exe bug)
# NOQA makes flake8 ignore locally-ununsed modules
Maxime Perrotin's avatar
Maxime Perrotin committed
33
# pylint: disable=W0611
34
import enum  # NOQA
35
import string  # NOQA
36
import fnmatch  # NOQA
37
import operator  # NOQA
38
import subprocess  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
39
import distutils  # NOQA
40
41
42
import tempfile  # NOQA
import uuid  # NOQA
import importlib  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
43
44
45
46
47
48
49
50
51
52
53
54
import antlr3  # NOQA
import antlr3.tree  # NOQA
import importlib  # NOQA
import PySide  # NOQA
import PySide.QtCore  # NOQA
import PySide.QtGui  # NOQA
import PySide.QtUiTools  # NOQA
import undoCommands  # NOQA
import sdl92Lexer  # NOQA
import sdl92Parser  # NOQA
import genericSymbols  # NOQA
import PySide.QtXml  # NOQA
55
56
import singledispatch  # NOQA
import Asn1scc  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
57
import Connectors  # NOQA
58
import TextInteraction  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
59
60
61
62
63
64
65
66
67
68
69
70
71
import pygraphviz  # NOQA
import sdlSymbols
import AdaGenerator
import ogParser
import ogAST
import Renderer
import Clipboard
import Statechart
import Lander
import Helper
import Pr
import CGenerator

Maxime Perrotin's avatar
Maxime Perrotin committed
72
73
# Enable mypy type checking
try:
Maxime Perrotin's avatar
Maxime Perrotin committed
74
    from typing import List, Union, Dict, Set, Any, Tuple
Maxime Perrotin's avatar
Maxime Perrotin committed
75
76
77
except ImportError:
    pass

Maxime Perrotin's avatar
Maxime Perrotin committed
78
79
80
81
try:
    import stringtemplate3  # NOQA
except ImportError:
    pass
Maxime Perrotin's avatar
Maxime Perrotin committed
82
83
84
85

#from PySide import phonon

from PySide import QtGui, QtCore
86
87
from PySide.QtCore import (Qt, QSize, QFile, QIODevice, QRectF, QTimer, QPoint,
                           QPointF, QLineF)
Maxime Perrotin's avatar
Maxime Perrotin committed
88
89
90
91

from PySide.QtUiTools import QUiLoader
from PySide import QtSvg

92
from genericSymbols import(Symbol, Comment, Cornergrabber, Connection)
Maxime Perrotin's avatar
Maxime Perrotin committed
93
94
from sdlSymbols import(Input, Output, Decision, DecisionAnswer, Task,
        ProcedureCall, TextSymbol, State, Start, Join, Label, Procedure,
95
96
        ProcedureStart, ProcedureStop, StateStart, Connect, Process,
        ContinuousSignal)
97
from TextInteraction import EditableText
Maxime Perrotin's avatar
Maxime Perrotin committed
98
99
100
101

# Icons and png files generated from the resource file:
import icons  # NOQA

Maxime Perrotin's avatar
Maxime Perrotin committed
102
# Logging: ist of properly loaded modules that will use it
Maxime Perrotin's avatar
Maxime Perrotin committed
103
LOG = logging.getLogger(__name__)
Maxime Perrotin's avatar
Maxime Perrotin committed
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
MODULES = [
    sdlSymbols,
    genericSymbols,
    ogAST,
    ogParser,
    Lander,
    AdaGenerator,
    undoCommands,
    Renderer,
    Clipboard,
    Statechart,
    Helper,
    Asn1scc,
    Connectors,
    Pr,
    TextInteraction,
    Connectors,
    CGenerator,
Maxime Perrotin's avatar
Maxime Perrotin committed
122
] # type: List[module]
123

124
125
126
# Define custom UserRoles
ANCHOR = Qt.UserRole + 1

Maxime Perrotin's avatar
Maxime Perrotin committed
127
128
try:
    import LlvmGenerator
Maxime Perrotin's avatar
Maxime Perrotin committed
129
    MODULES.append(LlvmGenerator)
Maxime Perrotin's avatar
Maxime Perrotin committed
130
except ImportError:
Maxime Perrotin's avatar
Maxime Perrotin committed
131
    pass
Maxime Perrotin's avatar
Maxime Perrotin committed
132

Maxime Perrotin's avatar
Maxime Perrotin committed
133
134
try:
    import StgBackend
Maxime Perrotin's avatar
Maxime Perrotin committed
135
    MODULES.append(StgBackend)
Maxime Perrotin's avatar
Maxime Perrotin committed
136
except ImportError:
Maxime Perrotin's avatar
Maxime Perrotin committed
137
    pass
Maxime Perrotin's avatar
Maxime Perrotin committed
138
139


Maxime Perrotin's avatar
Maxime Perrotin committed
140
__all__ = ['opengeode', 'SDL_Scene', 'SDL_View', 'parse']
Maxime Perrotin's avatar
Maxime Perrotin committed
141
__version__ = '1.5.7'
Maxime Perrotin's avatar
Maxime Perrotin committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176

if hasattr(sys, 'frozen'):
    # Detect if we are running on Windows (py2exe-generated)
    try:
        CUR_DIR = os.path.dirname(unicode
                (sys.executable, sys.getfilesystemencoding()))
    except TypeError:
        CUR_DIR = os.path.dirname(os.path.realpath(__file__))
    else:
        # Redirect stderr to a log file - to avoid py2exe error message
        # that pops up at application closure when app logs errors
        sys.stdout = open('opengeode_stdout.log', 'w')
        sys.stderr = open('opengeode_stderr.log', 'w')
else:
    CUR_DIR = os.path.dirname(os.path.realpath(__file__))


# Global handling all top-level elements
# It seems that if we don't keep a global list of these elements
# (START, STATE, and Text symbols)
# they sometimes get destroyed and disappear from the scene.
# As if a GC was deleting these object *even if they belong to the scene*
# (but have no parentItem). Most likely a Qt/Pyside bug.
G_SYMBOLS = set()


# Other Qt bug:
# QGraphicsTextItem don't stand that their parent item (usually an
# SDL symbol) is removed from the scene (scene.removeItem()). It
# provokes segfault when application exits.
# Workaround is to use hide()/show() to make items disappear
# from the scene (when deleted). Seems OK (MP 2013-03-26)

# Lookup table used to configure the context-dependent toolbars
ACTIONS = {
177
    'block': [Process, Comment, TextSymbol],
178
179
180
    'process': [Start, State, Input, Connect, ContinuousSignal, Task, Decision,
                DecisionAnswer, Output, ProcedureCall, TextSymbol, Comment,
                Label, Join, Procedure],
Maxime Perrotin's avatar
Maxime Perrotin committed
181
182
183
    'procedure': [ProcedureStart, Task, Decision,
                  DecisionAnswer, Output, ProcedureCall, TextSymbol,
                  Comment, Label, Join, ProcedureStop],
184
    'statechart': [],
185
186
187
    'state': [StateStart, State, Input, Connect, ContinuousSignal, Task,
              Decision, DecisionAnswer, Output, ProcedureCall, TextSymbol,
              Comment, Label, Join, ProcedureStop, Procedure],
Maxime Perrotin's avatar
Maxime Perrotin committed
188
189
    'clipboard': [Start, State, Input, Connect, Task, Decision, DecisionAnswer,
                  Output, ProcedureCall, TextSymbol, Comment, Label,
190
191
                  Join, Procedure, Process, StateStart, ProcedureStop,
                  ContinuousSignal],
Maxime Perrotin's avatar
Maxime Perrotin committed
192
193
    'lander': [],
    'asn1': []
Maxime Perrotin's avatar
Maxime Perrotin committed
194
195
196
}


197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def log_errors(window, errors, warnings, clearfirst=True):
    ''' Report Error and Warnings on the console and in the log window '''
    if window and clearfirst:
        window.clear()
    for error in errors:
        if type(error[0]) == list:
            # should be fixed now, CHECKME - NO, NOT FULLY FIXED
            # problem is in decision answers branches
            error[0] = 'Internal error - ' + str(error[0])
        LOG.error(error[0])
        item = QtGui.QListWidgetItem(u'[ERROR] ' + error[0])
        if len(error) == 3:
            item.setData(Qt.UserRole, error[1])
            #found = self.scene().symbol_near(QPoint(*error[1]), 1)
            # Pyside bug: setData cannot store 'found' directly
            #item.setData(Qt.UserRole + 1, id(found))
            item.setData(Qt.UserRole + 1, error[2])
        if window:
            window.addItem(item)
    for warning in warnings:
        LOG.warning(warning[0])
        item = QtGui.QListWidgetItem(u'[WARNING] ' + str(warning[0]))
        if len(warning) == 3:
            item.setData(Qt.UserRole, warning[1])
            item.setData(Qt.UserRole + 1, warning[2])
        if window:
            window.addItem(item)
    if not errors and not warnings and window:
        window.addItem('No errors, no warnings!')



Maxime Perrotin's avatar
Maxime Perrotin committed
229
230
231
232
233
class Vi_bar(QtGui.QLineEdit, object):
    ''' Line editor for the Vi-like command mode '''
    def __init__(self):
        ''' Create the bar - no need for parent '''
        super(Vi_bar, self).__init__()
234
235
        self.history = []
        self.pointer = 0
Maxime Perrotin's avatar
Maxime Perrotin committed
236
237

    def keyPressEvent(self, key_event):
238
        ''' Handle key press - Escape, command history '''
Maxime Perrotin's avatar
Maxime Perrotin committed
239
240
241
        super(Vi_bar, self).keyPressEvent(key_event)
        if key_event.key() == Qt.Key_Escape:
            self.clearFocus()
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
            self.pointer = len(self.history)
        elif key_event.key() == Qt.Key_Return:
            self.history.append(self.text())
            self.pointer = len(self.history)
        elif key_event.key() == Qt.Key_Up:
            if self.text() and self.text() not in self.history:
                self.history.insert(self.pointer + 1, self.text())
            self.pointer = max(0, self.pointer - 1)
            try:
                self.setText(self.history[self.pointer])
            except IndexError as err:
                pass
        elif key_event.key() == Qt.Key_Down:
            self.pointer = min(len(self.history), self.pointer + 1)
            try:
                self.setText(self.history[self.pointer])
            except IndexError:
                pass
            pass
Maxime Perrotin's avatar
Maxime Perrotin committed
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
301


class File_toolbar(QtGui.QToolBar, object):
    ''' Toolbar with file open, save, etc '''
    def __init__(self, parent):
        ''' Create the toolbar using standard icons '''
        super(File_toolbar, self).__init__(parent)
        self.setMovable(False)
        self.setFloatable(False)
        self.new_button = self.addAction(self.style().standardIcon(
            QtGui.QStyle.SP_FileIcon), 'New model')
        self.open_button = self.addAction(self.style().standardIcon(
            QtGui.QStyle.SP_DialogOpenButton), 'Open model')
        self.save_button = self.addAction(self.style().standardIcon(
            QtGui.QStyle.SP_DialogSaveButton), 'Save model')
        self.check_button = self.addAction(self.style().standardIcon(
            QtGui.QStyle.SP_DialogApplyButton), 'Check model')
        self.addSeparator()
        # Up arrow to come back from a subscene (e.g. procedure)
        self.up_button = self.addAction(self.style().standardIcon(
            QtGui.QStyle.SP_ArrowUp), 'Go one level above')
        self.up_button.setEnabled(False)


class Sdl_toolbar(QtGui.QToolBar, object):
    '''
        Toolbar with SDL symbols
        The list of symbols is passed as paramters at creation time ; the class
        looks for icons for the name of the symbols and .png extension.
        The buttons activation is context dependent. Configuration is done
        directly at symbol leval (using the "allowed_followers" property)
    '''
    def __init__(self, parent):
        ''' Create the toolbar, get icons and link actions '''
        super(Sdl_toolbar, self).__init__(parent)
        self.setMovable(False)
        self.setFloatable(False)
        self.setIconSize(QSize(35, 35))
        self.actions = {}

    def set_actions(self, bar_items):
Maxime Perrotin's avatar
Maxime Perrotin committed
302
        ''' Set the icons and actions on the toolbar '''
Maxime Perrotin's avatar
Maxime Perrotin committed
303
304
305
306
307
        self.actions = {}
        self.clear()
        for item in bar_items:
            item_name = item.__name__
            self.actions[item_name] = self.addAction(
Maxime Perrotin's avatar
Maxime Perrotin committed
308
309
                           QtGui.QIcon(':icons/{}.png'
                                       .format(item_name.lower())), item_name)
Maxime Perrotin's avatar
Maxime Perrotin committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        self.update_menu()

    def enable_action(self, action):
        ''' Used as a slot to allow a scene to enable a menu action,
            e.g. if the Start symbol is deleted, the Start button
            shall be activated '''
        self.actions[action].setEnabled(True)

    def disable_action(self, action):
        ''' See description in enable_action '''
        self.actions[action].setEnabled(False)

    def update_menu(self, scene=None):
        ''' Context-dependent enabling/disabling of menu buttons '''
        try:
Maxime Perrotin's avatar
Maxime Perrotin committed
325
            selection = list(scene.selected_symbols)
Maxime Perrotin's avatar
Maxime Perrotin committed
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
        except AttributeError:
            selection = []
        if not selection:
            # Second chance, check if an item has focus (editable text)
            try:
                selection.append(scene.focusItem().parentItem())
            except AttributeError:
                pass
        if len(selection) > 1:
            # When several items are selected, disable all menu entries
            for _, action in self.actions.viewitems():
                action.setEnabled(False)
        elif not selection:
            # When nothing is selected:
            # activate everything, and when user selects an icon,
            # keep the action on hold until he clicks on the scene
            for action in self.actions.viewkeys():
                self.actions[action].setEnabled(True)

            # Check for singletons (e.g. START symbol)
            try:
Maxime Perrotin's avatar
Maxime Perrotin committed
347
                for item in scene.visible_symb:
Maxime Perrotin's avatar
Maxime Perrotin committed
348
                    try:
349
                        if item.is_singleton:
Maxime Perrotin's avatar
Maxime Perrotin committed
350
351
352
353
354
355
356
357
358
359
360
                            self.actions[
                                    item.__class__.__name__].setEnabled(False)
                    except (AttributeError, KeyError) as error:
                        LOG.debug(str(error))
            except AttributeError:
                pass
        else:
            # Only one selected item
            selection, = selection
            for action in self.actions.viewkeys():
                self.actions[action].setEnabled(False)
361
            for action in getattr(selection, 'allowed_followers', []):
Maxime Perrotin's avatar
Maxime Perrotin committed
362
363
364
                try:
                    self.actions[action].setEnabled(True)
                except KeyError:
365
366
                    pass
                    #LOG.debug('No menu item for symbol "' + action + '"')
Maxime Perrotin's avatar
Maxime Perrotin committed
367
368
369
370
371
372


class SDL_Scene(QtGui.QGraphicsScene, object):
    ''' Main graphic scene (canvas) where the user can place SDL symbols '''
    # Signal to be emitted when the scene is left (e.g. UP button)
    scene_left = QtCore.Signal()
373
    context_change = QtCore.Signal()
Maxime Perrotin's avatar
Maxime Perrotin committed
374
375

    def __init__(self, context='process'):
376
377
378
379
380
        ''' Create a Scene for a given context:
            process, procedure, composite state, clipboard, etc.
            Design note: creating subclasses per context was evaluated but
            rejected - there are too few behavioural differences between them
            Creating tons of files / classes is not right. Keep it simple.
381
        '''
Maxime Perrotin's avatar
Maxime Perrotin committed
382
        super(SDL_Scene, self).__init__()
Maxime Perrotin's avatar
Maxime Perrotin committed
383
384
        # Reference to the parent scene
        self.parent_scene = None
385
386
        # mode can be "idle", "wait_connection_source", "select_items",
        # "wait_next_connection_point", "wait_placement"
Maxime Perrotin's avatar
Maxime Perrotin committed
387
388
        self.mode = 'idle'
        self.context = context
Maxime Perrotin's avatar
Maxime Perrotin committed
389
        self.allowed_symbols = ACTIONS[context]
Maxime Perrotin's avatar
Maxime Perrotin committed
390
391
392
393
394
395
396
397
398
399
400
401
402
        # Configure the action menu
        all_possible_actions = set()
        for action in ACTIONS.viewvalues():
            all_possible_actions |= set(action)
        self.actions = {action.__name__: partial(self.add_symbol, action)
                for action in all_possible_actions}

        # Create a stack for handling undo/redo commands
        # (defined in undoCommands.py)
        self.undo_stack = QtGui.QUndoStack(self)
        # buttonSelected is used to set which symbol to draw
        # on next scene click (see mousePressEvent)
        self.button_selected = None
403
404
        self.setBackgroundBrush(QtGui.QBrush(
                                           QtGui.QImage(':icons/texture.png')))
Maxime Perrotin's avatar
Maxime Perrotin committed
405
406
        self.messages_window = None
        self.click_coordinates = None
407
        self.orig_pos = None
408
409
410
        # When connecting symbols, store list of intermediate points
        self.edge_points = []   #  type: List[QPointF] in scene coordinates
        self.current_line = None  # type: QGraphicsLineItem
Maxime Perrotin's avatar
Maxime Perrotin committed
411
        self.process_name = 'opengeode'
Maxime Perrotin's avatar
Maxime Perrotin committed
412
413
        # Scene name is used to update the tab window name when scene changes
        self.name = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
414
415
416
417
418
        # search_item/search_pattern are used for search/replace function
        self.search_item = None
        self.search_pattern = None
        # Selection rectangle when user clicks on the scene and moves mouse
        self.select_rect = None
Maxime Perrotin's avatar
Maxime Perrotin committed
419
420
        # Keep a list of composite states: {'stateName': SDL_Scene}
        self._composite_states = {}
421
422
        # Keep a track of highlighted symbols: { symbol: brush }
        self.highlighted = {}
423
        self.refresh_requested = False
Maxime Perrotin's avatar
Maxime Perrotin committed
424

425

426
427
428
429
430
431
432
433
434
435
    def is_aggregation(self):
        ''' Determine if the current scene is a state aggregation, i.e. if
        if contains only floating states without children
        '''
        for each in self.visible_symb:
            if each.hasParent:
                return False
            if not isinstance(each, State):
                # At the moment do not support Text Areas
                return False
Maxime Perrotin's avatar
Maxime Perrotin committed
436
            if any(child for child in each.childSymbols()
437
438
439
440
441
                    if isinstance(child, (Input, ContinuousSignal))):
                return False
        return True


Maxime Perrotin's avatar
Maxime Perrotin committed
442
443
444
    @property
    def visible_symb(self):
        ''' Return the visible items of a scene '''
Maxime Perrotin's avatar
Maxime Perrotin committed
445
446
447
        return (it for it in self.items() if it.isVisible() and
                isinstance(it, Symbol))

448

Maxime Perrotin's avatar
Maxime Perrotin committed
449
450
451
452
453
    @property
    def editable_texts(self):
        ''' Return all EditableText areas of a scene '''
        return (it for it in self.items() if it.isVisible() and
                isinstance(it, EditableText))
Maxime Perrotin's avatar
Maxime Perrotin committed
454

455

Maxime Perrotin's avatar
Maxime Perrotin committed
456
457
458
459
    @property
    def floating_symb(self):
        ''' Return the top level floating items of a scene '''
        return (it for it in self.visible_symb if not it.hasParent)
Maxime Perrotin's avatar
Maxime Perrotin committed
460

461

462
463
464
465
466
467
    @property
    def processes(self):
        ''' Return visible processes components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, Process) and
                not isinstance(it, Procedure))

468

469
470
471
472
473
    @property
    def procedures(self):
        ''' Return visible procedures components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, Procedure))

474

Maxime Perrotin's avatar
Maxime Perrotin committed
475
476
477
478
479
    @property
    def states(self):
        ''' Return visible state components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, State))

480

Maxime Perrotin's avatar
Maxime Perrotin committed
481
482
483
484
485
    @property
    def texts(self):
        ''' Return visible text areas components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, TextSymbol))

486

Maxime Perrotin's avatar
Maxime Perrotin committed
487
488
489
490
491
    @property
    def procs(self):
        ''' Return visible procedure declaration components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, Procedure))

492

Maxime Perrotin's avatar
Maxime Perrotin committed
493
494
495
496
497
    @property
    def start(self):
        ''' Return visible start components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, Start))

498

Maxime Perrotin's avatar
Maxime Perrotin committed
499
500
501
    @property
    def floating_labels(self):
        ''' Return visible floating label components of the scene '''
Maxime Perrotin's avatar
Maxime Perrotin committed
502
        return (it for it in self.floating_symb if isinstance(it, Label))
Maxime Perrotin's avatar
Maxime Perrotin committed
503

504

Maxime Perrotin's avatar
Maxime Perrotin committed
505
506
507
508
509
510
    @property
    def returns(self):
        ''' Return visible return components of the scene '''
        return (it for it in self.visible_symb if isinstance(it,
                                                              ProcedureStop))

511

Maxime Perrotin's avatar
Maxime Perrotin committed
512
513
514
    @property
    def composite_states(self):
        ''' Return states that contain a composite part '''
Maxime Perrotin's avatar
Maxime Perrotin committed
515
516
517
518
        # Update the list first
        for each in self.states:
            if each.is_composite() and \
                  each.nested_scene not in self._composite_states.viewvalues():
Maxime Perrotin's avatar
Maxime Perrotin committed
519
                self._composite_states[unicode(each).split()[0].lower()] = \
Maxime Perrotin's avatar
Maxime Perrotin committed
520
                                                            each.nested_scene
Maxime Perrotin's avatar
Maxime Perrotin committed
521
522
        return self._composite_states

523

Maxime Perrotin's avatar
Maxime Perrotin committed
524
525
    @composite_states.setter
    def composite_states(self, value):
526
        ''' Attribute setter '''
Maxime Perrotin's avatar
Maxime Perrotin committed
527
528
        self._composite_states = value

529

Maxime Perrotin's avatar
Maxime Perrotin committed
530
531
532
533
    @property
    def all_nested_scenes(self):
        ''' Return all nested scenes, recursively '''
        for each in self.visible_symb:
534
            if each.nested_scene and isinstance(each.nested_scene, SDL_Scene):
Maxime Perrotin's avatar
Maxime Perrotin committed
535
536
537
                yield each.nested_scene
                for sub in each.nested_scene.all_nested_scenes:
                    yield sub
Maxime Perrotin's avatar
Maxime Perrotin committed
538

539

540
541
542
543
544
545
546
547
548
549
    @property
    def path(self):
        ''' Get the path to the current scene as a list
        e.g. ['BLOCK a', 'PROCESS b', ...]
        '''
        if not self.parent_scene:
            return [self.name[0:-3]]
        return self.parent_scene.path + [self.name[0:-3]]


Maxime Perrotin's avatar
Maxime Perrotin committed
550
551
552
553
554
555
556
557
558
    @property
    def selected_symbols(self):
        ''' Generate the list of selected symbols (excluding grabbers) '''
        for selection in self.selectedItems():
            if isinstance(selection, Symbol):
                yield selection
            elif isinstance(selection, Cornergrabber):
                yield selection.parent

559

Maxime Perrotin's avatar
Maxime Perrotin committed
560
561
562
563
    def quit_scene(self):
        ''' Called in case of scene switch (e.g. UP button) '''
        pass

564

565
    def render_everything(self, ast):
Maxime Perrotin's avatar
Maxime Perrotin committed
566
        ''' Render a process and its children scenes, recursively '''
Maxime Perrotin's avatar
Maxime Perrotin committed
567
        already_created = []
568

Maxime Perrotin's avatar
Maxime Perrotin committed
569
        def recursive_render(content, dest_scene):
570
571
572
573
            ''' Process the rendering in scenes and nested scenes '''
            if isinstance(content, ogAST.Process):
                # XXX - should be set when entering the process
                self.process_name = ast.processName
Maxime Perrotin's avatar
Maxime Perrotin committed
574

575
576
577
578
            try:
                # Render top-level items and their children:
                for each in Renderer.render(content, dest_scene):
                    G_SYMBOLS.add(each)
579
580
                # Refreshing the scene may result in resizing some symbols
                dest_scene.refresh()
581
582
583
584
585
                # Once everything is rendered, adjust position of each
                # symbol to the value from the AST (positions may be
                # slightly altered by the reshaping functions)
                def fix_pos_from_ast(symbol):
                    try:
586
587
                        if(symbol.ast.pos_x is not None
                                and symbol.ast.pos_y is not None):
588
589
590
591
592
593
594
                            relpos = symbol.mapFromScene(symbol.ast.pos_x,
                                                         symbol.ast.pos_y)
                            #symbol.pos_x += relpos.x()
                            #symbol.pos_y += relpos.y()
                            if not symbol.hasParent:
                                symbol.pos_x = symbol.ast.pos_x
                                symbol.pos_y = symbol.ast.pos_y
595
                            else:
596
597
598
599
600
601
602
603
604
                                symbol.position += relpos
                            symbol.update_connections()
                            # Update_position is called here because it
                            # is not possible to be sure that the
                            # positionning stored in the file will be
                            # rendered correctly on the host plaform.
                            # Font rendering may cause slight differences
                            # between Linux and Windows for example.
                            symbol.update_position()
Maxime Perrotin's avatar
Maxime Perrotin committed
605
                        else:
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
                            # No CIF coordinates: fix COMMENT position
                            if isinstance(symbol, genericSymbols.Comment):
                                symbol.pos_x = \
                                  symbol.parent.boundingRect().width() + 15
                                symbol.pos_y = 0
                            if not symbol.hasParent:
                                sc_br = dest_scene.itemsBoundingRect()
                                sy_br = symbol.mapRectToScene(
                                            symbol.boundingRect() |
                                            symbol.childrenBoundingRect())
                                symbol.pos_x += (sc_br.width() - sy_br.x())
                    except AttributeError:
                        # no AST, ignore (e.g. Connections, Cornergrabbers)
                        pass
                    else:
                        # Recursively fix pos of sub branches and followers
                        for branch in (elm for elm in symbol.childSymbols()
                                   if isinstance(elm,
                                         genericSymbols.HorizontalSymbol)):
                            fix_pos_from_ast(branch)
                        fix_pos_from_ast(symbol.next_aligned_symbol())
                        fix_pos_from_ast(symbol.comment)
                map(fix_pos_from_ast, dest_scene.floating_symb)
629
            except TypeError:
630
                LOG.error(traceback.format_exc())
Maxime Perrotin's avatar
Maxime Perrotin committed
631
632
633
634

            # Render nested scenes, recursively:
            for each in (item for item in dest_scene.visible_symb
                         if item.nested_scene):
635
                LOG.debug(u'Recursive scene: ' + unicode(each))
Maxime Perrotin's avatar
Maxime Perrotin committed
636
637
638
639
                if isinstance(each.nested_scene, ogAST.CompositeState) \
                        and (not each.nested_scene.statename
                             or each.nested_scene in already_created):
                    # Ignore nested state scenes that already exist
640
                    LOG.debug('Subscene "{}" ignored'.format(unicode(each)))
Maxime Perrotin's avatar
Maxime Perrotin committed
641
                    continue
642
                subscene = \
643
644
                        self.create_subscene(each.__class__.__name__.lower(),
                                             dest_scene)
Maxime Perrotin's avatar
Maxime Perrotin committed
645
                already_created.append(each.nested_scene)
646
                subscene.name = unicode(each)
Maxime Perrotin's avatar
Maxime Perrotin committed
647
                LOG.debug('Created scene: {}'.format(subscene.name))
Maxime Perrotin's avatar
Maxime Perrotin committed
648
649
650
651
652
653
                recursive_render(each.nested_scene.content, subscene)
                each.nested_scene = subscene

            # Make sure all composite states are initially up to date
            # (Needed for the symbol shape to have dashed lines)
            for each in dest_scene.states:
Maxime Perrotin's avatar
Maxime Perrotin committed
654
                if unicode(each).lower() in \
Maxime Perrotin's avatar
Maxime Perrotin committed
655
                        dest_scene.composite_states.viewkeys():
Maxime Perrotin's avatar
Maxime Perrotin committed
656
                    each.nested_scene = dest_scene.composite_states[
Maxime Perrotin's avatar
Maxime Perrotin committed
657
                                                         unicode(each).lower()]
Maxime Perrotin's avatar
Maxime Perrotin committed
658

659
        recursive_render(ast, self)
Maxime Perrotin's avatar
Maxime Perrotin committed
660

661

Maxime Perrotin's avatar
Maxime Perrotin committed
662
    def refresh(self):
663
        ''' Scene refresh - make sure it happens only once per cycle '''
Maxime Perrotin's avatar
Maxime Perrotin committed
664
665
        #LOG.debug('scene refresh requested by '
        #          + str(traceback.extract_stack(limit=2)[-2][1:3]))
666
667
668
669
670
        if not self.refresh_requested:
            self.refresh_requested = True
            QTimer.singleShot(0, self.scene_refresh)

    def scene_refresh(self):
Maxime Perrotin's avatar
Maxime Perrotin committed
671
        ''' Refresh the symbols and connections in the scene '''
672
        self.refresh_requested = False
Maxime Perrotin's avatar
Maxime Perrotin committed
673
674
675
676
        #LOG.debug('scene refresh done')
#       for symbol in self.visible_symb:
#           symbol.updateConnectionPointPosition()
#           symbol.updateConnectionPoints()
Maxime Perrotin's avatar
Maxime Perrotin committed
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
        for symbol in self.editable_texts:
            # EditableText refreshing - design explanation:
            # The first one is tricky: at symbol initialization,
            # the bounding rect of the text is computed from the raw
            # text value, without any formatting. However, it can
            # happen that text (especially when a model is loaded)
            # contains highlighted data (bold), which has the effect
            # of making the width of the text in fact wider than
            # the bounding rect. The set_text_alignment function,
            # that is applying the aligment of the text within its
            # bounding rect, can work only if the text width is fixed.
            # It has to set it according to the bounding rect, which,
            # therefore can be too small, and this has the effect of
            # pushing the exceeding character to the next line.
            # The only way to avoid this is to call setTextWidth
            # with the value -1 before the aligment is computed.
            # This has the effect of re-computing the bounding rect
            # and fixing the width issue.
            symbol.setTextWidth(-1)
Maxime Perrotin's avatar
Maxime Perrotin committed
696
            #symbol.set_textbox_position()
Maxime Perrotin's avatar
Maxime Perrotin committed
697
698
699
700
            symbol.try_resize()
            symbol.set_text_alignment()
        for symbol in self.visible_symb:
            symbol.update_connections()
Maxime Perrotin's avatar
Maxime Perrotin committed
701

702

Maxime Perrotin's avatar
Maxime Perrotin committed
703
704
705
706
707
708
709
710
711
712
713
714
    def set_cursor(self, follower):
        ''' Set the cursor shape depending on the selected menu item '''
        for item in self.items():
            try:
                if follower.__name__ not in item.allowed_followers:
                    item.setCursor(Qt.ForbiddenCursor)
                else:
                    item.setCursor(Qt.PointingHandCursor)
            except AttributeError:
                # if there are items not having allowed_followers
                pass

715

Maxime Perrotin's avatar
Maxime Perrotin committed
716
717
718
719
720
721
722
723
    def reset_cursor(self):
        ''' Reset the default cursor of an item '''
        for item in self.items():
            try:
                item.setCursor(item.default_cursor)
            except AttributeError:
                pass

724

Maxime Perrotin's avatar
Maxime Perrotin committed
725
726
727
728
729
730
    def translate_to_origin(self):
        '''
            Translate all items to coordinate system starting at (0,0),
            in order to avoid negative coordinates
        '''
        try:
731
732
            min_x = min(item.scenePos().x() for item in self.visible_symb)
            min_y = min(item.scenePos().y() for item in self.visible_symb)
Maxime Perrotin's avatar
Maxime Perrotin committed
733
734
        except ValueError:
            # No item in the scene
735
            return 0, 0
Maxime Perrotin's avatar
Maxime Perrotin committed
736
737
738
        delta_x = -min_x if min_x < 0 else 0
        delta_y = -min_y if min_y < 0 else 0
        for item in self.floating_symb:
739
740
            item.pos_x += delta_x
            item.pos_y += delta_y
Maxime Perrotin's avatar
Maxime Perrotin committed
741
742
        return delta_x, delta_y

743

Maxime Perrotin's avatar
Maxime Perrotin committed
744
745
746
    def set_selection(self, toolbar):
        ''' When the selection has changed, update menu, etc '''
        toolbar.update_menu(self)
Maxime Perrotin's avatar
Maxime Perrotin committed
747
        for item in self.selected_symbols:
Maxime Perrotin's avatar
Maxime Perrotin committed
748
749
            item.grabber.display()

750
751
752
753
754
755
756
757
758
759

    def syntax_errors(self, symb):
        ''' Parse a symbol and return a list of syntax errors '''
        return symb.check_syntax('\n'.join(Pr.generate(symb, recursive=False)))


    def check_syntax(self, symbol):
        ''' Check syntax of a symbol and display a pop-up in case of errors '''
        errors = self.syntax_errors(symbol)

Maxime Perrotin's avatar
Maxime Perrotin committed
760
761
        if not errors:
            return
762

Maxime Perrotin's avatar
Maxime Perrotin committed
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
        for view in self.views():
            errs = []
            for error in errors:
                split = error.split()
                if split[0] == 'line' and len(split) > 1:
                    line_col = split[1].split(':')
                    if len(line_col) == 2:
                        # Get line number and column..to locate error
                        # line_nb, col = line_col
                        errs.append(' '.join(split[2:]))
                    else:
                        errs.append(error)
                else:
                    errs.append(error)
            self.clear_focus()
            msg_box = QtGui.QMessageBox(view)
            msg_box.setIcon(QtGui.QMessageBox.Warning)
            msg_box.setWindowTitle('OpenGEODE - Syntax Error')
            msg_box.setInformativeText('\n'.join(errs))
            msg_box.setText("Syntax error!")
            msg_box.setStandardButtons(QtGui.QMessageBox.Discard)
            msg_box.setDefaultButton(QtGui.QMessageBox.Discard)
            msg_box.exec_()

787

788
    def global_syntax_check(self, ignore=set()):
789
        ''' Parse each visible symbol in the current scene and its children
790
791
792
793
            and check syntax using the parser
            Use a mutable parameter to avoid recursion on already visited
            scenes
        '''
794
        res = True
795
796
        reset = not ignore
        ignore.add(self)
797
        for each in self.visible_symb:
798
799
800
801
802
803
804
805
806
807
808
809
810
            errors = self.syntax_errors(each)
            if errors:
                res = False
            for err in errors:
                split = err.split()
                if split[0] == 'line' and len(split) > 1:
                    line_col = split[1].split(':')
                    if len(line_col) == 2:
                        # get line and col. line must be decremented because
                        # line 1 is the CIF comment which is not visible
                        line_nb, col = line_col
                        line_nb = int(line_nb) - 1
                        split[1] = '{}:{}'.format(line_nb, col)
811
812
                pos = each.scenePos()
                fmt = [[' '.join(split), [pos.x(), pos.y()], self.path]]
813
814
815
                log_errors(self.messages_window, fmt, [], clearfirst=False)

        for each in self.all_nested_scenes:
816
817
818
819
820
            if each not in ignore:
                if not each.global_syntax_check():
                    res = False
        if reset:
            ignore.clear()
821
        return res
822

Maxime Perrotin's avatar
Maxime Perrotin committed
823
824
825
826
827

    def update_completion_list(self, symbol):
        ''' When text has changed on a symbol, update the data dictionnary '''
        pr_text = '\n'.join(Pr.generate(symbol,
                                        recursive=False,
828
                                        nextstate=False, cpy=True))
Maxime Perrotin's avatar
Maxime Perrotin committed
829
        symbol.update_completion_list(pr_text=pr_text)
830
        self.context_change.emit()
Maxime Perrotin's avatar
Maxime Perrotin committed
831

832

833
834
835
836
837
    def highlight(self, item):
        ''' Highlight a symbol '''
        if item in self.highlighted:
            return
        bound = item.boundingRect()
838
        center = bound.center().x()
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
        gradient = QtGui.QLinearGradient(center, 0, center, bound.height())
        gradient.setColorAt(0, Qt.cyan)
        gradient.setColorAt(1, Qt.white)
        self.highlighted[item] = item.brush()
        item.setBrush(QtGui.QBrush(gradient))

    def clear_highlight(self, item=None, reset=True):
        ''' Remove the highlighting of one item or all items on the scene '''
        if item in self.highlighted:
            self.setBrush(self.highlighted.pop(item))
        if reset:
            for item, brush in self.highlighted.viewitems():
                item.setBrush(brush)
            self.highlighted = {}

854

Maxime Perrotin's avatar
Maxime Perrotin committed
855
856
857
858
859
    def find_text(self, pattern):
        ''' Return all symbols with matching text '''
        for item in (symbol for symbol in self.items()
                     if isinstance(symbol, EditableText)
                     and symbol.isVisible()):
860
861
862
863
864
865
            try:
                res = re.search(pattern, unicode(item), flags=re.IGNORECASE)
            except re.error:
                # invalid pattern
                raise StopIteration
            if res:
866
                yield item
Maxime Perrotin's avatar
Maxime Perrotin committed
867

868

869
870
871
872
873
    def search(self, pattern, replace_with=None, cmd=None):
        ''' Search and replace function ; get next search result with key n
        cmd is a user string from the vi bar that by default for a replace
        is "s" (substittute string) but that can be a different command,
        e.g. "state" to limit the substitution to State components'''
Maxime Perrotin's avatar
Maxime Perrotin committed
874
        self.clearSelection()
875
        self.clear_highlight()
Maxime Perrotin's avatar
Maxime Perrotin committed
876
877
878
879
880
881
882
883
884
        self.clear_focus()
        if pattern.endswith('\\'):
            # Avoid buggy pattern ending with a single backslash
            pattern += '\\'
        self.search_item = self.find_text(pattern)
        self.search_pattern = pattern
        if replace_with:
            with undoCommands.UndoMacro(self.undo_stack, 'Search and Replace'):
                for item in self.search_item:
885
886
887
888
889
                    if(cmd and cmd != "s" and
                        item.parentItem().__class__.__name__.lower()
                                                               != cmd.lower()):
                        # filter symbols based on the user command
                        continue
Maxime Perrotin's avatar
Maxime Perrotin committed
890
891
                    new_string = re.sub(pattern,
                                        replace_with,
892
                                        unicode(item),
Maxime Perrotin's avatar
Maxime Perrotin committed
893
894
                                        flags=re.IGNORECASE)
                    undo_cmd = undoCommands.ReplaceText(
895
                                     item, unicode(item), new_string)
Maxime Perrotin's avatar
Maxime Perrotin committed
896
                    self.undo_stack.push(undo_cmd)
897
898
                    item.try_resize()
                    item.parentItem().select()
899
                    self.update_completion_list(item.parent)
Maxime Perrotin's avatar
Maxime Perrotin committed
900
901
902
903
            self.refresh()
        else:
            try:
                item = self.search_item.next()
904
                item = item.parentItem()
Maxime Perrotin's avatar
Maxime Perrotin committed
905
                item.select()
906
                self.highlight(item)
Maxime Perrotin's avatar
Maxime Perrotin committed
907
908
909
910
                item.ensureVisible()
            except StopIteration:
                LOG.info('Pattern not found')

911

Maxime Perrotin's avatar
Maxime Perrotin committed
912
913
914
915
916
    def delete_selected_symbols(self):
        '''
            Remove selected symbols from the scene, with proper re-connections
        '''
        self.undo_stack.beginMacro('Delete items')
Maxime Perrotin's avatar
Maxime Perrotin committed
917
        for item in self.selected_symbols:
Maxime Perrotin's avatar
Maxime Perrotin committed
918
919
920
921
922
923
924
925
926
927
928
929
930
            if not item.scene():
                # Ignore if item has already been deleted
                # (in case of multiple selection)
                continue
            undo_cmd = undoCommands.DeleteSymbol(item)
            self.undo_stack.push(undo_cmd)
            try:
                item.branchEntryPoint.parent.updateConnectionPointPosition()
                item.branchEntryPoint.parent.updateConnectionPoints()
            except AttributeError:
                pass
        self.undo_stack.endMacro()

931

Maxime Perrotin's avatar
Maxime Perrotin committed
932
933
934
935
936
937
938
    def copy_selected_symbols(self):
        '''
            Create a copy of selected symbols to a buffer (in AST form)
            Called when user presses Ctrl-C
        '''
        self.click_coordinates = None
        try:
Maxime Perrotin's avatar
Maxime Perrotin committed
939
            Clipboard.copy(self.selected_symbols)
Maxime Perrotin's avatar
Maxime Perrotin committed
940
941
        except TypeError as error_msg:
            try:
942
                self.messages_window.addItem(unicode(error_msg))
Maxime Perrotin's avatar
Maxime Perrotin committed
943
            except AttributeError:
944
                LOG.error(unicode(error_msg))
Maxime Perrotin's avatar
Maxime Perrotin committed
945
946
            raise

947

Maxime Perrotin's avatar
Maxime Perrotin committed
948
949
950
951
952
953
954
955
956
957
958
    def cut_selected_symbols(self):
        '''
            Create a copy of selected symbols, then delete them
        '''
        try:
            self.copy_selected_symbols()
        except TypeError:
            LOG.error('Copy error - Cannot cut')
        else:
            self.delete_selected_symbols()

959

Maxime Perrotin's avatar
Maxime Perrotin committed
960
961
962
963
    def paste_symbols(self):
        '''
            Paste previously copied symbols at selection point
        '''
Maxime Perrotin's avatar
Maxime Perrotin committed
964
        parent = list(self.selected_symbols)
Maxime Perrotin's avatar
Maxime Perrotin committed
965
966
967
968
969
970
971
972
        if len(parent) > 1:
            self.messages_window.addItem(
                    'Cannot paste when several items are selected')
        else:
            parent_item, = parent or [None]
            try:
                new_items = Clipboard.paste(parent_item, self)
            except TypeError as error_msg:
973
974
975
976
977
                LOG.error(str(error_msg))
                try:
                    self.messages_window.addItem(str(error_msg))
                except AttributeError:
                    pass
Maxime Perrotin's avatar
Maxime Perrotin committed
978
979
980
981
            else:
                self.undo_stack.beginMacro('Paste')
                for item in new_items:
                    # Allow pasting inputs when input is selected
Maxime Perrotin's avatar
Maxime Perrotin committed
982
                    # Same for decision answers and connections
Maxime Perrotin's avatar
Maxime Perrotin committed
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
                    if(isinstance(parent_item, genericSymbols.HorizontalSymbol)
                            and type(parent_item) == type(item)):
                        parent_item = parent_item.parentItem()

                    undo_cmd = undoCommands.InsertSymbol(item, parent_item,
                            pos=None if parent_item
                                     else self.click_coordinates or item.pos())

                    self.undo_stack.push(undo_cmd)
                    if parent_item:
                        parent_item = item
                    else:
                        G_SYMBOLS.add(item)
                    item.cam(item.pos(), item.pos())
                self.undo_stack.endMacro()
                self.refresh()

1000

1001
    def sdl_to_statechart(self, basic=True):
Maxime Perrotin's avatar
Maxime Perrotin committed
1002
        ''' Create a graphviz representation of the SDL model '''
Maxime Perrotin's avatar
Maxime Perrotin committed
1003
        pr_raw = Pr.parse_scene(self)
Maxime Perrotin's avatar
Maxime Perrotin committed
1004
        pr_data = unicode('\n'.join(pr_raw))
1005
1006
1007
1008
        ast, _, _ = ogParser.parse_pr(string=pr_data)
        try:
            process_ast, = ast.processes
        except ValueError:
1009
            LOG.debug('No statechart to render')
1010
            return None
1011
1012
1013
1014
        # Flatten nested states (no, because neato does not support it,
        # dot supports only vertically-aligned states, and fdp does not
        # support curved edges and is buggy with pygraphviz anyway)
        # Helper.flatten(process_ast)
1015
        return Statechart.create_dot_graph(process_ast, basic)
Maxime Perrotin's avatar
Maxime Perrotin committed
1016

1017

Maxime Perrotin's avatar
Maxime Perrotin committed
1018
1019
    def export_branch_to_picture(self, symbol, filename, doc_format):
        ''' Save a symbol and its followers to a file '''
1020
        temp_scene = SDL_Scene(context=self.context)
Maxime Perrotin's avatar
Maxime Perrotin committed
1021
        temp_scene.messages_window = self.messages_window
Maxime Perrotin's avatar
Maxime Perrotin committed
1022
        self.clearSelection()
1023
        self.clear_highlight()
Maxime Perrotin's avatar
Maxime Perrotin committed
1024
1025
1026
1027
1028
1029
1030
1031
        symbol.select()
        try:
            self.copy_selected_symbols()
            temp_scene.paste_symbols()
            temp_scene.export_img(filename, doc_format)
        except AttributeError:
            pass

1032

Maxime Perrotin's avatar
Maxime Perrotin committed
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
    def export_img(self, filename=None, doc_format='png', split=False):
        ''' Save the scene as a PNG/SVG or PDF document
            If specified, split the diagram in multiple files, one
            per top-level floating item
        '''
        if not filename:
            return

        if split:
            # Save in multiple files
            index = 0
Maxime Perrotin's avatar
Maxime Perrotin committed
1044
            for item in self.floating_symb:
1045
                name = '{}-{}'.format(filename, str(index))
1046
                LOG.info('Saving {ext} file: {name}.{ext}'
1047
1048
                         .format(ext=doc_format, name=name))
                self.export_branch_to_picture(item, name, doc_format)
Maxime Perrotin's avatar
Maxime Perrotin committed
1049
1050
1051
1052
1053
1054
                index += 1

        if filename.split('.')[-1] != doc_format:
            filename += '.' + doc_format

        self.clearSelection()
1055
        self.clear_highlight()
Maxime Perrotin's avatar
Maxime Perrotin committed
1056
        self.clear_focus()
Maxime Perrotin's avatar
Maxime Perrotin committed
1057
        # Copy in a different scene to get the smallest rectangle
1058
        other_scene = SDL_Scene(context=self.context)
Maxime Perrotin's avatar
Maxime Perrotin committed
1059
1060
1061
1062
        other_scene.messages_window = self.messages_window
        other_scene.setBackgroundBrush(QtGui.QBrush())
        for each in self.floating_symb:
            each.select()
1063
1064
1065
            try:
                self.copy_selected_symbols()
            except AttributeError as err:
1066
                LOG.debug(str(traceback.format_exc()))
1067
                LOG.error(str(err))
Maxime Perrotin's avatar
Maxime Perrotin committed
1068
1069
1070
1071
            other_scene.paste_symbols()
            each.select(False)
        rect = other_scene.sceneRect()

Maxime Perrotin's avatar
Maxime Perrotin committed
1072
1073
1074
1075
        # enlarge the rect to fit extra pixels due to antialiasing
        rect.adjust(-5, -5, 5, 5)
        if doc_format == 'png':
            device = QtGui.QImage(rect.size().toSize(),
Maxime Perrotin's avatar
Maxime Perrotin committed
1076
                                  QtGui.QImage.Format_ARGB32)
Maxime Perrotin's avatar
Maxime Perrotin committed
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
            device.fill(Qt.transparent)
        elif doc_format == 'svg':
            device = QtSvg.QSvgGenerator()
            device.setFileName(filename)
            device.setTitle('OpenGEODE SDL Diagram')
            device.setSize(rect.size().toSize())
        elif doc_format == 'pdf':
            device = QtGui.QPrinter()
            device.setOutputFormat(QtGui.QPrinter.PdfFormat)
            device.setPaperSize(
                    rect.size().toSize(), QtGui.QPrinter.Point)
            device.setFullPage(True)
            device.setOutputFileName(filename)
        else:
            LOG.error('Output format not supported: ' + doc_format)
        painter = QtGui.QPainter(device)
Maxime Perrotin's avatar
Maxime Perrotin committed
1093
        other_scene.render(painter, source=rect)
Maxime Perrotin's avatar
Maxime Perrotin committed
1094
1095
1096
1097
1098
1099
1100
1101
        try:
            device.save(filename)
        except AttributeError:
            # Due to inconsistencies in Qt API - only QtGui.QImage has the save
            pass
        if painter.isActive():
            painter.end()

1102

Maxime Perrotin's avatar
Maxime Perrotin committed
1103
1104
1105
1106
1107
1108
1109
1110
    def clear_focus(self):
        ''' Clear focus from any item on the scene '''
        try:
            self.focusItem().clearFocus()
        except AttributeError:
            # if no focus item
            pass

1111

Maxime Perrotin's avatar
Maxime Perrotin committed
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
    def symbol_near(self, pos, dist=5, selectable_only=True):
        ''' If any, returns symbol around pos '''
        items = self.items(
                QRectF(pos.x() - dist, pos.y() - dist, 2 * dist, 2 * dist))
        for item in items:
            if((selectable_only and item.flags() &
                    QtGui.QGraphicsItem.ItemIsSelectable)
                    or not selectable_only):
                return item.parent if isinstance(item, Cornergrabber) else item

1122

Maxime Perrotin's avatar
Maxime Perrotin committed
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
    def can_insert(self, pos, item_type):
        ''' Check if we can add an item type at a given position '''
        parent_item = self.symbol_near(pos)
        if not parent_item:
            # No symbol at the given position
            if item_type.needs_parent:
                raise TypeError(str(item_type.__name__) + ' needs a parent')
            else:
                return None
        else:
            # Check if item as pos accepts item type as follower
            if item_type.__name__ in parent_item.allowed_followers:
                return parent_item
            else:
                raise TypeError(parent_item.__class__.__name__ +
                                ' symbol cannot be followed by ' +
                                item_type.__name__)

1141

Maxime Perrotin's avatar
Maxime Perrotin committed
1142
1143
1144
1145
1146
    def create_subscene(self, context, parent=None):
        ''' Create a new SDL scene, e.g. for nested symbols '''
        subscene = SDL_Scene(context=context)
        subscene.messages_window = self.messages_window
        subscene.parent_scene = parent
1147
        subscene.context_change.connect(self.context_change.emit)
Maxime Perrotin's avatar
Maxime Perrotin committed
1148
1149
1150
        return subscene


1151
    def place_symbol(self, item_type, parent, pos=None, rect=None):
Maxime Perrotin's avatar
Maxime Perrotin committed
1152
1153
        ''' Draw a symbol on the scene '''
        item = item_type()
1154
1155
1156
        if rect is not None:
            # Optionally size the new item
            item.set_shape(rect.width(), rect.height())
Maxime Perrotin's avatar
Maxime Perrotin committed
1157
1158
1159
        # Add the item to the scene
        if item not in self.items():
            self.addItem(item)
Maxime Perrotin's avatar
Maxime Perrotin committed
1160
        # Create Undo command (makes the call to the insert_symbol function):
Maxime Perrotin's avatar
Maxime Perrotin committed
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
        undo_cmd = undoCommands.InsertSymbol(item=item, parent=parent, pos=pos)
        self.undo_stack.push(undo_cmd)
        # If no item is selected (e.g. new STATE), add it to the scene
        if not parent:
            G_SYMBOLS.add(item)

        if item_type == Decision:
            # When creating a new decision, add two default answers
            self.place_symbol(item_type=DecisionAnswer, parent=item)
            self.place_symbol(item_type=DecisionAnswer, parent=item)
        elif item_type in (Procedure, State, Process):
            # Create a sub-scene for clickable symbols
            item.nested_scene = \
                    self.create_subscene(item_type.__name__.lower(), self)

        self.clearSelection()
1177
        self.clear_highlight()
Maxime Perrotin's avatar
Maxime Perrotin committed
1178
1179
1180
1181
1182
1183
1184
        self.clear_focus()
        item.select()
        item.cam(item.pos(), item.pos())
        # When item is placed, immediately set focus to input text
        item.edit_text()

        for view in self.views():
Maxime Perrotin's avatar
Maxime Perrotin committed
1185
            view.view_refresh()
Maxime Perrotin's avatar
Maxime Perrotin committed
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
            view.ensureVisible(item)
        return item



    def add_symbol(self, item_type):
        ''' Add a symbol, or postpone until a parent symbol is selected  '''
        try:
            # If an item is selected or if its text has focus,
            # use it as parent item for the newly inserted item
            selection, = (list(self.selected_symbols) or
                          [self.focusItem().parentItem()])
            with undoCommands.UndoMacro(self.undo_stack, 'Place Symbol'):
                self.place_symbol(item_type=item_type, parent=selection)
        except (ValueError, AttributeError):
            # Menu item clicked but no symbol selected
            # -> store until user clicks on the scene
            self.messages_window.clear()
            self.messages_window.addItem(
                    'Click on the scene to place the symbol')
            self.button_selected = item_type
            if item_type == Connection:
                self.mode = 'wait_connection_source'
            else:
                self.mode = 'wait_placement'
            self.set_cursor(item_type)
            return None



Maxime Perrotin's avatar
Maxime Perrotin committed
1216
1217
1218
1219
    # pylint: disable=C0103
    def mousePressEvent(self, event):
        '''
            Handle mouse click on the scene:
1220
1221
1222
1223
1224
1225
1226
            1) If a symbol was selected in the menu, place it in the scene
            2) Otherwise store the coordinates, in which case if the user does
               a paste action with floating items, they will be placed there.
            3) If there is no object at click coordinates, enter the
               selection mode. When mouse is released, check the selection
               rectangle. If no object is selected, open a pop-up menu to
               insert a new symbol, based on the scene context
Maxime Perrotin's avatar
Maxime Perrotin committed
1227
        '''
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
        def border_point(symb, point):
            ''' find the closest point on the border of a symbol '''
            rect = symb.sceneBoundingRect()
            center = rect.center()
            h_dist = min(point.y() - rect.y(),
                         rect.y() + rect.height() - point.y())
            v_dist = min(point.x() - rect.x(),
                         rect.x() + rect.width() - point.x())
            res = QPointF()
            res.setX(symb.pos_x
                    if point.x() <= center.x()
                    else symb.pos_x + symb.boundingRect().width())
            res.setY(symb.pos_y
                    if point.y() <= center.y()
                    else symb.pos_y + symb.boundingRect().height())
            if h_dist < v_dist:
                res.setX(point.x())
            else:
                res.setY(point.y())
            return res
Maxime Perrotin's avatar
Maxime Perrotin committed
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
        self.reset_cursor()
        # First propagate event to symbols for specific treatment
        super(SDL_Scene, self).mousePressEvent(event)
        # Store mouse coordinates as possible paste position
        self.click_coordinates = event.scenePos()
        # Enter state machine
        if self.mode == 'idle' and event.button() == Qt.LeftButton:
            # Idle mode: click triggers selection square
            nearby_connection = self.symbol_near(event.scenePos(),
                                                 selectable_only=False)
            connection_selected = False
Maxime Perrotin's avatar
Maxime Perrotin committed
1259
            if isinstance(nearby_connection, Connection):
Maxime Perrotin's avatar
Maxime Perrotin committed
1260
1261
1262
1263
                # Click near a connection - forward the event to it
                # (some connections like statechart Edges can react)
                nearby_connection.mousePressEvent(event)
                connection_selected = True
1264
1265
            symb = self.symbol_near(event.scenePos(), dist=1)
            if not symb:
Maxime Perrotin's avatar
Maxime Perrotin committed
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
                self.mode = 'select_items'
                self.orig_pos = event.scenePos()
                self.select_rect = self.addRect(
                        QRectF(self.orig_pos, self.orig_pos))
                if self.context == 'statechart' and not connection_selected:
                    # Specific treatment for statecharts - should subclass
                    for item in self.items():
                        # Remove all Edges control points from the scene
                        try:
                            item.bezier_set_visible(False)
                        except AttributeError:
                            pass
1278
1279
1280
1281
1282
1283
            elif symb.user_can_connect \
                    and event.modifiers() == Qt.ControlModifier:
                # TODO check if symbol can be a connection source, can have
                # more than one connection if there is already one, etc.
                self.mode = 'wait_next_connection_point'
                click_point = event.scenePos()
1284
                point = border_point(symb, click_point)
1285
1286
1287
1288
1289
                self.edge_points = [point]
                self.current_line = self.addLine(point.x(),
                                                 point.y(),
                                                 click_point.x(),
                                                 click_point.y())
1290
                self.connection_start = symb
Maxime Perrotin's avatar
Maxime Perrotin committed
1291
1292
1293

        elif self.mode == 'wait_placement':
            try:
1294
1295
                parent = self.can_insert(event.scenePos(),
                                         self.button_selected)
Maxime Perrotin's avatar
Maxime Perrotin committed
1296