opengeode.py 94.7 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
30
31

# Added to please py2exe - NOQA makes flake8 ignore the following lines:
# pylint: disable=W0611
32
import enum  # NOQA
33
import string  # NOQA
34
import fnmatch  # NOQA
35
import operator  # NOQA
36
import subprocess  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
37
import distutils  # NOQA
38
39
40
import tempfile  # NOQA
import uuid  # NOQA
import importlib  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
41
42
43
44
45
46
47
48
49
50
51
52
53
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 sdlSymbols
import PySide.QtXml  # NOQA
54
55
import singledispatch  # NOQA
import Asn1scc  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
56
import Connectors  # NOQA
57
import TextInteraction  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
58
59
60
61
try:
    import stringtemplate3  # NOQA
except ImportError:
    pass
Maxime Perrotin's avatar
Maxime Perrotin committed
62
63
64
65

#from PySide import phonon

from PySide import QtGui, QtCore
66
from PySide.QtCore import Qt, QSize, QFile, QIODevice, QRectF, QTimer, QPoint
Maxime Perrotin's avatar
Maxime Perrotin committed
67
68
69
70

from PySide.QtUiTools import QUiLoader
from PySide import QtSvg

71
from genericSymbols import(Symbol, Comment, Cornergrabber, Connection)
Maxime Perrotin's avatar
Maxime Perrotin committed
72
73
from sdlSymbols import(Input, Output, Decision, DecisionAnswer, Task,
        ProcedureCall, TextSymbol, State, Start, Join, Label, Procedure,
74
75
        ProcedureStart, ProcedureStop, StateStart, Connect, Process,
        ContinuousSignal)
76
from TextInteraction import EditableText
Maxime Perrotin's avatar
Maxime Perrotin committed
77
78
79
80

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

Maxime Perrotin's avatar
Maxime Perrotin committed
81
82
LOG = logging.getLogger(__name__)

Maxime Perrotin's avatar
Maxime Perrotin committed
83
84
85
86
87
88
89
import AdaGenerator
import ogParser
import ogAST
import Renderer
import Clipboard
import Statechart
import Lander
90
import Helper
Maxime Perrotin's avatar
Maxime Perrotin committed
91
import Pr
Maxime Perrotin's avatar
Maxime Perrotin committed
92
93
94
95
96
97


# Try importing graphviz for the SDL to Statechart converter
# This is optional, as graphviz installation can not be easily
# automated on some platforms by opengeode installation scripts.
try:
Maxime Perrotin's avatar
Maxime Perrotin committed
98
    import pygraphviz  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
99
100
101
102
    graphviz = True
except ImportError:
    graphviz = False

103
104
105
106
107
try:
    import CGenerator
except ImportError:
    CGenerator = None

Maxime Perrotin's avatar
Maxime Perrotin committed
108
109
110
try:
    import LlvmGenerator
except ImportError:
111
    LlvmGenerator = None
Maxime Perrotin's avatar
Maxime Perrotin committed
112

Maxime Perrotin's avatar
Maxime Perrotin committed
113
114
115
116
117
118
try:
    import StgBackend
except ImportError:
    StgBackend = False


Maxime Perrotin's avatar
Maxime Perrotin committed
119
__all__ = ['opengeode', 'SDL_Scene', 'SDL_View', 'parse']
Maxime Perrotin's avatar
Maxime Perrotin committed
120
__version__ = '1.3.15'
Maxime Perrotin's avatar
Maxime Perrotin committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

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 = {
156
    'block': [Process, Comment, TextSymbol],
157
158
159
    'process': [Start, State, Input, Connect, ContinuousSignal, Task, Decision,
                DecisionAnswer, Output, ProcedureCall, TextSymbol, Comment,
                Label, Join, Procedure],
Maxime Perrotin's avatar
Maxime Perrotin committed
160
161
162
    'procedure': [ProcedureStart, Task, Decision,
                  DecisionAnswer, Output, ProcedureCall, TextSymbol,
                  Comment, Label, Join, ProcedureStop],
163
    'statechart': [],
164
165
166
    'state': [StateStart, State, Input, Connect, ContinuousSignal, Task,
              Decision, DecisionAnswer, Output, ProcedureCall, TextSymbol,
              Comment, Label, Join, ProcedureStop, Procedure],
Maxime Perrotin's avatar
Maxime Perrotin committed
167
168
    'clipboard': [Start, State, Input, Connect, Task, Decision, DecisionAnswer,
                  Output, ProcedureCall, TextSymbol, Comment, Label,
169
170
                  Join, Procedure, Process, StateStart, ProcedureStop,
                  ContinuousSignal],
Maxime Perrotin's avatar
Maxime Perrotin committed
171
172
    'lander': [],
    'asn1': []
Maxime Perrotin's avatar
Maxime Perrotin committed
173
174
175
}


