mscdocument.py 16.2 KB
Newer Older
Maxime Perrotin's avatar
Maxime Perrotin committed
1 2 3 4 5 6 7 8 9
# -*- coding: utf-8 -*-
#******************************************************************************
#
# TASTE Msc Diagram Editor
# http://taste.tuxfamily.org/
#
#  This file is part of TASTE Msc Editor.
#
#  TASTE Msc Diagram Editor is free software: you can redistribute it and/or
10
#  modify it under the terms of the GNU Lesser General Public License as published
Maxime Perrotin's avatar
Maxime Perrotin committed
11 12 13 14 15 16
#  by the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  TASTE Msc Diagram Editor is distributed in the hope that it will be
#  useful,(but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
#  GNU Lesser General Public License for more details.
Maxime Perrotin's avatar
Maxime Perrotin committed
18
#
19
#  You should have received a copy of the GNU Lesser General Public License
Maxime Perrotin's avatar
Maxime Perrotin committed
20 21 22 23 24
#  along with TASTE Msc Diagram Editor.  If not, see
#  <http://www.gnu.org/licenses/>.
#
#  Author: Angel Esquinas <aesquina@datsi.fi.upm.es>
#
25
#  Copyright (c) 2012 UPM and European Space Agency
Maxime Perrotin's avatar
Maxime Perrotin committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 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 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 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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 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 468 469 470 471 472 473 474 475 476 477 478 479 480 481
#
#******************************************************************************
U"""
The :class:`msccore.MscDocument` class is the

Class that override MscElement. This class represent the whole msc
document as described in ITU-T Z.120 recommendation. It saves all the *Message
Sequence Chart* information of the document.

:attr:`dataHasChanged` signal only is emitted when the changes are performed 
in internal data. These are the name, kind, qualifier... but no when new msc,
kind or msg are added or remove. For this purpose the document have the
:attr:`MscDocument.msgDeclChanged`, :attr:`MscDocument.instKindDeclChanged`
and :attr:`MscDocument.mscsChanged`
signals.

.. TODO:: Explain more of document, document if the principal element of pymsc.
"""
import logging
logger = logging.getLogger(__name__)

from types import BooleanType

from PySide.QtCore import Signal

from mscelement import MscElement
from msc import Msc


