opengeode.py 76.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
26
#!/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
from functools import partial
Maxime Perrotin's avatar
Maxime Perrotin committed
27
28
from collections import deque
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 fnmatch  # NOQA
34
import operator  # NOQA
35
import subprocess  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
36
import distutils  # NOQA
37
38
39
import tempfile  # NOQA
import uuid  # NOQA
import importlib  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
40
41
42
43
44
45
46
47
48
49
50
51
52
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
53
54
import singledispatch  # NOQA
import Asn1scc  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
55
import Connectors  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
56
57
58
59
60
61
62
63
64

#from PySide import phonon

from PySide import QtGui, QtCore
from PySide.QtCore import Qt, QSize, QFile, QIODevice, QRectF, QTimer

from PySide.QtUiTools import QUiLoader
from PySide import QtSvg

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

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

import AdaGenerator
import ogParser
import ogAST
import Renderer
import Clipboard
import Statechart
import Lander
81
import Helper
Maxime Perrotin's avatar
Maxime Perrotin committed
82
import Pr
Maxime Perrotin's avatar
Maxime Perrotin committed
83
84
85
86
87
88


# 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
89
    import pygraphviz  # NOQA
Maxime Perrotin's avatar
Maxime Perrotin committed
90
91
92
93
94
95
96
97
98
99
100
    graphviz = True
except ImportError:
    graphviz = False

try:
    import LlvmGenerator
except ImportError:
    # not sure if LLVM is available on the Windows platform
    pass

__all__ = ['opengeode']
101
__version__ = '0.994'
Maxime Perrotin's avatar
Maxime Perrotin committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

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


LOG = logging.getLogger(__name__)


# 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 = {
Maxime Perrotin's avatar
Maxime Perrotin committed
140
    'block': [Process, Comment],
Maxime Perrotin's avatar
Maxime Perrotin committed
141
    'process': [Start, State, Input, Connect, Task, Decision, DecisionAnswer,
Maxime Perrotin's avatar
Maxime Perrotin committed
142
143
144
145
146
                Output, ProcedureCall, TextSymbol, Comment, Label,
                Join, Procedure],
    'procedure': [ProcedureStart, Task, Decision,
                  DecisionAnswer, Output, ProcedureCall, TextSymbol,
                  Comment, Label, Join, ProcedureStop],
147
    'statechart': [],
Maxime Perrotin's avatar
Maxime Perrotin committed
148
    'state': [StateStart, State, Input, Connect, Task, Decision,
Maxime Perrotin's avatar
Maxime Perrotin committed
149
              DecisionAnswer, Output, ProcedureCall, TextSymbol, Comment,
Maxime Perrotin's avatar
Maxime Perrotin committed
150
151
152
153
154
              Label, Join, ProcedureStop, Procedure],
    'clipboard': [Start, State, Input, Connect, Task, Decision, DecisionAnswer,
                  Output, ProcedureCall, TextSymbol, Comment, Label,
                  Join, Procedure, Process, StateStart, ProcedureStop],
    'lander': []
Maxime Perrotin's avatar
Maxime Perrotin committed
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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
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
}


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:
            selection = list(scene.selected_symbols())
        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
255
                for item in scene.visible_symb:
Maxime Perrotin's avatar
Maxime Perrotin committed
256
                    try:
257
                        if item.is_singleton:
Maxime Perrotin's avatar
Maxime Perrotin committed
258
259
260
261
262
263
264
265
266
267
268
                            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)
269
            for action in getattr(selection, 'allowed_followers', []):
Maxime Perrotin's avatar
Maxime Perrotin committed
270
271
272
273
274
275
276
277
278
279
280
281
                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'):
282
283
284
285
        '''
            Create an SDL Scene for a given context:
            process, procedure or composite state
        '''
Maxime Perrotin's avatar
Maxime Perrotin committed
286
287
288
        super(SDL_Scene, self).__init__()
        self.mode = 'idle'
        self.context = context
Maxime Perrotin's avatar
Maxime Perrotin committed
289
        self.allowed_symbols = ACTIONS[context]
Maxime Perrotin's avatar
Maxime Perrotin committed
290
291
292
293
294
295
296
297
298
299
300
301
302
        # 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
303
304
        self.setBackgroundBrush(QtGui.QBrush(
                                           QtGui.QImage(':icons/texture.png')))
Maxime Perrotin's avatar
Maxime Perrotin committed
305
306
        self.messages_window = None
        self.click_coordinates = None
307
        self.orig_pos = None
Maxime Perrotin's avatar
Maxime Perrotin committed
308
        self.process_name = 'opengeode'
Maxime Perrotin's avatar
Maxime Perrotin committed
309
310
        # Scene name is used to update the tab window name when scene changes
        self.name = ''
Maxime Perrotin's avatar
Maxime Perrotin committed
311
312
313
314
315
        # 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
316
317
        # Keep a list of composite states: {'stateName': SDL_Scene}
        self._composite_states = {}
Maxime Perrotin's avatar
Maxime Perrotin committed
318

Maxime Perrotin's avatar
Maxime Perrotin committed
319
320
321
    @property
    def visible_symb(self):
        ''' Return the visible items of a scene '''
Maxime Perrotin's avatar
Maxime Perrotin committed
322
323
324
325
326
327
328
329
        return (it for it in self.items() if it.isVisible() and
                isinstance(it, Symbol))

    @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
330

Maxime Perrotin's avatar
Maxime Perrotin committed
331
332
333
334
    @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
335

336
337
338
339
340
341
    @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))

Maxime Perrotin's avatar
Maxime Perrotin committed
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
    @property
    def states(self):
        ''' Return visible state components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, State))

    @property
    def texts(self):
        ''' Return visible text areas components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, TextSymbol))

    @property
    def procs(self):
        ''' Return visible procedure declaration components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, Procedure))

    @property
    def start(self):
        ''' Return visible start components of the scene '''
        return (it for it in self.visible_symb if isinstance(it, Start))

    @property
    def floating_labels(self):
        ''' Return visible floating label components of the scene '''
Maxime Perrotin's avatar
Maxime Perrotin committed
365
        return (it for it in self.floating_symb if isinstance(it, Label))
Maxime Perrotin's avatar
Maxime Perrotin committed
366
367
368
369
370
371
372
373
374
375

    @property
    def returns(self):
        ''' Return visible return components of the scene '''
        return (it for it in self.visible_symb if isinstance(it,
                                                              ProcedureStop))

    @property
    def composite_states(self):
        ''' Return states that contain a composite part '''
Maxime Perrotin's avatar
Maxime Perrotin committed
376
377
378
379
        # 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
380
                self._composite_states[unicode(each).split()[0].lower()] = \
Maxime Perrotin's avatar
Maxime Perrotin committed
381
                                                            each.nested_scene
Maxime Perrotin's avatar
Maxime Perrotin committed
382
383
384
385
        return self._composite_states

    @composite_states.setter
    def composite_states(self, value):
386
        ''' Attribute setter '''
Maxime Perrotin's avatar
Maxime Perrotin committed
387
388
389
390
391
392
        self._composite_states = value

    @property
    def all_nested_scenes(self):
        ''' Return all nested scenes, recursively '''
        for each in self.visible_symb:
393
            if each.nested_scene and isinstance(each.nested_scene, SDL_Scene):
Maxime Perrotin's avatar
Maxime Perrotin committed
394
395
396
                yield each.nested_scene
                for sub in each.nested_scene.all_nested_scenes:
                    yield sub
Maxime Perrotin's avatar
Maxime Perrotin committed
397

Maxime Perrotin's avatar
Maxime Perrotin committed
398
399
400
401
    def quit_scene(self):
        ''' Called in case of scene switch (e.g. UP button) '''
        pass

402
    def render_everything(self, ast):
Maxime Perrotin's avatar
Maxime Perrotin committed
403
404
        ''' Render a process and its children scenes, recursively '''
        def recursive_render(content, dest_scene):
405
406
407
408
            ''' 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