176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
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__()

    def keyPressEvent(self, key_event):
        ''' Handle key press - in particular Escape '''
        super(Vi_bar, self).keyPressEvent(key_event)
        if key_event.key() == Qt.Key_Escape:
            self.clearFocus()


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):
        ''' Set the acons and actions on the toolbar '''
        self.actions = {}
        self.clear()
        for item in bar_items:
            item_name = item.__name__
            self.actions[item_name] = self.addAction(
                           QtGui.QIcon(':icons/{icon}'.format(
                           icon=item_name.lower() + '.png')), item_name)
        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
283
            selection = list(scene.selected_symbols)
Maxime Perrotin's avatar
Maxime Perrotin committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
        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
305
                for item in scene.visible_symb:
Maxime Perrotin's avatar
Maxime Perrotin committed
306
                    try:
307
                        if item.is_singleton:
Maxime Perrotin's avatar
Maxime Perrotin committed
308
309
310
311
312
313
314
315
316
317
318
                            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)
319
            for action in getattr(selection, 'allowed_followers', []):
Maxime Perrotin's avatar
Maxime Perrotin committed
320
321
322
323
324
325
326
327
328
329
330
331
                try:
                    self.actions[action].setEnabled(True)
                except KeyError:
                    LOG.debug('No menu item for symbol "' + action + '"')


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()

    def __init__(self, context='process'):
332
333
334
335
        '''
            Create an SDL Scene for a given context:
            process, procedure or composite state
        '''
Maxime Perrotin's avatar
Maxime Perrotin committed
336
        super(SDL_Scene, self).__init__()
Maxime Perrotin's avatar
Maxime Perrotin committed
337
338
        # Reference to the parent scene
        self.parent_scene = None
Maxime Perrotin's avatar
Maxime Perrotin committed
339
340
        self.mode = 'idle'
        self.context = context
Maxime Perrotin's avatar
Maxime Perrotin committed
341
        self.allowed_symbols = ACTIONS[context]
Maxime Perrotin's avatar
Maxime Perrotin committed
342
343
344
345
346
347
348
349
350
351
352
353
354
        # 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
355
356
        self.setBackgroundBrush(QtGui.QBrush(
                                           QtGui.QImage(':icons/texture.png')))
Maxime Perrotin's avatar
Maxime Perrotin committed
357
358
        self.messages_window = None
        self.click_coordinates = None
359
        self.orig_pos = None
Maxime Perrotin's avatar
Maxime Perrotin committed
360
        self.process_name = 'opengeode'
Maxime Perrotin's avatar
Maxime Perrotin committed
361
362
        # Scene name is used to update the tab window name when scene changes
        self.name = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
363
364
365
366
367
        # 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
368
369
        # Keep a list of composite states: {'stateName': SDL_Scene}
        self._composite_states = {}
370
371
        # Keep a track of highlighted symbols: { symbol: brush }
        self.highlighted = {}
Maxime Perrotin's avatar
Maxime Perrotin committed
372

373

Maxime Perrotin's avatar
Maxime Perrotin committed
374
375
376
    @property
    def visible_symb(self):
        ''' Return the visible items of a scene '''
Maxime Perrotin's avatar
Maxime Perrotin committed
377
378
379
        return (it for it in self.items() if it.isVisible() and
                isinstance(it, Symbol))

380

Maxime Perrotin's avatar
Maxime Perrotin committed
381
382
383
384
385
    @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
386

387

Maxime Perrotin's avatar
Maxime Perrotin committed
388
389
390
391
    @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
392

393

394
395
396
397
398
399
    @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))

400

401
402
403
404
405
    @property
    def procedures(self):
        ''' Return visible procedures components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, Procedure))

406

Maxime Perrotin's avatar
Maxime Perrotin committed
407
408
409
410
411
    @property
    def states(self):
        ''' Return visible state components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, State))