class MscDocument(MscElement):
    u"""
    :param unicode name: Name of document
    :param unicode kind: Kind of document
    :param unicode qualifier: Qualifier of document
    :param parent: Default `None`, parent of the object.
    :type parent: :class:`PySide.QtCore.QObject`

    Constructs a new :class:`~msccore.MscDocument`, and passes
    `parent` and `name` to :class:`~msccore.MscElement` ‘s
    constructor.
    """
    #: Constant with the name of the object
    TYPE = 'MscDocument'

    # Signal to
    msgDeclChanged = Signal()
    instKindsDeclChanged = Signal()
    mscsChanged = Signal()
    languageChanged = Signal()
    dataDefinitionChanged = Signal()

    modificationChanged = Signal(bool)
    """
    This signal is emitted whenever the content of the document changes in a
    way that affects the modification state. If changed is true, the document
    has been modified; otherwise it is false.
    """
    _modified = False

    def __init__(self, name, kind=u'', qualifier=u'', parent=None):
        u"""
        Create new document with name, kind and qualifier.
        """
        super(MscDocument, self).__init__(name, parent, self.TYPE)

        self._kind = kind
        self._qualifier = qualifier
        self._language = None
        self._dataDefinition = None
        self._modified = False

        # Mscs that make up the document
        self._mscs = []
        # Kinds used inside the document
        self.kindsUsed = []
        # Messages Declared Types
        self.messagesDeclUsed = []

    #**************************************************************************
    # Language and Data Definition
    #**************************************************************************
    def language(self):
        """
        Return the *data language* property of the document.
        If not set then return `None`.

        :rtype: unicode or `None`
        """

        return self._language

    def setLanguage(self, lang=None):
        """
        Set the *data language* of document.

        :param unicode lang: Default is `None`.

        The `lang` argument is the new value of language property.
        """
        self._language = lang
        self.dataChanged()
        self.languageChanged.emit()
        self._contentsChanged()

    def dataDefinition(self):
        u"""Return the value of `data definition` property.

        :rtype: unicode or `None`

        This property is conform to ITU-T Z.120 recommendation. This property
        save a `unicode` string with context of type references used in
        variables, wilcard timer and message declaration, according to the
        rules of the data language declared.
        """
        return self._dataDefinition

    def setDataDefinition(self, data=None):
        u"""
        Set *data definition* property value.

        :param unicode data: By default is None.

        This property is conform to ITU-T Z.120 recommendation. This property
        save a `unicode` string with context of type references used in
        variables, wilcard timer and message declaration, according to the
        rules of the data language declared.
        """
        self._dataDefinition = data
        self.dataChanged()
        self.dataDefinitionChanged.emit()
        self._contentsChanged()

    #**************************************************************************
    # MSCS
    #**************************************************************************
    def addMsc(self, msc):
        u"""
        Add the `msc` to the document.

        :param msc:
        :type msc: :class:`msccore.BasicMsc`
        :rtype: Boolean

        Return `False` if any problem occur when trying to add the `msc` to
        the document.

        This functions emit :attr:`mscsChanged` signal, if the `msc` is added.
        """
        if not isinstance(msc, Msc):
            logger.error("Impossible to add no msc object to document {dname}"
                         .format(dname=self.name()))
            return False

        # Setting the parent
        msc.setParent(self)
        self._mscs.append(msc)

        # Connect signals
        msc.contentsChanged.connect(self._contentsChanged)
        msc.deleted.connect(self.removeMsc)

        # self.elementAdded(msc)
        logger.debug("Added msc '%(mscname)s' to document '%(dname)s'",
                     {'mscname': msc.name(), 'dname': self.name()})

        # Emit signals to signal the changes
        self.mscsChanged.emit()
        self._contentsChanged()  # Call this function to advise of change

    def removeMsc(self, msc):
        u"""
        Remove the basic msc given in `msc`.

        :param msc: Msc object to remove from document.
        :type msc: :class:`MscDocument.BasicMsc`

        The :attr:`MsDocument.mscsChanged` signal is emmited if the basic msc
        given as `msc` is removed.
        """
        logger.debug("Removing msc '%(mscname)s' from document '%(dname)s'",
                     {'mscname': msc.name(), 'dname': self.name()})

        try:
            self._mscs.remove(msc)
        except ValueError:
            logger.error("Removing msc {msc} from document {dname}"
                         .format(msc=msc, dname=self.name()))
            return False

        # Disconnect signals
        msc.deleted.disconnect(self.removeMsc)
        msc.contentsChanged.disconnect(self._contentsChanged)

        # To know when mscs are added or removed from document
        self.mscsChanged.emit()
        self._contentsChanged()
        logger.debug("Finish removed")
        return True

    def mscs(self):
        u"""
        Return a list of the basic mscs included within document.

        :rtype: list<msccore.BasicMsc>

        """
        return self._mscs

    def deleteMscs(self):
        u"""
        Remove all basic msc's included within this document
        """
        for m in self._mscs:
            # First remove the msc as child
            self.removeMsc(m)
            # Then delete the msc
            m.delete()

    #**************************************************************************
    # Instance Kinds
    #**************************************************************************
    def addInstanceKind(self, instanceKind):
        u"""
        Add a new instance kind to this document.

        :param instanceKind: Instance Kind to add.
        :type instanceKind: msccore.MscInstanceKind
        :rtype: msccore.MscInstanceKind

        If the kind was added before to this document, then **instance kind**
        declared before is returned.
        """
        logger.debug("MscDocument: addInstanceKind: adding instance Kind: {}"
               .format(instanceKind))
        find = None
        for k in self.kindsUsed:
            if k == instanceKind:
                find = k
                break

        if find == None:
            self.kindsUsed.append(instanceKind)
            # Connect signals
            instanceKind.deleted.connect(self.removeInstanceKind)
            instanceKind.dataHasChanged.connect(self.instKindsDeclChanged)
            instanceKind.contentsChanged.connect(self._contentsChanged)
            find = instanceKind
            self.instKindsDeclChanged.emit()
            # Emit contents changed
            self._contentsChanged()
        return find

    def removeInstanceKind(self, kind):
        u"""
        Remove the **instance kind** given as `kind` from document.

        :param kind: Instance Kind object to remove from document.
        :type kind: msccore.MscInstanceKind
        :rtype: Boolean

        The :attr:`instKindsDeclChanged` signal is emmited if the *instance
        kind* given as `kind` argument is removed.
        """
        if self.kindsUsed.count(kind) == 0:
            #TODO: Communicate error by logger
            logger.error("Instance kind '%(kname)s' is not part of document "
                         "'%(dname)s'.", {'kname': kind.name(),
                                          'dname': self.name()})
            return False

        self.kindsUsed.remove(kind)
        # Disconnect 'deleted' signal from Instance Kind
        kind.deleted.disconnect(self.removeInstanceKind)
        kind.dataHasChanged.disconnect(self.instKindsDeclChanged)
        kind.contentsChanged.disconnect(self._contentsChanged)
        # Emit 'instanceKindsDeclChanged'
        self.instKindsDeclChanged.emit()
        # Contents are changed
        self._contentsChanged()

    def instanceKindsUsed(self):
        u"""
        Return a list with the *instance kinds* objects declared within
        this document.

        :rtype: list<msccore.MscInstanceKind>
        """
        return self.kindsUsed

    #**************************************************************************
    # Messages Declared
    #**************************************************************************
    def addMessageDecl(self, msg):
        u"""
        Add a new declaration of message *(type of message)* to this document.

        :param msg: Type of message to add.
        :type msg: msccore.MscMessageDecl
        :rtype: Boolean

        If the type of mesasge, given as argument, was added before to this
        document, then `False` is returned.

        :attr:`MscDocument.msgDeclChanged` is emitted if the operation was
        successful.
        """
        find = False
        for m in self.messagesDeclUsed:
            if m.name() == msg.name():  # Check if message is declared before
                logger.error("""Message '%(mname)s has been declared before """
                             """into '%(dname)s' msc document""",
                             {'mname': msg.name(), 'dname': self.name()})
                return False

        self.messagesDeclUsed.append(msg)
        msg.deleted.connect(self.removeMessageDecl)
        # To know when a msgDecl are change
        msg.dataHasChanged.connect(self.msgDeclChanged)
        msg.contentsChanged.connect(self._contentsChanged)

        self.msgDeclChanged.emit()
        # Contents are changed
        self._contentsChanged()
        return True

    def removeMessageDecl(self, msg):
        u"""
        Remove the `MessageDecl` *(type of message)* object given as `msg`
        from this document.

        :param msg: Message type to remove from this document.
        :type kind: msccore.MscMessageDecl
        :rtype: Boolean

        The :attr:`MscDocument.msgDeclChanged` signal is emmited if the 
        the message type given as argument is removed.
        """
        if self.messagesDeclUsed.count(msg) == 0:
            logger.error("Trying to remove message declaration '%s' that are "
                         "not associated with document '%s'", msg.name(),
                         self.name())
            return False
        self.messagesDeclUsed.remove(msg)
        # Disconnect 'deleted' signal from message decl
        msg.deleted.disconnect(self.removeMessageDecl)
        msg.dataHasChanged.disconnect(self.msgDeclChanged)
        msg.contentsChanged.disconnect(self._contentsChanged)
        # Emit 'msgDeclChanged'
        self.msgDeclChanged.emit()
        # Contents are changed
        self._contentsChanged()
        return True

    def messageDecl(self):
        u"""
        Return a list with message types *(:class:msccore.MscMessageDecl)*
        objects declared within this document.

        :rtype: list<msccore.MscMessageDecl>
        """
        return self.messagesDeclUsed

    #**************************************************************************
    # Document Control
    #**************************************************************************
    def isModified(self):
        u"""
        Return the **modified** propertie value.

        :rtype: Boolean

        The propertie **modified** holds the state modified of document.

        This function return `True` if the document is modified, if not return
        `False`.
        """
        return self._modified

    def setModified(self, state):
        u"""
        Set the modified propertie to 'mod' value. 

        :param Boolean state: New modified state of document.

        The propertie **modified** holds the state modified of document.

        If the state of the **modified** property change when call this
        funcition then :attr:`MscDocument.modificationChanged` signal is
        emitted with the new value.
        """
        if not isinstance(state, BooleanType):
            logger.error("")
            return False

        if state != self._modified:
            self._modified = state
            self.modificationChanged.emit(self._modified)

    def _contentsChanged(self):
        u""" Handler for content changed in document """
        self.setModified(True)

        # Emit contentsChanged signal because contents of document change
        self.contentsChanged.emit()

    #**************************************************************************
    # DELETE
    #**************************************************************************
    # Delete
    def delete(self):
        u"""
        Delete this document.

        .. note::
           After document is deleted, its reference are not valid. Its can not
           be used.
        """
        self.deleted.emit(self)
        self.deleteMscs()  # Remove the mscs included
        self.deleteLater()

    def accept(self, visitor):
        u"""
        Implementation of visitor pattern for :class:`msccore.MscDocument`.

        :param visitor:
        :type visitor: :class:`msccore.MscVisitor`

        This function call :meth:`msccore.MscVisitor.visitorMscDocument`.
        """
        visitor.visitorMscDocument(self)

    #**************************************************************************
    # Print/String functions
    #**************************************************************************

    def show(self, n=1):
        tab = ''
        i = 1
        while (i < n):
            tab = tab + '  '
            i = i + 1
        print tab + '{0}'.format(self)
        for k in self.instanceKindsUsed():
            print " {}".format(k)
        for i in self._mscs:
            i.show(n+1)

    def __str__(self):
        text = ("{2}: Name: {3}, Kind: {0}, Qualifier: {1}\n"
                "   Language {4}; data {5}\n"
                "   {6}"
                .format(self._kind, self._qualifier, self.TYPE, self.getName(),
                        self.language(), self.dataDefinition(),
                        '\n   '.join([str(x) for x in self.messagesDeclUsed])))
        return text