409

410
411
412
413
414
415
            try:
                # Render top-level items and their children:
                for each in Renderer.render(content, dest_scene):
                    G_SYMBOLS.add(each)
            except TypeError as err:
                LOG.error(traceback.format_exc())
Maxime Perrotin's avatar
Maxime Perrotin committed
416
417
418
419

            # Render nested scenes, recursively:
            for each in (item for item in dest_scene.visible_symb
                         if item.nested_scene):
420
421
422
423
424
                subscene = \
                        self.create_subscene(each.__class__.__name__.lower())
                #subscene = SDL_Scene(context=each.__class__.__name__.lower())
                #subscene.messages_window = self.messages_window
                subscene.name = unicode(each)
Maxime Perrotin's avatar
Maxime Perrotin committed
425
426
427
428
429
430
                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
431
432
433
                if unicode(each).lower() in \
                        dest_scene.composite_states.viewkeys() and not \
                        each.nested_scene:
Maxime Perrotin's avatar
Maxime Perrotin committed
434
                    each.nested_scene = dest_scene.composite_states[
Maxime Perrotin's avatar
Maxime Perrotin committed
435
                                                         unicode(each).lower()]
Maxime Perrotin's avatar
Maxime Perrotin committed
436

437
        recursive_render(ast, self)
Maxime Perrotin's avatar
Maxime Perrotin committed
438
439
440

    def refresh(self):
        ''' Refresh the symbols and connections in the scene '''
Maxime Perrotin's avatar
Maxime Perrotin committed
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
        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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488

    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

    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

Maxime Perrotin's avatar
Maxime Perrotin committed
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
    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
            return
        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:
            item.moveBy(delta_x, delta_y)
        return delta_x, delta_y

Maxime Perrotin's avatar
Maxime Perrotin committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
    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

    def set_selection(self, toolbar):
        ''' When the selection has changed, update menu, etc '''
        toolbar.update_menu(self)
        for item in self.selected_symbols():
            item.grabber.display()

    def raise_syntax_errors(self, errors=None):
        ''' Display an syntax error pop-up message '''
        if not errors:
            return
        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_()

Maxime Perrotin's avatar
Maxime Perrotin committed
548
549
550
551
552
553
554
555
556
557
558
559
560
    def check_syntax(self, symbol):
        ''' Create PR representation for a symbol and check its syntax '''
        pr_text = '\n'.join(Pr.generate(symbol, recursive=False))
        errors = symbol.check_syntax(pr_text)
        self.raise_syntax_errors(errors)

    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,
                                        nextstate=False))
        symbol.update_completion_list(pr_text=pr_text)

Maxime Perrotin's avatar
Maxime Perrotin committed
561
562
563
564
565
    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
566
            if re.search(pattern, unicode(item), flags=re.IGNORECASE):
Maxime Perrotin's avatar
Maxime Perrotin committed
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
                yield item.parentItem()

    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
583
                                        unicode(item.text),
Maxime Perrotin's avatar
Maxime Perrotin committed
584
585
                                        flags=re.IGNORECASE)
                    undo_cmd = undoCommands.ReplaceText(
Maxime Perrotin's avatar
Maxime Perrotin committed
586
                                     item.text, unicode(item.text), new_string)
Maxime Perrotin's avatar
Maxime Perrotin committed
587
588
589
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
                    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')

    def show_item(self, item):
        '''
            Select an item and make sure it is visible
            (used when user clicks on a warning or error to locate the symbol)
        '''
        abs_coordinates = item.data(Qt.UserRole)
        if not abs_coordinates:
            LOG.info('Corresponding symbol not found')
            return
        item = self.itemAt(*abs_coordinates)
        if item:
            self.clearSelection()
            self.clear_focus()
            item.setSelected(True)
            item.ensureVisible()

    def delete_selected_symbols(self):
        '''
            Remove selected symbols from the scene, with proper re-connections
        '''
        self.undo_stack.beginMacro('Delete items')
        for item in self.selected_symbols():
            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()

    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:
            Clipboard.copy(self.selected_symbols())
        except TypeError as error_msg:
            try:
643
                self.messages_window.addItem(unicode(error_msg))
Maxime Perrotin's avatar
Maxime Perrotin committed
644
            except AttributeError:
645
                LOG.error(unicode(error_msg))
Maxime Perrotin's avatar
Maxime Perrotin committed
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
            raise

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

    def paste_symbols(self):
        '''
            Paste previously copied symbols at selection point
        '''
        parent = list(self.selected_symbols())
        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:
672
673
674
675
676
                LOG.error(str(error_msg))
                try:
                    self.messages_window.addItem(str(error_msg))
                except AttributeError:
                    pass
Maxime Perrotin's avatar
Maxime Perrotin committed
677
678
679
680
            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
681
                    # Same for decision answers and connections
Maxime Perrotin's avatar
Maxime Perrotin committed
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
                    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()

    def sdl_to_statechart(self):
        ''' Create a graphviz representation of the SDL model '''
Maxime Perrotin's avatar
Maxime Perrotin committed
701
        pr_raw = Pr.parse_scene(self)
Maxime Perrotin's avatar
Maxime Perrotin committed
702
        pr_data = unicode('\n'.join(pr_raw))
703
704
705
706
707
        ast, _, _ = ogParser.parse_pr(string=pr_data)
        try:
            process_ast, = ast.processes
        except ValueError:
            LOG.error('No statechart to render')
708
709
710
711
            return None
        # Flatten nested states
        Helper.flatten(process_ast)
        return Statechart.create_dot_graph(process_ast)
Maxime Perrotin's avatar
Maxime Perrotin committed
712
713
714

    def export_branch_to_picture(self, symbol, filename, doc_format):
        ''' Save a symbol and its followers to a file '''