412

Maxime Perrotin's avatar
Maxime Perrotin committed
413
414
415
416
417
    @property
    def texts(self):
        ''' Return visible text areas components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, TextSymbol))

418

Maxime Perrotin's avatar
Maxime Perrotin committed
419
420
421
422
423
    @property
    def procs(self):
        ''' Return visible procedure declaration components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, Procedure))

424

Maxime Perrotin's avatar
Maxime Perrotin committed
425
426
427
428
429
    @property
    def start(self):
        ''' Return visible start components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, Start))

430

Maxime Perrotin's avatar
Maxime Perrotin committed
431
432
433
    @property
    def floating_labels(self):
        ''' Return visible floating label components of the scene '''
Maxime Perrotin's avatar
Maxime Perrotin committed
434
        return (it for it in self.floating_symb if isinstance(it, Label))
Maxime Perrotin's avatar
Maxime Perrotin committed
435

436

Maxime Perrotin's avatar
Maxime Perrotin committed
437
438
439
440
441
442
    @property
    def returns(self):
        ''' Return visible return components of the scene '''
        return (it for it in self.visible_symb if isinstance(it,
                                                              ProcedureStop))

443

Maxime Perrotin's avatar
Maxime Perrotin committed
444
445
446
    @property
    def composite_states(self):
        ''' Return states that contain a composite part '''
Maxime Perrotin's avatar
Maxime Perrotin committed
447
448
449
450
        # 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
451
                self._composite_states[unicode(each).split()[0].lower()] = \
Maxime Perrotin's avatar
Maxime Perrotin committed
452
                                                            each.nested_scene
Maxime Perrotin's avatar
Maxime Perrotin committed
453
454
        return self._composite_states

455

Maxime Perrotin's avatar
Maxime Perrotin committed
456
457
    @composite_states.setter
    def composite_states(self, value):
458
        ''' Attribute setter '''
Maxime Perrotin's avatar
Maxime Perrotin committed
459
460
        self._composite_states = value

461

Maxime Perrotin's avatar
Maxime Perrotin committed
462
463
464
465
    @property
    def all_nested_scenes(self):
        ''' Return all nested scenes, recursively '''
        for each in self.visible_symb:
466
            if each.nested_scene and isinstance(each.nested_scene, SDL_Scene):
Maxime Perrotin's avatar
Maxime Perrotin committed
467
468
469
                yield each.nested_scene
                for sub in each.nested_scene.all_nested_scenes:
                    yield sub
Maxime Perrotin's avatar
Maxime Perrotin committed
470

471

472
473
474
475
476
477
478
479
480
481
    @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
482
483
484
485
486
487
488
489
490
    @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

491

Maxime Perrotin's avatar
Maxime Perrotin committed
492
493
494
495
    def quit_scene(self):
        ''' Called in case of scene switch (e.g. UP button) '''
        pass

496

497
    def render_everything(self, ast):
Maxime Perrotin's avatar
Maxime Perrotin committed
498
        ''' Render a process and its children scenes, recursively '''
Maxime Perrotin's avatar
Maxime Perrotin committed
499
        already_created = []
500

Maxime Perrotin's avatar
Maxime Perrotin committed
501
        def recursive_render(content, dest_scene):
502
503
504
505
            ''' 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
506

507
508
509
510
            try:
                # Render top-level items and their children:
                for each in Renderer.render(content, dest_scene):
                    G_SYMBOLS.add(each)
511
512
513
514
515
516
517
518
519
520
521
                # Refreshing the scene may result in resizing some symbols
                dest_scene.refresh()
                for each in dest_scene.floating_symb:
                    # 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:
                            if symbol.ast.pos_x and symbol.ast.pos_y:
                                relpos = symbol.mapFromScene(symbol.ast.pos_x,
                                                           symbol.ast.pos_y)
522
523
                                symbol.pos_x += relpos.x()
                                symbol.pos_y += relpos.y()
524
                                symbol.update_connections()
Maxime Perrotin's avatar
Maxime Perrotin committed
525
526
527
528
529
530
531
                                # 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()
532
533
                            else:
                                # No CIF coordinates: (1) fix COMMENT position
534
                                # and (2) if floating call CAM