715
        temp_scene = SDL_Scene(context=self.context)
Maxime Perrotin's avatar
Maxime Perrotin committed
716
        temp_scene.messages_window = self.messages_window
Maxime Perrotin's avatar
Maxime Perrotin committed
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
        self.clearSelection()
        symbol.select()
        try:
            self.copy_selected_symbols()
            temp_scene.paste_symbols()
            temp_scene.export_img(filename, doc_format)
        except AttributeError:
            pass

    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
737
            for item in self.floating_symb:
738
                name = '{}-{}'.format(filename, str(index))
739
                LOG.info('Saving {ext} file: {name}.{ext}'
740
741
                         .format(ext=doc_format, name=name))
                self.export_branch_to_picture(item, name, doc_format)
Maxime Perrotin's avatar
Maxime Perrotin committed
742
743
744
745
746
747
748
                index += 1

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

        self.clearSelection()
        self.clear_focus()
Maxime Perrotin's avatar
Maxime Perrotin committed
749
        # Copy in a different scene to get the smallest rectangle
750
        other_scene = SDL_Scene(context=self.context)
Maxime Perrotin's avatar
Maxime Perrotin committed
751
752
753
754
        other_scene.messages_window = self.messages_window
        other_scene.setBackgroundBrush(QtGui.QBrush())
        for each in self.floating_symb:
            each.select()
755
756
757
            try:
                self.copy_selected_symbols()
            except AttributeError as err:
758
                LOG.debug(str(traceback.format_exc()))
759
                LOG.error(str(err))
Maxime Perrotin's avatar
Maxime Perrotin committed
760
761
762
763
            other_scene.paste_symbols()
            each.select(False)
        rect = other_scene.sceneRect()

Maxime Perrotin's avatar
Maxime Perrotin committed
764
765
766
767
        # 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
768
                                  QtGui.QImage.Format_ARGB32)
Maxime Perrotin's avatar
Maxime Perrotin committed
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
            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
785
        other_scene.render(painter, source=rect)
Maxime Perrotin's avatar
Maxime Perrotin committed
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
        try:
            device.save(filename)
        except AttributeError:
            # Due to inconsistencies in Qt API - only QtGui.QImage has the save
            pass
        if painter.isActive():
            painter.end()

    def clear_focus(self):
        ''' Clear focus from any item on the scene '''
        try:
            self.focusItem().clearFocus()
        except AttributeError:
            # if no focus item
            pass

    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

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

    # pylint: disable=C0103
    def mousePressEvent(self, event):
        '''
            Handle mouse click on the scene:
            If a symbol was selected in the menu, check if it can be inserted
            Otherwise store the coordinates, in which case if the user does
            a paste action with floating items, they will be placed there.
        '''
        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
849
            if isinstance(nearby_connection, Connection):
Maxime Perrotin's avatar
Maxime Perrotin committed
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
                # Click near a connection - forward the event to it
                # (some connections like statechart Edges can react)
                nearby_connection.mousePressEvent(event)
                connection_selected = True
            if not self.symbol_near(event.scenePos(), dist=1):
                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

        elif self.mode == 'wait_placement':
            try:
870
871
                parent = \
                        self.can_insert(event.scenePos(), self.button_selected)
Maxime Perrotin's avatar
Maxime Perrotin committed
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
            except TypeError as err:
                self.messages_window.addItem(str(err))
            else:
                with undoCommands.UndoMacro(self.undo_stack, 'Place Symbol'):
                    item = self.place_symbol(
                            item_type=self.button_selected,
                            parent=parent,
                            pos=event.scenePos() if not parent else None)
            # self.button_selected = None
            self.mode = 'idle'
        elif self.mode == 'wait_connection_source':
            # Check location, and if ok:
            self.mode = 'wait_next_connection_point'
            # if not OK, reset and:
            self.mode = 'idle'

    # pylint: disable=C0103
    def mouseMoveEvent(self, event):
        ''' Handle Click + Mouse move, based on the mode '''
        if event.buttons() == Qt.NoButton or self.mode == 'idle':
            return super(SDL_Scene, self).mouseMoveEvent(event)
        elif self.mode == 'select_items':
            rect = QRectF(self.orig_pos, event.scenePos())
            self.select_rect.setRect(rect.normalized())
        elif self.mode == 'wait_next_connection_point':
            # Update the line
            pass

    # pylint: disable=C0103
    def mouseReleaseEvent(self, event):
        if self.mode == 'select_items':
            for item in self.items(self.select_rect.rect().toRect(),
                    mode=Qt.ContainsItemBoundingRect):
                try:
                    item.select()
                except AttributeError:
                    pass
909
910
911
            #self.removeItem(self.select_rect)
            # XXX stop with removeItem, it provokes segfault
            self.select_rect.hide()
Maxime Perrotin's avatar
Maxime Perrotin committed
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
        self.mode = 'idle'
        super(SDL_Scene, self).mouseReleaseEvent(event)

    # pylint: disable=C0103
    def keyPressEvent(self, event):
        ''' Handle keyboard: Delete, Undo/Redo '''
        super(SDL_Scene, self).keyPressEvent(event)
        if event.matches(QtGui.QKeySequence.Delete) and self.selectedItems():
            self.delete_selected_symbols()
            self.clearSelection()
            self.clear_focus()
        elif event.matches(QtGui.QKeySequence.Undo):
            if not isinstance(self.focusItem(), EditableText):
                LOG.debug('UNDO ' + self.undo_stack.undoText())
                self.undo_stack.undo()
                self.clearSelection()
                self.refresh()
                # Emit a selection change to make sure the toolbar is updated
                # (e.g. when Undoing a Place START symbol)
                self.selectionChanged.emit()
                self.clear_focus()
        elif event.matches(QtGui.QKeySequence.Redo):
            if not isinstance(self.focusItem(), EditableText):
                LOG.debug('REDO ' + self.undo_stack.redoText())
                self.undo_stack.redo()
                self.clearSelection()
                self.refresh()
                self.clear_focus()
                # Emit a selection change to make sure the toolbar is updated
                self.selectionChanged.emit()
        elif event.matches(QtGui.QKeySequence.Copy):
            if not isinstance(self.focusItem(), EditableText):
                try:
                    self.copy_selected_symbols()
                except TypeError:
                    LOG.error('Cannot copy')
        elif event.matches(QtGui.QKeySequence.Cut):
            self.cut_selected_symbols()
        elif event.matches(QtGui.QKeySequence.Paste):
            if not isinstance(self.focusItem(), EditableText):
                self.paste_symbols()
                self.refresh()
                self.clear_focus()
        elif event.key() == Qt.Key_N:
            # n to select the next item in a search (vim mode)
            if self.focusItem():
                # Only active when no item has keyboard focus
                return
            try:
                self.clearSelection()
                item = self.search_item.next()
                item.select()
                item.ensureVisible()
            except StopIteration:
                LOG.info('No more matches')
                self.search(self.search_pattern)
            except AttributeError:
                LOG.info('No search pattern set. Use "/<pattern>"')
        elif (event.key() == Qt.Key_J and
                event.modifiers() == Qt.ControlModifier):
            # Debug mode
            for selection in self.selected_symbols():
Maxime Perrotin's avatar
Maxime Perrotin committed
974
                LOG.info(unicode(selection))
Maxime Perrotin's avatar
Maxime Perrotin committed
975
976
977
978
979
980
981
982
983
                LOG.info('Position: ' + str(selection.pos()))
                LOG.info('ScenePos: ' + str(selection.scenePos()))
                LOG.info('BoundingRect: ' + str(selection.boundingRect()))
                #LOG.info('ChildrenList: ' + str(selection.childItems()))
                LOG.info('ChildrenBoundingRect: ' +
                        str(selection.childrenBoundingRect()))
                pprint.pprint(selection.__dict__, None, 2, 1)
            code.interact('type your command:', local=locals())

984
985
986
987
988
989
990
991

    def create_subscene(self, context):
        ''' Create a new SDL scene, e.g. for nested symbols '''
        subscene = SDL_Scene(context=context)
        subscene.messages_window = self.messages_window
        return subscene


Maxime Perrotin's avatar
Maxime Perrotin committed
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
    def place_symbol(self, item_type, parent, pos=None):
        ''' Draw a symbol on the scene '''
        item = item_type()
        # Add the item to the scene
        if item not in self.items():
            self.addItem(item)
        # Create Undo command (makes the call to the insertSymbol function):
        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)
1009
1010
1011
1012
        elif item_type in (Procedure, State, Process):
            # Create a sub-scene for clickable symbols
            item.nested_scene = \
                    self.create_subscene(item_type.__name__.lower())
Maxime Perrotin's avatar
Maxime Perrotin committed
1013
1014
1015
1016
1017
1018
1019
1020
1021

        self.clearSelection()
        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():
1022
            view.refresh()
Maxime Perrotin's avatar
Maxime Perrotin committed
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
            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
Maxime Perrotin's avatar
Maxime Perrotin committed
1042
            if item_type == Connection:
Maxime Perrotin's avatar
Maxime Perrotin committed
1043
1044
1045
1046
1047
1048
1049
1050
1051
                self.mode = 'wait_connection_source'
            else:
                self.mode = 'wait_placement'
            self.set_cursor(item_type)
            return None


class SDL_View(QtGui.QGraphicsView, object):
    ''' Main graphic view used to display the SDL scene and handle zoom '''
1052
1053
    # signal to ask the main application that a new scene is needed
    need_new_scene = QtCore.Signal()
Maxime Perrotin's avatar
Maxime Perrotin committed
1054

Maxime Perrotin's avatar
Maxime Perrotin committed
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
    def __init__(self, scene):
        ''' Create the SDL view holding the scene '''
        super(SDL_View, self).__init__(scene)
        self.wrapping_window = None
        self.messages_window = None
        self.mode = ''
        self.phantom_rect = None
        self.filename = ''
        self.orig_pos = None
        # mouse_pos is used to handle screen scrolling with middle mouse button
        self.mouse_pos = None
        # Up button allows to move from one scene to another
        self.up_button = None
        # Toolbar with the icons of the SDL symbols
        self.toolbar = None
        # Scene stack (used for nested symbols)
        self.parent_scene = []
        # Set of PR files that are not saved back (e.g. system structure)
        self.readonly_pr = None
        # Special scene for the Lander module
        self.lander_scene = SDL_Scene(context='lander')
        # Do not initialize the lander now - only if needed
        self.lander = None

    def set_toolbar(self):
        ''' Define the toolbar depending on the context '''
        self.toolbar.set_actions(
                bar_items=ACTIONS.get(self.scene().context, []))

        # Connect toolbar actions
        self.scene().selectionChanged.connect(partial(
                                    self.scene().set_selection, self.toolbar))
        for item in self.toolbar.actions.viewkeys():
            self.toolbar.actions[item].triggered.connect(
                                                   self.scene().actions[item])
        self.toolbar.update_menu(self.scene())

    # pylint: disable=C0103
    def keyPressEvent(self, event):
        ''' Handle keyboard: Zoom, open/save diagram, etc. '''
        if event.matches(QtGui.QKeySequence.ZoomOut):
            self.scale(0.8, 0.8)
        elif event.matches(QtGui.QKeySequence.ZoomIn):
            self.scale(1.2, 1.2)
        elif event.matches(QtGui.QKeySequence.Save):
            self.save_diagram()
        elif (event.key() == Qt.Key_G and
                event.modifiers() == Qt.ControlModifier):
            self.generate_ada()
        elif event.key() == Qt.Key_F7:
            self.check_model()
        elif event.key() == Qt.Key_F5:
            self.refresh()
1108
1109
1110
            # Refresh statechart
            if graphviz:
                Statechart.update(self.scene())
Maxime Perrotin's avatar
Maxime Perrotin committed
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
        elif event.matches(QtGui.QKeySequence.Open):
            self.open_diagram()
        elif event.matches(QtGui.QKeySequence.New):
            self.new_diagram()
        elif (event.key() == Qt.Key_F12 and
                event.modifiers() == Qt.ControlModifier and
                self.scene() != self.lander_scene):
            self.lander_scene.setSceneRect(0, 0, self.width(), self.height())
            if not self.lander:
                self.lander = Lander.Lander(self.lander_scene)
1121
1122
1123
            horpos = self.horizontalScrollBar().value()
            verpos = self.verticalScrollBar().value()
            self.parent_scene.append((self.scene(), horpos, verpos))
Maxime Perrotin's avatar
Maxime Perrotin committed
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
            self.scene().clear_focus()
            self.setScene(self.lander_scene)
            self.up_button.setEnabled(True)
            self.set_toolbar()
            self.lander.play()
        super(SDL_View, self).keyPressEvent(event)

    def refresh(self):
        ''' Refresh the complete view '''
        self.scene().refresh()
        self.setSceneRect(self.scene().sceneRect())
        self.viewport().update()

    # pylint: disable=C0103
    def resizeEvent(self, event):
        '''
           Called by Qt when window is resized
           Make sure that the scene that is displayed is at least
           of the size of the view, by drawing a transparent rectangle
           Otherwise, the scene is centered on the view, with the size
           of its bounding rect. This is nice in theory, except when
           the user wants to place a symbol at an exact position - in
           that case, the automatic centering is not appropriate.
        '''
        LOG.debug('resizing view')
        scene_rect = self.scene().itemsBoundingRect()
        view_size = self.size()
        scene_rect.setWidth(max(scene_rect.width(), view_size.width()))
        scene_rect.setHeight(max(scene_rect.height(), view_size.height()))
        if self.phantom_rect and self.phantom_rect in self.scene().items():