535
536
537
538
539
540
541
                                if isinstance(symbol, genericSymbols.Comment):
                                    symbol.pos_x = \
                                      symbol.parent.boundingRect().width() + 15
                                    symbol.pos_y = 0
                                if not symbol.hasParent:
                                    symbol.cam(symbol.position,
                                               symbol.position)
542
                        except AttributeError:
Maxime Perrotin's avatar
Maxime Perrotin committed
543
                            # no AST, ignore (e.g. Connections, Cornergrabbers)
544
                            pass
Maxime Perrotin's avatar
Maxime Perrotin committed
545
                        else:
546
547
548
549
550
                            # 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)
Maxime Perrotin's avatar
Maxime Perrotin committed
551
552
                            fix_pos_from_ast(symbol.next_aligned_symbol())
                            fix_pos_from_ast(symbol.comment)
553
                    fix_pos_from_ast(each)
554
            except TypeError:
555
                LOG.error(traceback.format_exc())
Maxime Perrotin's avatar
Maxime Perrotin committed
556
557
558
559

            # Render nested scenes, recursively:
            for each in (item for item in dest_scene.visible_symb
                         if item.nested_scene):
560
                LOG.debug(u'Recursive scene: ' + unicode(each))
Maxime Perrotin's avatar
Maxime Perrotin committed
561
562
563
564
                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
565
                    LOG.debug('Subscene "{}" ignored'.format(unicode(each)))
Maxime Perrotin's avatar
Maxime Perrotin committed
566
                    continue
567
                subscene = \
568
569
                        self.create_subscene(each.__class__.__name__.lower(),
                                             dest_scene)
Maxime Perrotin's avatar
Maxime Perrotin committed
570
                already_created.append(each.nested_scene)
571
                subscene.name = unicode(each)
Maxime Perrotin's avatar
Maxime Perrotin committed
572
                LOG.debug('Created scene: {}'.format(subscene.name))
Maxime Perrotin's avatar
Maxime Perrotin committed
573
574
575
576
577
578
                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
579
                if unicode(each).lower() in \
Maxime Perrotin's avatar
Maxime Perrotin committed
580
                        dest_scene.composite_states.viewkeys():
Maxime Perrotin's avatar
Maxime Perrotin committed
581
                    each.nested_scene = dest_scene.composite_states[
Maxime Perrotin's avatar
Maxime Perrotin committed
582
                                                         unicode(each).lower()]
Maxime Perrotin's avatar
Maxime Perrotin committed
583

584
        recursive_render(ast, self)
Maxime Perrotin's avatar
Maxime Perrotin committed
585

586

Maxime Perrotin's avatar
Maxime Perrotin committed
587
588
    def refresh(self):
        ''' Refresh the symbols and connections in the scene '''
Maxime Perrotin's avatar
Maxime Perrotin committed
589
        LOG.debug('scene refresh')
Maxime Perrotin's avatar
Maxime Perrotin committed
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
        for symbol in self.visible_symb:
            symbol.updateConnectionPointPosition()
            symbol.updateConnectionPoints()
        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)
            symbol.set_textbox_position()
            symbol.try_resize()
            symbol.set_text_alignment()
        for symbol in self.visible_symb:
            symbol.update_connections()
Maxime Perrotin's avatar
Maxime Perrotin committed
617

618

Maxime Perrotin's avatar
Maxime Perrotin committed
619
620
621
622
623
624
625
626
627
628
629
630
    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

631

Maxime Perrotin's avatar
Maxime Perrotin committed
632
633
634
635
636
637
638
639
    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

640

Maxime Perrotin's avatar
Maxime Perrotin committed
641
642
643
644
645
646
647
648
649
650
    def translate_to_origin(self):
        '''
            Translate all items to coordinate system starting at (0,0),
            in order to avoid negative coordinates
        '''
        try:
            min_x = min(item.x() for item in self.floating_symb)
            min_y = min(item.y() for item in self.floating_symb)
        except ValueError:
            # No item in the scene
651
            return 0, 0
Maxime Perrotin's avatar
Maxime Perrotin committed
652
653
654
        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:
655
656
            item.pos_x += delta_x
            item.pos_y += delta_y
Maxime Perrotin's avatar
Maxime Perrotin committed
657
658
        return delta_x, delta_y

659

Maxime Perrotin's avatar
Maxime Perrotin committed
660
661
662
    def set_selection(self, toolbar):
        ''' When the selection has changed, update menu, etc '''
        toolbar.update_menu(self)