1154
1155
1156
            #self.scene().removeItem(self.phantom_rect)
            # XXX stop with removeItem, it provokes segfault
            self.phantom_rect.hide()
Maxime Perrotin's avatar
Maxime Perrotin committed
1157
1158
1159
1160
        self.phantom_rect = self.scene().addRect(scene_rect,
                pen=QtGui.QPen(QtGui.QColor(0, 0, 0, 0)))
        # Hide the rectangle so that it does not collide with the symbols
        self.phantom_rect.hide()
Maxime Perrotin's avatar
Maxime Perrotin committed
1161
        self.refresh()
Maxime Perrotin's avatar
Maxime Perrotin committed
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
        super(SDL_View, self).resizeEvent(event)

    def about_og(self):
        ''' Display the About dialog '''
        QtGui.QMessageBox.about(self, 'About OpenGEODE',
                'OpenGEODE - a tiny SDL editor for TASTE\n\n'
                'Author: \nMaxime Perrotin'
                '\n\nContact: maxime.perrotin@esa.int\n\n'
                'Coded with Pyside (Python + Qt)\n'
                'and ANTLR 3.1.3 for Python (parser)')

    # pylint: disable=C0103
    def wheelEvent(self, wheelEvent):
        '''
            Catch the mouse Wheel event
        '''
        if wheelEvent.modifiers() == Qt.ControlModifier:
            # Google-Earth zoom mode (Zoom with center on the mouse position)
            self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
            if wheelEvent.delta() < 0:
                self.scale(0.9, 0.9)
            else:
                self.scale(1.1, 1.1)
            self.setTransformationAnchor(QtGui.QGraphicsView.AnchorViewCenter)
        else:
1187
            return super(SDL_View, self).wheelEvent(wheelEvent)
Maxime Perrotin's avatar
Maxime Perrotin committed
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202

    # pylint: disable=C0103
    def mousePressEvent(self, evt):
        '''
            Catch mouse press event to move (when middle button is clicked)
            or to select multiple items
        '''
        # First propagate the click (then scene will receive it first):
        super(SDL_View, self).mousePressEvent(evt)
        self.mouse_pos = evt.pos()
        if evt.button() == Qt.MidButton:
            self.mode = 'moveScreen'

    def go_up(self):
        '''
1203
            When Up button is clicked, go up one nested scene level
Maxime Perrotin's avatar
Maxime Perrotin committed
1204
1205
1206
1207
1208
        '''
        LOG.debug('GO_UP')
        self.scene().clear_focus()
        # Scene may need to be informed when it is left:
        self.scene().scene_left.emit()
1209
1210
        scene, horpos, verpos = self.parent_scene.pop()
        self.setScene(scene)
Maxime Perrotin's avatar
Maxime Perrotin committed
1211
        self.wrapping_window.setWindowTitle(self.scene().name)
1212
1213
        self.horizontalScrollBar().setSliderPosition(horpos)
        self.verticalScrollBar().setSliderPosition(verpos)
Maxime Perrotin's avatar
Maxime Perrotin committed
1214
1215
1216
1217
        self.set_toolbar()
        if not self.parent_scene:
            self.up_button.setEnabled(False)
        self.refresh()
1218
1219
        self.horizontalScrollBar().setSliderPosition(horpos)
        self.verticalScrollBar().setSliderPosition(verpos)
Maxime Perrotin's avatar
Maxime Perrotin committed
1220

Maxime Perrotin's avatar
Maxime Perrotin committed
1221
    def go_down(self, scene, name=''):
1222
        ''' Enter a nested diagram (procedure, composite state) '''
1223
1224
        horpos = self.horizontalScrollBar().value()
        verpos = self.verticalScrollBar().value()
Maxime Perrotin's avatar
Maxime Perrotin committed
1225
        self.scene().name = self.wrapping_window.windowTitle()
1226
        self.parent_scene.append((self.scene(), horpos, verpos))
1227
1228
        self.scene().clear_focus()
        self.setScene(scene)
Maxime Perrotin's avatar
Maxime Perrotin committed
1229
1230
        self.scene().name = name + '[*]'
        self.wrapping_window.setWindowTitle(self.scene().name)
1231
1232
1233
1234
1235
        self.up_button.setEnabled(True)
        self.set_toolbar()
        self.scene().scene_left.emit()
        self.refresh()

Maxime Perrotin's avatar
Maxime Perrotin committed
1236
1237
1238
1239
1240
1241
1242
    # pylint: disable=C0103
    def mouseDoubleClickEvent(self, evt):
        ''' Catch a double click - possibly change the scene '''
        super(SDL_View, self).mouseDoubleClickEvent(evt)
        if evt.button() == Qt.LeftButton:
            item = self.scene().symbol_near(self.mapToScene(evt.pos()))
            try:
1243
                if item.allow_nesting:
Maxime Perrotin's avatar
Maxime Perrotin committed
1244
                    item.double_click()
Maxime Perrotin's avatar
Maxime Perrotin committed
1245
                    ctx = unicode(item.__class__.__name__.lower())
Maxime Perrotin's avatar
Maxime Perrotin committed
1246
                    if not isinstance(item.nested_scene, SDL_Scene):
1247
1248
                        item.nested_scene = \
                                self.scene().create_subscene(context=ctx)
Maxime Perrotin's avatar
Maxime Perrotin committed
1249
1250
                    self.go_down(item.nested_scene,
                                 name=ctx + u' ' + unicode(item))
Maxime Perrotin's avatar
Maxime Perrotin committed
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
                else:
                    # Otherwise, double-click edits the item text
                    item.edit_text(self.mapToScene(evt.pos()))
            except AttributeError:
                LOG.debug('Ignoring double click')

    # pylint: disable=C0103
    def mouseMoveEvent(self, evt):
        ''' Handle the screen move when user clicks '''
        if evt.buttons() == Qt.NoButton:
            return super(SDL_View, self).mouseMoveEvent(evt)
        new_pos = evt.pos()
        if self.mode == 'moveScreen':
            diff_x = self.mouse_pos.x() - new_pos.x()
            diff_y = self.mouse_pos.y() - new_pos.y()
            h_scroll = self.horizontalScrollBar()
            v_scroll = self.verticalScrollBar()
            h_scroll.setValue(h_scroll.value() + diff_x)
            v_scroll.setValue(v_scroll.value() + diff_y)
            self.mouse_pos = new_pos
        else:
            return super(SDL_View, self).mouseMoveEvent(evt)

    # pylint: disable=C0103
    def mouseReleaseEvent(self, evt):
        self.mode = ''
1277
1278
1279
        # Adjust scrollbars if diagram got bigger due to a move
        if self.scene().context != 'statechart':
            # Make sure scene size remains OK when adding/moving symbols
1280
1281
1282
1283
            # Avoid doing it when editing texts - it would prevent text
            # selection or cursor move
            if not isinstance(self.scene().focusItem(), EditableText):
                self.refresh()