Maxime Perrotin's avatar
Maxime Perrotin committed
663
        for item in self.selected_symbols:
Maxime Perrotin's avatar
Maxime Perrotin committed
664
665
            item.grabber.display()

666
667
668
669
670
671
672
673
674
675

    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
676
677
        if not errors:
            return
678

Maxime Perrotin's avatar
Maxime Perrotin committed
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
        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_()

703

704
    def global_syntax_check(self, ignore=set()):
705
        ''' Parse each visible symbol in the current scene and its children
706
707
708
709
            and check syntax using the parser
            Use a mutable parameter to avoid recursion on already visited
            scenes
        '''
710
        res = True
711
712
        reset = not ignore
        ignore.add(self)
713
        for each in self.visible_symb:
714
715
716
717
718
719
720
721
722
723
724
725
726
            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)
727
728
                pos = each.scenePos()
                fmt = [[' '.join(split), [pos.x(), pos.y()], self.path]]
729
730
731
                log_errors(self.messages_window, fmt, [], clearfirst=False)

        for each in self.all_nested_scenes:
732
733
734
735
736
            if each not in ignore:
                if not each.global_syntax_check():
                    res = False
        if reset:
            ignore.clear()
737
        return res
738

Maxime Perrotin's avatar
Maxime Perrotin committed
739
740
741
742
743

    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,
744
                                        nextstate=False, cpy=True))
Maxime Perrotin's avatar
Maxime Perrotin committed
745
746
        symbol.update_completion_list(pr_text=pr_text)

747

748
749
750
751
752
    def highlight(self, item):
        ''' Highlight a symbol '''
        if item in self.highlighted:
            return
        bound = item.boundingRect()
753
        center = bound.center().x()
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
        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 = {}

769

Maxime Perrotin's avatar
Maxime Perrotin committed
770
771
772
773
774
    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()):
Maxime Perrotin's avatar
Maxime Perrotin committed
775
            if re.search(pattern, unicode(item), flags=re.IGNORECASE):
Maxime Perrotin's avatar
Maxime Perrotin committed
776
777
                yield item.parentItem()

778

Maxime Perrotin's avatar
Maxime Perrotin committed
779
780
781
782
783
784
785
786
787
788
789
790
791
792
    def search(self, pattern, replace_with=None):
        ''' Search and replace function ; get next search result with key n '''
        self.clearSelection()
        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:
                    new_string = re.sub(pattern,
                                        replace_with,
Maxime Perrotin's avatar
Maxime Perrotin committed
793
                                        unicode(item.text),
Maxime Perrotin's avatar
Maxime Perrotin committed
794
795
                                        flags=re.IGNORECASE)
                    undo_cmd = undoCommands.ReplaceText(
Maxime Perrotin's avatar
Maxime Perrotin committed
796
                                     item.text, unicode(item.text), new_string)
Maxime Perrotin's avatar
Maxime Perrotin committed
797
798
799
800
801
802
803
804
805
806
807
                    self.undo_stack.push(undo_cmd)
                    item.select()
            self.refresh()
        else:
            try:
                item = self.search_item.next()
                item.select()
                item.ensureVisible()
            except StopIteration:
                LOG.info('Pattern not found')

808

Maxime Perrotin's avatar
Maxime Perrotin committed
809
810
811
812
813
    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
814
        for item in self.selected_symbols:
Maxime Perrotin's avatar
Maxime Perrotin committed
815
816
817
818
819
820
821
822
823
824
825
826
827
            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()

828

Maxime Perrotin's avatar
Maxime Perrotin committed
829
830
831
832
833
834
835
    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
836
            Clipboard.copy(self.selected_symbols)
Maxime Perrotin's avatar
Maxime Perrotin committed
837
838
        except TypeError as error_msg:
            try:
839
                self.messages_window.addItem(unicode(error_msg))
Maxime Perrotin's avatar
Maxime Perrotin committed
840
            except AttributeError:
841
                LOG.error(unicode(error_msg))
Maxime Perrotin's avatar
Maxime Perrotin committed
842
843
            raise

844

Maxime Perrotin's avatar
Maxime Perrotin committed
845
846
847
848
849
850
851
852
853
854
855
    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()

856

Maxime Perrotin's avatar
Maxime Perrotin committed
857
858
859
860
    def paste_symbols(self):
        '''
            Paste previously copied symbols at selection point
        '''