Maxime Perrotin's avatar
Maxime Perrotin committed
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
        super(SDL_View, self).mouseReleaseEvent(evt)

    def save_as(self):
        ''' Save As function '''
        self.save_diagram(save_as=True)

    def save_diagram(self, save_as=False, autosave=False):
        ''' Save the diagram to a .pr file '''
        if (not self.filename or save_as) and not autosave:
            self.filename = QtGui.QFileDialog.getSaveFileName(
                    self, "Save model", ".", "SDL Model (*.pr)")[0]
        if self.filename and self.filename.split('.')[-1] != 'pr':
            self.filename += ".pr"
        filename = (
                (self.filename or '_opengeode')
                + '.autosave') if autosave else self.filename
        if not filename and not autosave:
            return False
        else:
            pr_file = QFile(filename)
            pr_file.open(QIODevice.WriteOnly | QIODevice.Text)
            if not autosave:
                self.scene().process_name = ''.join(filename
                        .split(os.path.extsep)[0:-1]).split(os.path.sep)[-1]
                self.wrapping_window.setWindowTitle(
                        'process ' + self.scene().process_name + '[*]')
        # If the current scene is a nested one, save the top parent
        if self.parent_scene:
1312
            scene = self.parent_scene[0][0]
Maxime Perrotin's avatar
Maxime Perrotin committed
1313
1314
        else:
            scene = self.scene()
Maxime Perrotin's avatar
Maxime Perrotin committed
1315
1316
1317
1318
1319
        # Translate scenes to avoid negative coordinates
        for each in scene.all_nested_scenes:
            each.translate_to_origin()
        delta_x, delta_y = scene.translate_to_origin()

Maxime Perrotin's avatar
Maxime Perrotin committed
1320
        pr_raw = Pr.parse_scene(scene)
Maxime Perrotin's avatar
Maxime Perrotin committed
1321
1322
1323
1324
1325

        # Move items back to original place to avoid scrollbar jumps
        for item in scene.floating_symb:
            item.moveBy(-delta_x, -delta_y)

Maxime Perrotin's avatar
Maxime Perrotin committed
1326
        pr_data = unicode('\n'.join(pr_raw))
Maxime Perrotin's avatar
Maxime Perrotin committed
1327
        try:
Maxime Perrotin's avatar
Maxime Perrotin committed
1328
            pr_file.write(pr_data.encode('utf-8'))
Maxime Perrotin's avatar
Maxime Perrotin committed
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
            pr_file.close()
            if not autosave:
                self.scene().clear_focus()
                self.scene().undo_stack.setClean()
            else:
                LOG.debug('Auto-saving backup file completed:' + filename)
            return True
        except AttributeError:
            LOG.error('Impossible to save the file')
            return False

    def save_png(self):
        ''' Save the current view as a PNG image '''
        filename = QtGui.QFileDialog.getSaveFileName(
                self, "Save picture", ".", "Image (*.png)")[0]
        self.scene().export_img(filename, doc_format='png')

    def load_file(self, files):
        ''' Parse a PR file and render it on the scene '''
        try:
            ast, warnings, errors = ogParser.parse_pr(files=files)
        except IOError:
            LOG.error('Aborting: could not open or parse input file')
            return
        try:
            process, = ast.processes
            self.filename = process.filename
            self.readonly_pr = ast.pr_files - {self.filename}
        except ValueError:
            LOG.error('Cannot load more than one process at a time')
            return
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
        try:
            syst, = ast.systems
            block, = syst.blocks
            if block.processes[0].referenced:
                LOG.debug('Process is referenced, fixing')
                block.processes = [process]
        except ValueError:
            # No System/Block hierarchy, creating single block
            block = ogAST.Block()
            block.processes = [process]
Maxime Perrotin's avatar
Maxime Perrotin committed
1370
1371
1372
        LOG.debug('Parsing complete. Summary, found ' + str(len(warnings)) +
                ' warnings and ' + str(len(errors)) + ' errors')
        self.log_errors(errors, warnings)
1373
1374
1375
1376
        self.scene().render_everything(block)
        self.toolbar.update_menu(self.scene())
        self.wrapping_window.setWindowTitle('block ' +
                                            process.processName + '[*]')
Maxime Perrotin's avatar
Maxime Perrotin committed
1377
1378
1379
1380
1381
1382
1383
        self.refresh()
        self.centerOn(self.sceneRect().topLeft())
        self.scene().undo_stack.clear()
        return ast

    def open_diagram(self):
        ''' Load one or several .pr file and display the state machine '''
1384
1385
1386
1387
1388
1389
1390
1391
1392
        if not self.new_diagram():
            return
        filenames, _ = QtGui.QFileDialog.getOpenFileNames(self,
                "Open model(s)", ".", "SDL model (*.pr)")
        if not filenames:
            return
        else:
            self.load_file(filenames)

1393
    def is_model_clean(self):
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
        ''' Check recursively if anything has changed in any scene '''
        if self.parent_scene:
            scene = self.parent_scene[0][0]
        else:
            scene = self.scene()
        for each in chain([scene], scene.all_nested_scenes):
            if not each.undo_stack.isClean():
                return False
        return True

    def propose_to_save(self):
        ''' Display a dialog to let the user save his diagram '''
        msg_box = QtGui.QMessageBox(self)
        msg_box.setWindowTitle('OpenGEODE')
        msg_box.setText("The model has been modified.")
        msg_box.setInformativeText("Do you want to save your changes?")
        msg_box.setStandardButtons(QtGui.QMessageBox.Save |
                QtGui.QMessageBox.Discard |
                QtGui.QMessageBox.Cancel)
        msg_box.setDefaultButton(QtGui.QMessageBox.Save)
        ret = msg_box.exec_()
        if ret == QtGui.QMessageBox.Save:
            if not self.save_diagram():
                return False
        elif ret == QtGui.QMessageBox.Cancel:
            return False
        return True
Maxime Perrotin's avatar
Maxime Perrotin committed
1421
1422
1423

    def new_diagram(self):
        ''' If model state is clean, reset current diagram '''
1424
        if not self.is_model_clean():
Maxime Perrotin's avatar
Maxime Perrotin committed
1425
            # If changes occured since last save, pop up a window
1426
            if not self.propose_to_save():
Maxime Perrotin's avatar
Maxime Perrotin committed
1427
                return False
1428
1429
        self.need_new_scene.emit()
        self.parent_scene = []
Maxime Perrotin's avatar
Maxime Perrotin committed
1430
        self.scene().undo_stack.clear()
1431
        #self.scene().clear()
Maxime Perrotin's avatar
Maxime Perrotin committed
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
        G_SYMBOLS.clear()
        self.scene().process_name = ''
        self.filename = None
        self.readonly_pr = None
        self.wrapping_window.setWindowTitle('process[*]')
        self.set_toolbar()
        return True

    def log_errors(self, errors, warnings):
        ''' Report Error and Warnings on the console and in the log window '''
        if self.messages_window:
            self.messages_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
1448
                error[0] = 'Internal error - ' + str(error[0])
Maxime Perrotin's avatar
Maxime Perrotin committed
1449
1450
1451
1452
1453
1454
1455
1456
            LOG.error(error[0])
            item = QtGui.QListWidgetItem(u'[ERROR] ' + error[0])
            if len(error) == 2:
                item.setData(Qt.UserRole, error[1])
            if self.messages_window:
                self.messages_window.addItem(item)
        for warning in warnings:
            LOG.warning(warning[0])
1457
            item = QtGui.QListWidgetItem(u'[WARNING] ' + str(warning[0]))
Maxime Perrotin's avatar
Maxime Perrotin committed
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
            if len(warning) == 2:
                item.setData(Qt.UserRole, warning[1])
            if self.messages_window:
                self.messages_window.addItem(item)
        if not errors and not warnings and self.messages_window:
            self.messages_window.addItem('No errors, no warnings!')

    def check_model(self):
        ''' Parse the model and check for warnings and errors '''
        # If the current scene is a nested one, save the top parent
        if self.parent_scene:
1469
            scene = self.parent_scene[0][0]
Maxime Perrotin's avatar
Maxime Perrotin committed
1470
1471
        else:
            scene = self.scene()
Maxime Perrotin's avatar
Maxime Perrotin committed
1472
        pr_raw = Pr.parse_scene(scene)
Maxime Perrotin's avatar
Maxime Perrotin committed
1473
        pr_data = unicode('\n'.join(pr_raw))
Maxime Perrotin's avatar
Maxime Perrotin committed
1474
1475
1476
1477
1478
1479
1480
1481
1482
        if pr_data:
            _, warnings, errors = ogParser.parse_pr(files=self.readonly_pr,
                                                    string=pr_data)
            self.log_errors(errors, warnings)

    def generate_ada(self):
        ''' Generate Ada code '''
        # If the current scene is a nested one, save the top parent
        if self.parent_scene:
1483
            scene = self.parent_scene[0][0]
Maxime Perrotin's avatar
Maxime Perrotin committed
1484
1485
        else:
            scene = self.scene()
Maxime Perrotin's avatar
Maxime Perrotin committed
1486
        pr_raw = Pr.parse_scene(scene)
Maxime Perrotin's avatar
Maxime Perrotin committed
1487
        pr_data = unicode('\n'.join(pr_raw))
Maxime Perrotin's avatar
Maxime Perrotin committed
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
        if pr_data:
            ast, warnings, errors = ogParser.parse_pr(files=self.readonly_pr,
                                                      string=pr_data)
            process, = ast.processes
            self.log_errors(errors, warnings)
            if len(errors) > 0:
                self.messages_window.addItem(
                        'Aborting: too many errors to generate code')
            else:
                self.messages_window.addItem('Generating Ada code')
                try:
                    AdaGenerator.generate(process)
                    self.messages_window.addItem('Done')
                except (TypeError, ValueError, NameError) as err:
                    self.messages_window.addItem(
                            'Code generation failed:' + str(err))
                    LOG.error(str(traceback.format_exc()))


class OG_MainWindow(QtGui.QMainWindow, object):
    ''' Main GUI window '''
    def __init__(self, parent=None):
        ''' Create the main window '''
        super(OG_MainWindow, self).__init__(parent)
        self.view = None
        self.scene = None
        self.statechart_view = None
        self.statechart_scene = None
        self.vi_bar = Vi_bar()
1517
1518
1519
1520
        # Docking areas
        self.datatypes_view = None
        self.datatypes_scene = None
        self.asn1_area = None
Maxime Perrotin's avatar
Maxime Perrotin committed
1521

1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
    def new_scene(self):
        ''' Create a new, clean SDL scene. This function is necessary because
        it is not possible to use QGraphicsScene.clear(), because of Pyside
        bugs with deletion of items on application exit '''
        self.scene = SDL_Scene(context='block')
        if self.view:
            self.scene.messages_window = self.view.messages_window
            self.view.setScene(self.scene)
            self.view.refresh()

Maxime Perrotin's avatar
Maxime Perrotin committed
1532
1533
1534
    def start(self, file_name):
        ''' Initializes all objects to start the application '''
        # Create a graphic scene: the main canvas
1535
        self.new_scene()
Maxime Perrotin's avatar
Maxime Perrotin committed
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
        # Find SDL_View widget
        self.view = self.findChild(SDL_View, 'graphicsView')
        self.view.setScene(self.scene)

        # Find Menu Actions
        open_action = self.findChild(QtGui.QAction, 'actionOpen')
        new_action = self.findChild(QtGui.QAction, 'actionNew')
        save_action = self.findChild(QtGui.QAction, 'actionSave')
        save_as_action = self.findChild(QtGui.QAction, 'actionSaveAs')
        quit_action = self.findChild(QtGui.QAction, 'actionQuit')
        check_action = self.findChild(QtGui.QAction, 'actionCheck_model')
        about_action = self.findChild(QtGui.QAction, 'actionAbout')
        ada_action = self.findChild(QtGui.QAction, 'actionGenerate_Ada_code')
        png_action = self.findChild(QtGui.QAction, 'actionExport_to_PNG')

        # Connect menu actions
        open_action.activated.connect(self.view.open_diagram)
        save_action.activated.connect(self.view.save_diagram)
        save_as_action.activated.connect(self.view.save_as)
        quit_action.activated.connect(self.close)
        new_action.activated.connect(self.view.new_diagram)
        check_action.activated.connect(self.view.check_model)
        about_action.activated.connect(self.view.about_og)
        ada_action.activated.connect(self.view.generate_ada)
        png_action.activated.connect(self.view.save_png)

1562
1563
1564
        # Connect signal to let the view request a new scene
        self.view.need_new_scene.connect(self.new_scene)