Maxime Perrotin's avatar
Maxime Perrotin committed
861
        parent = list(self.selected_symbols)
Maxime Perrotin's avatar
Maxime Perrotin committed
862
863
864
865
866
867
868
869
        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:
870
871
872
873
874
                LOG.error(str(error_msg))
                try:
                    self.messages_window.addItem(str(error_msg))
                except AttributeError:
                    pass
Maxime Perrotin's avatar
Maxime Perrotin committed
875
876
877
878
            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
879
                    # Same for decision answers and connections
Maxime Perrotin's avatar
Maxime Perrotin committed
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
                    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()

897

898
    def sdl_to_statechart(self, basic=True):
Maxime Perrotin's avatar
Maxime Perrotin committed
899
        ''' Create a graphviz representation of the SDL model '''
Maxime Perrotin's avatar
Maxime Perrotin committed
900
        pr_raw = Pr.parse_scene(self)
Maxime Perrotin's avatar
Maxime Perrotin committed
901
        pr_data = unicode('\n'.join(pr_raw))
902
903
904
905
        ast, _, _ = ogParser.parse_pr(string=pr_data)
        try:
            process_ast, = ast.processes
        except ValueError:
906
            LOG.debug('No statechart to render')
907
            return None
908
909
910
911
        # 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)
912
        return Statechart.create_dot_graph(process_ast, basic)
Maxime Perrotin's avatar
Maxime Perrotin committed
913

914

Maxime Perrotin's avatar
Maxime Perrotin committed
915
916
    def export_branch_to_picture(self, symbol, filename, doc_format):
        ''' Save a symbol and its followers to a file '''
917
        temp_scene = SDL_Scene(context=self.context)
Maxime Perrotin's avatar
Maxime Perrotin committed
918
        temp_scene.messages_window = self.messages_window
Maxime Perrotin's avatar
Maxime Perrotin committed
919
920
921
922
923
924
925
926
927
        self.clearSelection()
        symbol.select()
        try:
            self.copy_selected_symbols()
            temp_scene.paste_symbols()
            temp_scene.export_img(filename, doc_format)
        except AttributeError:
            pass

928

Maxime Perrotin's avatar
Maxime Perrotin committed
929
930
931
932
933
934
935
936
937
938
939
    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
940
            for item in self.floating_symb:
941
                name = '{}-{}'.format(filename, str(index))
942
                LOG.info('Saving {ext} file: {name}.{ext}'
943
944
                         .format(ext=doc_format, name=name))
                self.export_branch_to_picture(item, name, doc_format)
Maxime Perrotin's avatar
Maxime Perrotin committed
945
946
947
948
949
950
951
                index += 1

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

        self.clearSelection()
        self.clear_focus()
Maxime Perrotin's avatar
Maxime Perrotin committed
952
        # Copy in a different scene to get the smallest rectangle
953
        other_scene = SDL_Scene(context=self.context)
Maxime Perrotin's avatar
Maxime Perrotin committed
954
955
956
957
        other_scene.messages_window = self.messages_window
        other_scene.setBackgroundBrush(QtGui.QBrush())
        for each in self.floating_symb:
            each.select()
958
959
960
            try:
                self.copy_selected_symbols()
            except AttributeError as err:
961
                LOG.debug(str(traceback.format_exc()))
962
                LOG.error(str(err))
Maxime Perrotin's avatar
Maxime Perrotin committed
963
964
965
966
            other_scene.paste_symbols()
            each.select(False)
        rect = other_scene.sceneRect()

Maxime Perrotin's avatar
Maxime Perrotin committed
967
968
969
970
        # 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
971
                                  QtGui.QImage.Format_ARGB32)
Maxime Perrotin's avatar
Maxime Perrotin committed
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
            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
988
        other_scene.render(painter, source=rect)
Maxime Perrotin's avatar
Maxime Perrotin committed
989
990
991
992
993
994
995
996
        try:
            device.save(filename)
        except AttributeError:
            # Due to inconsistencies in Qt API - only QtGui.QImage has the save
            pass
        if painter.isActive():
            painter.end()

997

Maxime Perrotin's avatar
Maxime Perrotin committed
998
999
1000
    def clear_focus(self):
        ''' Clear focus from any item on the scene '''
        try:
For faster browsing, not all history is shown. View entire blame