Maxime Perrotin's avatar
Maxime Perrotin committed
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
        # Add a toolbar widget (not in .ui file due to pyside bugs)
        toolbar = Sdl_toolbar(self)

        # Associate the toolbar to the scene
        self.view.toolbar = toolbar

        # Set initial toolbar to the PROCESS editor
        self.view.set_toolbar()

        self.addToolBar(Qt.LeftToolBarArea, toolbar)

        # Add a toolbar with New/Open/Save/Check buttons
        filebar = File_toolbar(self)
        filebar.open_button.activated.connect(self.view.open_diagram)
        filebar.new_button.activated.connect(self.view.new_diagram)
        filebar.check_button.activated.connect(self.view.check_model)
        filebar.save_button.activated.connect(self.view.save_diagram)
        self.view.up_button = filebar.up_button
        filebar.up_button.activated.connect(self.view.go_up)
        self.addToolBar(Qt.TopToolBarArea, filebar)

        self.scene.clearSelection()
        self.scene.clear_focus()

        # widget wrapping the view. We have to maximize it
        process_widget = self.findChild(QtGui.QWidget, 'process')
        process_widget.showMaximized()
        self.view.wrapping_window = process_widget
        self.scene.undo_stack.cleanChanged.connect(
                lambda x: process_widget.setWindowModified(not x))

        # get the messages list window (to display errors and warnings)
        # it is a QtGui.QListWidget
        msg_dock = self.findChild(QtGui.QDockWidget, 'msgDock')
        msg_dock.setWindowTitle('Use F7 to check the model')
        msg_dock.setStyleSheet('QDockWidget::title {background: lightgrey;}')
        messages = self.findChild(QtGui.QListWidget, 'messages')
        messages.addItem('Welcome to OpenGEODE.')
        self.view.messages_window = messages
        self.scene.messages_window = messages
        messages.itemClicked.connect(self.scene.show_item)

        statechart_dock = self.findChild(QtGui.QDockWidget, 'statechart_dock')
        #statechart_dock.setWindowTitle('Statechart view - F4 to update')
        if graphviz:
            self.statechart_view = self.findChild(SDL_View, 'statechart_view')
            self.statechart_scene = SDL_Scene(context='statechart')
            self.statechart_view.setScene(self.statechart_scene)
        else:
            statechart_dock.hide()

        # Set up the dock area to display the ASN.1 Data model
1617
        #asn1_dock = self.findChild(QtGui.QDockWidget, 'datatypes_dock')
Maxime Perrotin's avatar
Maxime Perrotin committed
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
        self.datatypes_view = self.findChild(SDL_View, 'datatypes_view')
        self.datatypes_scene = SDL_Scene(context='process')
        self.datatypes_view.setScene(self.datatypes_scene)
        self.asn1_area = sdlSymbols.ASN1Viewer()
        self.asn1_area.text.setPlainText('-- ASN.1 Data Types')
        self.asn1_area.text.try_resize()

        self.datatypes_scene.addItem(self.asn1_area)

        # Create a timer for periodically saving a backup of the model
        autosave = QTimer(self)
        autosave.timeout.connect(
                partial(self.view.save_diagram, autosave=True))
        autosave.start(60000)

        # Add a line editor on the status bar for the vim mode
        self.statusBar().addPermanentWidget(self.vi_bar)
        self.vi_bar.hide()
        self.vi_bar.editingFinished.connect(self.vi_bar.hide)
        self.vi_bar.returnPressed.connect(self.vi_command)

        # Display the view and the scene (allows size() to be up to date)
        self.show()

        if file_name:
            types = []
            ast = self.view.load_file(file_name)
            # Update the dock widget with ASN.1 files content
            try:
                for asn1file in ast.asn1_filenames:
                    with open(asn1file, 'r') as file_handler:
                        types.append('-- ' + asn1file)
                        types.append(file_handler.read())
                if types:
                    self.asn1_area.text.setPlainText('\n'.join(types))
1653
1654
1655
                    # ASN.1 text area is read-only:
                    self.asn1_area.text.setTextInteractionFlags(
                                            QtCore.Qt.TextBrowserInteraction)
Maxime Perrotin's avatar
Maxime Perrotin committed
1656
                    self.asn1_area.text.try_resize()
1657

1658
1659
1660
1661
            except IOError as err:
                LOG.warning('ASN.1 file(s) could not be loaded : ' + str(err))
            except AttributeError:
                LOG.warning('No AST, check input files')
Maxime Perrotin's avatar
Maxime Perrotin committed
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674

    def vi_command(self):
        '''
            Process a vi command as entered in the Vi command line
            Supported commands:
            :<w><q><!> (save, quit)
            /<search pattern>
            :%s/<search_patten>/<replace_with>/g
        '''
        command = self.vi_bar.text()
        # Match vi-like search and replace pattern (e.g. :%s,a,b,g)
        search = re.compile(r':%s(.)(.*)\1(.*)\1(.)')
        try:
1675
            _, pattern, new, _ = search.match(command).groups()
Maxime Perrotin's avatar
Maxime Perrotin committed
1676
1677
            LOG.debug('Replacing {this} with {that}'
                          .format(this=pattern, that=new))
1678
            self.view.scene().search(pattern, replace_with=new)
Maxime Perrotin's avatar
Maxime Perrotin committed
1679
1680
1681
        except AttributeError:
            if command.startswith('/') and len(command) > 1:
                LOG.debug('Searching for ' + command[1:])
1682
                self.view.scene().search(command[1:])
Maxime Perrotin's avatar
Maxime Perrotin committed
1683
1684
1685
1686
1687
1688
1689
1690
1691
            else:
                saveclose = re.compile(r':(w)?(q)?(!)?')
                try:
                    save, close_app, force = saveclose.match(command).groups()
                    if save:
                        saved = self.view.save_diagram()
                        if not saved and not force and close_app:
                            return
                    if force and close_app:
1692
                        self.view.scene().undo_stack.clear()
Maxime Perrotin's avatar
Maxime Perrotin committed
1693
1694
1695
1696
1697
1698
1699
1700
1701
                    if close_app:
                        self.close()
                except AttributeError:
                    pass

    # pylint: disable=C0103
    def keyPressEvent(self, key_event):
        ''' Handle keyboard: Statechart rendering '''
        if key_event.key() == Qt.Key_F4 and graphviz:
1702
1703
1704
1705
1706
            if self.view.parent_scene:
                scene = self.view.parent_scene[0][0]
            else:
                scene = self.view.scene()
            graph = scene.sdl_to_statechart()
Maxime Perrotin's avatar
Maxime Perrotin committed
1707
1708
            try:
                Statechart.render_statechart(self.statechart_scene, graph)
1709
                self.statechart_view.refresh()
Maxime Perrotin's avatar
Maxime Perrotin committed
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
            except (IOError, TypeError) as err:
                LOG.debug(str(err))
        elif key_event.key() == Qt.Key_Colon:
            self.vi_bar.show()
            self.vi_bar.setFocus()
            self.vi_bar.setText(':')
        elif key_event.key() == Qt.Key_Slash:
            self.vi_bar.show()
            self.vi_bar.setFocus()
            self.vi_bar.setText('/')
        super(OG_MainWindow, self).keyPressEvent(key_event)

    # pylint: disable=C0103
    def closeEvent(self, event):
        ''' Close main application '''
1725
        if not self.view.is_model_clean():
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
            if not self.view.propose_to_save():
                event.ignore()
                return
        # Clear the list of top-level symbols to avoid possible exit-crash
        # due to pyside badly handling items that are not part of any scene
        G_SYMBOLS.clear()
        # Also clear undo stack that may keep reference to items
        self.scene.undo_stack.clear()
        LOG.debug('Bye bye!')