Bug Summary

File:OMEdit/OMEditLIB/Modeling/ModelWidgetContainer.cpp
Warning:line 8233, column 43
Called C++ object pointer is null

Annotated Source Code

[?] Use j/k keys for keyboard navigation

1/*
2 * This file is part of OpenModelica.
3 *
4 * Copyright (c) 1998-CurrentYear, Open Source Modelica Consortium (OSMC),
5 * c/o Linköpings universitet, Department of Computer and Information Science,
6 * SE-58183 Linköping, Sweden.
7 *
8 * All rights reserved.
9 *
10 * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
11 * THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
12 * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
13 * RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
14 * ACCORDING TO RECIPIENTS CHOICE.
15 *
16 * The OpenModelica software and the Open Source Modelica
17 * Consortium (OSMC) Public License (OSMC-PL) are obtained
18 * from OSMC, either from the above address,
19 * from the URLs: http://www.ida.liu.se/projects/OpenModelica or
20 * http://www.openmodelica.org, and in the OpenModelica distribution.
21 * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
22 *
23 * This program is distributed WITHOUT ANY WARRANTY; without
24 * even the implied warranty of MERCHANTABILITY or FITNESS
25 * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
26 * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
27 *
28 * See the full OSMC Public License conditions for more details.
29 *
30 */
31/*
32 * @author Adeel Asghar <adeel.asghar@liu.se>
33 */
34
35#include "Modeling/ModelWidgetContainer.h"
36#include "MainWindow.h"
37#include "LibraryTreeWidget.h"
38#include "ItemDelegate.h"
39#include "Options/OptionsDialog.h"
40#include "MessagesWidget.h"
41#include "DocumentationWidget.h"
42#include "Annotations/ShapePropertiesDialog.h"
43#include "Component/ComponentProperties.h"
44#include "Commands.h"
45#include "TLM/FetchInterfaceDataDialog.h"
46#include "Options/NotificationsDialog.h"
47#include "ModelicaClassDialog.h"
48#include "TLM/TLMCoSimulationDialog.h"
49#include "Git/GitCommands.h"
50#if !defined(WITHOUT_OSG)
51#include "Animation/ThreeDViewer.h"
52#endif
53#include "OMS/OMSProxy.h"
54#include "OMS/ModelDialog.h"
55#include "OMS/BusDialog.h"
56#include "OMS/SystemSimulationInformationDialog.h"
57#include "Util/ResourceCache.h"
58
59#include <QNetworkReply>
60#include <QMessageBox>
61#include <QMenu>
62#include <QMenuBar>
63#include <QGraphicsDropShadowEffect>
64#include <QButtonGroup>
65#include <QDockWidget>
66#include <QPrinter>
67#include <QPrintDialog>
68#include <QDesktopServices>
69#include <QClipboard>
70
71/*!
72 * \class GraphicsScene
73 * \brief The GraphicsScene class is a container for graphicsl components in a simulationmodel.
74 */
75/*!
76 * \brief GraphicsScene::GraphicsScene
77 * \param viewType
78 * \param pModelWidget
79 */
80GraphicsScene::GraphicsScene(StringHandler::ViewType viewType, ModelWidget *pModelWidget)
81 : QGraphicsScene(pModelWidget), mViewType(viewType)
82{
83 mpModelWidget = pModelWidget;
84}
85
86/*!
87 * \class GraphicsView
88 * \brief The GraphicsView class is a class which display the content of a scene of components.
89 */
90/*!
91 * \brief GraphicsView::GraphicsView
92 * \param viewType
93 * \param pModelWidget
94 * \param visualizationView
95 */
96GraphicsView::GraphicsView(StringHandler::ViewType viewType, ModelWidget *pModelWidget, bool visualizationView)
97 : QGraphicsView(pModelWidget), mViewType(viewType), mVisualizationView(visualizationView), mSkipBackground(false)
98{
99 /* Ticket #3275
100 * Set the scroll bars policy to always on to avoid unnecessary resize events.
101 */
102 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
103 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
104 setFrameShape(QFrame::StyledPanel);
105 setDragMode(QGraphicsView::RubberBandDrag);
106 setAcceptDrops(true);
107 setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
108 setMouseTracking(true);
109 mpModelWidget = pModelWidget;
110 // set the coOrdinate System
111 mCoOrdinateSystem = CoOrdinateSystem();
112 GraphicalViewsPage *pGraphicalViewsPage;
113 pGraphicalViewsPage = OptionsDialog::instance()->getGraphicalViewsPage();
114 QList<QPointF> extent;
115 qreal left = (mViewType == StringHandler::Icon) ? pGraphicalViewsPage->getIconViewExtentLeft() : pGraphicalViewsPage->getDiagramViewExtentLeft();
116 qreal bottom = (mViewType == StringHandler::Icon) ? pGraphicalViewsPage->getIconViewExtentBottom() : pGraphicalViewsPage->getDiagramViewExtentBottom();
117 qreal right = (mViewType == StringHandler::Icon) ? pGraphicalViewsPage->getIconViewExtentRight() : pGraphicalViewsPage->getDiagramViewExtentRight();
118 qreal top = (mViewType == StringHandler::Icon) ? pGraphicalViewsPage->getIconViewExtentTop() : pGraphicalViewsPage->getDiagramViewExtentTop();
119 extent << QPointF(left, bottom) << QPointF(right, top);
120 mCoOrdinateSystem.setExtent(extent);
121 mCoOrdinateSystem.setPreserveAspectRatio((mViewType == StringHandler::Icon) ? pGraphicalViewsPage->getIconViewPreserveAspectRation() : pGraphicalViewsPage->getDiagramViewPreserveAspectRation());
122 mCoOrdinateSystem.setInitialScale((mViewType == StringHandler::Icon) ? pGraphicalViewsPage->getIconViewScaleFactor() : pGraphicalViewsPage->getDiagramViewScaleFactor());
123 qreal horizontal = (mViewType == StringHandler::Icon) ? pGraphicalViewsPage->getIconViewGridHorizontal() : pGraphicalViewsPage->getDiagramViewGridHorizontal();
124 qreal vertical = (mViewType == StringHandler::Icon) ? pGraphicalViewsPage->getIconViewGridVertical() : pGraphicalViewsPage->getDiagramViewGridVertical();
125 mCoOrdinateSystem.setGrid(QPointF(horizontal, vertical));
126 setExtentRectangle(left, bottom, right, top);
127 scale(1.0, -1.0); // invert the drawing area.
128 setIsCustomScale(false);
129 setAddClassAnnotationNeeded(false);
130 setIsCreatingConnection(false);
131 setIsCreatingTransition(false);
132 mIsCreatingLineShape = false;
133 mIsCreatingPolygonShape = false;
134 mIsCreatingRectangleShape = false;
135 mIsCreatingEllipseShape = false;
136 mIsCreatingTextShape = false;
137 mIsCreatingBitmapShape = false;
138 mIsPanning = false;
139 mLastMouseEventPos = QPoint(0, 0);
140 mpClickedComponent = 0;
141 mpClickedState = 0;
142 setIsMovingComponentsAndShapes(false);
143 setRenderingLibraryPixmap(false);
144 mComponentsList.clear();
145 mOutOfSceneComponentsList.clear();
146 mConnectionsList.clear();
147 mOutOfSceneConnectionsList.clear();
148 mTransitionsList.clear();
149 mOutOfSceneTransitionsList.clear();
150 mInitialStatesList.clear();
151 mOutOfSceneInitialStatesList.clear();
152 mShapesList.clear();
153 mOutOfSceneShapesList.clear();
154 mInheritedComponentsList.clear();
155 mInheritedConnectionsList.clear();
156 mInheritedShapesList.clear();
157 mpConnectionLineAnnotation = 0;
158 mpTransitionLineAnnotation = 0;
159 mpLineShapeAnnotation = 0;
160 mpPolygonShapeAnnotation = 0;
161 mpRectangleShapeAnnotation = 0;
162 mpEllipseShapeAnnotation = 0;
163 mpTextShapeAnnotation = 0;
164 mpBitmapShapeAnnotation = 0;
165 createActions();
166 mAllItems.clear();
167}
168
169bool GraphicsView::isCreatingShape()
170{
171 return isCreatingLineShape() ||
172 isCreatingPolygonShape() ||
173 isCreatingRectangleShape() ||
174 isCreatingEllipseShape() ||
175 isCreatingBitmapShape() ||
176 isCreatingTextShape();
177}
178
179void GraphicsView::setExtentRectangle(qreal left, qreal bottom, qreal right, qreal top)
180{
181 mExtentRectangle = QRectF(left, bottom, fabs(left - right), fabs(bottom - top));
182 /* Ticket:4340 Extend vertical space
183 * Make the drawing area 25% bigger than the actual size. So we can better use the panning feature.
184 */
185 QRectF sceneRectangle(left * 1.5, bottom * 1.5, fabs(left - right) * 1.5, fabs(bottom - top) * 1.5);
186 setSceneRect(sceneRectangle);
187 centerOn(sceneRectangle.center());
188}
189
190void GraphicsView::setIsCreatingConnection(const bool enable)
191{
192 mIsCreatingConnection = enable;
193 setIsCreatingPrologue(enable);
194}
195
196void GraphicsView::setIsCreatingTransition(const bool enable)
197{
198 mIsCreatingTransition = enable;
199 setIsCreatingPrologue(enable);
200}
201
202void GraphicsView::setIsCreatingLineShape(const bool enable)
203{
204 mIsCreatingLineShape = enable;
205 setIsCreatingPrologue(enable);
206 updateUndoRedoActions(enable);
207}
208
209void GraphicsView::setIsCreatingPolygonShape(const bool enable)
210{
211 mIsCreatingPolygonShape = enable;
212 setIsCreatingPrologue(enable);
213 updateUndoRedoActions(enable);
214}
215
216void GraphicsView::setIsCreatingRectangleShape(const bool enable)
217{
218 mIsCreatingRectangleShape = enable;
219 setIsCreatingPrologue(enable);
220 updateUndoRedoActions(enable);
221}
222
223void GraphicsView::setIsCreatingEllipseShape(const bool enable)
224{
225 mIsCreatingEllipseShape = enable;
226 setIsCreatingPrologue(enable);
227 updateUndoRedoActions(enable);
228}
229
230void GraphicsView::setIsCreatingTextShape(const bool enable)
231{
232 mIsCreatingTextShape = enable;
233 setIsCreatingPrologue(enable);
234 updateUndoRedoActions(enable);
235}
236
237void GraphicsView::setIsCreatingBitmapShape(const bool enable)
238{
239 mIsCreatingBitmapShape = enable;
240 setIsCreatingPrologue(enable);
241 updateUndoRedoActions(enable);
242}
243
244void GraphicsView::setIsCreatingPrologue(const bool enable)
245{
246 setDragModeInternal(enable);
247 setItemsFlags(!enable);
248}
249
250void GraphicsView::setIsPanning(const bool enable)
251{
252 mIsPanning = enable;
253 setDragModeInternal(enable, true);
254 setItemsFlags(!enable);
255}
256
257void GraphicsView::setDragModeInternal(bool enable, bool updateCursor)
258{
259 if (enable) {
260 setDragMode(QGraphicsView::NoDrag);
261 if (updateCursor) {
262 viewport()->setCursor(Qt::ClosedHandCursor);
263 }
264 } else {
265 setDragMode(QGraphicsView::RubberBandDrag);
266 if (updateCursor) {
267 viewport()->unsetCursor();
268 }
269 }
270}
271
272void GraphicsView::setItemsFlags(bool enable)
273{
274 // set components, shapes and connection flags accordingly
275 foreach(Component *pComponent, mComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
276 pComponent->setComponentFlags(enable);
277 }
278 foreach(ShapeAnnotation *pShapeAnnotation, mShapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mShapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (ShapeAnnotation
*pShapeAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
279 pShapeAnnotation->setShapeFlags(enable);
280 }
281 foreach(LineAnnotation *pLineAnnotation, mConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pLineAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
282 pLineAnnotation->setShapeFlags(enable);
283 }
284}
285
286/*!
287 * \brief GraphicsView::updateUndoRedoActions
288 * Updates the Undo Redo actions depending shape(s) creation state.
289 * \param enable
290 */
291void GraphicsView::updateUndoRedoActions(bool enable)
292{
293 if (enable) {
294 MainWindow::instance()->getUndoAction()->setEnabled(!enable);
295 MainWindow::instance()->getRedoAction()->setEnabled(!enable);
296 } else {
297 mpModelWidget->updateUndoRedoActions();
298 }
299}
300
301bool GraphicsView::addComponent(QString className, QPointF position)
302{
303 MainWindow *pMainWindow = MainWindow::instance();
304 LibraryTreeItem *pLibraryTreeItem = pMainWindow->getLibraryWidget()->getLibraryTreeModel()->findLibraryTreeItem(className);
305 if (!pLibraryTreeItem) {
306 return false;
307 }
308 // if we are dropping something on meta-model editor then we can skip Modelica stuff.
309 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel) {
310 if (!pLibraryTreeItem->isSaved()) {
311 QMessageBox::information(pMainWindow, QString(Helper::applicationName).append(" - ").append(Helper::information),
312 tr("The class <b>%1</b> is not saved. You can only drag & drop saved classes.")
313 .arg(pLibraryTreeItem->getNameStructure()), Helper::ok);
314 return false;
315 } else {
316 // item not to be dropped on itself; if dropping an item on itself
317 if (isClassDroppedOnItself(pLibraryTreeItem)) {
318 return false;
319 }
320 QString name = getUniqueComponentName(StringHandler::toCamelCase(pLibraryTreeItem->getName()));
321 ComponentInfo *pComponentInfo = new ComponentInfo;
322 QFileInfo fileInfo(pLibraryTreeItem->getFileName());
323 // create StartCommand depending on the external model file extension.
324 if (fileInfo.suffix().compare("mo") == 0) {
325 pComponentInfo->setStartCommand("StartTLMOpenModelica");
326 } else if (fileInfo.suffix().compare("in") == 0) {
327 pComponentInfo->setStartCommand("StartTLMBeast");
328 } else if (fileInfo.suffix().compare("hmf") == 0) {
329 pComponentInfo->setStartCommand("StartTLMHopsan");
330 } else if (fileInfo.suffix().compare("fmu") == 0) {
331 pComponentInfo->setStartCommand("StartTLMFmiWrapper");
332 } else if (fileInfo.suffix().compare("slx") == 0) {
333 pComponentInfo->setStartCommand("StartTLMSimulink");
334 } else {
335 pComponentInfo->setStartCommand("");
336 }
337 pComponentInfo->setModelFile(fileInfo.fileName());
338 addComponentToView(name, pLibraryTreeItem, "", position, pComponentInfo, true, false, true);
339 return true;
340 }
341 } else {
342 // Only allow drag & drop of Modelica LibraryTreeItem on a Modelica LibraryTreeItem
343 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() != pLibraryTreeItem->getLibraryType()) {
344 QMessageBox::information(pMainWindow, QString("%1 - %2").arg(Helper::applicationName, Helper::information),
345 tr("You can only drag & drop Modelica models."), Helper::ok);
346 return false;
347 }
348 StringHandler::ModelicaClasses type = pLibraryTreeItem->getRestriction();
349 OptionsDialog *pOptionsDialog = OptionsDialog::instance();
350 // item not to be dropped on itself; if dropping an item on itself
351 if (isClassDroppedOnItself(pLibraryTreeItem)) {
352 return false;
353 } else { // check if the model is partial
354 if (pLibraryTreeItem->isPartial()) {
355 if (pOptionsDialog->getNotificationsPage()->getReplaceableIfPartialCheckBox()->isChecked()) {
356 NotificationsDialog *pNotificationsDialog = new NotificationsDialog(NotificationsDialog::ReplaceableIfPartial,
357 NotificationsDialog::InformationIcon,
358 MainWindow::instance());
359 pNotificationsDialog->setNotificationLabelString(GUIMessages::getMessage(GUIMessages::MAKE_REPLACEABLE_IF_PARTIAL)
360 .arg(StringHandler::getModelicaClassType(type).toLower()).arg(pLibraryTreeItem->getName()));
361 if (!pNotificationsDialog->exec()) {
362 return false;
363 }
364 }
365 }
366 // get the model defaultComponentPrefixes
367 QString defaultPrefix = pMainWindow->getOMCProxy()->getDefaultComponentPrefixes(pLibraryTreeItem->getNameStructure());
368 // get the model defaultComponentName
369 QString defaultName = pMainWindow->getOMCProxy()->getDefaultComponentName(pLibraryTreeItem->getNameStructure());
370 QString name;
371 if (!defaultName.isEmpty()) {
372 name = getUniqueComponentName(StringHandler::toCamelCase(defaultName));
373 } else {
374 name = getUniqueComponentName(StringHandler::toCamelCase(pLibraryTreeItem->getName()));
375 }
376 // Allow user to change the component name if always ask for component name settings is true.
377 if (pOptionsDialog->getNotificationsPage()->getAlwaysAskForDraggedComponentName()->isChecked()) {
378 ComponentNameDialog *pComponentNameDialog = new ComponentNameDialog(name, this, pMainWindow);
379 if (pComponentNameDialog->exec()) {
380 name = pComponentNameDialog->getComponentName();
381 pComponentNameDialog->deleteLater();
382 } else {
383 pComponentNameDialog->deleteLater();
384 return false;
385 }
386 }
387 // if we or user has changed the default name
388 if (!defaultName.isEmpty() && name.compare(defaultName) != 0) {
389 // show the information to the user if we have changed the name of some inner component.
390 if (defaultPrefix.contains("inner")) {
391 if (pOptionsDialog->getNotificationsPage()->getInnerModelNameChangedCheckBox()->isChecked()) {
392 NotificationsDialog *pNotificationsDialog = new NotificationsDialog(NotificationsDialog::InnerModelNameChanged,
393 NotificationsDialog::InformationIcon,
394 MainWindow::instance());
395 pNotificationsDialog->setNotificationLabelString(GUIMessages::getMessage(GUIMessages::INNER_MODEL_NAME_CHANGED)
396 .arg(defaultName).arg(name));
397 if (!pNotificationsDialog->exec()) {
398 return false;
399 }
400 }
401 }
402 }
403 ComponentInfo *pComponentInfo = new ComponentInfo;
404 pComponentInfo->applyDefaultPrefixes(defaultPrefix);
405 // if dropping an item on the diagram layer
406 if (mViewType == StringHandler::Diagram) {
407 // if item is a class, model, block, connector or record. then we can drop it to the graphicsview
408 if ((type == StringHandler::Class) || (type == StringHandler::Model) || (type == StringHandler::Block) ||
409 (type == StringHandler::ExpandableConnector) || (type == StringHandler::Connector) || (type == StringHandler::Record)) {
410 addComponentToView(name, pLibraryTreeItem, "", position, pComponentInfo, true, false, true);
411 return true;
412 } else {
413 QMessageBox::information(pMainWindow, QString(Helper::applicationName).append(" - ").append(Helper::information),
414 GUIMessages::getMessage(GUIMessages::DIAGRAM_VIEW_DROP_MSG).arg(pLibraryTreeItem->getNameStructure())
415 .arg(StringHandler::getModelicaClassType(type)), Helper::ok);
416 return false;
417 }
418 } else if (mViewType == StringHandler::Icon) { // if dropping an item on the icon layer
419 // if item is a connector. then we can drop it to the graphicsview
420 if (type == StringHandler::Connector || type == StringHandler::ExpandableConnector) {
421 addComponentToView(name, pLibraryTreeItem, "", position, pComponentInfo, true, false, true);
422 return true;
423 } else {
424 QMessageBox::information(pMainWindow, QString(Helper::applicationName).append(" - ").append(Helper::information),
425 GUIMessages::getMessage(GUIMessages::ICON_VIEW_DROP_MSG).arg(pLibraryTreeItem->getNameStructure())
426 .arg(StringHandler::getModelicaClassType(type)), Helper::ok);
427 return false;
428 }
429 }
430 }
431 }
432 return false;
433}
434
435/*!
436 * \brief GraphicsView::addComponentToView
437 * Adds the Component to the Graphical Views.
438 * \param name
439 * \param pLibraryTreeItem
440 * \param annotation
441 * \param position
442 * \param pComponentInfo
443 * \param addObject
444 * \param openingClass
445 * \param emitComponentAdded
446 */
447void GraphicsView::addComponentToView(QString name, LibraryTreeItem *pLibraryTreeItem, QString annotation, QPointF position,
448 ComponentInfo *pComponentInfo, bool addObject, bool openingClass, bool emitComponentAdded)
449{
450 AddComponentCommand *pAddComponentCommand;
451 pAddComponentCommand = new AddComponentCommand(name, pLibraryTreeItem, annotation, position, pComponentInfo, addObject, openingClass, this);
452 mpModelWidget->getUndoStack()->push(pAddComponentCommand);
453 if (emitComponentAdded) {
454 mpModelWidget->getLibraryTreeItem()->emitComponentAdded(pAddComponentCommand->getComponent());
455 }
456 if (!openingClass) {
457 mpModelWidget->updateModelText();
458 }
459}
460
461void GraphicsView::addComponentToClass(Component *pComponent)
462{
463 if (mpModelWidget->getLibraryTreeItem()->getLibraryType()== LibraryTreeItem::Modelica) {
464 MainWindow *pMainWindow = MainWindow::instance();
465 // Add the component to model in OMC.
466 /* Ticket:4132
467 * Always send the full path so that addComponent API doesn't fail when it makes a call to getDefaultPrefixes.
468 * I updated the addComponent API to make path relative.
469 */
470 pMainWindow->getOMCProxy()->addComponent(pComponent->getName(), pComponent->getComponentInfo()->getClassName(),
471 mpModelWidget->getLibraryTreeItem()->getNameStructure(), pComponent->getPlacementAnnotation());
472 LibraryTreeModel *pLibraryTreeModel = pMainWindow->getLibraryWidget()->getLibraryTreeModel();
473 // get the toplevel class of dragged component
474 QString packageName = StringHandler::getFirstWordBeforeDot(pComponent->getLibraryTreeItem()->getNameStructure());
475 LibraryTreeItem *pPackageLibraryTreeItem = pLibraryTreeModel->findLibraryTreeItem(packageName);
476 // get the top level class of current class
477 QString topLevelClassName = StringHandler::getFirstWordBeforeDot(mpModelWidget->getLibraryTreeItem()->getNameStructure());
478 LibraryTreeItem *pTopLevelLibraryTreeItem = pLibraryTreeModel->findLibraryTreeItem(topLevelClassName);
479 if (pPackageLibraryTreeItem && pTopLevelLibraryTreeItem) {
480 // get uses annotation of the toplevel class
481 QList<QList<QString > > usesAnnotation = pMainWindow->getOMCProxy()->getUses(pTopLevelLibraryTreeItem->getNameStructure());
482 QStringList newUsesAnnotation;
483 for (int i = 0 ; i < usesAnnotation.size() ; i++) {
484 if (usesAnnotation.at(i).at(0).compare(packageName) == 0) {
485 return; // if the package is already in uses annotation of class then simply return without doing anything.
486 } else {
487 newUsesAnnotation.append(QString("%1(version=\"%2\")").arg(usesAnnotation.at(i).at(0)).arg(usesAnnotation.at(i).at(1)));
488 }
489 }
490 // if the package has version only then add the uses annotation
491 if (!pPackageLibraryTreeItem->mClassInformation.version.isEmpty() &&
492 // Do not add a uses-annotation to itself
493 pTopLevelLibraryTreeItem->getNameStructure() != packageName) {
494 newUsesAnnotation.append(QString("%1(version=\"%2\")").arg(packageName).arg(pPackageLibraryTreeItem->mClassInformation.version));
495 QString usesAnnotationString = QString("annotate=$annotation(uses(%1))").arg(newUsesAnnotation.join(","));
496 pMainWindow->getOMCProxy()->addClassAnnotation(pTopLevelLibraryTreeItem->getNameStructure(), usesAnnotationString);
497 }
498 }
499 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType()== LibraryTreeItem::CompositeModel) {
500 // add SubModel Element
501 CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpModelWidget->getEditor());
502 pCompositeModelEditor->addSubModel(pComponent);
503 /* We need to iterate over Component childrens
504 * because if user deletes a submodel for which interfaces are already fetched
505 * then undoing the delete operation reaches here and we should add the interfaces back.
506 */
507 foreach (Component *pInterfaceComponent, pComponent->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pComponent
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pInterfaceComponent = *_container_.i; _container_
.control; _container_.control = 0)
{
508 pCompositeModelEditor->addInterface(pInterfaceComponent, pComponent->getName());
509 }
510 }
511}
512
513/*!
514 * \brief GraphicsView::deleteComponent
515 * Delete the component and its corresponding connections from the components list and OMC.
516 * \param component is the object to be deleted.
517 */
518void GraphicsView::deleteComponent(Component *pComponent)
519{
520 // First Remove the connections associated to this component
521 int i = 0;
522 while(i != mConnectionsList.size()) {
523 QString startComponentName = StringHandler::getFirstWordBeforeDot(mConnectionsList[i]->getStartComponentName());
524 if (startComponentName.contains("[")) {
525 startComponentName = startComponentName.mid(0, startComponentName.indexOf("["));
526 }
527 QString endComponentName = StringHandler::getFirstWordBeforeDot(mConnectionsList[i]->getEndComponentName());
528 if (endComponentName.contains("[")) {
529 endComponentName = endComponentName.mid(0, endComponentName.indexOf("["));
530 }
531 if (startComponentName == pComponent->getName() || endComponentName == pComponent->getName()) {
532 deleteConnection(mConnectionsList[i]);
533 i = 0; //Restart iteration if map has changed
534 } else {
535 ++i;
536 }
537 }
538 pComponent->setSelected(false);
539 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
540 mpModelWidget->getUndoStack()->push(new DeleteSubModelCommand(pComponent, this));
541 } else {
542 mpModelWidget->getUndoStack()->push(new DeleteComponentCommand(pComponent, this));
543 }
544
545}
546
547/*!
548 * \brief GraphicsView::deleteComponentObject
549 * Deletes the Component.
550 * \param pComponent
551 */
552void GraphicsView::deleteComponentFromClass(Component *pComponent)
553{
554 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
555 OMCProxy *pOMCProxy = MainWindow::instance()->getOMCProxy();
556 // delete the component from OMC
557 pOMCProxy->deleteComponent(pComponent->getName(), mpModelWidget->getLibraryTreeItem()->getNameStructure());
558 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType()== LibraryTreeItem::CompositeModel) {
559 CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpModelWidget->getEditor());
560 pCompositeModelEditor->deleteSubModel(pComponent->getName());
561 }
562}
563
564/*!
565 * \brief GraphicsView::getComponentObject
566 * Finds the Component
567 * \param componentName
568 * \return
569 */
570Component* GraphicsView::getComponentObject(QString componentName)
571{
572 // look in inherited components
573 foreach (Component *pInheritedComponent, mInheritedComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInheritedComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pInheritedComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
574 if (pInheritedComponent->getName().compare(componentName) == 0) {
575 return pInheritedComponent;
576 }
577 }
578 // look in components
579 foreach (Component *pComponent, mComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
580 if (pComponent->getName().compare(componentName) == 0) {
581 return pComponent;
582 }
583 }
584 return 0;
585}
586
587/*!
588 * \brief GraphicsView::getUniqueComponentName
589 * Creates a unique component name.
590 * \param componentName
591 * \param number
592 * \return
593 */
594QString GraphicsView::getUniqueComponentName(QString componentName, int number)
595{
596 QString name = componentName;
597 if (number > 0) {
598 name = QString("%1%2").arg(componentName).arg(number);
599 }
600
601 if (!checkComponentName(name)) {
602 name = getUniqueComponentName(componentName, ++number);
603 }
604 return name;
605}
606
607/*!
608 * \brief GraphicsView::checkComponentName
609 * Checks the component name against the Modelica keywords as well.
610 * Checks if the component with the same name already exists or not.
611 * \param componentName
612 * \return
613 */
614bool GraphicsView::checkComponentName(QString componentName)
615{
616 // if component name is any keyword of Modelica
617 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
618 if (ModelicaHighlighter::getKeywords().contains(componentName)) {
619 return false;
620 }
621 }
622 // if component with same name exists
623 foreach (Component *pComponent, mComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
624 if (pComponent->getName().compare(componentName, Qt::CaseSensitive) == 0) {
625 return false;
626 }
627 }
628 return true;
629}
630
631/*!
632 * \brief updateConnectionIndexes
633 * Updates the connection indexes in the connection name with the passed index.
634 * \param connectionComponentName
635 * \param componentConnectionIndex
636 * \return
637 */
638QString updateConnectionIndexes(const QString &connectionComponentName, int &componentConnectionIndex) {
639 QString newConnectionComponentName = "";
640 int endIndex = connectionComponentName.lastIndexOf(']');
641 int startIndex = connectionComponentName.lastIndexOf('[', endIndex);
642 if (startIndex > -1 && endIndex > -1) {
643 newConnectionComponentName = connectionComponentName.left(startIndex);
644 newConnectionComponentName += "[";
645 QStringList range = connectionComponentName.mid(startIndex + 1, endIndex - startIndex - 1).split(':');
646 if (range.size() > 1) {
647 newConnectionComponentName += QString("%1:%2").arg(componentConnectionIndex).arg(componentConnectionIndex + (range.at(1).toInt() - range.at(0).toInt()));
648 componentConnectionIndex = componentConnectionIndex + (range.at(1).toInt() - range.at(0).toInt());
649 } else {
650 newConnectionComponentName += QString("%1").arg(componentConnectionIndex);
651 }
652 newConnectionComponentName += "]";
653 }
654 return newConnectionComponentName;
655}
656
657/*!
658 * \brief GraphicsView::addConnectionToClass
659 * Adds the connection to class.
660 * \param pConnectionLineAnnotation - the connection to add.
661 * \param deleteUndo - True when undo of a delete connection is called.
662 * \return
663 */
664bool GraphicsView::addConnectionToClass(LineAnnotation *pConnectionLineAnnotation, bool deleteUndo)
665{
666 if (mpModelWidget->getLibraryTreeItem()->getLibraryType()== LibraryTreeItem::CompositeModel) {
667 CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpModelWidget->getEditor());
668 if (pCompositeModelEditor) {
669 pCompositeModelEditor->createConnection(pConnectionLineAnnotation);
670 }
671 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType()== LibraryTreeItem::OMS) {
672 // if TLM connection
673 bool connectionSuccessful = false;
674 if (pConnectionLineAnnotation->getOMSConnectionType() == oms_connection_tlm) {
675 connectionSuccessful = OMSProxy::instance()->addTLMConnection(pConnectionLineAnnotation->getStartComponentName(), pConnectionLineAnnotation->getEndComponentName(),
676 pConnectionLineAnnotation->getDelay().toDouble(), pConnectionLineAnnotation->getAlpha().toDouble(),
677 pConnectionLineAnnotation->getZf().toDouble(), pConnectionLineAnnotation->getZfr().toDouble());
678 } else {
679 connectionSuccessful = OMSProxy::instance()->addConnection(pConnectionLineAnnotation->getStartComponentName(), pConnectionLineAnnotation->getEndComponentName());
680 }
681 if (connectionSuccessful) {
682 pConnectionLineAnnotation->updateOMSConnection();
683 return true;
684 } else {
685 removeCurrentConnection();
686 return false;
687 }
688 } else {
689 MainWindow *pMainWindow = MainWindow::instance();
690 // update connectorSizing on start component if exists
691 bool isStartComponentConnectorSizing = GraphicsView::updateComponentConnectorSizingParameter(this, mpModelWidget->getLibraryTreeItem()->getNameStructure(), pConnectionLineAnnotation->getStartComponent());
692 // update connectorSizing on end component if exists
693 bool isEndComponentConnectorSizing = GraphicsView::updateComponentConnectorSizingParameter(this, mpModelWidget->getLibraryTreeItem()->getNameStructure(), pConnectionLineAnnotation->getEndComponent());
694 if (deleteUndo) {
695 if (isStartComponentConnectorSizing) {
696 int connectionIndex = numberOfComponentConnections(pConnectionLineAnnotation->getStartComponent(), pConnectionLineAnnotation) + 1;
697 QString newStartComponentName = updateConnectionIndexes(pConnectionLineAnnotation->getStartComponentName(), connectionIndex);
698 if (!newStartComponentName.isEmpty()) {
699 pConnectionLineAnnotation->setStartComponentName(newStartComponentName);
700 pConnectionLineAnnotation->updateToolTip();
701 }
702 }
703 if (isEndComponentConnectorSizing) {
704 int connectionIndex = numberOfComponentConnections(pConnectionLineAnnotation->getEndComponent(), pConnectionLineAnnotation) + 1;
705 QString newEndComponentName = updateConnectionIndexes(pConnectionLineAnnotation->getEndComponentName(), connectionIndex);
706 if (!newEndComponentName.isEmpty()) {
707 pConnectionLineAnnotation->setEndComponentName(newEndComponentName);
708 pConnectionLineAnnotation->updateToolTip();
709 }
710 }
711 }
712 // add connection
713 if (pMainWindow->getOMCProxy()->addConnection(pConnectionLineAnnotation->getStartComponentName(), pConnectionLineAnnotation->getEndComponentName(),
714 mpModelWidget->getLibraryTreeItem()->getNameStructure(), QString("annotate=").append(pConnectionLineAnnotation->getShapeAnnotation()))) {
715 /* Ticket #2450
716 * Do not check for the ports compatibility via instantiatemodel. Just let the user create the connection.
717 */
718 //pMainWindow->getOMCProxy()->instantiateModelSucceeds(mpModelWidget->getNameStructure());
719 }
720 }
721 return true;
722}
723
724/*!
725 * \brief componentIndexesRangeInConnection
726 * Returns the component array index in connection.
727 * It could be just index or range e.g., 1:3
728 * \param connectionComponentName
729 * \return
730 */
731QStringList componentIndexesRangeInConnection(const QString &connectionComponentName)
732{
733 int endIndex = connectionComponentName.lastIndexOf(']');
734 int startIndex = connectionComponentName.lastIndexOf('[', endIndex);
735 if (startIndex > -1 && endIndex > -1) {
736 return connectionComponentName.mid(startIndex + 1, endIndex - startIndex - 1).split(':');
737 }
738 return QStringList();
739}
740
741/*!
742 * \brief componentIndexInConnection
743 * Return the component array index used in connection.
744 * If the index is range then the start of range is returned e.g., 1:3 returns 1 and 2:4 returns 2.
745 * \param connectionComponentName
746 * \return
747 */
748int componentIndexInConnection(const QString &connectionComponentName)
749{
750 QStringList range = componentIndexesRangeInConnection(connectionComponentName);
751 return range.value(0, "0").toInt();
752}
753
754/*!
755 * \brief GraphicsView::deleteConnectionFromClass
756 * Deletes the connection from class.
757 * \param pConnectionLineAnnotation - the connection to delete.
758 */
759void GraphicsView::deleteConnectionFromClass(LineAnnotation *pConnectionLineAnnotation)
760{
761 MainWindow *pMainWindow = MainWindow::instance();
762 if (mpModelWidget->getLibraryTreeItem()->getLibraryType()== LibraryTreeItem::CompositeModel) {
763 CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpModelWidget->getEditor());
764 pCompositeModelEditor->deleteConnection(pConnectionLineAnnotation->getStartComponentName(), pConnectionLineAnnotation->getEndComponentName());
765 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType()== LibraryTreeItem::OMS) {
766 OMSProxy::instance()->deleteConnection(pConnectionLineAnnotation->getStartComponentName(), pConnectionLineAnnotation->getEndComponentName());
767 } else {
768 // delete the connection
769 if (pMainWindow->getOMCProxy()->deleteConnection(pConnectionLineAnnotation->getStartComponentName(), pConnectionLineAnnotation->getEndComponentName(), mpModelWidget->getLibraryTreeItem()->getNameStructure())) {
770 // update connectorSizing on start component if exists
771 bool isStartComponentConnectorSizing = GraphicsView::updateComponentConnectorSizingParameter(this, mpModelWidget->getLibraryTreeItem()->getNameStructure(), pConnectionLineAnnotation->getStartComponent());
772 // update connectorSizing on end component if exists
773 bool isEndComponentConnectorSizing = GraphicsView::updateComponentConnectorSizingParameter(this, mpModelWidget->getLibraryTreeItem()->getNameStructure(), pConnectionLineAnnotation->getEndComponent());
774 // if the component is connectorSizing then get the index used in deleted connection
775 int startConnectionIndex = 0;
776 if (isStartComponentConnectorSizing) {
777 startConnectionIndex = componentIndexInConnection(pConnectionLineAnnotation->getStartComponentName());
778 }
779 int endConnectionIndex = 0;
780 if (isEndComponentConnectorSizing) {
781 endConnectionIndex = componentIndexInConnection(pConnectionLineAnnotation->getEndComponentName());
782 }
783 if (isStartComponentConnectorSizing || isEndComponentConnectorSizing) {
784 // update the connections if some middle connectorSizing connection is removed
785 foreach (LineAnnotation *pOtherConnectionLineAnnotation, mConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pOtherConnectionLineAnnotation = *_container_.i; _container_
.control; _container_.control = 0)
{
786 // if deleted connection then continue
787 if (pOtherConnectionLineAnnotation == pConnectionLineAnnotation) {
788 continue;
789 }
790 bool updateConnection = false;
791 // start component matches
792 QString startComponentName = pOtherConnectionLineAnnotation->getStartComponentName();
793 if (pOtherConnectionLineAnnotation->getStartComponent() == pConnectionLineAnnotation->getStartComponent()) {
794 if (componentIndexInConnection(startComponentName) > startConnectionIndex) {
795 pOtherConnectionLineAnnotation->setStartComponentName(updateConnectionIndexes(startComponentName, startConnectionIndex));
796 startConnectionIndex++;
797 updateConnection = true;
798 }
799 }
800 if (pOtherConnectionLineAnnotation->getStartComponent() == pConnectionLineAnnotation->getEndComponent()) {
801 if (componentIndexInConnection(startComponentName) > endConnectionIndex) {
802 pOtherConnectionLineAnnotation->setStartComponentName(updateConnectionIndexes(startComponentName, endConnectionIndex));
803 endConnectionIndex++;
804 updateConnection = true;
805 }
806 }
807 // end component matches
808 QString endComponentName = pOtherConnectionLineAnnotation->getEndComponentName();
809 if (pOtherConnectionLineAnnotation->getEndComponent() == pConnectionLineAnnotation->getEndComponent()) {
810 if (componentIndexInConnection(endComponentName) > endConnectionIndex) {
811 pOtherConnectionLineAnnotation->setEndComponentName(updateConnectionIndexes(endComponentName, endConnectionIndex));
812 endConnectionIndex++;
813 updateConnection = true;
814 }
815 }
816 if (pOtherConnectionLineAnnotation->getEndComponent() == pConnectionLineAnnotation->getStartComponent()) {
817 if (componentIndexInConnection(endComponentName) > startConnectionIndex) {
818 pOtherConnectionLineAnnotation->setEndComponentName(updateConnectionIndexes(endComponentName, startConnectionIndex));
819 startConnectionIndex++;
820 updateConnection = true;
821 }
822 }
823 // update the connection with updated connectorSizing indexes.
824 if (updateConnection) {
825 pMainWindow->getOMCProxy()->updateConnectionNames(mpModelWidget->getLibraryTreeItem()->getNameStructure(), startComponentName, endComponentName,
826 pOtherConnectionLineAnnotation->getStartComponentName(), pOtherConnectionLineAnnotation->getEndComponentName());
827 pOtherConnectionLineAnnotation->updateToolTip();
828 }
829 }
830 }
831 }
832 }
833}
834
835/*!
836 * \brief GraphicsView::updateConnectionInClass
837 * Updates a connection in a class.
838 * \param pConnectonLineAnnotation
839 */
840void GraphicsView::updateConnectionInClass(LineAnnotation *pConnectionLineAnnotation)
841{
842 if (mpModelWidget->getLibraryTreeItem()->getLibraryType()== LibraryTreeItem::CompositeModel) {
843 CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpModelWidget->getEditor());
844 if (pCompositeModelEditor) {
845 pCompositeModelEditor->updateConnection(pConnectionLineAnnotation);
846 }
847 }
848}
849
850/*!
851 * \brief GraphicsView::removeConnectionsFromView
852 * Removes the connections from the view.
853 */
854void GraphicsView::removeConnectionsFromView()
855{
856 foreach (LineAnnotation *pConnectionLineAnnotation, mConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pConnectionLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
857 deleteConnectionFromList(pConnectionLineAnnotation);
858 removeItem(pConnectionLineAnnotation);
859 }
860}
861
862/*!
863 * \brief GraphicsView::numberOfComponentConnections
864 * Counts the number of connections of the component.
865 * \param pComponent
866 * \param pExcludeConnectionLineAnnotation
867 * \return
868 */
869int GraphicsView::numberOfComponentConnections(Component *pComponent, LineAnnotation *pExcludeConnectionLineAnnotation)
870{
871 int connections = 0;
872 foreach (LineAnnotation *pConnectionLineAnnotation, mConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pConnectionLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
873 if (pExcludeConnectionLineAnnotation && pExcludeConnectionLineAnnotation == pConnectionLineAnnotation) {
874 continue;
875 }
876 if (pConnectionLineAnnotation->getStartComponent() == pComponent || pConnectionLineAnnotation->getEndComponent() == pComponent) {
877 // always count one connection if we are in here. Then look for array connections.
878 connections++;
879 QString connectionComponentName;
880 if (pConnectionLineAnnotation->getStartComponent() == pComponent) {
881 connectionComponentName = pConnectionLineAnnotation->getStartComponentName();
882 } else {
883 connectionComponentName = pConnectionLineAnnotation->getEndComponentName();
884 }
885 QStringList range = componentIndexesRangeInConnection(connectionComponentName);
886 if (range.size() > 1) {
887 connections += (range.at(1).toInt() - range.at(0).toInt());
888 }
889 }
890 }
891 return connections;
892}
893
894/*!
895 * \brief GraphicsView::addTransitionToClass
896 * Adds the transition to class.
897 * \param pTransitionLineAnnotation - the transition to add.
898 */
899void GraphicsView::addTransitionToClass(LineAnnotation *pTransitionLineAnnotation)
900{
901 OMCProxy *pOMCProxy = MainWindow::instance()->getOMCProxy();
902 if (pOMCProxy->addTransition(mpModelWidget->getLibraryTreeItem()->getNameStructure(), pTransitionLineAnnotation->getStartComponentName(),
903 pTransitionLineAnnotation->getEndComponentName(), pTransitionLineAnnotation->getCondition(),
904 pTransitionLineAnnotation->getImmediate(), pTransitionLineAnnotation->getReset(),
905 pTransitionLineAnnotation->getSynchronize(), pTransitionLineAnnotation->getPriority(),
906 QString("annotate=$annotation(%1,%2)").arg(pTransitionLineAnnotation->getShapeAnnotation())
907 .arg(pTransitionLineAnnotation->getTextAnnotation()->getShapeAnnotation()))) {
908 }
909}
910
911/*!
912 * \brief GraphicsView::deleteTransitionFromClass
913 * Deletes the transition from class.
914 * \param pTransitionLineAnnotation - the transition to delete.
915 */
916void GraphicsView::deleteTransitionFromClass(LineAnnotation *pTransitionLineAnnotation)
917{
918 OMCProxy *pOMCProxy = MainWindow::instance()->getOMCProxy();
919 pOMCProxy->deleteTransition(mpModelWidget->getLibraryTreeItem()->getNameStructure(), pTransitionLineAnnotation->getStartComponentName(),
920 pTransitionLineAnnotation->getEndComponentName(), pTransitionLineAnnotation->getCondition(),
921 pTransitionLineAnnotation->getImmediate(), pTransitionLineAnnotation->getReset(),
922 pTransitionLineAnnotation->getSynchronize(), pTransitionLineAnnotation->getPriority());
923}
924
925/*!
926 * \brief GraphicsView::removeTransitionsFromView
927 * Removes the transitions from the view.
928 */
929void GraphicsView::removeTransitionsFromView()
930{
931 foreach (LineAnnotation *pTransitionLineAnnotation, mTransitionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mTransitionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pTransitionLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
932 deleteTransitionFromList(pTransitionLineAnnotation);
933 removeItem(pTransitionLineAnnotation);
934 }
935}
936
937/*!
938 * \brief GraphicsView::addInitialStateToClass
939 * Adds the initial state to class.
940 * \param pInitialStateLineAnnotation - the initial state to add.
941 */
942void GraphicsView::addInitialStateToClass(LineAnnotation *pInitialStateLineAnnotation)
943{
944 OMCProxy *pOMCProxy = MainWindow::instance()->getOMCProxy();
945 if (pOMCProxy->addInitialState(mpModelWidget->getLibraryTreeItem()->getNameStructure(),
946 pInitialStateLineAnnotation->getStartComponentName(),
947 QString("annotate=").append(pInitialStateLineAnnotation->getShapeAnnotation()))) {
948 }
949}
950
951/*!
952 * \brief GraphicsView::deleteInitialStateFromClass
953 * Deletes the initial state from class.
954 * \param pInitialStateLineAnnotation - the initial state to delete.
955 */
956void GraphicsView::deleteInitialStateFromClass(LineAnnotation *pInitialStateLineAnnotation)
957{
958 OMCProxy *pOMCProxy = MainWindow::instance()->getOMCProxy();
959 pOMCProxy->deleteInitialState(mpModelWidget->getLibraryTreeItem()->getNameStructure(), pInitialStateLineAnnotation->getStartComponentName());
960}
961
962/*!
963 * \brief GraphicsView::removeInitialStatesFromView
964 * Removes the initial states from the view.
965 */
966void GraphicsView::removeInitialStatesFromView()
967{
968 foreach (LineAnnotation *pInitialStateLineAnnotation, mInitialStatesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInitialStatesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pInitialStateLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
969 deleteInitialStateFromList(pInitialStateLineAnnotation);
970 removeItem(pInitialStateLineAnnotation);
971 }
972}
973
974/*!
975 * \brief GraphicsView::addShapeToList
976 * \param pShape
977 * \param index
978 */
979void GraphicsView::addShapeToList(ShapeAnnotation *pShape, int index)
980{
981 if (index <= -1) {
982 mShapesList.append(pShape);
983 } else {
984 mShapesList.insert(index, pShape);
985 }
986}
987
988/*!
989 * \brief GraphicsView::deleteShape
990 * Deletes the shape from the icon/diagram layer.
991 * \param pShapeAnnotation
992 */
993void GraphicsView::deleteShape(ShapeAnnotation *pShapeAnnotation)
994{
995 pShapeAnnotation->setSelected(false);
996 mpModelWidget->getUndoStack()->push(new DeleteShapeCommand(pShapeAnnotation));
997}
998
999/*!
1000 * \brief GraphicsView::deleteShapeFromList
1001 * \param pShape
1002 * \return
1003 */
1004int GraphicsView::deleteShapeFromList(ShapeAnnotation *pShape)
1005{
1006 int index = mShapesList.indexOf(pShape);
1007 mShapesList.removeOne(pShape);
1008 return index;
1009}
1010
1011/*!
1012 * \brief GraphicsView::reOrderShapes
1013 * Reorders the shapes.
1014 */
1015void GraphicsView::reOrderShapes()
1016{
1017 int zValue = 0;
1018 // set stacking order for inherited shapes
1019 foreach (ShapeAnnotation *pShapeAnnotation, mInheritedShapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInheritedShapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (ShapeAnnotation
*pShapeAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
1020 zValue++;
1021 pShapeAnnotation->setZValue(zValue);
1022 }
1023 // set stacking order for shapes.
1024 foreach (ShapeAnnotation *pShapeAnnotation, mShapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mShapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (ShapeAnnotation
*pShapeAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
1025 zValue++;
1026 pShapeAnnotation->setZValue(zValue);
1027 }
1028}
1029
1030/*!
1031 * \brief GraphicsView::bringToFront
1032 * \param pShape
1033 * Brings the shape to front of all other shapes.
1034 */
1035void GraphicsView::bringToFront(ShapeAnnotation *pShape)
1036{
1037 deleteShapeFromList(pShape);
1038 int i = 0;
1039 // update the shapes z index
1040 for (; i < mShapesList.size() ; i++) {
1041 mShapesList.at(i)->setZValue(i + 1);
1042 }
1043 pShape->setZValue(i + 1);
1044 mShapesList.append(pShape);
1045 // update class annotation.
1046 addClassAnnotation();
1047}
1048
1049/*!
1050 * \brief GraphicsView::bringForward
1051 * \param pShape
1052 * Brings the shape one level forward.
1053 */
1054void GraphicsView::bringForward(ShapeAnnotation *pShape)
1055{
1056 int shapeIndex = mShapesList.indexOf(pShape);
1057 if (shapeIndex == -1 || shapeIndex == mShapesList.size() - 1) { // if the shape is already at top.
1058 return;
1059 }
1060 // swap the shapes in the list
1061 mShapesList.swap(shapeIndex, shapeIndex + 1);
1062 // update the shapes z index
1063 for (int i = 0 ; i < mShapesList.size() ; i++) {
1064 mShapesList.at(i)->setZValue(i + 1);
1065 }
1066 // update class annotation.
1067 addClassAnnotation();
1068}
1069
1070/*!
1071 * \brief GraphicsView::sendToBack
1072 * \param pShape
1073 * Sends the shape to back of all other shapes.
1074 */
1075void GraphicsView::sendToBack(ShapeAnnotation *pShape)
1076{
1077 deleteShapeFromList(pShape);
1078 int i = 0;
1079 pShape->setZValue(i + 1);
1080 mShapesList.prepend(pShape);
1081 // update the shapes z index
1082 for (i = 1 ; i < mShapesList.size() ; i++) {
1083 mShapesList.at(i)->setZValue(i + 1);
1084 }
1085 // update class annotation.
1086 addClassAnnotation();
1087}
1088
1089/*!
1090 * \brief GraphicsView::sendBackward
1091 * \param pShape
1092 * Sends the shape one level backward.
1093 */
1094void GraphicsView::sendBackward(ShapeAnnotation *pShape)
1095{
1096 int shapeIndex = mShapesList.indexOf(pShape);
1097 if (shapeIndex <= 0) { // if the shape is already at bottom.
1098 return;
1099 }
1100 // swap the shapes in the list
1101 mShapesList.swap(shapeIndex - 1, shapeIndex);
1102 // update the shapes z index
1103 for (int i = 0 ; i < mShapesList.size() ; i++) {
1104 mShapesList.at(i)->setZValue(i + 1);
1105 }
1106 // update class annotation.
1107 addClassAnnotation();
1108}
1109
1110/*!
1111 * \brief GraphicsView::clearGraphicsView
1112 * Clears everything from the GraphicsView.
1113 */
1114void GraphicsView::clearGraphicsView()
1115{
1116 removeAllShapes();
1117 removeOutOfSceneShapes();
1118 removeAllConnections();
1119 removeOutOfSceneConnections();
1120 removeAllTransitions();
1121 removeOutOfSceneTransitions();
1122 removeAllInitialStates();
1123 removeOutOfSceneInitialStates();
1124 removeClassComponents();
1125 removeOutOfSceneClassComponents();
1126 removeInheritedClassShapes();
1127 removeInheritedClassConnections();
1128 removeInheritedClassComponents();
1129 scene()->clear();
1130 mAllItems.clear();
1131}
1132
1133/*!
1134 * \brief GraphicsView::removeClassComponents
1135 * Removes all the class components.
1136 */
1137void GraphicsView::removeClassComponents()
1138{
1139 foreach (Component *pComponent, mComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
1140 pComponent->removeChildren();
1141 deleteComponentFromList(pComponent);
1142 removeItem(pComponent->getOriginItem());
1143 delete pComponent->getOriginItem();
1144 removeItem(pComponent);
1145 pComponent->emitDeleted();
1146 delete pComponent;
1147 }
1148}
1149
1150/*!
1151 * \brief GraphicsView::removeOutOfSceneClassComponents
1152 * Removes all the class components that are not deleted but are removed from scene.
1153 */
1154void GraphicsView::removeOutOfSceneClassComponents()
1155{
1156 foreach (Component *pComponent, mOutOfSceneComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mOutOfSceneComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
1157 pComponent->removeChildren();
1158 deleteComponentFromOutOfSceneList(pComponent);
1159 delete pComponent->getOriginItem();
1160 pComponent->emitDeleted();
1161 delete pComponent;
1162 }
1163}
1164
1165/*!
1166 * \brief GraphicsView::removeInheritedClassShapes
1167 * Removes all the inherited class shapes.
1168 */
1169void GraphicsView::removeInheritedClassShapes()
1170{
1171 foreach (ShapeAnnotation *pShapeAnnotation, mInheritedShapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInheritedShapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (ShapeAnnotation
*pShapeAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
1172 deleteInheritedShapeFromList(pShapeAnnotation);
1173 removeItem(pShapeAnnotation);
1174 delete pShapeAnnotation;
1175 }
1176}
1177
1178/*!
1179 * \brief GraphicsView::removeInheritedClassComponents
1180 * Removes all the class inherited components.
1181 */
1182void GraphicsView::removeInheritedClassComponents()
1183{
1184 foreach (Component *pComponent, mInheritedComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInheritedComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
1185 pComponent->removeChildren();
1186 deleteInheritedComponentFromList(pComponent);
1187 removeItem(pComponent->getOriginItem());
1188 delete pComponent->getOriginItem();
1189 removeItem(pComponent);
1190 pComponent->emitDeleted();
1191 delete pComponent;
1192 }
1193}
1194
1195/*!
1196 * \brief GraphicsView::removeInheritedClassConnections
1197 * Removes all the class inherited class connections.
1198 */
1199void GraphicsView::removeInheritedClassConnections()
1200{
1201 foreach (LineAnnotation *pConnectionLineAnnotation, mInheritedConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInheritedConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pConnectionLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
1202 deleteInheritedConnectionFromList(pConnectionLineAnnotation);
1203 removeItem(pConnectionLineAnnotation);
1204 delete pConnectionLineAnnotation;
1205 }
1206}
1207
1208/*!
1209 * \brief GraphicsView::removeOutOfSceneShapes
1210 * Removes all the shapes that are not deleted but are removed from scene.
1211 */
1212void GraphicsView::removeOutOfSceneShapes()
1213{
1214 foreach (ShapeAnnotation *pShapeAnnotation, mOutOfSceneShapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mOutOfSceneShapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (ShapeAnnotation
*pShapeAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
1215 deleteShapeFromOutOfSceneList(pShapeAnnotation);
1216 delete pShapeAnnotation;
1217 }
1218}
1219
1220/*!
1221 * \brief GraphicsView::removeOutOfSceneConnections
1222 * Removes all the connections that are not deleted but are removed from scene.
1223 */
1224void GraphicsView::removeOutOfSceneConnections()
1225{
1226 foreach (LineAnnotation *pLineAnnotation, mOutOfSceneConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mOutOfSceneConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pLineAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
1227 deleteConnectionFromOutOfSceneList(pLineAnnotation);
1228 delete pLineAnnotation;
1229 }
1230}
1231
1232/*!
1233 * \brief GraphicsView::removeOutOfSceneTransitions
1234 * Removes all the class transitions that are not deleted but are removed from scene.
1235 */
1236void GraphicsView::removeOutOfSceneTransitions()
1237{
1238 foreach (LineAnnotation *pLineAnnotation, mOutOfSceneTransitionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mOutOfSceneTransitionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pLineAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
1239 deleteTransitionFromOutOfSceneList(pLineAnnotation);
1240 delete pLineAnnotation;
1241 }
1242}
1243
1244/*!
1245 * \brief GraphicsView::removeOutOfSceneInitialStates
1246 * Removes all the initial states that are not deleted but are removed from scene.
1247 */
1248void GraphicsView::removeOutOfSceneInitialStates()
1249{
1250 foreach (LineAnnotation *pLineAnnotation, mOutOfSceneInitialStatesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mOutOfSceneInitialStatesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pLineAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
1251 deleteInitialStateFromOutOfSceneList(pLineAnnotation);
1252 delete pLineAnnotation;
1253 }
1254}
1255
1256void GraphicsView::createLineShape(QPointF point)
1257{
1258 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) {
1259 return;
1260 }
1261
1262 if (!isCreatingLineShape()) {
1263 mpLineShapeAnnotation = new LineAnnotation("", this);
1264 mpModelWidget->getUndoStack()->push(new AddShapeCommand(mpLineShapeAnnotation));
1265 setIsCreatingLineShape(true);
1266 mpLineShapeAnnotation->addPoint(point);
1267 mpLineShapeAnnotation->addPoint(point);
1268 } else { // if we are already creating a line then only add one point.
1269 mpLineShapeAnnotation->addPoint(point);
1270 }
1271}
1272
1273void GraphicsView::createPolygonShape(QPointF point)
1274{
1275 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) {
1276 return;
1277 }
1278
1279 if (!isCreatingPolygonShape()) {
1280 mpPolygonShapeAnnotation = new PolygonAnnotation("", this);
1281 mpModelWidget->getUndoStack()->push(new AddShapeCommand(mpPolygonShapeAnnotation));
1282 setIsCreatingPolygonShape(true);
1283 mpPolygonShapeAnnotation->addPoint(point);
1284 mpPolygonShapeAnnotation->addPoint(point);
1285 mpPolygonShapeAnnotation->addPoint(point);
1286 } else { // if we are already creating a polygon then only add one point.
1287 mpPolygonShapeAnnotation->addPoint(point);
1288 }
1289}
1290
1291void GraphicsView::createRectangleShape(QPointF point)
1292{
1293 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) {
1294 return;
1295 }
1296
1297 if (!isCreatingRectangleShape()) {
1298 mpRectangleShapeAnnotation = new RectangleAnnotation("", this);
1299 mpModelWidget->getUndoStack()->push(new AddShapeCommand(mpRectangleShapeAnnotation));
1300 setIsCreatingRectangleShape(true);
1301 mpRectangleShapeAnnotation->replaceExtent(0, point);
1302 mpRectangleShapeAnnotation->replaceExtent(1, point);
1303 } else { // if we are already creating a rectangle then finish creating it.
1304 finishDrawingRectangleShape();
1305 }
1306}
1307
1308void GraphicsView::createEllipseShape(QPointF point)
1309{
1310 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) {
1311 return;
1312 }
1313
1314 if (!isCreatingEllipseShape()) {
1315 mpEllipseShapeAnnotation = new EllipseAnnotation("", this);
1316 mpModelWidget->getUndoStack()->push(new AddShapeCommand(mpEllipseShapeAnnotation));
1317 setIsCreatingEllipseShape(true);
1318 mpEllipseShapeAnnotation->replaceExtent(0, point);
1319 mpEllipseShapeAnnotation->replaceExtent(1, point);
1320 } else { // if we are already creating an ellipse then finish creating it.
1321 finishDrawingEllipseShape();
1322 }
1323}
1324
1325void GraphicsView::createTextShape(QPointF point)
1326{
1327 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) {
1328 return;
1329 }
1330
1331 if (!isCreatingTextShape()) {
1332 mpTextShapeAnnotation = new TextAnnotation("", this);
1333 mpModelWidget->getUndoStack()->push(new AddShapeCommand(mpTextShapeAnnotation));
1334 setIsCreatingTextShape(true);
1335 mpTextShapeAnnotation->setTextString("text");
1336 mpTextShapeAnnotation->replaceExtent(0, point);
1337 mpTextShapeAnnotation->replaceExtent(1, point);
1338 } else { // if we are already creating a text then finish creating it.
1339 finishDrawingTextShape();
1340 }
1341}
1342
1343void GraphicsView::createBitmapShape(QPointF point)
1344{
1345 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) {
1346 return;
1347 }
1348
1349 if (!isCreatingBitmapShape()) {
1350 mpBitmapShapeAnnotation = new BitmapAnnotation(mpModelWidget->getLibraryTreeItem()->getFileName(), "", this);
1351 mpModelWidget->getUndoStack()->push(new AddShapeCommand(mpBitmapShapeAnnotation));
1352 setIsCreatingBitmapShape(true);
1353 mpBitmapShapeAnnotation->replaceExtent(0, point);
1354 mpBitmapShapeAnnotation->replaceExtent(1, point);
1355 } else { // if we are already creating a bitmap then finish creating it.
1356 finishDrawingBitmapShape();
1357 }
1358}
1359
1360void GraphicsView::finishDrawingGenericShape()
1361{
1362 if (mIsCreatingLineShape){
1363 finishDrawingLineShape();
1364 } else if (mIsCreatingPolygonShape) {
1365 finishDrawingPolygonShape();
1366 } else if (mIsCreatingRectangleShape) {
1367 finishDrawingRectangleShape();
1368 } else if (mIsCreatingEllipseShape) {
1369 finishDrawingEllipseShape();
1370 } else if (mIsCreatingTextShape) {
1371 finishDrawingTextShape();
1372 } else /*Otherwise we have a bitmap*/{
1373 finishDrawingBitmapShape();
1374 }
1375}
1376
1377void GraphicsView::finishDrawingLineShape(bool removeLastAddedPoint)
1378{
1379 setIsCreatingLineShape(false);
1380 if (removeLastAddedPoint) {
1381 mpLineShapeAnnotation->removePoint(mpLineShapeAnnotation->getPoints().size() - 1);
1382 }
1383 setOriginAdjustAndInitialize(mpLineShapeAnnotation);
1384 mpLineShapeAnnotation->setSelected(true);
1385 uncheckAllShapeDrawingActions();
1386 checkEmitUpdateSelect(false, mpLineShapeAnnotation);
1387}
1388
1389void GraphicsView::finishDrawingPolygonShape(bool removeLastAddedPoint)
1390{
1391 setIsCreatingPolygonShape(false);
1392 if (removeLastAddedPoint) {
1393 mpPolygonShapeAnnotation->removePoint(mpPolygonShapeAnnotation->getPoints().size() - 1);
1394 }
1395 setOriginAdjustAndInitialize(mpPolygonShapeAnnotation);
1396 mpPolygonShapeAnnotation->setSelected(true);
1397 uncheckAllShapeDrawingActions();
1398 checkEmitUpdateSelect(false, mpPolygonShapeAnnotation);
1399}
1400
1401void GraphicsView::finishDrawingRectangleShape()
1402{
1403 setIsCreatingRectangleShape(false);
1404 setOriginAdjustAndInitialize(mpRectangleShapeAnnotation);
1405 mpRectangleShapeAnnotation->setSelected(true);
1406 uncheckAllShapeDrawingActions();
1407 checkEmitUpdateSelect(false, mpRectangleShapeAnnotation);
1408}
1409
1410
1411void GraphicsView::finishDrawingEllipseShape()
1412{
1413 setIsCreatingEllipseShape(false);
1414 setOriginAdjustAndInitialize(mpEllipseShapeAnnotation);
1415 mpEllipseShapeAnnotation->setSelected(true);
1416 uncheckAllShapeDrawingActions();
1417 checkEmitUpdateSelect(false, mpEllipseShapeAnnotation);
1418}
1419
1420void GraphicsView::finishDrawingTextShape()
1421{
1422 setIsCreatingTextShape(false);
1423 setOriginAdjustAndInitialize(mpTextShapeAnnotation);
1424 uncheckAllShapeDrawingActions();
1425 checkEmitUpdateSelect(true, mpTextShapeAnnotation);
1426}
1427
1428void GraphicsView::finishDrawingBitmapShape() {
1429 setIsCreatingBitmapShape(false);
1430 setOriginAdjustAndInitialize(mpBitmapShapeAnnotation);
1431 uncheckAllShapeDrawingActions();
1432 checkEmitUpdateSelect(true, mpBitmapShapeAnnotation);
1433}
1434
1435void GraphicsView::checkEmitUpdateSelect(const bool showPropertiesAndSelect, ShapeAnnotation* shapeAnnotation)
1436{
1437 MainWindow *pMainWindow = MainWindow::instance();
1438 pMainWindow->getConnectModeAction()->setChecked(true);
1439 mpModelWidget->getLibraryTreeItem()->emitShapeAdded(shapeAnnotation, this);
1440 if (showPropertiesAndSelect) {
1441 shapeAnnotation->showShapeProperties();
1442 // set the focus back on GraphicsView once the shape properties dialog is closed.
1443 setFocus(Qt::ActiveWindowFocusReason);
1444 }
1445 mpModelWidget->updateClassAnnotationIfNeeded();
1446 mpModelWidget->updateModelText();
1447 if (showPropertiesAndSelect) {
1448 shapeAnnotation->setSelected(true);
1449 }
1450}
1451
1452void GraphicsView::setOriginAdjustAndInitialize(ShapeAnnotation* shapeAnnotation)
1453{
1454 shapeAnnotation->setOrigin(shapeAnnotation->sceneBoundingRect().center());
1455 adjustInitializeDraw(shapeAnnotation);
1456}
1457
1458void GraphicsView::setOriginAdjustAndInitialize(PolygonAnnotation* shapeAnnotation)
1459{
1460 shapeAnnotation->setOrigin(roundPoint(shapeAnnotation->sceneBoundingRect().center()));
1461 adjustInitializeDraw(shapeAnnotation);
1462}
1463
1464void GraphicsView::adjustInitializeDraw(ShapeAnnotation* shapeAnnotation)
1465{
1466 if (dynamic_cast<LineAnnotation*>(shapeAnnotation) || dynamic_cast<PolygonAnnotation*>(shapeAnnotation)) {
1467 shapeAnnotation->adjustPointsWithOrigin();
1468 } else {
1469 shapeAnnotation->adjustExtentsWithOrigin();
1470 }
1471 shapeAnnotation->initializeTransformation();
1472 shapeAnnotation->drawCornerItems();
1473}
1474
1475/*!
1476 * \brief GraphicsView::itemsBoundingRect
1477 * Gets the bounding rectangle of all the items added to the view, excluding background and so on
1478 * \return
1479 */
1480QRectF GraphicsView::itemsBoundingRect()
1481{
1482 QRectF rect;
1483 foreach (Component *pComponent, mComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
1484 rect |= pComponent->itemsBoundingRect();
1485 }
1486 foreach (QGraphicsItem *item, mShapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mShapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QGraphicsItem
*item = *_container_.i; _container_.control; _container_.control
= 0)
{
1487 if (TextAnnotation *pTextAnnotation = dynamic_cast<TextAnnotation*>(item)) {
1488 rect |= pTextAnnotation->mExportBoundingRect;
1489 } else {
1490 rect |= item->sceneBoundingRect();
1491 }
1492 }
1493 foreach (QGraphicsItem *item, mConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QGraphicsItem
*item = *_container_.i; _container_.control; _container_.control
= 0)
{
1494 rect |= item->sceneBoundingRect();
1495 }
1496 foreach (Component *pComponent, mInheritedComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInheritedComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
1497 rect |= pComponent->itemsBoundingRect();
1498 }
1499 foreach (QGraphicsItem *item, mInheritedShapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInheritedShapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QGraphicsItem
*item = *_container_.i; _container_.control; _container_.control
= 0)
{
1500 rect |= item->sceneBoundingRect();
1501 }
1502 foreach (QGraphicsItem *item, mInheritedConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInheritedConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QGraphicsItem
*item = *_container_.i; _container_.control; _container_.control
= 0)
{
1503 rect |= item->sceneBoundingRect();
1504 }
1505 qreal x1, y1, x2, y2;
1506 rect.getCoords(&x1, &y1, &x2, &y2);
1507 rect.setCoords(x1 -5, y1 -5, x2 + 5, y2 + 5);
1508 return mapFromScene(rect).boundingRect();
1509}
1510
1511QPointF GraphicsView::snapPointToGrid(QPointF point)
1512{
1513 qreal stepX = mCoOrdinateSystem.getHorizontalGridStep();
1514 qreal stepY = mCoOrdinateSystem.getVerticalGridStep();
1515 point.setX(stepX * qFloor((point.x() / stepX) + 0.5));
1516 point.setY(stepY * qFloor((point.y() / stepY) + 0.5));
1517 return point;
1518}
1519
1520QPointF GraphicsView::movePointByGrid(QPointF point, QPointF origin, bool useShiftModifier)
1521{
1522 qreal stepX = mCoOrdinateSystem.getHorizontalGridStep() * ((useShiftModifier && QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)) ? 5 : 1);
1523 qreal stepY = mCoOrdinateSystem.getVerticalGridStep() * ((useShiftModifier && QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)) ? 5 : 1);
1524 if (useShiftModifier && QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)) {
1525 int modX = (int)fabs(origin.x()) % (int)stepX;
1526 int modY = (int)fabs(origin.y()) % (int)stepY;
1527 if (modX != 0) {
1528 if ((point.x() < 0 && origin.x() > 0) || (point.x() > 0 && origin.x() < 0)) {
1529 stepX = modX;
1530 } else if ((point.x() > 0 && origin.x() > 0) || (point.x() < 0 && origin.x() < 0)) {
1531 stepX = stepX - modX;
1532 }
1533 }
1534 if (modY != 0) {
1535 if ((point.y() < 0 && origin.y() > 0) || (point.y() > 0 && origin.y() < 0)) {
1536 stepY = modY;
1537 } else if ((point.y() > 0 && origin.y() > 0) || (point.y() < 0 && origin.y() < 0)) {
1538 stepY = stepY - modY;
1539 }
1540 }
1541 }
1542 point.setX(qRound(point.x() / stepX) * stepX);
1543 point.setY(qRound(point.y() / stepY) * stepY);
1544 return point;
1545}
1546
1547QPointF GraphicsView::roundPoint(QPointF point)
1548{
1549 qreal divisor = 0.5;
1550 qreal x = (fmod(point.x(), divisor) == 0) ? point.x() : qRound(point.x());
1551 qreal y = (fmod(point.y(), divisor) == 0) ? point.y() : qRound(point.y());
1552 return QPointF(x, y);
1553}
1554
1555/*!
1556 * \brief GraphicsView::hasIconAnnotation
1557 * Checks if class has annotation.
1558 * \return
1559 */
1560bool GraphicsView::hasAnnotation()
1561{
1562 // check inherited shapes and components
1563 if (!mInheritedShapesList.isEmpty()) {
1564 return true;
1565 }
1566 foreach (Component *pInheritedComponent, mInheritedComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInheritedComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pInheritedComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
1567 if (pInheritedComponent->hasShapeAnnotation(pInheritedComponent) && pInheritedComponent->isVisible()) {
1568 return true;
1569 }
1570 }
1571 // check shapes and components
1572 if (!mShapesList.isEmpty()) {
1573 return true;
1574 }
1575 foreach (Component *pComponent, mComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
1576 if (pComponent->hasShapeAnnotation(pComponent) && pComponent->isVisible()) {
1577 return true;
1578 }
1579 }
1580 return false;
1581}
1582
1583/*!
1584 * \brief GraphicsView::addItem
1585 * Adds the QGraphicsItem from GraphicsView
1586 * \param pGraphicsItem
1587 */
1588void GraphicsView::addItem(QGraphicsItem *pGraphicsItem)
1589{
1590 if (!mAllItems.contains(pGraphicsItem)) {
1591 mAllItems.insert(pGraphicsItem);
1592 scene()->addItem(pGraphicsItem);
1593 }
1594}
1595
1596/*!
1597 * \brief GraphicsView::removeItem
1598 * Removes the QGraphicsItem from GraphicsView
1599 * \param pGraphicsItem
1600 */
1601void GraphicsView::removeItem(QGraphicsItem *pGraphicsItem)
1602{
1603 if (mAllItems.contains(pGraphicsItem)) {
1604 mAllItems.remove(pGraphicsItem);
1605 scene()->removeItem(pGraphicsItem);
1606 }
1607}
1608
1609/*!
1610 * \brief GraphicsView::fitInView
1611 * Fits the view.
1612 */
1613void GraphicsView::fitInViewInternal()
1614{
1615 // only resize the view if user has not set any custom scaling like zoom in and zoom out.
1616 if (!isCustomScale()) {
1617 // make the fitInView rectangle bigger so that the scene rectangle will show up properly on the screen.
1618 QRectF extentRectangle = getExtentRectangle();
1619 qreal x1, y1, x2, y2;
1620 extentRectangle.getCoords(&x1, &y1, &x2, &y2);
1621 extentRectangle.setCoords(x1 -5, y1 -5, x2 + 5, y2 + 5);
1622 fitInView(extentRectangle, Qt::KeepAspectRatio);
1623 }
1624}
1625
1626/*!
1627 * \brief GraphicsView::createActions
1628 * Creates the actions for the GraphicsView.
1629 */
1630void GraphicsView::createActions()
1631{
1632 bool isSystemLibrary = mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView();
1633 // Graphics View Properties Action
1634 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
1635 mpPropertiesAction = new QAction(Helper::systemSimulationInformation, this);
1636 } else {
1637 mpPropertiesAction = new QAction(Helper::properties, this);
1638 }
1639 connect(mpPropertiesAction, SIGNAL(triggered())"2""triggered()", SLOT(showGraphicsViewProperties())"1""showGraphicsViewProperties()");
1640 // rename Action
1641 mpRenameAction = new QAction(Helper::rename, this);
1642 mpRenameAction->setStatusTip(Helper::renameTip);
1643 connect(mpRenameAction, SIGNAL(triggered())"2""triggered()", SLOT(showRenameDialog())"1""showRenameDialog()");
1644 // Simulation Params Action
1645 mpSimulationParamsAction = new QAction(ResourceCache::getIcon(":/Resources/icons/simulation-parameters.svg"), Helper::simulationParams, this);
1646 mpSimulationParamsAction->setStatusTip(Helper::simulationParamsTip);
1647 connect(mpSimulationParamsAction, SIGNAL(triggered())"2""triggered()", SLOT(showSimulationParamsDialog())"1""showSimulationParamsDialog()");
1648 // Actions for shapes and Components
1649 // Manhattanize Action
1650 mpManhattanizeAction = new QAction(tr("Manhattanize"), this);
1651 mpManhattanizeAction->setStatusTip(tr("Manhattanize the lines"));
1652 mpManhattanizeAction->setDisabled(isSystemLibrary);
1653 connect(mpManhattanizeAction, SIGNAL(triggered())"2""triggered()", SLOT(manhattanizeItems())"1""manhattanizeItems()");
1654 // Delete Action
1655 mpDeleteAction = new QAction(ResourceCache::getIcon(":/Resources/icons/delete.svg"), Helper::deleteStr, this);
1656 mpDeleteAction->setStatusTip(tr("Deletes the item"));
1657 mpDeleteAction->setShortcut(QKeySequence::Delete);
1658 mpDeleteAction->setDisabled(isSystemLibrary);
1659 connect(mpDeleteAction, SIGNAL(triggered())"2""triggered()", SLOT(deleteItems())"1""deleteItems()");
1660 // cut action
1661 mpCutAction = new QAction(ResourceCache::getIcon(":/Resources/icons/cut.svg"), tr("Cut"), this);
1662 mpCutAction->setShortcut(QKeySequence("Ctrl+x"));
1663 mpCutAction->setDisabled(isSystemLibrary);
1664 connect(mpCutAction, SIGNAL(triggered())"2""triggered()", SLOT(cutItems())"1""cutItems()");
1665 // copy action
1666 mpCopyAction = new QAction(ResourceCache::getIcon(":/Resources/icons/copy.svg"), Helper::copy, this);
1667 mpCopyAction->setShortcut(QKeySequence("Ctrl+c"));
1668 connect(mpCopyAction, SIGNAL(triggered())"2""triggered()", SLOT(copyItems())"1""copyItems()");
1669 // paste action
1670 mpPasteAction = new QAction(ResourceCache::getIcon(":/Resources/icons/paste.svg"), tr("Paste"), this);
1671 mpPasteAction->setShortcut(QKeySequence("Ctrl+v"));
1672 mpPasteAction->setDisabled(isSystemLibrary);
1673 connect(mpPasteAction, SIGNAL(triggered())"2""triggered()", SLOT(pasteItems())"1""pasteItems()");
1674 // Duplicate Action
1675 mpDuplicateAction = new QAction(ResourceCache::getIcon(":/Resources/icons/duplicate.svg"), Helper::duplicate, this);
1676 mpDuplicateAction->setStatusTip(Helper::duplicateTip);
1677 mpDuplicateAction->setShortcut(QKeySequence("Ctrl+d"));
1678 mpDuplicateAction->setDisabled(isSystemLibrary);
1679 connect(mpDuplicateAction, SIGNAL(triggered())"2""triggered()", SLOT(duplicateItems())"1""duplicateItems()");
1680 // Bring To Front Action
1681 mpBringToFrontAction = new QAction(ResourceCache::getIcon(":/Resources/icons/bring-to-front.svg"), tr("Bring to Front"), this);
1682 mpBringToFrontAction->setStatusTip(tr("Brings the item to front"));
1683 mpBringToFrontAction->setDisabled(isSystemLibrary);
1684 mpBringToFrontAction->setDisabled(true);
1685 // Bring Forward Action
1686 mpBringForwardAction = new QAction(ResourceCache::getIcon(":/Resources/icons/bring-forward.svg"), tr("Bring Forward"), this);
1687 mpBringForwardAction->setStatusTip(tr("Brings the item one level forward"));
1688 mpBringForwardAction->setDisabled(isSystemLibrary);
1689 mpBringForwardAction->setDisabled(true);
1690 // Send To Back Action
1691 mpSendToBackAction = new QAction(ResourceCache::getIcon(":/Resources/icons/send-to-back.svg"), tr("Send to Back"), this);
1692 mpSendToBackAction->setStatusTip(tr("Sends the item to back"));
1693 mpSendToBackAction->setDisabled(isSystemLibrary);
1694 mpSendToBackAction->setDisabled(true);
1695 // Send Backward Action
1696 mpSendBackwardAction = new QAction(ResourceCache::getIcon(":/Resources/icons/send-backward.svg"), tr("Send Backward"), this);
1697 mpSendBackwardAction->setStatusTip(tr("Sends the item one level backward"));
1698 mpSendBackwardAction->setDisabled(isSystemLibrary);
1699 mpSendBackwardAction->setDisabled(true);
1700 // Rotate ClockWise Action
1701 mpRotateClockwiseAction = new QAction(ResourceCache::getIcon(":/Resources/icons/rotateclockwise.svg"), tr("Rotate Clockwise"), this);
1702 mpRotateClockwiseAction->setStatusTip(tr("Rotates the item clockwise"));
1703 mpRotateClockwiseAction->setShortcut(QKeySequence("Ctrl+r"));
1704 mpRotateClockwiseAction->setDisabled(isSystemLibrary);
1705 connect(mpRotateClockwiseAction, SIGNAL(triggered())"2""triggered()", SLOT(rotateClockwise())"1""rotateClockwise()");
1706 // Rotate Anti-ClockWise Action
1707 mpRotateAntiClockwiseAction = new QAction(ResourceCache::getIcon(":/Resources/icons/rotateanticlockwise.svg"), tr("Rotate Anticlockwise"), this);
1708 mpRotateAntiClockwiseAction->setStatusTip(tr("Rotates the item anticlockwise"));
1709 mpRotateAntiClockwiseAction->setShortcut(QKeySequence("Ctrl+Shift+r"));
1710 mpRotateAntiClockwiseAction->setDisabled(isSystemLibrary);
1711 connect(mpRotateAntiClockwiseAction, SIGNAL(triggered())"2""triggered()", SLOT(rotateAntiClockwise())"1""rotateAntiClockwise()");
1712 // Flip Horizontal Action
1713 mpFlipHorizontalAction = new QAction(ResourceCache::getIcon(":/Resources/icons/flip-horizontal.svg"), tr("Flip Horizontal"), this);
1714 mpFlipHorizontalAction->setStatusTip(tr("Flips the item horizontally"));
1715 mpFlipHorizontalAction->setShortcut(QKeySequence("h"));
1716 mpFlipHorizontalAction->setDisabled(isSystemLibrary);
1717 connect(mpFlipHorizontalAction, SIGNAL(triggered())"2""triggered()", SLOT(flipHorizontal())"1""flipHorizontal()");
1718 // Flip Vertical Action
1719 mpFlipVerticalAction = new QAction(ResourceCache::getIcon(":/Resources/icons/flip-vertical.svg"), tr("Flip Vertical"), this);
1720 mpFlipVerticalAction->setStatusTip(tr("Flips the item vertically"));
1721 mpFlipVerticalAction->setShortcut(QKeySequence("v"));
1722 mpFlipVerticalAction->setDisabled(isSystemLibrary);
1723 connect(mpFlipVerticalAction, SIGNAL(triggered())"2""triggered()", SLOT(flipVertical())"1""flipVertical()");
1724 // set initial state Action
1725 mpSetInitialStateAction = new QAction(tr("Set Initial State"), this);
1726 mpSetInitialStateAction->setStatusTip(tr("Sets the state as initial state"));
1727 connect(mpSetInitialStateAction, SIGNAL(triggered())"2""triggered()", SLOT(setInitialState())"1""setInitialState()");
1728 // cancel transition Action
1729 mpCancelTransitionAction = new QAction(tr("Cancel Transition"), this);
1730 mpCancelTransitionAction->setStatusTip(tr("Cancels the current transition"));
1731 connect(mpCancelTransitionAction, SIGNAL(triggered())"2""triggered()", SLOT(cancelTransition())"1""cancelTransition()");
1732}
1733
1734/*!
1735 * \brief GraphicsView::isItemDroppedOnItself
1736 * Checks if item is dropped on itself.
1737 * \param pLibraryTreeItem
1738 * \return
1739 */
1740bool GraphicsView::isClassDroppedOnItself(LibraryTreeItem *pLibraryTreeItem)
1741{
1742 OptionsDialog *pOptionsDialog = OptionsDialog::instance();
1743 if (mpModelWidget->getLibraryTreeItem()->getNameStructure().compare(pLibraryTreeItem->getNameStructure()) == 0) {
1744 if (pOptionsDialog->getNotificationsPage()->getItemDroppedOnItselfCheckBox()->isChecked()) {
1745 NotificationsDialog *pNotificationsDialog = new NotificationsDialog(NotificationsDialog::ItemDroppedOnItself,
1746 NotificationsDialog::InformationIcon,
1747 MainWindow::instance());
1748 pNotificationsDialog->exec();
1749 }
1750 return true;
1751 }
1752 return false;
1753}
1754
1755/*!
1756 * \brief GraphicsView::isAnyItemSelectedAndEditable
1757 * If the class is system library then returns false.
1758 * Checks all the selected items. If the selected item is not inherited then returns true otherwise false.
1759 * \param key
1760 * \return
1761 */
1762bool GraphicsView::isAnyItemSelectedAndEditable(int key)
1763{
1764 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) {
1765 return false;
1766 }
1767 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
1768 if (mpModelWidget->getLibraryTreeItem()->isComponentElement()) {
1769 switch (key) {
1770 case Qt::Key_Delete:
1771 case Qt::Key_R: // rotate
1772 case Qt::Key_H: // horizontal flip
1773 case Qt::Key_V: // vertical flip
1774 return false;
1775 default:
1776 break;
1777 }
1778 }
1779 }
1780 bool selectedAndEditable = false;
1781 QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
1782 for (int i = 0 ; i < selectedItems.size() ; i++) {
1783 // check the selected components.
1784 Component *pComponent = dynamic_cast<Component*>(selectedItems.at(i));
1785 if (pComponent && !pComponent->isInheritedComponent()) {
1786 return true;
1787 }
1788 // check the selected connections and shapes.
1789 ShapeAnnotation *pShapeAnnotation = dynamic_cast<ShapeAnnotation*>(selectedItems.at(i));
1790 if (pShapeAnnotation && !pShapeAnnotation->isInheritedShape()) {
1791 LineAnnotation *pLineAnnotation = dynamic_cast<LineAnnotation*>(pShapeAnnotation);
1792 // if the shape is connection line then we only return true for certain cases.
1793 if (pLineAnnotation && pLineAnnotation->getLineType() == LineAnnotation::ConnectionType) {
1794 switch (key) {
1795 case Qt::Key_Delete:
1796 selectedAndEditable = true;
1797 break;
1798 default:
1799 selectedAndEditable = false;
1800 break;
1801 }
1802 } else {
1803 return true;
1804 }
1805 }
1806 }
1807 return selectedAndEditable;
1808}
1809
1810/*!
1811 * \brief GraphicsView::getComponentFromQGraphicsItem
1812 * \param pGraphicsItem
1813 * A QGraphicsItem can be a Component or a ShapeAnnotation inside a Component.
1814 * \return
1815 */
1816Component *GraphicsView::getComponentFromQGraphicsItem(QGraphicsItem *pGraphicsItem)
1817{
1818 if (pGraphicsItem) {
1819 Component *pComponent = dynamic_cast<Component*>(pGraphicsItem);
1820 if (!pComponent && pGraphicsItem->parentItem()) {
1821 pComponent = dynamic_cast<Component*>(pGraphicsItem->parentItem());
1822 }
1823 return pComponent;
1824 }
1825 return 0;
1826}
1827
1828/*!
1829 * \brief GraphicsView::componentAtPosition
1830 * Returns the first component at the position.
1831 * \param position
1832 * \return
1833 */
1834Component *GraphicsView::componentAtPosition(QPoint position)
1835{
1836 QList<QGraphicsItem*> graphicsItems = items(position);
1837 foreach (QGraphicsItem *pGraphicsItem, graphicsItems)for (auto _container_ = QtPrivate::qMakeForeachContainer(graphicsItems
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QGraphicsItem
*pGraphicsItem = *_container_.i; _container_.control; _container_
.control = 0)
{
1838 Component *pComponent = getComponentFromQGraphicsItem(pGraphicsItem);
1839 if (pComponent) {
1840 Component *pRootComponent = pComponent->getRootParentComponent();
1841 if (pRootComponent && pRootComponent->getLibraryTreeItem() && !pRootComponent->getLibraryTreeItem()->isNonExisting()) {
1842 return pRootComponent;
1843 }
1844 }
1845 }
1846 return 0;
1847}
1848
1849/*!
1850 * \brief GraphicsView::connectorComponentAtPosition
1851 * Returns the connector component at the position.
1852 * \param position
1853 * \return
1854 */
1855Component* GraphicsView::connectorComponentAtPosition(QPoint position)
1856{
1857 /* Ticket:4215
1858 * Allow making connection from the connectors which are under some other shape or component.
1859 * itemAt() only returns the top level item.
1860 * Use items() to get all items at position and then return the first connector component from the list.
1861 */
1862 QList<QGraphicsItem*> graphicsItems = items(position);
1863 foreach (QGraphicsItem *pGraphicsItem, graphicsItems)for (auto _container_ = QtPrivate::qMakeForeachContainer(graphicsItems
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QGraphicsItem
*pGraphicsItem = *_container_.i; _container_.control; _container_
.control = 0)
{
1864 Component *pComponent = getComponentFromQGraphicsItem(pGraphicsItem);
1865 if (pComponent) {
1866 Component *pRootComponent = pComponent->getRootParentComponent();
1867 if (pRootComponent && pRootComponent->isSelected()) {
1868 return 0;
1869 } else if (pRootComponent && !pRootComponent->isSelected()) {
1870 if (MainWindow::instance()->getConnectModeAction()->isChecked() && mViewType == StringHandler::Diagram &&
1871 !(mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) &&
1872 ((pComponent->getLibraryTreeItem() && pComponent->getLibraryTreeItem()->isConnector()) ||
1873 (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel &&
1874 pComponent->getComponentType() == Component::Port) ||
1875 (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS &&
1876 (pComponent->getLibraryTreeItem()->getOMSConnector() || pComponent->getLibraryTreeItem()->getOMSBusConnector()
1877 || pComponent->getLibraryTreeItem()->getOMSTLMBusConnector() || pComponent->getComponentType() == Component::Port)))) {
1878 return pComponent;
1879 }
1880 }
1881 }
1882 }
1883 return 0;
1884}
1885
1886/*!
1887 * \brief GraphicsView::stateComponentAtPosition
1888 * Returns the state component at the position.
1889 * \param position
1890 * \return
1891 */
1892Component* GraphicsView::stateComponentAtPosition(QPoint position)
1893{
1894 QList<QGraphicsItem*> graphicsItems = items(position);
1895 foreach (QGraphicsItem *pGraphicsItem, graphicsItems)for (auto _container_ = QtPrivate::qMakeForeachContainer(graphicsItems
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QGraphicsItem
*pGraphicsItem = *_container_.i; _container_.control; _container_
.control = 0)
{
1896 Component *pComponent = getComponentFromQGraphicsItem(pGraphicsItem);
1897 if (pComponent) {
1898 Component *pRootComponent = pComponent->getRootParentComponent();
1899 if (pRootComponent && !pRootComponent->isSelected()) {
1900 if (MainWindow::instance()->getTransitionModeAction()->isChecked() && mViewType == StringHandler::Diagram &&
1901 !(mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) &&
1902 ((pComponent->getLibraryTreeItem() && pComponent->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica &&
1903 !pComponent->getLibraryTreeItem()->isNonExisting() && pComponent->getLibraryTreeItem()->isState()))) {
1904 return pComponent;
1905 }
1906 }
1907 }
1908 }
1909 return 0;
1910}
1911
1912/*!
1913 * \brief GraphicsView::updateComponentConnectorSizingParameter
1914 * Updates the component's connectorSizing parameter via the modifier.
1915 * \param pGraphicsView
1916 * \param className
1917 * \param pComponent
1918 * \return
1919 */
1920bool GraphicsView::updateComponentConnectorSizingParameter(GraphicsView *pGraphicsView, QString className, Component *pComponent)
1921{
1922 // if connectorSizing then set a new value for the connectorSizing parameter.
1923 if (pComponent->isConnectorSizing()) {
1924 QString parameter = pComponent->getComponentInfo()->getArrayIndex();
1925 int numberOfComponentConnections = pGraphicsView->numberOfComponentConnections(pComponent);
1926 QString modifierKey = QString("%1.%2").arg(pComponent->getRootParentComponent()->getName()).arg(parameter);
1927 MainWindow::instance()->getOMCProxy()->setComponentModifierValue(className, modifierKey, QString::number(numberOfComponentConnections));
1928 return true;
1929 }
1930 return false;
1931}
1932
1933/*!
1934 * \brief GraphicsView::addConnection
1935 * Adds the connection to GraphicsView.
1936 * \param pComponent
1937 */
1938void GraphicsView::addConnection(Component *pComponent)
1939{
1940 // When clicking the start component
1941 if (!isCreatingConnection()) {
1942 QPointF startPos;
1943 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
1944 startPos = roundPoint(pComponent->mapToScene(pComponent->boundingRect().center()));
1945 } else {
1946 startPos = snapPointToGrid(pComponent->mapToScene(pComponent->boundingRect().center()));
1947 }
1948 mpConnectionLineAnnotation = new LineAnnotation(LineAnnotation::ConnectionType, pComponent, this);
1949 setIsCreatingConnection(true);
1950 mpConnectionLineAnnotation->addPoint(startPos);
1951 mpConnectionLineAnnotation->addPoint(startPos);
1952 mpConnectionLineAnnotation->addPoint(startPos);
1953 /* Ticket:4196
1954 * If we are starting connection from expandable connector or (array && !connectorSizing) connector
1955 * then set the line thickness to 0.5
1956 */
1957 Component *pRootParentComponent = pComponent->getParentComponent() ? pComponent->getRootParentComponent() : 0;
1958 if (pComponent->isExpandableConnector()
1959 || (pComponent->isArray() && !pComponent->isConnectorSizing())
1960 || (pRootParentComponent && (pRootParentComponent->isExpandableConnector() || (pRootParentComponent->isArray() && !pRootParentComponent->isConnectorSizing())))) {
1961 mpConnectionLineAnnotation->setLineThickness(0.5);
1962 }
1963 } else { // When clicking the end component
1964 mpConnectionLineAnnotation->setEndComponent(pComponent);
1965 // update the last point to the center of component
1966 QPointF newPos;
1967 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
1968 newPos = roundPoint(pComponent->mapToScene(pComponent->boundingRect().center()));
1969 } else {
1970 newPos = snapPointToGrid(pComponent->mapToScene(pComponent->boundingRect().center()));
1971 }
1972 mpConnectionLineAnnotation->updateEndPoint(newPos);
1973 mpConnectionLineAnnotation->update();
1974 // check if connection is valid
1975 Component *pStartComponent = mpConnectionLineAnnotation->getStartComponent();
1976 MainWindow *pMainWindow = MainWindow::instance();
1977 if (pStartComponent == pComponent) {
1978 QMessageBox::information(pMainWindow, QString(Helper::applicationName).append(" - ").append(Helper::information),
1979 GUIMessages::getMessage(GUIMessages::SAME_COMPONENT_CONNECT), Helper::ok);
1980 removeCurrentConnection();
1981 } else {
1982 /* Ticket:4956
1983 * Only set the connection line thickness to 0.5 when both connectors are either expandable or (array && !connectorSizing).
1984 * Otherwise set it to 0.25 i.e., default.
1985 */
1986 Component *pStartRootParentComponent = pStartComponent->getParentComponent() ? pStartComponent->getRootParentComponent() : 0;
1987 Component *pRootParentComponent = pComponent->getParentComponent() ? pComponent->getRootParentComponent() : 0;
1988
1989 if ((pStartComponent->isExpandableConnector() || (pStartComponent->isArray() && !pStartComponent->isConnectorSizing())
1990 || (pStartRootParentComponent && (pStartRootParentComponent->isExpandableConnector() || (pStartRootParentComponent->isArray() && !pStartRootParentComponent->isConnectorSizing()))))
1991 && (pComponent->isExpandableConnector() || (pComponent->isArray() && !pComponent->isConnectorSizing())
1992 || (pRootParentComponent && (pRootParentComponent->isExpandableConnector() || (pRootParentComponent->isArray() && !pRootParentComponent->isConnectorSizing()))))) {
1993 mpConnectionLineAnnotation->setLineThickness(0.5);
1994 } else {
1995 /* Ticket:4956
1996 * If the start connector is either expandable or array and the end connector is not then change the line color to end connector.
1997 */
1998 if ((pStartComponent->isExpandableConnector() || pStartComponent->isArray()
1999 || (pStartRootParentComponent && (pStartRootParentComponent->isExpandableConnector() || pStartRootParentComponent->isArray())))
2000 && (!(pComponent->isExpandableConnector() || pComponent->isArray()
2001 || (pRootParentComponent && (pRootParentComponent->isExpandableConnector() || pRootParentComponent->isArray()))))) {
2002 if (pComponent->getLibraryTreeItem()) {
2003 if (!pComponent->getLibraryTreeItem()->getModelWidget()) {
2004 MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel()->showModelWidget(pComponent->getLibraryTreeItem(), false);
2005 }
2006 ShapeAnnotation *pShapeAnnotation;
2007 if (pComponent->getLibraryTreeItem()->getModelWidget()->getIconGraphicsView()
2008 && pComponent->getLibraryTreeItem()->getModelWidget()->getIconGraphicsView()->getShapesList().size() > 0) {
2009 pShapeAnnotation = pComponent->getLibraryTreeItem()->getModelWidget()->getIconGraphicsView()->getShapesList().at(0);
2010 mpConnectionLineAnnotation->setLineColor(pShapeAnnotation->getLineColor());
2011 } else if (pComponent->getShapesList().size() > 0) {
2012 ShapeAnnotation *pShapeAnnotation = pComponent->getShapesList().at(0);
2013 mpConnectionLineAnnotation->setLineColor(pShapeAnnotation->getLineColor());
2014 }
2015 }
2016 }
2017 mpConnectionLineAnnotation->setLineThickness(0.25);
2018 }
2019 // check if any of starting or ending components are array
2020 bool showConnectionArrayDialog = false;
2021 if ((pStartComponent->isExpandableConnector() || (pStartComponent->isArray() && !pStartComponent->isConnectorSizing())
2022 || (pStartRootParentComponent && (pStartRootParentComponent->isExpandableConnector() || (pStartRootParentComponent->isArray() && !pStartRootParentComponent->isConnectorSizing()))))
2023 || (pComponent->isExpandableConnector() || (pComponent->isArray() && !pComponent->isConnectorSizing())
2024 || (pRootParentComponent && (pRootParentComponent->isExpandableConnector() || (pRootParentComponent->isArray() && !pRootParentComponent->isConnectorSizing()))))) {
2025 showConnectionArrayDialog = true;
2026 }
2027 // check if any starting or ending components are bus
2028 bool showBusConnectionDialog = false;
2029 if ((pStartComponent->getLibraryTreeItem() && pStartComponent->getLibraryTreeItem()->getOMSBusConnector())
2030 || (pComponent->getLibraryTreeItem() && pComponent->getLibraryTreeItem()->getOMSBusConnector())) {
2031 showBusConnectionDialog = true;
2032 }
2033 // if connectorSizing annotation is set then don't show the CreateConnectionDialog
2034 if (showConnectionArrayDialog) {
2035 CreateConnectionDialog *pConnectionArray = new CreateConnectionDialog(this, mpConnectionLineAnnotation, MainWindow::instance());
2036 // if user cancels the array connection
2037 if (!pConnectionArray->exec()) {
2038 removeCurrentConnection();
2039 }
2040 } else if (showBusConnectionDialog) {
2041 BusConnectionDialog *pBusConnectionDialog = new BusConnectionDialog(this, mpConnectionLineAnnotation);
2042 // if user cancels the bus connection
2043 if (!pBusConnectionDialog->exec()) {
2044 removeCurrentConnection();
2045 }
2046 } else if ((pStartComponent->getLibraryTreeItem() && pStartComponent->getLibraryTreeItem()->getOMSTLMBusConnector())
2047 && (pComponent->getLibraryTreeItem() && pComponent->getLibraryTreeItem()->getOMSTLMBusConnector())) {
2048 TLMConnectionDialog *pTLMBusConnectionDialog = new TLMConnectionDialog(this, mpConnectionLineAnnotation);
2049 // if user cancels the tlm bus connection
2050 if (!pTLMBusConnectionDialog->exec()) {
2051 removeCurrentConnection();
2052 }
2053 } else {
2054 QString startComponentName, endComponentName;
2055 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
2056 if (pStartComponent->getLibraryTreeItem()) {
2057 startComponentName = pStartComponent->getLibraryTreeItem()->getNameStructure();
2058 }
2059 if (pComponent->getLibraryTreeItem()) {
2060 endComponentName = pComponent->getLibraryTreeItem()->getNameStructure();
2061 }
2062 } else {
2063 int numberOfStartComponentConnections = numberOfComponentConnections(pStartComponent);
2064 if (pStartComponent->getParentComponent()) {
2065 if (pStartComponent->isConnectorSizing()) {
2066 startComponentName = QString("%1.%2[%3]").arg(pStartComponent->getRootParentComponent()->getName()).arg(pStartComponent->getName()).arg(++numberOfStartComponentConnections);
2067 } else {
2068 startComponentName = QString("%1.%2").arg(pStartComponent->getRootParentComponent()->getName()).arg(pStartComponent->getName());
2069 }
2070 } else {
2071 if (pStartComponent->isConnectorSizing()) {
2072 startComponentName = QString("%1[%2]").arg(pStartComponent->getName()).arg(++numberOfStartComponentConnections);
2073 } else {
2074 startComponentName = pStartComponent->getName();
2075 }
2076 }
2077 int numberOfEndComponentConnections = numberOfComponentConnections(pComponent);
2078 if (pComponent->getParentComponent()) {
2079 if (pComponent->isConnectorSizing()) {
2080 endComponentName = QString("%1.%2[%3]").arg(pComponent->getRootParentComponent()->getName()).arg(pComponent->getName()).arg(++numberOfEndComponentConnections);
2081 } else {
2082 endComponentName = QString("%1.%2").arg(pComponent->getRootParentComponent()->getName()).arg(pComponent->getName());
2083 }
2084 } else {
2085 if (pComponent->isConnectorSizing()) {
2086 endComponentName = QString("%1[%2]").arg(pComponent->getName()).arg(++numberOfEndComponentConnections);
2087 } else {
2088 endComponentName = pComponent->getName();
2089 }
2090 }
2091 }
2092 mpConnectionLineAnnotation->setStartComponentName(startComponentName);
2093 mpConnectionLineAnnotation->setEndComponentName(endComponentName);
2094 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel) {
2095 CompositeModelEditor* editor = dynamic_cast<CompositeModelEditor*>(mpModelWidget->getEditor());
2096 if (!editor->okToConnect(mpConnectionLineAnnotation)) {
2097 removeCurrentConnection();
2098 }
2099 else {
2100 CompositeModelConnectionAttributes *pCompositeModelConnectionAttributes;
2101 pCompositeModelConnectionAttributes = new CompositeModelConnectionAttributes(this, mpConnectionLineAnnotation, false, MainWindow::instance());
2102 // if user cancels the array connection
2103 if (!pCompositeModelConnectionAttributes->exec()) {
2104 removeCurrentConnection();
2105 }
2106 }
2107 } else {
2108 mpModelWidget->getUndoStack()->push(new AddConnectionCommand(mpConnectionLineAnnotation, true));
2109 mpModelWidget->getLibraryTreeItem()->emitConnectionAdded(mpConnectionLineAnnotation);
2110 mpModelWidget->updateModelText();
2111 }
2112 }
2113 setIsCreatingConnection(false);
2114 }
2115 }
2116}
2117
2118/*!
2119 * \brief GraphicsView::removeCurrentConnection
2120 * Removes the current connecting connector from the model.
2121 */
2122void GraphicsView::removeCurrentConnection()
2123{
2124 if (isCreatingConnection()) {
2125 setIsCreatingConnection(false);
2126 removeItem(mpConnectionLineAnnotation);
2127 delete mpConnectionLineAnnotation;
2128 mpConnectionLineAnnotation = 0;
2129 }
2130}
2131
2132void GraphicsView::addTransition(Component *pComponent)
2133{
2134 // When clicking the start state
2135 if (!isCreatingTransition()) {
2136 QPointF startPos = snapPointToGrid(pComponent->mapToScene(pComponent->boundingRect().center()));
2137 mpTransitionLineAnnotation = new LineAnnotation(LineAnnotation::TransitionType, pComponent, this);
2138 mpTransitionLineAnnotation->getTextAnnotation()->setVisible(false);
2139 setIsCreatingTransition(true);
2140 mpTransitionLineAnnotation->addPoint(startPos);
2141 mpTransitionLineAnnotation->addPoint(startPos);
2142 mpTransitionLineAnnotation->addPoint(startPos);
2143 } else if (isCreatingTransition()) { // When clicking the end state
2144 mpTransitionLineAnnotation->setEndComponent(pComponent);
2145 // Remove reduntant points so that Liang Barsky algorithm can work well.
2146 mpTransitionLineAnnotation->removeRedundantPointsGeometriesAndCornerItems();
2147 QList<QPointF> points = mpTransitionLineAnnotation->getPoints();
2148 // Find the start state intersection point.
2149 QRectF sceneRectF = mpTransitionLineAnnotation->getStartComponent()->sceneBoundingRect();
2150 QList<QPointF> newPos = Utilities::liangBarskyClipper(sceneRectF.topLeft().x(), sceneRectF.topLeft().y(),
2151 sceneRectF.bottomRight().x(), sceneRectF.bottomRight().y(),
2152 points.at(0).x(), points.at(0).y(),
2153 points.at(1).x(), points.at(1).y());
2154 mpTransitionLineAnnotation->updateStartPoint(snapPointToGrid(newPos.at(1)));
2155 // Find the end state intersection point.
2156 sceneRectF = pComponent->sceneBoundingRect();
2157 newPos = Utilities::liangBarskyClipper(sceneRectF.topLeft().x(), sceneRectF.topLeft().y(),
2158 sceneRectF.bottomRight().x(), sceneRectF.bottomRight().y(),
2159 points.at(points.size() - 2).x(), points.at(points.size() - 2).y(),
2160 points.at(points.size() - 1).x(), points.at(points.size() - 1).y());
2161 mpTransitionLineAnnotation->updateEndPoint(snapPointToGrid(newPos.at(0)));
2162 mpTransitionLineAnnotation->update();
2163 // check if connection is valid
2164 Component *pStartComponent = mpTransitionLineAnnotation->getStartComponent();
2165 if (pStartComponent == pComponent) {
2166 QMessageBox::information(MainWindow::instance(), QString(Helper::applicationName).append(" - ").append(Helper::information),
2167 GUIMessages::getMessage(GUIMessages::SAME_COMPONENT_CONNECT), Helper::ok);
2168 removeCurrentTransition();
2169 } else {
2170 QString startComponentName, endComponentName;
2171 if (pStartComponent->getParentComponent()) {
2172 startComponentName = QString(pStartComponent->getRootParentComponent()->getName()).append(".").append(pStartComponent->getName());
2173 } else {
2174 startComponentName = pStartComponent->getName();
2175 }
2176 if (pComponent->getParentComponent()) {
2177 endComponentName = QString(pComponent->getRootParentComponent()->getName()).append(".").append(pComponent->getName());
2178 } else {
2179 endComponentName = pComponent->getName();
2180 }
2181 mpTransitionLineAnnotation->setStartComponentName(startComponentName);
2182 mpTransitionLineAnnotation->setEndComponentName(endComponentName);
2183 CreateOrEditTransitionDialog *pCreateOrEditTransitionDialog = new CreateOrEditTransitionDialog(this, mpTransitionLineAnnotation, false,
2184 MainWindow::instance());
2185 if (!pCreateOrEditTransitionDialog->exec()) {
2186 removeCurrentTransition();
2187 }
2188 }
2189 setIsCreatingTransition(false);
2190 }
2191}
2192
2193/*!
2194 * \brief GraphicsView::removeCurrentTransition
2195 * Removes the current connecting transition from the model.
2196 */
2197void GraphicsView::removeCurrentTransition()
2198{
2199 if (isCreatingTransition()) {
2200 setIsCreatingTransition(false);
2201 delete mpTransitionLineAnnotation;
2202 mpTransitionLineAnnotation = 0;
2203 }
2204}
2205
2206/*!
2207 * \brief GraphicsView::deleteConnection
2208 * Deletes the connection from the class.
2209 * \param pConnectionLineAnnotation - is a pointer to the connection to delete.
2210 */
2211void GraphicsView::deleteConnection(LineAnnotation *pConnectionLineAnnotation)
2212{
2213 pConnectionLineAnnotation->setSelected(false);
2214 // if deleting a bus connection
2215 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
2216 if (pConnectionLineAnnotation->getStartComponent()->getLibraryTreeItem()
2217 && pConnectionLineAnnotation->getStartComponent()->getLibraryTreeItem()->getOMSBusConnector()
2218 && pConnectionLineAnnotation->getEndComponent()->getLibraryTreeItem()
2219 && pConnectionLineAnnotation->getEndComponent()->getLibraryTreeItem()->getOMSBusConnector()) {
2220 oms_busconnector_t *pStartBus = pConnectionLineAnnotation->getStartComponent()->getLibraryTreeItem()->getOMSBusConnector();
2221 oms_busconnector_t *pEndBus = pConnectionLineAnnotation->getEndComponent()->getLibraryTreeItem()->getOMSBusConnector();
2222 // start bus connectors
2223 QStringList startBusConnectors;
2224 if (pStartBus->connectors) {
2225 for (int i = 0; pStartBus->connectors[i] ; ++i) {
2226 startBusConnectors.append(QString(pStartBus->connectors[i]));
2227 }
2228 }
2229 // end bus connectors
2230 QStringList endBusConnectors;
2231 if (pEndBus->connectors) {
2232 for (int i = 0; pEndBus->connectors[i] ; ++i) {
2233 endBusConnectors.append(QString(pEndBus->connectors[i]));
2234 }
2235 }
2236 // Delete the atomic connections before deleting the actual bus connection.
2237 foreach (LineAnnotation *pAtomicConnectionLineAnnotation, mConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pAtomicConnectionLineAnnotation = *_container_.i; _container_
.control; _container_.control = 0)
{
2238 if (pAtomicConnectionLineAnnotation->getOMSConnectionType() == oms_connection_single) {
2239 if (pStartBus->connectors) {
2240 for (int i = 0; pStartBus->connectors[i] ; ++i) {
2241 if (startBusConnectors.contains(pAtomicConnectionLineAnnotation->getStartComponent()->getName())
2242 && endBusConnectors.contains(pAtomicConnectionLineAnnotation->getEndComponent()->getName())) {
2243 mpModelWidget->getUndoStack()->push(new DeleteConnectionCommand(pAtomicConnectionLineAnnotation));
2244 break;
2245 }
2246 }
2247 }
2248 }
2249 }
2250 }
2251 }
2252 // Delete the connection
2253 mpModelWidget->getUndoStack()->push(new DeleteConnectionCommand(pConnectionLineAnnotation));
2254}
2255
2256/*!
2257 * \brief GraphicsView::deleteTransition
2258 * Deletes the transition from the class.
2259 * \param pTransitionLineAnnotation - is a pointer to the transition to delete.
2260 */
2261void GraphicsView::deleteTransition(LineAnnotation *pTransitionLineAnnotation)
2262{
2263 pTransitionLineAnnotation->setSelected(false);
2264 mpModelWidget->getUndoStack()->push(new DeleteTransitionCommand(pTransitionLineAnnotation));
2265}
2266
2267/*!
2268 * \brief GraphicsView::deleteInitialState
2269 * Deletes an initial state from the class.
2270 * \param pInitialLineAnnotation - is a pointer to the initial state to delete.
2271 */
2272void GraphicsView::deleteInitialState(LineAnnotation *pInitialLineAnnotation)
2273{
2274 pInitialLineAnnotation->setSelected(false);
2275 mpModelWidget->getUndoStack()->push(new DeleteInitialStateCommand(pInitialLineAnnotation));
2276}
2277
2278//! Resets zoom factor to 100%.
2279//! @see zoomIn()
2280//! @see zoomOut()
2281void GraphicsView::resetZoom()
2282{
2283 resetMatrix();
2284 scale(1.0, -1.0);
2285 setIsCustomScale(false);
2286 resizeEvent(new QResizeEvent(QSize(0,0), QSize(0,0)));
2287}
2288
2289//! Increases zoom factor by 12%.
2290//! @see resetZoom()
2291//! @see zoomOut()
2292void GraphicsView::zoomIn()
2293{
2294 // zoom in limitation max: 1000%
2295 if (matrix().m11() < 34 && matrix().m22() > -34) {
2296 setIsCustomScale(true);
2297 scale(1.12, 1.12);
2298 }
2299}
2300
2301//! Decreases zoom factor by 12%.
2302//! @see resetZoom()
2303//! @see zoomIn()
2304void GraphicsView::zoomOut()
2305{
2306 // zoom out limitation min: 10%
2307 if (matrix().m11() > 0.2 && matrix().m22() < -0.2) {
2308 setIsCustomScale(true);
2309 scale(1/1.12, 1/1.12);
2310 }
2311}
2312
2313/*!
2314 * \brief GraphicsView::selectAll
2315 * Selects all shapes, components and connectors.
2316 */
2317void GraphicsView::selectAll()
2318{
2319 foreach (QGraphicsItem *pGraphicsItem, items())for (auto _container_ = QtPrivate::qMakeForeachContainer(items
()); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QGraphicsItem
*pGraphicsItem = *_container_.i; _container_.control; _container_
.control = 0)
{
2320 pGraphicsItem->setSelected(true);
2321 }
2322}
2323
2324/*!
2325 * \brief GraphicsView::cutItems
2326 * Slot activated when mpCutAction triggered SIGNAL is raised.
2327 */
2328void GraphicsView::cutItems()
2329{
2330 copyItems(true);
2331}
2332
2333/*!
2334 * \brief GraphicsView::copyItems
2335 * Slot activated when mpCopyAction triggered SIGNAL is raised.
2336 */
2337void GraphicsView::copyItems()
2338{
2339 copyItems(false);
2340}
2341
2342/*!
2343 * \brief GraphicsView::copyItems
2344 * Copies the selected items to the clipboard.
2345 * \param cut - flag to know if we should cut the items or not.
2346 */
2347void GraphicsView::copyItems(bool cut)
2348{
2349 QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
2350 if (!selectedItems.isEmpty()) {
2351 QStringList components, connections, shapes, allItems;
2352 connections << "equation";
2353 MimeData *pMimeData = new MimeData;
2354 for (int i = 0 ; i < selectedItems.size() ; i++) {
2355 if (Component *pComponent = dynamic_cast<Component*>(selectedItems.at(i))) {
2356 // we need to get the modifiers here instead of inside pasteItems() because in case of cut the component is removed and then we can't fetch the modifiers.
2357 pComponent->getComponentInfo()->getModifiersMap(MainWindow::instance()->getOMCProxy(), pComponent->getGraphicsView()->getModelWidget()->getLibraryTreeItem()->getNameStructure(), pComponent);
2358 pMimeData->addComponent(pComponent);
2359 components << QString("%1 %2%3 %4;").arg(pComponent->getComponentInfo()->getClassName(), pComponent->getName(), "", pComponent->getPlacementAnnotation(true));
2360 } else if (ShapeAnnotation *pShapeAnnotation = dynamic_cast<ShapeAnnotation*>(selectedItems.at(i))) {
2361 LineAnnotation *pLineAnnotation = dynamic_cast<LineAnnotation*>(selectedItems.at(i));
2362 if (pLineAnnotation && pLineAnnotation->getLineType() == LineAnnotation::ConnectionType) {
2363 // Only consider the connection for copying if both the start and the end components are selected.
2364 if (pLineAnnotation->getStartComponent()->getRootParentComponent()->isSelected() && pLineAnnotation->getEndComponent()->getRootParentComponent()->isSelected()) {
2365 pMimeData->addConnection(pLineAnnotation);
2366 connections << QString("connect(%1, %2) annotation %3;").arg(pLineAnnotation->getStartComponentName(), pLineAnnotation->getEndComponentName(), pLineAnnotation->getShapeAnnotation());
2367 }
2368 } else {
2369 pMimeData->addShape(pShapeAnnotation);
2370 shapes << pShapeAnnotation->getShapeAnnotation();
2371 }
2372 }
2373 }
2374 allItems << components << connections << (shapes.isEmpty() ? "" : QString("annotation (%1)").arg(shapes.join(", ")));
2375 pMimeData->setText(allItems.join("\n"));
2376 QApplication::clipboard()->setMimeData(pMimeData);
2377 // if cut flag is set
2378 if (cut) {
2379 deleteItems();
2380 }
2381 }
2382}
2383
2384/*!
2385 * \brief GraphicsView::modelicaGraphicsViewContextMenu
2386 * Creates a context menu for Modelica class.
2387 * \param pMenu
2388 */
2389void GraphicsView::modelicaGraphicsViewContextMenu(QMenu *pMenu)
2390{
2391 QMenu *pExportMenu = pMenu->addMenu(Helper::exportt);
2392 pExportMenu->addAction(MainWindow::instance()->getExportToClipboardAction());
2393 pExportMenu->addAction(MainWindow::instance()->getExportAsImageAction());
2394 if (!isVisualizationView()) {
2395 pExportMenu->addAction(MainWindow::instance()->getExportToOMNotebookAction());
2396 pMenu->addSeparator();
2397 mpPasteAction->setEnabled(QApplication::clipboard()->mimeData()->hasFormat(Helper::cutCopyPasteFormat) && qobject_cast<const MimeData*>(QApplication::clipboard()->mimeData()));
2398 pMenu->addAction(mpPasteAction);
2399 }
2400 pMenu->addSeparator();
2401 pMenu->addAction(MainWindow::instance()->getPrintModelAction());
2402 pMenu->addSeparator();
2403 pMenu->addAction(mpPropertiesAction);
2404}
2405
2406/*!
2407 * \brief GraphicsView::modelicaOneShapeContextMenu
2408 * Creates a context menu for Modelica class when one shape is right clicked.
2409 * \param pShapeAnnotation
2410 * \param pMenu
2411 */
2412void GraphicsView::modelicaOneShapeContextMenu(ShapeAnnotation *pShapeAnnotation, QMenu *pMenu)
2413{
2414 LineAnnotation *pLineAnnotation = dynamic_cast<LineAnnotation*>(pShapeAnnotation);
2415 pMenu->addAction(pShapeAnnotation->getShapePropertiesAction());
2416 pMenu->addSeparator();
2417 pMenu->addAction(mpDeleteAction);
2418 pMenu->addSeparator();
2419 pMenu->addAction(mpCutAction);
2420 pMenu->addAction(mpCopyAction);
2421 if (pLineAnnotation && pLineAnnotation->getLineType() == LineAnnotation::ConnectionType) {
2422 // nothing special for connection
2423 } else if (pLineAnnotation && pLineAnnotation->getLineType() == LineAnnotation::TransitionType) {
2424 pMenu->addSeparator();
2425 pMenu->addAction(pShapeAnnotation->getEditTransitionAction());
2426 } else if (pLineAnnotation && pLineAnnotation->getLineType() == LineAnnotation::ShapeType) {
2427 pMenu->addAction(mpDuplicateAction);
2428 pMenu->addSeparator();
2429 pMenu->addAction(mpManhattanizeAction);
2430 } else {
2431 pMenu->addAction(mpDuplicateAction);
2432 pMenu->addSeparator();
2433 pMenu->addAction(mpRotateClockwiseAction);
2434 pMenu->addAction(mpRotateAntiClockwiseAction);
2435 pMenu->addSeparator();
2436 pMenu->addAction(mpBringToFrontAction);
2437 pMenu->addAction(mpBringForwardAction);
2438 pMenu->addAction(mpSendToBackAction);
2439 pMenu->addAction(mpSendBackwardAction);
2440 }
2441}
2442
2443/*!
2444 * \brief GraphicsView::modelicaOneComponentContextMenu
2445 * Creates a context menu for Modelica class when one component is right clicked.
2446 * \param pComponent
2447 * \param pMenu
2448 */
2449void GraphicsView::modelicaOneComponentContextMenu(Component *pComponent, QMenu *pMenu)
2450{
2451 pMenu->addAction(pComponent->getParametersAction());
2452 pMenu->addAction(pComponent->getAttributesAction());
2453 pMenu->addSeparator();
2454 pMenu->addAction(pComponent->getOpenClassAction());
2455 pMenu->addSeparator();
2456 pMenu->addAction(mpDeleteAction);
2457 pMenu->addSeparator();
2458 pMenu->addAction(mpCutAction);
2459 pMenu->addAction(mpCopyAction);
2460 pMenu->addAction(mpDuplicateAction);
2461 pMenu->addSeparator();
2462 pMenu->addAction(mpRotateClockwiseAction);
2463 pMenu->addAction(mpRotateAntiClockwiseAction);
2464 pMenu->addAction(mpFlipHorizontalAction);
2465 pMenu->addAction(mpFlipVerticalAction);
2466}
2467
2468/*!
2469 * \brief GraphicsView::modelicaMultipleItemsContextMenu
2470 * Creates a context menu for Modelica class when multiple items are right clicked.
2471 * \param pMenu
2472 */
2473void GraphicsView::modelicaMultipleItemsContextMenu(QMenu *pMenu)
2474{
2475 pMenu->addAction(mpDeleteAction);
2476 pMenu->addSeparator();
2477 pMenu->addAction(mpCutAction);
2478 pMenu->addAction(mpCopyAction);
2479 pMenu->addAction(mpDuplicateAction);
2480 pMenu->addSeparator();
2481 pMenu->addAction(mpRotateClockwiseAction);
2482 pMenu->addAction(mpRotateAntiClockwiseAction);
2483}
2484
2485/*!
2486 * \brief GraphicsView::compositeModelGraphicsViewContextMenu
2487 * Creates a context menu for Composite model.
2488 * \param pMenu
2489 */
2490void GraphicsView::compositeModelGraphicsViewContextMenu(QMenu *pMenu)
2491{
2492 QMenu *pExportMenu = pMenu->addMenu(Helper::exportt);
2493 pExportMenu->addAction(MainWindow::instance()->getExportToClipboardAction());
2494 pExportMenu->addAction(MainWindow::instance()->getExportAsImageAction());
2495 pMenu->addSeparator();
2496 pMenu->addAction(MainWindow::instance()->getPrintModelAction());
2497 pMenu->addSeparator();
2498 pMenu->addAction(mpRenameAction);
2499 pMenu->addSeparator();
2500 pMenu->addAction(mpSimulationParamsAction);
2501}
2502
2503/*!
2504 * \brief GraphicsView::compositeModelOneShapeContextMenu
2505 * Creates a context menu for Composite model when one shape is right clicked.
2506 * \param pShapeAnnotation
2507 * \param pMenu
2508 */
2509void GraphicsView::compositeModelOneShapeContextMenu(ShapeAnnotation *pShapeAnnotation, QMenu *pMenu)
2510{
2511 pMenu->addAction(pShapeAnnotation->getShapeAttributesAction());
2512 //Only show align interfaces action for bidirectional connections
2513 LineAnnotation *pConnectionLineAnnotation = dynamic_cast<LineAnnotation*>(pShapeAnnotation);
2514 if (pConnectionLineAnnotation) {
2515 QString startName = pConnectionLineAnnotation->getStartComponentName();
2516 QString endName = pConnectionLineAnnotation->getEndComponentName();
2517 CompositeModelEditor *pEditor = dynamic_cast<CompositeModelEditor*>(mpModelWidget->getEditor());
2518 if (pEditor && pEditor->getInterfaceCausality(startName) == StringHandler::getTLMCausality(StringHandler::TLMBidirectional) &&
2519 pEditor->getInterfaceCausality(endName) == StringHandler::getTLMCausality(StringHandler::TLMBidirectional)) {
2520 pMenu->addSeparator();
2521 pMenu->addAction(pShapeAnnotation->getAlignInterfacesAction());
2522 }
2523 }
2524 pMenu->addSeparator();
2525 pMenu->addAction(mpDeleteAction);
2526}
2527
2528/*!
2529 * \brief GraphicsView::compositeModelOneComponentContextMenu
2530 * Creates a context menu for Composite model when one component is right clicked.
2531 * \param pComponent
2532 * \param pMenu
2533 */
2534void GraphicsView::compositeModelOneComponentContextMenu(Component *pComponent, QMenu *pMenu)
2535{
2536 pMenu->addAction(pComponent->getFetchInterfaceDataAction());
2537 pMenu->addSeparator();
2538 pMenu->addAction(pComponent->getSubModelAttributesAction());
2539 pMenu->addSeparator();
2540 pMenu->addAction(mpDeleteAction);
2541 pMenu->addSeparator();
2542 pMenu->addAction(mpRotateClockwiseAction);
2543 pMenu->addAction(mpRotateAntiClockwiseAction);
2544 pMenu->addAction(mpFlipHorizontalAction);
2545 pMenu->addAction(mpFlipVerticalAction);
2546}
2547
2548/*!
2549 * \brief GraphicsView::compositeModelMultipleItemsContextMenu
2550 * Creates a context menu for Composite model when multiple items are right clicked.
2551 * \param pMenu
2552 */
2553void GraphicsView::compositeModelMultipleItemsContextMenu(QMenu *pMenu)
2554{
2555 pMenu->addAction(mpDeleteAction);
2556 pMenu->addSeparator();
2557 pMenu->addAction(mpRotateClockwiseAction);
2558 pMenu->addAction(mpRotateAntiClockwiseAction);
2559 pMenu->addAction(mpFlipHorizontalAction);
2560 pMenu->addAction(mpFlipVerticalAction);
2561}
2562
2563/*!
2564 * \brief GraphicsView::omsGraphicsViewContextMenu
2565 * Creates a context menu for OMSimulator model.
2566 * \param pMenu
2567 */
2568void GraphicsView::omsGraphicsViewContextMenu(QMenu *pMenu)
2569{
2570 QMenu *pExportMenu = pMenu->addMenu(Helper::exportt);
2571 pExportMenu->addAction(MainWindow::instance()->getExportToClipboardAction());
2572 pExportMenu->addAction(MainWindow::instance()->getExportAsImageAction());
2573 pMenu->addSeparator();
2574 pMenu->addAction(MainWindow::instance()->getPrintModelAction());
2575 pMenu->addSeparator();
2576 if (mpModelWidget->getLibraryTreeItem()->isTopLevel() || mpModelWidget->getLibraryTreeItem()->isSystemElement()) {
2577 pMenu->addSeparator();
2578 pMenu->addAction(MainWindow::instance()->getAddSystemAction());
2579 if (mpModelWidget->getLibraryTreeItem()->isTopLevel()) {
2580 pMenu->addSeparator();
2581 pMenu->addAction(mpPropertiesAction);
2582 }
2583 }
2584 if (mpModelWidget->getLibraryTreeItem()->isSystemElement() || mpModelWidget->getLibraryTreeItem()->isComponentElement()) {
2585 pMenu->addSeparator();
2586 pMenu->addAction(MainWindow::instance()->getAddOrEditIconAction());
2587 pMenu->addAction(MainWindow::instance()->getDeleteIconAction());
2588 pMenu->addSeparator();
2589 pMenu->addAction(MainWindow::instance()->getAddConnectorAction());
2590 pMenu->addAction(MainWindow::instance()->getAddBusAction());
2591 pMenu->addAction(MainWindow::instance()->getAddTLMBusAction());
2592 if (mpModelWidget->getLibraryTreeItem()->isSystemElement()) {
2593 pMenu->addSeparator();
2594 pMenu->addAction(MainWindow::instance()->getAddSubModelAction());
2595 pMenu->addSeparator();
2596 pMenu->addAction(mpPropertiesAction);
2597 }
2598 }
2599}
2600
2601/*!
2602 * \brief GraphicsView::omsOneShapeContextMenu
2603 * Creates a context menu for OMSimulator model when one shape is right clicked.
2604 * \param pShapeAnnotation
2605 * \param pMenu
2606 */
2607void GraphicsView::omsOneShapeContextMenu(ShapeAnnotation *pShapeAnnotation, QMenu *pMenu)
2608{
2609 BitmapAnnotation *pBitmapAnnotation = dynamic_cast<BitmapAnnotation*>(pShapeAnnotation);
2610 if (pBitmapAnnotation && mpModelWidget->getLibraryTreeItem()->getOMSElement()) {
2611 pMenu->addAction(MainWindow::instance()->getAddOrEditIconAction());
2612 pMenu->addAction(MainWindow::instance()->getDeleteIconAction());
2613 }
2614}
2615
2616/*!
2617 * \brief GraphicsView::omsOneComponentContextMenu
2618 * Creates a context menu for OMSimulator model when one component is right clicked.
2619 * \param pComponent
2620 * \param pMenu
2621 */
2622void GraphicsView::omsOneComponentContextMenu(Component *pComponent, QMenu *pMenu)
2623{
2624 if (pComponent->getLibraryTreeItem()->isSystemElement() || pComponent->getLibraryTreeItem()->isComponentElement()) {
2625 pMenu->addAction(pComponent->getElementPropertiesAction());
2626 }
2627 pMenu->addSeparator();
2628 pMenu->addAction(mpDeleteAction);
2629 pMenu->addSeparator();
2630 pMenu->addAction(mpRotateClockwiseAction);
2631 pMenu->addAction(mpRotateAntiClockwiseAction);
2632 pMenu->addAction(mpFlipHorizontalAction);
2633 pMenu->addAction(mpFlipVerticalAction);
2634}
2635
2636/*!
2637 * \brief GraphicsView::omsMultipleItemsContextMenu
2638 * Creates a context menu for OMSimulator model when multiple items are right clicked.
2639 * \param pMenu
2640 */
2641void GraphicsView::omsMultipleItemsContextMenu(QMenu *pMenu)
2642{
2643 pMenu->addAction(mpDeleteAction);
2644 pMenu->addSeparator();
2645 pMenu->addAction(mpRotateClockwiseAction);
2646 pMenu->addAction(mpRotateAntiClockwiseAction);
2647 pMenu->addAction(mpFlipHorizontalAction);
2648 pMenu->addAction(mpFlipVerticalAction);
2649}
2650
2651/*!
2652 * \brief replaceComponentNameInConnection
2653 * Helper function to GraphicsView::pasteItems(). Updates the connections component names if the component name is changed during paste operation.
2654 * \param oldConnectionComponentName
2655 * \param newConnectionComponentName
2656 * \return
2657 */
2658QString replaceComponentNameInConnection(const QString &oldConnectionComponentName, const QString &newConnectionComponentName)
2659{
2660 QString connectionComponentName;
2661 QStringList connectionComponentList = oldConnectionComponentName.split(".");
2662 if (connectionComponentList.size() > 1) {
2663 connectionComponentName = QString("%1.%2").arg(newConnectionComponentName, connectionComponentList.at(1));
2664 } else {
2665 connectionComponentName = connectionComponentList.at(0);
2666 if (connectionComponentName.contains("[")) {
2667 connectionComponentName = QString("%1%2").arg(newConnectionComponentName, connectionComponentName.mid(connectionComponentName.indexOf("[")));
2668 } else {
2669 connectionComponentName = newConnectionComponentName;
2670 }
2671 }
2672 return connectionComponentName;
2673}
2674
2675/*!
2676 * \brief GraphicsView::pasteItems
2677 * Slot activated when mpPasteAction triggered SIGNAL is raised.
2678 * Reads the items from the clipboard and adds them to the view.
2679 */
2680void GraphicsView::pasteItems()
2681{
2682 QClipboard *pClipboard = QApplication::clipboard();
2683 if (pClipboard->mimeData()->hasFormat(Helper::cutCopyPasteFormat)) {
2684 if (const MimeData *pMimeData = qobject_cast<const MimeData*>(pClipboard->mimeData())) {
2685 mpModelWidget->beginMacro("Paste items from clipboard");
2686 // map to store
2687 QMap<Component*, QString> renamedComponents;
2688 // paste the components
2689 foreach (Component *pComponent, pMimeData->getComponents())for (auto _container_ = QtPrivate::qMakeForeachContainer(pMimeData
->getComponents()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pComponent = *_container_.i; _container_.control
; _container_.control = 0)
{
2690 QString name = pComponent->getName();
2691 if (!checkComponentName(name)) {
2692 name = getUniqueComponentName(StringHandler::toCamelCase(pComponent->getLibraryTreeItem()->getName()));
2693 renamedComponents.insert(pComponent, name);
2694 }
2695 ComponentInfo *pComponentInfo = new ComponentInfo(pComponent->getComponentInfo());
2696 pComponentInfo->setName(name);
2697 addComponentToView(name, pComponent->getLibraryTreeItem(), pComponent->getOMCPlacementAnnotation(QPointF(0, 0)), QPointF(0, 0), pComponentInfo, true, true, true);
2698 Component *pNewComponent = mComponentsList.last();
2699 pNewComponent->setSelected(true);
2700 }
2701 // paste the connections
2702 foreach (LineAnnotation *pConnectionLineAnnotation, pMimeData->getConnections())for (auto _container_ = QtPrivate::qMakeForeachContainer(pMimeData
->getConnections()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (LineAnnotation *pConnectionLineAnnotation = *_container_
.i; _container_.control; _container_.control = 0)
{
2703 QString startComponentName = pConnectionLineAnnotation->getStartComponentName();
2704 if (renamedComponents.contains(pConnectionLineAnnotation->getStartComponent()->getRootParentComponent())) {
2705 startComponentName = replaceComponentNameInConnection(startComponentName, renamedComponents.value(pConnectionLineAnnotation->getStartComponent()->getRootParentComponent()));
2706 }
2707 QString endComponentName = pConnectionLineAnnotation->getEndComponentName();
2708 if (renamedComponents.contains(pConnectionLineAnnotation->getEndComponent()->getRootParentComponent())) {
2709 endComponentName = replaceComponentNameInConnection(endComponentName, renamedComponents.value(pConnectionLineAnnotation->getEndComponent()->getRootParentComponent()));
2710 }
2711 QStringList connectionList;
2712 connectionList << startComponentName << endComponentName << QString("");
2713 QString connectionAnnotation = pConnectionLineAnnotation->getOMCShapeAnnotationWithShapeName();
2714 mpModelWidget->addConnection(connectionList, connectionAnnotation, true, true);
2715 }
2716 // paste the shapes
2717 QStringList shapes;
2718 foreach (ShapeAnnotation *pShapeAnnotation, pMimeData->getShapes())for (auto _container_ = QtPrivate::qMakeForeachContainer(pMimeData
->getShapes()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (ShapeAnnotation *pShapeAnnotation = *_container_.i; _container_
.control; _container_.control = 0)
{
2719 shapes << pShapeAnnotation->getOMCShapeAnnotationWithShapeName();
2720 }
2721 if (!shapes.isEmpty()) {
2722 mpModelWidget->drawModelIconDiagramShapes(shapes, this, true);
2723 }
2724 // update the model text
2725 mpModelWidget->updateClassAnnotationIfNeeded();
2726 mpModelWidget->updateModelText();
2727 mpModelWidget->endMacro();
2728 }
2729 }
2730}
2731
2732/*!
2733 * \brief GraphicsView::clearSelection
2734 * Clears the selection of all shapes, components and connectors.
2735 * Selects the passed item if its valid.
2736 * \param pSelectGraphicsItem
2737 */
2738void GraphicsView::clearSelection(QGraphicsItem *pSelectGraphicsItem)
2739{
2740 foreach (QGraphicsItem *pGraphicsItem, items())for (auto _container_ = QtPrivate::qMakeForeachContainer(items
()); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QGraphicsItem
*pGraphicsItem = *_container_.i; _container_.control; _container_
.control = 0)
{
2741 pGraphicsItem->setSelected(false);
2742 }
2743 // only select the item if it is valid
2744 if (pSelectGraphicsItem) {
2745 pSelectGraphicsItem->setSelected(true);
2746 }
2747}
2748
2749/*!
2750 * \brief GraphicsView::addClassAnnotation
2751 * Adds the annotation string of Icon and Diagram layer to the model. Also creates the model icon in the tree.
2752 * If some custom models are cross referenced then update them accordingly.
2753 * \param alwaysAdd - if false then skip the OMCProxy::addClassAnnotation() if annotation is empty.
2754 */
2755void GraphicsView::addClassAnnotation(bool alwaysAdd)
2756{
2757 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) {
2758 return;
2759 }
2760 MainWindow *pMainWindow = MainWindow::instance();
2761 // coordinate system
2762 QStringList coOrdinateSystemList;
2763 QList<QPointF> extent = mCoOrdinateSystem.getExtent();
2764 qreal x1 = extent.at(0).x();
2765 qreal y1 = extent.at(0).y();
2766 qreal x2 = extent.at(1).x();
2767 qreal y2 = extent.at(1).y();
2768 if (x1 != -100 || y1 != -100 || x2 != 100 || y2 != 100) {
2769 coOrdinateSystemList.append(QString("extent={{%1, %2}, {%3, %4}}").arg(x1).arg(y1).arg(x2).arg(y2));
2770 }
2771 // add the preserveAspectRatio
2772 if (!mCoOrdinateSystem.getPreserveAspectRatio()) {
2773 coOrdinateSystemList.append(QString("preserveAspectRatio=%1").arg(mCoOrdinateSystem.getPreserveAspectRatio() ? "true" : "false"));
2774 }
2775 // add the initial scale
2776 if (mCoOrdinateSystem.getInitialScale() != 0.1) {
2777 coOrdinateSystemList.append(QString("initialScale=%1").arg(mCoOrdinateSystem.getInitialScale()));
2778 }
2779 // add the grid
2780 QPointF grid = mCoOrdinateSystem.getGrid();
2781 if (grid.x() != 2 || grid.y() != 2) {
2782 coOrdinateSystemList.append(QString("grid={%1, %2}").arg(grid.x()).arg(grid.y()));
2783 }
2784 // graphics annotations
2785 QStringList graphicsList;
2786 if (mShapesList.size() > 0) {
2787 foreach (ShapeAnnotation *pShapeAnnotation, mShapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mShapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (ShapeAnnotation
*pShapeAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
2788 /* Don't add the inherited shape to the addClassAnnotation. */
2789 if (!pShapeAnnotation->isInheritedShape()) {
2790 graphicsList.append(pShapeAnnotation->getShapeAnnotation());
2791 }
2792 }
2793 }
2794 // build the annotation string
2795 QString annotationString;
2796 QString viewType = (mViewType == StringHandler::Icon) ? "Icon" : "Diagram";
2797 if (coOrdinateSystemList.size() > 0 && graphicsList.size() > 0) {
2798 annotationString = QString("annotate=%1(coordinateSystem=CoordinateSystem(%2), graphics={%3})").arg(viewType)
2799 .arg(coOrdinateSystemList.join(",")).arg(graphicsList.join(","));
2800 } else if (coOrdinateSystemList.size() > 0) {
2801 annotationString = QString("annotate=%1(coordinateSystem=CoordinateSystem(%2))").arg(viewType).arg(coOrdinateSystemList.join(","));
2802 } else if (graphicsList.size() > 0) {
2803 annotationString = QString("annotate=%1(graphics={%2})").arg(viewType).arg(graphicsList.join(","));
2804 } else {
2805 annotationString = QString("annotate=%1()").arg(viewType);
2806 /* Ticket #3731
2807 * Return from here since we don't want empty Icon & Diagram annotations.
2808 */
2809 if (!alwaysAdd) {
2810 return;
2811 }
2812 }
2813 // add the class annotation to model through OMC
2814 if (pMainWindow->getOMCProxy()->addClassAnnotation(mpModelWidget->getLibraryTreeItem()->getNameStructure(), annotationString)) {
2815 /* When something is added/changed in the icon layer then update the LibraryTreeItem in the Library Browser */
2816 if (mViewType == StringHandler::Icon) {
2817 mpModelWidget->getLibraryTreeItem()->handleIconUpdated();
2818 }
2819 } else {
2820 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
2821 tr("Error in class annotation ") + pMainWindow->getOMCProxy()->getResult(),
2822 Helper::scriptingKind, Helper::errorLevel));
2823 }
2824}
2825
2826/*!
2827 * \brief GraphicsView::showGraphicsViewProperties
2828 * Opens the GraphicsViewProperties dialog.
2829 */
2830void GraphicsView::showGraphicsViewProperties()
2831{
2832 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
2833 GraphicsViewProperties *pGraphicsViewProperties = new GraphicsViewProperties(this);
2834 pGraphicsViewProperties->exec();
2835 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
2836 ModelWidget *pModelWidget = 0;
2837 if (mpModelWidget->getLibraryTreeItem()->isTopLevel()) {
2838 if (mpModelWidget->getLibraryTreeItem()->childrenSize() > 0) {
2839 LibraryTreeItem *pSystemLibraryTreeItem = mpModelWidget->getLibraryTreeItem()->childAt(0);
2840 if (pSystemLibraryTreeItem && pSystemLibraryTreeItem->getModelWidget()) {
2841 pModelWidget = pSystemLibraryTreeItem->getModelWidget();
2842 }
2843 }
2844 } else {
2845 pModelWidget = mpModelWidget;
2846 }
2847 if (pModelWidget) {
2848 SystemSimulationInformationDialog *pSystemSimulationInformationDialog = new SystemSimulationInformationDialog(pModelWidget);
2849 pSystemSimulationInformationDialog->exec();
2850 }
2851 }
2852}
2853
2854/*!
2855 * \brief GraphicsView::showSimulationParamsDialog
2856 * Opens the CompositeModelSimulationParamsDialog.
2857 */
2858void GraphicsView::showSimulationParamsDialog()
2859{
2860 CompositeModelSimulationParamsDialog *pCompositeModelSimulationParamsDialog = new CompositeModelSimulationParamsDialog(this);
2861 pCompositeModelSimulationParamsDialog->exec();
2862}
2863
2864/*!
2865 * \brief GraphicsView::showRenameDialog
2866 * Opens the RenameItemDialog.
2867 */
2868void GraphicsView::showRenameDialog()
2869{
2870 RenameItemDialog *pRenameItemDialog;
2871 pRenameItemDialog = new RenameItemDialog(mpModelWidget->getLibraryTreeItem(), MainWindow::instance());
2872 pRenameItemDialog->exec();
2873}
2874
2875/*!
2876 * \brief GraphicsView::manhattanizeItems
2877 * Manhattanize the selected items by emitting GraphicsView::manhattanize() SIGNAL.
2878 */
2879void GraphicsView::manhattanizeItems()
2880{
2881 mpModelWidget->beginMacro("Manhattanize");
2882 emit manhattanize();
2883 mpModelWidget->updateClassAnnotationIfNeeded();
2884 mpModelWidget->updateModelText();
2885 mpModelWidget->endMacro();
2886}
2887
2888/*!
2889 * \brief GraphicsView::deleteItems
2890 * Deletes the selected items by emitting GraphicsView::deleteSignal() SIGNAL.
2891 */
2892void GraphicsView::deleteItems()
2893{
2894 mpModelWidget->beginMacro("Delete items");
2895 emit deleteSignal();
2896 mpModelWidget->updateClassAnnotationIfNeeded();
2897 mpModelWidget->updateModelText();
2898 mpModelWidget->endMacro();
2899}
2900
2901/*!
2902 * \brief GraphicsView::duplicateItems
2903 * Duplicates the selected items by emitting GraphicsView::mouseDuplicate() SIGNAL.
2904 */
2905void GraphicsView::duplicateItems()
2906{
2907 mpModelWidget->beginMacro("Duplicate by mouse");
2908 emit mouseDuplicate();
2909 mpModelWidget->updateClassAnnotationIfNeeded();
2910 mpModelWidget->updateModelText();
2911 mpModelWidget->endMacro();
2912}
2913
2914/*!
2915 * \brief GraphicsView::rotateClockwise
2916 * Rotates the selected items clockwise by emitting GraphicsView::mouseRotateClockwise() SIGNAL.
2917 */
2918void GraphicsView::rotateClockwise()
2919{
2920 mpModelWidget->beginMacro("Rotate clockwise by mouse");
2921 emit mouseRotateClockwise();
2922 mpModelWidget->updateClassAnnotationIfNeeded();
2923 mpModelWidget->updateModelText();
2924 mpModelWidget->endMacro();
2925}
2926
2927/*!
2928 * \brief GraphicsView::rotateAntiClockwise
2929 * Rotates the selected items anti clockwise by emitting GraphicsView::mouseRotateAntiClockwise() SIGNAL.
2930 */
2931void GraphicsView::rotateAntiClockwise()
2932{
2933 mpModelWidget->beginMacro("Rotate anti clockwise by mouse");
2934 emit mouseRotateAntiClockwise();
2935 mpModelWidget->updateClassAnnotationIfNeeded();
2936 mpModelWidget->updateModelText();
2937 mpModelWidget->endMacro();
2938}
2939
2940/*!
2941 * \brief GraphicsView::flipHorizontal
2942 * Flips the selected items horizontally emitting GraphicsView::mouseFlipHorizontal() SIGNAL.
2943 */
2944void GraphicsView::flipHorizontal()
2945{
2946 mpModelWidget->beginMacro("Flip horizontal by mouse");
2947 emit mouseFlipHorizontal();
2948 mpModelWidget->updateClassAnnotationIfNeeded();
2949 mpModelWidget->updateModelText();
2950 mpModelWidget->endMacro();
2951}
2952
2953/*!
2954 * \brief GraphicsView::flipVertical
2955 * Flips the selected items vertically emitting GraphicsView::mouseFlipVertical() SIGNAL.
2956 */
2957void GraphicsView::flipVertical()
2958{
2959 mpModelWidget->beginMacro("Flip vertical by mouse");
2960 emit mouseFlipVertical();
2961 mpModelWidget->updateClassAnnotationIfNeeded();
2962 mpModelWidget->updateModelText();
2963 mpModelWidget->endMacro();
2964}
2965
2966/*!
2967 * \brief GraphicsView::setInitialState
2968 * Sets the state as initial.
2969 */
2970void GraphicsView::setInitialState()
2971{
2972 if (mpTransitionLineAnnotation) {
2973 QString startComponentName;
2974 if (mpTransitionLineAnnotation->getStartComponent()->getParentComponent()) {
2975 startComponentName = QString(mpTransitionLineAnnotation->getStartComponent()->getRootParentComponent()->getName()).append(".")
2976 .append(mpTransitionLineAnnotation->getStartComponent()->getName());
2977 } else {
2978 startComponentName = mpTransitionLineAnnotation->getStartComponent()->getName();
2979 }
2980 mpTransitionLineAnnotation->setStartComponentName(startComponentName);
2981 mpTransitionLineAnnotation->setEndComponentName("");
2982 mpTransitionLineAnnotation->setLineType(LineAnnotation::InitialStateType);
2983 mpModelWidget->getUndoStack()->push(new AddInitialStateCommand(mpTransitionLineAnnotation, true));
2984 mpModelWidget->updateModelText();
2985 setIsCreatingTransition(false);
2986 }
2987}
2988
2989/*!
2990 * \brief GraphicsView::cancelTransition
2991 * Cancels the current transition.
2992 */
2993void GraphicsView::cancelTransition()
2994{
2995 if (mpTransitionLineAnnotation) {
2996 removeCurrentTransition();
2997 }
2998}
2999
3000/*!
3001 * \brief GraphicsView::dragMoveEvent
3002 * Defines what happens when dragged and moved an object in a GraphicsView.
3003 * \param event - contains information of the drag operation.
3004 */
3005void GraphicsView::dragMoveEvent(QDragMoveEvent *event)
3006{
3007 // check if the class is system library or a package or a OMSimulator model
3008 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView() ||
3009 mpModelWidget->getLibraryTreeItem()->getRestriction() == StringHandler::Package ||
3010 mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
3011 event->ignore();
3012 return;
3013 }
3014 // read the mime data from the event
3015 if (event->mimeData()->hasFormat(Helper::modelicaComponentFormat) || event->mimeData()->hasFormat(Helper::modelicaFileFormat)) {
3016 event->setDropAction(Qt::CopyAction);
3017 event->accept();
3018 } else {
3019 event->ignore();
3020 }
3021}
3022
3023/*!
3024 * \brief GraphicsView::dropEvent
3025 * Defines what happens when an object is dropped in a GraphicsView.
3026 * \param event - contains information of the drop operation.
3027 */
3028void GraphicsView::dropEvent(QDropEvent *event)
3029{
3030 setFocus();
3031 MainWindow *pMainWindow = MainWindow::instance();
3032 // check mimeData
3033 if (!event->mimeData()->hasFormat(Helper::modelicaComponentFormat) && !event->mimeData()->hasFormat(Helper::modelicaFileFormat)) {
3034 event->ignore();
3035 return;
3036 } else if (event->mimeData()->hasFormat(Helper::modelicaFileFormat)) {
3037 pMainWindow->openDroppedFile(event->mimeData());
3038 event->accept();
3039 } else if (event->mimeData()->hasFormat(Helper::modelicaComponentFormat)) {
3040 // check if the class is system library
3041 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) {
3042 event->ignore();
3043 return;
3044 }
3045 QByteArray itemData = event->mimeData()->data(Helper::modelicaComponentFormat);
3046 QDataStream dataStream(&itemData, QIODevice::ReadOnly);
3047 QString className;
3048 dataStream >> className;
3049 if (addComponent(className, mapToScene(event->pos()))) {
3050 event->accept();
3051 } else {
3052 event->ignore();
3053 }
3054 } else {
3055 event->ignore();
3056 }
3057}
3058
3059void GraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
3060{
3061 if (mSkipBackground) {
3062 return;
3063 }
3064 QPen grayPen(QBrush(QColor(192, 192, 192)), 0);
3065 QPen lightGrayPen(QBrush(QColor(229, 229, 229)), 0);
3066 if (mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView()) {
3067 painter->setBrush(QBrush(Qt::white, Qt::SolidPattern));
3068 } else if (mViewType == StringHandler::Icon) {
3069 painter->setBrush(QBrush(QColor(229, 244, 255), Qt::SolidPattern));
3070 } else {
3071 painter->setBrush(QBrush(QColor(242, 242, 242), Qt::SolidPattern));
3072 }
3073 // draw scene rectangle white background
3074 painter->setPen(Qt::NoPen);
3075 painter->drawRect(rect);
3076 painter->setBrush(QBrush(Qt::white, Qt::SolidPattern));
3077 painter->drawRect(getExtentRectangle());
3078 if (mpModelWidget->getModelWidgetContainer()->isShowGridLines() && !(mpModelWidget->getLibraryTreeItem()->isSystemLibrary() || isVisualizationView())) {
3079 painter->setBrush(Qt::NoBrush);
3080 painter->setPen(lightGrayPen);
3081 /* Draw left half vertical lines */
3082 int horizontalGridStep = mCoOrdinateSystem.getHorizontalGridStep() * 10;
3083 qreal xAxisStep = 0;
3084 qreal yAxisStep = rect.y();
3085 xAxisStep -= horizontalGridStep;
3086 while (xAxisStep > rect.left()) {
3087 painter->drawLine(QPointF(xAxisStep, yAxisStep), QPointF(xAxisStep, rect.bottom()));
3088 xAxisStep -= horizontalGridStep;
3089 }
3090 /* Draw right half vertical lines */
3091 xAxisStep = 0;
3092 while (xAxisStep < rect.right()) {
3093 painter->drawLine(QPointF(xAxisStep, yAxisStep), QPointF(xAxisStep, rect.bottom()));
3094 xAxisStep += horizontalGridStep;
3095 }
3096 /* Draw left half horizontal lines */
3097 int verticalGridStep = mCoOrdinateSystem.getVerticalGridStep() * 10;
3098 xAxisStep = rect.x();
3099 yAxisStep = 0;
3100 yAxisStep += verticalGridStep;
3101 while (yAxisStep < rect.bottom()) {
3102 painter->drawLine(QPointF(xAxisStep, yAxisStep), QPointF(rect.right(), yAxisStep));
3103 yAxisStep += verticalGridStep;
3104 }
3105 /* Draw right half horizontal lines */
3106 yAxisStep = 0;
3107 while (yAxisStep > rect.top()) {
3108 painter->drawLine(QPointF(xAxisStep, yAxisStep), QPointF(rect.right(), yAxisStep));
3109 yAxisStep -= verticalGridStep;
3110 }
3111 /* set the middle horizontal and vertical line gray */
3112 painter->setPen(grayPen);
3113 painter->drawLine(QPointF(rect.left(), 0), QPointF(rect.right(), 0));
3114 painter->drawLine(QPointF(0, rect.top()), QPointF(0, rect.bottom()));
3115 }
3116 // draw scene rectangle
3117 painter->setPen(grayPen);
3118 painter->drawRect(getExtentRectangle());
3119}
3120
3121//! Defines what happens when clicking in a GraphicsView.
3122//! @param event contains information of the mouse click operation.
3123void GraphicsView::mousePressEvent(QMouseEvent *event)
3124{
3125 if (event->button() == Qt::RightButton) {
3126 return;
3127 }
3128 // if user is starting panning.
3129 if (QApplication::keyboardModifiers() == Qt::ControlModifier) {
3130 setIsPanning(true);
3131 mLastMouseEventPos = event->pos();
3132 QGraphicsView::mousePressEvent(event);
3133 return;
3134 }
3135 MainWindow *pMainWindow = MainWindow::instance();
3136 QPointF snappedPoint = snapPointToGrid(mapToScene(event->pos()));
3137 bool eventConsumed = false;
3138 // if left button presses and we are creating a connector
3139 if (isCreatingConnection()) {
3140 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
3141 mpConnectionLineAnnotation->addPoint(roundPoint(mapToScene(event->pos())));
3142 } else {
3143 mpConnectionLineAnnotation->addPoint(snappedPoint);
3144 }
3145 eventConsumed = true;
3146 } else if (isCreatingTransition()) {
3147 mpTransitionLineAnnotation->addPoint(snappedPoint);
3148 eventConsumed = true;
3149 } else if (pMainWindow->getLineShapeAction()->isChecked()) {
3150 /* if line shape tool button is checked then create a line */
3151 createLineShape(snappedPoint);
3152 } else if (pMainWindow->getPolygonShapeAction()->isChecked()) {
3153 /* if polygon shape tool button is checked then create a polygon */
3154 createPolygonShape(snappedPoint);
3155 } else if (pMainWindow->getRectangleShapeAction()->isChecked()) {
3156 /* if rectangle shape tool button is checked then create a rectangle */
3157 createRectangleShape(snappedPoint);
3158 } else if (pMainWindow->getEllipseShapeAction()->isChecked()) {
3159 /* if ellipse shape tool button is checked then create an ellipse */
3160 createEllipseShape(snappedPoint);
3161 } else if (pMainWindow->getTextShapeAction()->isChecked()) {
3162 /* if text shape tool button is checked then create a text */
3163 createTextShape(snappedPoint);
3164 eventConsumed = true;
3165 } else if (pMainWindow->getBitmapShapeAction()->isChecked()) {
3166 /* if bitmap shape tool button is checked then create a bitmap */
3167 createBitmapShape(snappedPoint);
3168 eventConsumed = true;
3169 } else if (dynamic_cast<ResizerItem*>(itemAt(event->pos()))) {
3170 // do nothing if resizer item is clicked. It will be handled in its class mousePressEvent();
3171 } else {
3172 // this flag is just used to have separate identity for if statement in mouse release event of graphicsview
3173 setIsMovingComponentsAndShapes(true);
3174 // save the position of all components
3175 foreach (Component *pComponent, mComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
3176 pComponent->setOldPosition(pComponent->pos());
3177 pComponent->setOldScenePosition(pComponent->scenePos());
3178 }
3179 // save the position of all shapes
3180 foreach (ShapeAnnotation *pShapeAnnotation, mShapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mShapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (ShapeAnnotation
*pShapeAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
3181 pShapeAnnotation->setOldScenePosition(pShapeAnnotation->scenePos());
3182 }
3183 // save annotations of all connections
3184 foreach (LineAnnotation *pConnectionLineAnnotation, mConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pConnectionLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
3185 pConnectionLineAnnotation->setOldAnnotation(pConnectionLineAnnotation->getOMCShapeAnnotation());
3186 }
3187 // save annotations of all transitions
3188 foreach (LineAnnotation *pTransitionLineAnnotation, mTransitionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mTransitionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pTransitionLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
3189 pTransitionLineAnnotation->setOldAnnotation(pTransitionLineAnnotation->getOMCShapeAnnotation());
3190 }
3191 // save annotations of all initial states
3192 foreach (LineAnnotation *pInitialStateLineAnnotation, mInitialStatesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInitialStatesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pInitialStateLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
3193 pInitialStateLineAnnotation->setOldAnnotation(pInitialStateLineAnnotation->getOMCShapeAnnotation());
3194 }
3195 }
3196 // if some item is clicked
3197 if (Component *pComponent = connectorComponentAtPosition(event->pos())) {
3198 if (!isCreatingConnection()) {
3199 mpClickedComponent = pComponent;
3200 } else if (isCreatingConnection()) {
3201 addConnection(pComponent); // end the connection
3202 eventConsumed = true; // consume the event so that connection line or end component will not become selected
3203 }
3204 } else if (Component *pComponent = stateComponentAtPosition(event->pos())) {
3205 if (!isCreatingTransition()) {
3206 mpClickedState = pComponent;
3207 } else if (isCreatingTransition()) {
3208 addTransition(pComponent); // end the transition
3209 eventConsumed = true; // consume the event so that transition line or end component will not become selected
3210 }
3211 }
3212 if (!eventConsumed) {
3213 /* Ticket:4379 Select multiple objects with [Shift] key (not with [Control] key)
3214 * To provide multi select we switch the shift key with control.
3215 */
3216 if (event->modifiers() & Qt::ShiftModifier) {
3217 event->setModifiers((event->modifiers() & ~Qt::ShiftModifier) | Qt::ControlModifier);
3218 }
3219 QGraphicsView::mousePressEvent(event);
3220 }
3221}
3222
3223/*!
3224 * \brief GraphicsView::mouseMoveEvent
3225 * Defines what happens when the mouse is moving in a GraphicsView.
3226 * \param event contains information of the mouse moving operation.
3227 */
3228void GraphicsView::mouseMoveEvent(QMouseEvent *event)
3229{
3230 // if we are in panning mode
3231 if (isPanning()) {
3232 QScrollBar *pHorizontalScrollBar = horizontalScrollBar();
3233 QScrollBar *pVerticalScrollBar = verticalScrollBar();
3234 QPoint delta = event->pos() - mLastMouseEventPos;
3235 mLastMouseEventPos = event->pos();
3236 pHorizontalScrollBar->setValue(pHorizontalScrollBar->value() + (isRightToLeft() ? delta.x() : -delta.x()));
3237 pVerticalScrollBar->setValue(pVerticalScrollBar->value() - delta.y());
3238 QGraphicsView::mouseMoveEvent(event);
3239 return;
3240 }
3241 // update the position label
3242 Label *pPositionLabel = MainWindow::instance()->getPositionLabel();
3243 pPositionLabel->setText(QString("X: %1, Y: %2").arg(QString::number(qRound(mapToScene(event->pos()).x())))
3244 .arg(QString::number(qRound(mapToScene(event->pos()).y()))));
3245 QPointF snappedPoint = snapPointToGrid(mapToScene(event->pos()));
3246 // if user mouse over connector show Qt::CrossCursor.
3247 bool setCrossCursor = false;
3248 if (connectorComponentAtPosition(event->pos()) || stateComponentAtPosition(event->pos())) {
3249 setCrossCursor = true;
3250 /* If setOverrideCursor() has been called twice, calling restoreOverrideCursor() will activate the first cursor set.
3251 * Calling this function a second time restores the original widgets' cursors.
3252 * So we only set the cursor if it is not already Qt::CrossCursor.
3253 */
3254 if (!QApplication::overrideCursor() || QApplication::overrideCursor()->shape() != Qt::CrossCursor) {
3255 QApplication::setOverrideCursor(Qt::CrossCursor);
3256 }
3257 }
3258 // if user mouse is not on connector then reset the cursor.
3259 if (!setCrossCursor && QApplication::overrideCursor()) {
3260 QApplication::restoreOverrideCursor();
3261 }
3262 //If creating connector, the end port shall be updated to the mouse position.
3263 if (isCreatingConnection()) {
3264 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
3265 mpConnectionLineAnnotation->updateEndPoint(roundPoint(mapToScene(event->pos())));
3266 } else {
3267 mpConnectionLineAnnotation->updateEndPoint(snappedPoint);
3268 }
3269 mpConnectionLineAnnotation->update();
3270 } else if (isCreatingTransition()) {
3271 mpTransitionLineAnnotation->updateEndPoint(snappedPoint);
3272 mpTransitionLineAnnotation->update();
3273 } else if (isCreatingLineShape()) {
3274 mpLineShapeAnnotation->updateEndPoint(snappedPoint);
3275 mpLineShapeAnnotation->update();
3276 } else if (isCreatingPolygonShape()) {
3277 mpPolygonShapeAnnotation->updateEndPoint(snappedPoint);
3278 mpPolygonShapeAnnotation->update();
3279 } else if (isCreatingRectangleShape()) {
3280 mpRectangleShapeAnnotation->updateEndExtent(snappedPoint);
3281 mpRectangleShapeAnnotation->update();
3282 } else if (isCreatingEllipseShape()) {
3283 mpEllipseShapeAnnotation->updateEndExtent(snappedPoint);
3284 mpEllipseShapeAnnotation->update();
3285 } else if (isCreatingTextShape()) {
3286 mpTextShapeAnnotation->updateEndExtent(snappedPoint);
3287 mpTextShapeAnnotation->update();
3288 } else if (isCreatingBitmapShape()) {
3289 mpBitmapShapeAnnotation->updateEndExtent(snappedPoint);
3290 mpBitmapShapeAnnotation->update();
3291 } else if (mpClickedComponent) {
3292 addConnection(mpClickedComponent); // start the connection
3293 if (mpClickedComponent) { // if we creating a connection then don't select the starting component.
3294 mpClickedComponent->setSelected(false);
3295 }
3296 } else if (mpClickedState) {
3297 addTransition(mpClickedState); // start the transition
3298 if (mpClickedState) { // if we creating a transition then don't select the starting state.
3299 mpClickedState->setSelected(false);
3300 }
3301 }
3302 QGraphicsView::mouseMoveEvent(event);
3303}
3304
3305void GraphicsView::mouseReleaseEvent(QMouseEvent *event)
3306{
3307 if (event->button() == Qt::RightButton) {
3308 return;
3309 }
3310 setIsPanning(false);
3311 mpClickedComponent = 0;
3312 mpClickedState = 0;
3313 if (isMovingComponentsAndShapes()) {
3314 setIsMovingComponentsAndShapes(false);
3315 bool hasComponentMoved = false;
3316 bool hasShapeMoved = false;
3317 bool beginMacro = false;
3318 // if component position is really changed then update component annotation
3319 foreach (Component *pComponent, mComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (Component
*pComponent = *_container_.i; _container_.control; _container_
.control = 0)
{
3320 if (pComponent->getOldPosition() != pComponent->pos()) {
3321 if (!beginMacro) {
3322 mpModelWidget->beginMacro("Move items by mouse");
3323 beginMacro = true;
3324 }
3325 Transformation oldTransformation = pComponent->mTransformation;
3326 QPointF positionDifference = pComponent->scenePos() - pComponent->getOldScenePosition();
3327 pComponent->mTransformation.adjustPosition(positionDifference.x(), positionDifference.y());
3328 pComponent->updateComponentTransformations(oldTransformation);
3329 hasComponentMoved = true;
3330 }
3331 }
3332 // if shape position is changed then update class annotation
3333 foreach (ShapeAnnotation *pShapeAnnotation, mShapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mShapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (ShapeAnnotation
*pShapeAnnotation = *_container_.i; _container_.control; _container_
.control = 0)
{
3334 if (pShapeAnnotation->getOldScenePosition() != pShapeAnnotation->scenePos()) {
3335 if (!beginMacro) {
3336 mpModelWidget->beginMacro("Move items by mouse");
3337 beginMacro = true;
3338 }
3339 QString oldAnnotation = pShapeAnnotation->getOMCShapeAnnotation();
3340 pShapeAnnotation->mTransformation.setOrigin(pShapeAnnotation->scenePos());
3341 bool state = pShapeAnnotation->flags().testFlag(QGraphicsItem::ItemSendsGeometryChanges);
3342 pShapeAnnotation->setFlag(QGraphicsItem::ItemSendsGeometryChanges, false);
3343 pShapeAnnotation->setPos(0, 0);
3344 pShapeAnnotation->setFlag(QGraphicsItem::ItemSendsGeometryChanges, state);
3345 pShapeAnnotation->setTransform(pShapeAnnotation->mTransformation.getTransformationMatrix());
3346 pShapeAnnotation->setOrigin(pShapeAnnotation->mTransformation.getPosition());
3347 QString newAnnotation = pShapeAnnotation->getOMCShapeAnnotation();
3348 mpModelWidget->getUndoStack()->push(new UpdateShapeCommand(pShapeAnnotation, oldAnnotation, newAnnotation));
3349 hasShapeMoved = true;
3350 }
3351 }
3352 if (hasShapeMoved) {
3353 addClassAnnotation();
3354 }
3355 if (hasComponentMoved || hasShapeMoved) {
3356 mpModelWidget->updateModelText();
3357 }
3358 // if we have started he undo stack macro then we should end it.
3359 if (beginMacro) {
3360 mpModelWidget->endMacro();
3361 }
3362 }
3363 /* Ticket:4379 Select multiple objects with [Shift] key (not with [Control] key)
3364 * To provide multi select we switch the shift key with control.
3365 * Yes we need to do this in both mousePressEvent and mouseReleaseEvent.
3366 */
3367 if (event->modifiers() & Qt::ShiftModifier) {
3368 event->setModifiers((event->modifiers() & ~Qt::ShiftModifier) | Qt::ControlModifier);
3369 }
3370 QGraphicsView::mouseReleaseEvent(event);
3371}
3372
3373bool GraphicsView::handleDoubleClickOnComponent(QMouseEvent *event)
3374{
3375 QGraphicsItem *pGraphicsItem = itemAt(event->pos());
3376 bool shouldEnactQTDoubleClick = true;
3377 Component *pComponent = getComponentFromQGraphicsItem(pGraphicsItem);
3378 if (pComponent) {
3379 shouldEnactQTDoubleClick = false;
3380 Component *pRootComponent = pComponent->getRootParentComponent();
3381 if (pRootComponent) {
3382 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel) {
3383 pRootComponent->showSubModelAttributes();
3384 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
3385 removeCurrentConnection();
3386 pRootComponent->handleOMSComponentDoubleClick();
3387 } else {
3388 removeCurrentConnection();
3389 removeCurrentTransition();
3390 /* ticket:4401 Open component class with shift + double click */
3391 if (QApplication::keyboardModifiers() == Qt::ShiftModifier) {
3392 pRootComponent->openClass();
3393 } else {
3394 pRootComponent->showParameters();
3395 }
3396 }
3397 }
3398 }
3399 return shouldEnactQTDoubleClick;
3400}
3401
3402
3403void GraphicsView::mouseDoubleClickEvent(QMouseEvent *event)
3404{
3405 const bool removeLastAddedPoint = true;
3406 if (isCreatingLineShape()) {
3407 finishDrawingLineShape(removeLastAddedPoint);
3408 return;
3409 } else if (isCreatingPolygonShape()) {
3410 finishDrawingPolygonShape(removeLastAddedPoint);
3411 return;
3412 }
3413 ShapeAnnotation *pShapeAnnotation = dynamic_cast<ShapeAnnotation*>(itemAt(event->pos()));
3414 /* Double click on Component also end up here.
3415 * But we don't have GraphicsView for the shapes inside the Component so we can go out of this block.
3416 */
3417 if (!isCreatingConnection() && !isCreatingTransition() && pShapeAnnotation && pShapeAnnotation->getGraphicsView()) {
3418 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
3419 LineAnnotation *pTransitionLineAnnotation = dynamic_cast<LineAnnotation*>(pShapeAnnotation);
3420 if (pTransitionLineAnnotation && pTransitionLineAnnotation->getLineType() == LineAnnotation::TransitionType) {
3421 pShapeAnnotation->editTransition();
3422 } else {
3423 pShapeAnnotation->showShapeProperties();
3424 }
3425 return;
3426 }
3427 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
3428 LineAnnotation *pConnectionLineAnnotation = dynamic_cast<LineAnnotation*>(pShapeAnnotation);
3429 if (pConnectionLineAnnotation && pConnectionLineAnnotation->getLineType() == LineAnnotation::ConnectionType) {
3430 pConnectionLineAnnotation->showOMSConnection();
3431 }
3432 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel) {
3433 pShapeAnnotation->showShapeAttributes();
3434 return;
3435 }
3436 }
3437 if (!handleDoubleClickOnComponent(event)) {
3438 return;
3439 }
3440 QGraphicsView::mouseDoubleClickEvent(event);
3441}
3442
3443/*!
3444 * \brief GraphicsView::focusOutEvent
3445 * \param event
3446 */
3447void GraphicsView::focusOutEvent(QFocusEvent *event)
3448{
3449 // makesure we reset the Qt::CrossCursor
3450 if (QApplication::overrideCursor() && QApplication::overrideCursor()->shape() == Qt::CrossCursor) {
3451 QApplication::restoreOverrideCursor();
3452 }
3453 /*If we get a focus out event while drawing. Stop drawing.*/
3454 if (isCreatingShape()) {
3455 finishDrawingGenericShape();
3456 }
3457 QGraphicsView::focusOutEvent(event);
3458}
3459
3460void GraphicsView::keyPressEvent(QKeyEvent *event)
3461{
3462 // save annotations of all connections
3463 foreach (LineAnnotation *pConnectionLineAnnotation, mConnectionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mConnectionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pConnectionLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
3464 pConnectionLineAnnotation->setOldAnnotation(pConnectionLineAnnotation->getOMCShapeAnnotation());
3465 }
3466 // save annotations of all transitions
3467 foreach (LineAnnotation *pTransitionLineAnnotation, mTransitionsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mTransitionsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pTransitionLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
3468 pTransitionLineAnnotation->setOldAnnotation(pTransitionLineAnnotation->getOMCShapeAnnotation());
3469 }
3470 // save annotations of all initial states
3471 foreach (LineAnnotation *pInitialStateLineAnnotation, mInitialStatesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInitialStatesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pInitialStateLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
3472 pInitialStateLineAnnotation->setOldAnnotation(pInitialStateLineAnnotation->getOMCShapeAnnotation());
3473 }
3474 bool shiftModifier = event->modifiers().testFlag(Qt::ShiftModifier);
3475 bool controlModifier = event->modifiers().testFlag(Qt::ControlModifier);
3476 if (event->key() == Qt::Key_Delete && isAnyItemSelectedAndEditable(event->key())) {
3477 deleteItems();
3478 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_Up && isAnyItemSelectedAndEditable(event->key())) {
3479 mpModelWidget->beginMacro("Move up by key press");
3480 emit keyPressUp();
3481 mpModelWidget->endMacro();
3482 } else if (shiftModifier && !controlModifier && event->key() == Qt::Key_Up && isAnyItemSelectedAndEditable(event->key())) {
3483 mpModelWidget->beginMacro("Move shift up by key press");
3484 emit keyPressShiftUp();
3485 mpModelWidget->endMacro();
3486 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_Up && isAnyItemSelectedAndEditable(event->key())) {
3487 mpModelWidget->beginMacro("Move control up by key press");
3488 emit keyPressCtrlUp();
3489 mpModelWidget->endMacro();
3490 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_Down && isAnyItemSelectedAndEditable(event->key())) {
3491 mpModelWidget->beginMacro("Move down by key press");
3492 emit keyPressDown();
3493 mpModelWidget->endMacro();
3494 } else if (shiftModifier && !controlModifier && event->key() == Qt::Key_Down && isAnyItemSelectedAndEditable(event->key())) {
3495 mpModelWidget->beginMacro("Move shift down by key press");
3496 emit keyPressShiftDown();
3497 mpModelWidget->endMacro();
3498 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_Down && isAnyItemSelectedAndEditable(event->key())) {
3499 mpModelWidget->beginMacro("Move control down by key press");
3500 emit keyPressCtrlDown();
3501 mpModelWidget->endMacro();
3502 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_Left && isAnyItemSelectedAndEditable(event->key())) {
3503 mpModelWidget->beginMacro("Move left by key press");
3504 emit keyPressLeft();
3505 mpModelWidget->endMacro();
3506 } else if (shiftModifier && !controlModifier && event->key() == Qt::Key_Left && isAnyItemSelectedAndEditable(event->key())) {
3507 mpModelWidget->beginMacro("Move shift left by key press");
3508 emit keyPressShiftLeft();
3509 mpModelWidget->endMacro();
3510 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_Left && isAnyItemSelectedAndEditable(event->key())) {
3511 mpModelWidget->beginMacro("Move control left by key press");
3512 emit keyPressCtrlLeft();
3513 mpModelWidget->endMacro();
3514 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_Right && isAnyItemSelectedAndEditable(event->key())) {
3515 mpModelWidget->beginMacro("Move right by key press");
3516 emit keyPressRight();
3517 mpModelWidget->endMacro();
3518 } else if (shiftModifier && !controlModifier && event->key() == Qt::Key_Right && isAnyItemSelectedAndEditable(event->key())) {
3519 mpModelWidget->beginMacro("Move shift right by key press");
3520 emit keyPressShiftRight();
3521 mpModelWidget->endMacro();
3522 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_Right && isAnyItemSelectedAndEditable(event->key())) {
3523 mpModelWidget->beginMacro("Move control right by key press");
3524 emit keyPressCtrlRight();
3525 mpModelWidget->endMacro();
3526 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_A) {
3527 selectAll();
3528 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_X && isAnyItemSelectedAndEditable(event->key()) && mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
3529 cutItems();
3530 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_C && mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
3531 copyItems();
3532 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_V && mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
3533 pasteItems();
3534 } else if (controlModifier && event->key() == Qt::Key_D && isAnyItemSelectedAndEditable(event->key())) {
3535 mpModelWidget->beginMacro("Duplicate by key press");
3536 emit keyPressDuplicate();
3537 mpModelWidget->endMacro();
3538 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_R && isAnyItemSelectedAndEditable(event->key())) {
3539 mpModelWidget->beginMacro("Rotate clockwise by key press");
3540 emit keyPressRotateClockwise();
3541 mpModelWidget->endMacro();
3542 } else if (shiftModifier && controlModifier && event->key() == Qt::Key_R && isAnyItemSelectedAndEditable(event->key())) {
3543 mpModelWidget->beginMacro("Rotate anti clockwise by key press");
3544 emit keyPressRotateAntiClockwise();
3545 mpModelWidget->endMacro();
3546 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_H && isAnyItemSelectedAndEditable(event->key())) {
3547 mpModelWidget->beginMacro("Flip horizontal by key press");
3548 emit keyPressFlipHorizontal();
3549 mpModelWidget->endMacro();
3550 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_V && isAnyItemSelectedAndEditable(event->key())) {
3551 mpModelWidget->beginMacro("Flip vertical by key press");
3552 emit keyPressFlipVertical();
3553 mpModelWidget->endMacro();
3554 } else if (shiftModifier && !controlModifier && (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)) {
3555 /* ticket:4401 Open component class with shift + Enter */
3556 QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
3557 if (selectedItems.size() == 1) {
3558 Component *pComponent = dynamic_cast<Component*>(selectedItems.at(0));
3559 if (pComponent) {
3560 Component *pRootComponent = pComponent->getRootParentComponent();
3561 if (pRootComponent) {
3562 pRootComponent->openClass();
3563 }
3564 }
3565 }
3566 } else if (event->key() == Qt::Key_Escape && isCreatingConnection()) {
3567 removeCurrentConnection();
3568 } else if (event->key() == Qt::Key_Escape && isCreatingTransition()) {
3569 removeCurrentTransition();
3570 } else if (event->key() == Qt::Key_Escape && isCreatingShape()) {
3571 finishDrawingGenericShape();
3572 } else {
3573 QGraphicsView::keyPressEvent(event);
3574 }
3575}
3576
3577void GraphicsView::uncheckAllShapeDrawingActions()
3578{
3579 MainWindow *pMainWindow = MainWindow::instance();
3580 pMainWindow->toggleShapesButton();
3581}
3582
3583//! Defines what shall happen when a key is released.
3584//! @param event contains information about the keypress operation.
3585void GraphicsView::keyReleaseEvent(QKeyEvent *event)
3586{
3587 /* if user has pressed and hold the key. */
3588 if (event->isAutoRepeat()) {
3589 return QGraphicsView::keyReleaseEvent(event);
3590 }
3591 bool shiftModifier = event->modifiers().testFlag(Qt::ShiftModifier);
3592 bool controlModifier = event->modifiers().testFlag(Qt::ControlModifier);
3593 /* handle keys */
3594 if (!shiftModifier && !controlModifier && event->key() == Qt::Key_Up && isAnyItemSelectedAndEditable(event->key())) {
3595 mpModelWidget->updateClassAnnotationIfNeeded();
3596 mpModelWidget->updateModelText();
3597 } else if (shiftModifier && !controlModifier && event->key() == Qt::Key_Up && isAnyItemSelectedAndEditable(event->key())) {
3598 mpModelWidget->updateClassAnnotationIfNeeded();
3599 mpModelWidget->updateModelText();
3600 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_Up && isAnyItemSelectedAndEditable(event->key())) {
3601 mpModelWidget->updateClassAnnotationIfNeeded();
3602 mpModelWidget->updateModelText();
3603 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_Down && isAnyItemSelectedAndEditable(event->key())) {
3604 mpModelWidget->updateClassAnnotationIfNeeded();
3605 mpModelWidget->updateModelText();
3606 } else if (shiftModifier && !controlModifier && event->key() == Qt::Key_Down && isAnyItemSelectedAndEditable(event->key())) {
3607 mpModelWidget->updateClassAnnotationIfNeeded();
3608 mpModelWidget->updateModelText();
3609 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_Down && isAnyItemSelectedAndEditable(event->key())) {
3610 mpModelWidget->updateClassAnnotationIfNeeded();
3611 mpModelWidget->updateModelText();
3612 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_Left && isAnyItemSelectedAndEditable(event->key())) {
3613 mpModelWidget->updateClassAnnotationIfNeeded();
3614 mpModelWidget->updateModelText();
3615 } else if (shiftModifier && !controlModifier && event->key() == Qt::Key_Left && isAnyItemSelectedAndEditable(event->key())) {
3616 mpModelWidget->updateClassAnnotationIfNeeded();
3617 mpModelWidget->updateModelText();
3618 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_Left && isAnyItemSelectedAndEditable(event->key())) {
3619 mpModelWidget->updateClassAnnotationIfNeeded();
3620 mpModelWidget->updateModelText();
3621 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_Right && isAnyItemSelectedAndEditable(event->key())) {
3622 mpModelWidget->updateClassAnnotationIfNeeded();
3623 mpModelWidget->updateModelText();
3624 } else if (shiftModifier && !controlModifier && event->key() == Qt::Key_Right && isAnyItemSelectedAndEditable(event->key())) {
3625 mpModelWidget->updateClassAnnotationIfNeeded();
3626 mpModelWidget->updateModelText();
3627 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_Right && isAnyItemSelectedAndEditable(event->key())) {
3628 mpModelWidget->updateClassAnnotationIfNeeded();
3629 mpModelWidget->updateModelText();
3630 } else if (controlModifier && event->key() == Qt::Key_D && isAnyItemSelectedAndEditable(event->key())) {
3631 mpModelWidget->updateClassAnnotationIfNeeded();
3632 mpModelWidget->updateModelText();
3633 } else if (!shiftModifier && controlModifier && event->key() == Qt::Key_R && isAnyItemSelectedAndEditable(event->key())) {
3634 mpModelWidget->updateClassAnnotationIfNeeded();
3635 mpModelWidget->updateModelText();
3636 } else if (shiftModifier && controlModifier && event->key() == Qt::Key_R && isAnyItemSelectedAndEditable(event->key())) {
3637 mpModelWidget->updateClassAnnotationIfNeeded();
3638 mpModelWidget->updateModelText();
3639 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_H && isAnyItemSelectedAndEditable(event->key())) {
3640 mpModelWidget->updateClassAnnotationIfNeeded();
3641 mpModelWidget->updateModelText();
3642 } else if (!shiftModifier && !controlModifier && event->key() == Qt::Key_V && isAnyItemSelectedAndEditable(event->key())) {
3643 mpModelWidget->updateClassAnnotationIfNeeded();
3644 mpModelWidget->updateModelText();
3645 } else {
3646 QGraphicsView::keyReleaseEvent(event);
3647 }
3648}
3649
3650void GraphicsView::contextMenuEvent(QContextMenuEvent *event)
3651{
3652 /* If we are creating the connection OR creating any shape then don't show context menu */
3653 if (isCreatingShape() || isCreatingConnection()) {
3654 return;
3655 }
3656 // if creating a transition
3657 if (isCreatingTransition()) {
3658 QMenu menu(MainWindow::instance());
3659 menu.addAction(mpSetInitialStateAction);
3660 menu.addSeparator();
3661 menu.addAction(mpCancelTransitionAction);
3662 menu.exec(event->globalPos());
3663 return;
3664 }
3665 // if some item is right clicked then don't show graphics view context menu
3666 if (!itemAt(event->pos())) {
3667 QMenu menu;
3668 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
3669 modelicaGraphicsViewContextMenu(&menu);
3670 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel) {
3671 compositeModelGraphicsViewContextMenu(&menu);
3672 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
3673 omsGraphicsViewContextMenu(&menu);
3674 }
3675 menu.exec(event->globalPos());
3676 return; // return from it because at a time we only want one context menu.
3677 } else { // if we click on some item.
3678 bool oneShapeSelected = false;
3679 bool oneComponentSelected = false;
3680 // if a shape is right clicked
3681 ShapeAnnotation *pShapeAnnotation = dynamic_cast<ShapeAnnotation*>(itemAt(event->pos()));
3682 Component *pComponent = 0;
3683 if (pShapeAnnotation && pShapeAnnotation->getGraphicsView()) {
3684 if (!pShapeAnnotation->isSelected()) {
3685 clearSelection(pShapeAnnotation);
3686 }
3687 oneShapeSelected = scene()->selectedItems().size() == 1;
3688 } else {
3689 // if a component is right clicked
3690 pComponent = componentAtPosition(event->pos());
3691 if (pComponent) {
3692 if (!pComponent->isSelected()) {
3693 clearSelection(pComponent);
3694 }
3695 oneComponentSelected = scene()->selectedItems().size() == 1;
3696 }
3697 }
3698 // construct context menu now
3699 QMenu menu;
3700 if (oneShapeSelected) {
3701 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
3702 modelicaOneShapeContextMenu(pShapeAnnotation, &menu);
3703 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel) {
3704 compositeModelOneShapeContextMenu(pShapeAnnotation, &menu);
3705 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
3706 omsOneShapeContextMenu(pShapeAnnotation, &menu);
3707 }
3708 } else if (oneComponentSelected) {
3709 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
3710 modelicaOneComponentContextMenu(pComponent, &menu);
3711 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel) {
3712 compositeModelOneComponentContextMenu(pComponent, &menu);
3713 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
3714 // No context menu for component of type OMS connector i.e., input/output signal or OMS bus connector.
3715 if (pComponent->getLibraryTreeItem() && pComponent->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS
3716 && (pComponent->getLibraryTreeItem()->getOMSConnector()
3717 || pComponent->getLibraryTreeItem()->getOMSBusConnector()
3718 || pComponent->getLibraryTreeItem()->getOMSTLMBusConnector())) {
3719 return;
3720 }
3721 omsOneComponentContextMenu(pComponent, &menu);
3722 }
3723 } else {
3724 if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
3725 modelicaMultipleItemsContextMenu(&menu);
3726 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel) {
3727 compositeModelMultipleItemsContextMenu(&menu);
3728 } else if (mpModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
3729 omsMultipleItemsContextMenu(&menu);
3730 }
3731 }
3732 // enable/disable common actions based on if any inherited item is selected
3733 bool noInheritedItemSelected = true;
3734 QList<QGraphicsItem*> graphicsItems = scene()->selectedItems();
3735 foreach (QGraphicsItem *pGraphicsItem, graphicsItems)for (auto _container_ = QtPrivate::qMakeForeachContainer(graphicsItems
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QGraphicsItem
*pGraphicsItem = *_container_.i; _container_.control; _container_
.control = 0)
{
3736 Component *pComponent = getComponentFromQGraphicsItem(pGraphicsItem);
3737 if (pComponent) {
3738 Component *pRootComponent = pComponent->getRootParentComponent();
3739 if (pRootComponent && pRootComponent->isInheritedComponent() && pRootComponent->isSelected()) {
3740 noInheritedItemSelected = false;
3741 }
3742 } else if (ShapeAnnotation *pShapeAnnotation = dynamic_cast<ShapeAnnotation*>(pGraphicsItem)) {
3743 if (pShapeAnnotation->isInheritedShape() && pShapeAnnotation->isSelected()) {
3744 noInheritedItemSelected = false;
3745 }
3746 }
3747 }
3748 mpManhattanizeAction->setEnabled(noInheritedItemSelected);
3749 mpDeleteAction->setEnabled(noInheritedItemSelected);
3750 mpCutAction->setEnabled(noInheritedItemSelected);
3751 mpDuplicateAction->setEnabled(noInheritedItemSelected);
3752 mpRotateClockwiseAction->setEnabled(noInheritedItemSelected);
3753 mpRotateAntiClockwiseAction->setEnabled(noInheritedItemSelected);
3754 mpFlipHorizontalAction->setEnabled(noInheritedItemSelected);
3755 mpFlipVerticalAction->setEnabled(noInheritedItemSelected);
3756 menu.exec(event->globalPos());
3757 return; // return from it because at a time we only want one context menu.
3758 }
3759 QGraphicsView::contextMenuEvent(event);
3760}
3761
3762void GraphicsView::resizeEvent(QResizeEvent *event)
3763{
3764 fitInViewInternal();
3765 QGraphicsView::resizeEvent(event);
3766}
3767
3768/*!
3769 * \brief GraphicsView::wheelEvent
3770 * Reimplementation of QGraphicsView::wheelEvent.
3771 * Allows zooming with mouse.
3772 * \param event
3773 */
3774void GraphicsView::wheelEvent(QWheelEvent *event)
3775{
3776 int numDegrees = event->delta() / 8;
3777 int numSteps = numDegrees * 3;
3778 bool controlModifier = event->modifiers().testFlag(Qt::ControlModifier);
3779 bool shiftModifier = event->modifiers().testFlag(Qt::ShiftModifier);
3780 // If Ctrl key is pressed and user has scrolled vertically then Zoom In/Out based on the scroll distance.
3781 if (event->orientation() == Qt::Vertical && controlModifier) {
3782 if (event->delta() > 0) {
3783 zoomIn();
3784 } else {
3785 zoomOut();
3786 }
3787 } else if ((event->orientation() == Qt::Horizontal) || (event->orientation() == Qt::Vertical && shiftModifier)) {
3788 // If Shift key is pressed and user has scrolled vertically then scroll the horizontal scrollbars.
3789 // If user has scrolled horizontally then scroll the horizontal scrollbars.
3790 horizontalScrollBar()->setValue(horizontalScrollBar()->value() - numSteps);
3791 } else if (event->orientation() == Qt::Vertical) {
3792 // If user has scrolled vertically then scroll the vertical scrollbars.
3793 verticalScrollBar()->setValue(verticalScrollBar()->value() - numSteps);
3794 } else {
3795 QGraphicsView::wheelEvent(event);
3796 }
3797}
3798
3799/*!
3800 * \brief GraphicsView::leaveEvent
3801 * Reimplementation of QGraphicsView::leaveEvent.
3802 * Clears the position label in the status bar.
3803 * \param event
3804 */
3805void GraphicsView::leaveEvent(QEvent *event)
3806{
3807 // clear the position label
3808 MainWindow::instance()->getPositionLabel()->clear();
3809 QGraphicsView::leaveEvent(event);
3810}
3811
3812WelcomePageWidget::WelcomePageWidget(QWidget *pParent)
3813 : QWidget(pParent)
3814{
3815 // main frame
3816 mpMainFrame = new QFrame;
3817 mpMainFrame->setContentsMargins(0, 0, 0, 0);
3818 mpMainFrame->setStyleSheet("QFrame{color:gray;}");
3819 // top frame
3820 mpTopFrame = new QFrame;
3821 mpTopFrame->setStyleSheet("QFrame{background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #828282, stop: 1 #5e5e5e);}");
3822 // top frame pixmap
3823 mpPixmapLabel = new Label;
3824 QPixmap pixmap(":/Resources/icons/omedit.png");
3825 mpPixmapLabel->setPixmap(pixmap.scaled(75, 72, Qt::KeepAspectRatio, Qt::SmoothTransformation));
3826 mpPixmapLabel->setStyleSheet("background-color : transparent;");
3827 // top frame heading
3828 mpHeadingLabel = Utilities::getHeadingLabel(QString(Helper::applicationName).append(" - ").append(Helper::applicationIntroText));
3829 mpHeadingLabel->setStyleSheet("background-color : transparent; color : white;");
3830#ifndef Q_OS_MAC
3831 mpHeadingLabel->setGraphicsEffect(new QGraphicsDropShadowEffect);
3832#endif
3833 mpHeadingLabel->setElideMode(Qt::ElideMiddle);
3834 // top frame layout
3835 QHBoxLayout *topFrameLayout = new QHBoxLayout;
3836 topFrameLayout->setAlignment(Qt::AlignLeft);
3837 topFrameLayout->addWidget(mpPixmapLabel);
3838 topFrameLayout->addWidget(mpHeadingLabel);
3839 mpTopFrame->setLayout(topFrameLayout);
3840 // RecentFiles Frame
3841 mpRecentFilesFrame = new QFrame;
3842 mpRecentFilesFrame->setFrameShape(QFrame::StyledPanel);
3843 mpRecentFilesFrame->setStyleSheet("QFrame{background-color: white;}");
3844 // recent items list
3845 mpRecentFilesLabel = Utilities::getHeadingLabel(tr("Recent Files"));
3846 mpNoRecentFileLabel = new Label(tr("No recent files found."));
3847 mpRecentItemsList = new QListWidget;
3848 mpRecentItemsList->setObjectName("RecentItemsList");
3849 mpRecentItemsList->setContentsMargins(0, 0, 0, 0);
3850 mpRecentItemsList->setSpacing(5);
3851 mpRecentItemsList->setFrameStyle(QFrame::NoFrame);
3852 mpRecentItemsList->setViewMode(QListView::ListMode);
3853 mpRecentItemsList->setMovement(QListView::Static);
3854 mpRecentItemsList->setIconSize(Helper::iconSize);
3855 mpRecentItemsList->setCurrentRow(0, QItemSelectionModel::Select);
3856 connect(mpRecentItemsList, SIGNAL(itemClicked(QListWidgetItem*))"2""itemClicked(QListWidgetItem*)", SLOT(openRecentFileItem(QListWidgetItem*))"1""openRecentFileItem(QListWidgetItem*)");
3857 mpClearRecentFilesListButton = new QPushButton(tr("Clear Recent Files"));
3858 mpClearRecentFilesListButton->setStyleSheet("QPushButton{padding: 5px 15px 5px 15px;}");
3859 connect(mpClearRecentFilesListButton, SIGNAL(clicked())"2""clicked()", MainWindow::instance(), SLOT(clearRecentFilesList())"1""clearRecentFilesList()");
3860 // RecentFiles Frame layout
3861 QVBoxLayout *recentFilesFrameVBLayout = new QVBoxLayout;
3862 recentFilesFrameVBLayout->addWidget(mpRecentFilesLabel);
3863 recentFilesFrameVBLayout->addWidget(mpNoRecentFileLabel);
3864 recentFilesFrameVBLayout->addWidget(mpRecentItemsList);
3865 QHBoxLayout *recentFilesHBLayout = new QHBoxLayout;
3866 recentFilesHBLayout->addWidget(mpClearRecentFilesListButton, 0, Qt::AlignLeft);
3867 recentFilesFrameVBLayout->addLayout(recentFilesHBLayout);
3868 mpRecentFilesFrame->setLayout(recentFilesFrameVBLayout);
3869 // LatestNews Frame
3870 mpLatestNewsFrame = new QFrame;
3871 mpLatestNewsFrame->setFrameShape(QFrame::StyledPanel);
3872 mpLatestNewsFrame->setStyleSheet("QFrame{background-color: white;}");
3873 /* Read the show latest news settings */
3874 if (!OptionsDialog::instance()->getGeneralSettingsPage()->getShowLatestNewsCheckBox()->isChecked()) {
3875 mpLatestNewsFrame->setVisible(false);
3876 }
3877 // latest news
3878 mpLatestNewsLabel = Utilities::getHeadingLabel(tr("Latest News"));
3879 mpNoLatestNewsLabel = new Label;
3880 mpLatestNewsListWidget = new QListWidget;
3881 mpLatestNewsListWidget->setObjectName("LatestNewsList");
3882 mpLatestNewsListWidget->setContentsMargins(0, 0, 0, 0);
3883 mpLatestNewsListWidget->setSpacing(5);
3884 mpLatestNewsListWidget->setFrameStyle(QFrame::NoFrame);
3885 mpLatestNewsListWidget->setViewMode(QListView::ListMode);
3886 mpLatestNewsListWidget->setMovement(QListView::Static);
3887 mpLatestNewsListWidget->setIconSize(Helper::iconSize);
3888 mpLatestNewsListWidget->setCurrentRow(0, QItemSelectionModel::Select);
3889 mpReloadLatestNewsButton = new QPushButton(Helper::reload);
3890 mpReloadLatestNewsButton->setStyleSheet("QPushButton{padding: 5px 15px 5px 15px;}");
3891 connect(mpReloadLatestNewsButton, SIGNAL(clicked())"2""clicked()", SLOT(addLatestNewsListItems())"1""addLatestNewsListItems()");
3892 mpVisitWebsiteLabel = new Label(tr("For more details visit our website <u><a href=\"http://www.openmodelica.org\">www.openmodelica.org</a></u>"));
3893 mpVisitWebsiteLabel->setTextFormat(Qt::RichText);
3894 mpVisitWebsiteLabel->setTextInteractionFlags(mpVisitWebsiteLabel->textInteractionFlags() | Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
3895 mpVisitWebsiteLabel->setOpenExternalLinks(true);
3896 connect(mpLatestNewsListWidget, SIGNAL(itemClicked(QListWidgetItem*))"2""itemClicked(QListWidgetItem*)", SLOT(openLatestNewsItem(QListWidgetItem*))"1""openLatestNewsItem(QListWidgetItem*)");
3897 // Latest News Frame layout
3898 QVBoxLayout *latestNewsFrameVBLayout = new QVBoxLayout;
3899 latestNewsFrameVBLayout->addWidget(mpLatestNewsLabel);
3900 latestNewsFrameVBLayout->addWidget(mpNoLatestNewsLabel);
3901 latestNewsFrameVBLayout->addWidget(mpLatestNewsListWidget);
3902 QHBoxLayout *latestNewsFrameHBLayout = new QHBoxLayout;
3903 latestNewsFrameHBLayout->addWidget(mpReloadLatestNewsButton, 0, Qt::AlignLeft);
3904 latestNewsFrameHBLayout->addWidget(mpVisitWebsiteLabel, 0, Qt::AlignRight);
3905 latestNewsFrameVBLayout->addLayout(latestNewsFrameHBLayout);
3906 mpLatestNewsFrame->setLayout(latestNewsFrameVBLayout);
3907 // create http object for request
3908 mpLatestNewsNetworkAccessManager = new QNetworkAccessManager;
3909 connect(mpLatestNewsNetworkAccessManager, SIGNAL(finished(QNetworkReply*))"2""finished(QNetworkReply*)", SLOT(readLatestNewsXML(QNetworkReply*))"1""readLatestNewsXML(QNetworkReply*)");
3910 addLatestNewsListItems();
3911 // splitter
3912 mpSplitter = new QSplitter;
3913 /* Read the welcome page view settings */
3914 switch (OptionsDialog::instance()->getGeneralSettingsPage()->getWelcomePageView()){
3915 case 2:
3916 mpSplitter->setOrientation(Qt::Vertical);
3917 break;
3918 case 1:
3919 default:
3920 mpSplitter->setOrientation(Qt::Horizontal);
3921 break;
3922 }
3923 mpSplitter->setChildrenCollapsible(false);
3924 mpSplitter->setHandleWidth(4);
3925 mpSplitter->setContentsMargins(0, 0, 0, 0);
3926 mpSplitter->addWidget(mpRecentFilesFrame);
3927 mpSplitter->addWidget(mpLatestNewsFrame);
3928 // Read the welcome page splitter state
3929 QSettings *pSettings = Utilities::getApplicationSettings();
3930 mpSplitter->restoreState(pSettings->value("welcomePage/splitterState").toByteArray());
3931 // bottom frame
3932 mpBottomFrame = new QFrame;
3933 mpBottomFrame->setStyleSheet("QFrame{background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #828282, stop: 1 #5e5e5e);}");
3934 // bottom frame create and open buttons buttons
3935 mpCreateModelButton = new QPushButton(Helper::createNewModelicaClass);
3936 mpCreateModelButton->setStyleSheet("QPushButton{padding: 5px 15px 5px 15px;}");
3937 connect(mpCreateModelButton, SIGNAL(clicked())"2""clicked()", MainWindow::instance(), SLOT(createNewModelicaClass())"1""createNewModelicaClass()");
3938 mpOpenModelButton = new QPushButton(Helper::openModelicaFiles);
3939 mpOpenModelButton->setStyleSheet("QPushButton{padding: 5px 15px 5px 15px;}");
3940 connect(mpOpenModelButton, SIGNAL(clicked())"2""clicked()", MainWindow::instance(), SLOT(openModelicaFile())"1""openModelicaFile()");
3941 // bottom frame layout
3942 QHBoxLayout *bottomFrameLayout = new QHBoxLayout;
3943 bottomFrameLayout->addWidget(mpCreateModelButton, 0, Qt::AlignLeft);
3944 bottomFrameLayout->addWidget(mpOpenModelButton, 0, Qt::AlignRight);
3945 mpBottomFrame->setLayout(bottomFrameLayout);
3946 // vertical layout for frames
3947 QVBoxLayout *verticalLayout = new QVBoxLayout;
3948 verticalLayout->setSpacing(4);
3949 verticalLayout->setContentsMargins(0, 0, 0, 0);
3950 verticalLayout->addWidget(mpTopFrame, 0, Qt::AlignTop);
3951 verticalLayout->addWidget(mpSplitter, 1);
3952 verticalLayout->addWidget(mpBottomFrame, 0, Qt::AlignBottom);
3953 // main frame layout
3954 mpMainFrame->setLayout(verticalLayout);
3955 QHBoxLayout *layout = new QHBoxLayout;
3956 layout->setContentsMargins(0, 0, 0, 0);
3957 layout->addWidget(mpMainFrame);
3958 setLayout(layout);
3959}
3960
3961void WelcomePageWidget::addRecentFilesListItems()
3962{
3963 // remove list items first
3964 mpRecentItemsList->clear();
3965 QSettings *pSettings = Utilities::getApplicationSettings();
3966 QList<QVariant> files = pSettings->value("recentFilesList/files").toList();
3967 int numRecentFiles = qMin(files.size(), (int)MainWindow::instance()->MaxRecentFiles);
3968 for (int i = 0; i < numRecentFiles; ++i)
3969 {
3970 RecentFile recentFile = qvariant_cast<RecentFile>(files[i]);
3971 QListWidgetItem *listItem = new QListWidgetItem(mpRecentItemsList);
3972 listItem->setIcon(ResourceCache::getIcon(":/Resources/icons/next.svg"));
3973 listItem->setText(recentFile.fileName);
3974 listItem->setData(Qt::UserRole, recentFile.encoding);
3975 }
3976 if (files.size() > 0)
3977 mpNoRecentFileLabel->setVisible(false);
3978 else
3979 mpNoRecentFileLabel->setVisible(true);
3980}
3981
3982QFrame* WelcomePageWidget::getLatestNewsFrame()
3983{
3984 return mpLatestNewsFrame;
3985}
3986
3987QSplitter* WelcomePageWidget::getSplitter()
3988{
3989 return mpSplitter;
3990}
3991
3992void WelcomePageWidget::addLatestNewsListItems()
3993{
3994 mpLatestNewsListWidget->clear();
3995 /* if show latest news settings is not set then don't fetch the latest news items. */
3996 if (OptionsDialog::instance()->getGeneralSettingsPage()->getShowLatestNewsCheckBox()->isChecked())
3997 {
3998 QUrl newsUrl("https://openmodelica.org/index.php?option=com_content&view=category&id=23&format=feed&amp;type=rss");
3999 QNetworkReply *pNetworkReply = mpLatestNewsNetworkAccessManager->get(QNetworkRequest(newsUrl));
4000 pNetworkReply->ignoreSslErrors();
4001 }
4002}
4003
4004void WelcomePageWidget::readLatestNewsXML(QNetworkReply *pNetworkReply)
4005{
4006 if (pNetworkReply->error() == QNetworkReply::HostNotFoundError)
4007 {
4008 mpNoLatestNewsLabel->setVisible(true);
4009 mpNoLatestNewsLabel->setText(tr("Sorry, no internet no news items."));
4010 }
4011 else if (pNetworkReply->error() == QNetworkReply::NoError)
4012 {
4013 QByteArray response(pNetworkReply->readAll());
4014 QXmlStreamReader xml(response);
4015 int count = 0;
4016 QString title, link;
4017 while (!xml.atEnd())
4018 {
4019 mpNoLatestNewsLabel->setVisible(false);
4020 xml.readNext();
4021 if (xml.tokenType() == QXmlStreamReader::StartElement)
4022 {
4023 if (xml.name() == "item")
4024 {
4025 while (!xml.atEnd())
4026 {
4027 xml.readNext();
4028 if (xml.tokenType() == QXmlStreamReader::StartElement)
4029 {
4030 if (xml.name() == "title")
4031 title = xml.readElementText();
4032 if (xml.name() == "link")
4033 {
4034 link = xml.readElementText();
4035 if (count >= (int)MainWindow::instance()->MaxRecentFiles)
4036 break;
4037 count++;
4038 QListWidgetItem *listItem = new QListWidgetItem(mpLatestNewsListWidget);
4039 listItem->setIcon(ResourceCache::getIcon(":/Resources/icons/next.svg"));
4040 listItem->setText(title);
4041 listItem->setData(Qt::UserRole, link);
4042 break;
4043 }
4044 }
4045 }
4046 }
4047 }
4048 if (count >= (int)MainWindow::instance()->MaxRecentFiles)
4049 break;
4050 }
4051 }
4052 else
4053 {
4054 mpNoLatestNewsLabel->setVisible(true);
4055 mpNoLatestNewsLabel->setText(QString(Helper::error).append(" - ").append(pNetworkReply->errorString()));
4056 }
4057}
4058
4059void WelcomePageWidget::openRecentFileItem(QListWidgetItem *pItem)
4060{
4061 MainWindow::instance()->getLibraryWidget()->openFile(pItem->text(), pItem->data(Qt::UserRole).toString(), true, true);
4062}
4063
4064void WelcomePageWidget::openLatestNewsItem(QListWidgetItem *pItem)
4065{
4066 QUrl url(pItem->data(Qt::UserRole).toString());
4067 QDesktopServices::openUrl(url);
4068}
4069
4070/*!
4071 * \class UndoStack
4072 * \brief Subclass QUndoStack.\n
4073 * We need to handle which commands to push to the stack.
4074 */
4075/*!
4076 * \brief UndoStack::UndoStack
4077 * \param parent
4078 */
4079UndoStack::UndoStack(QObject *parent)
4080 : QUndoStack(parent)
4081{
4082 mEnabled = true;
4083}
4084
4085/*!
4086 * \brief UndoStack::push
4087 * \param cmd
4088 */
4089void UndoStack::push(UndoCommand *cmd)
4090{
4091 /* We only push the commands to the stack when its enabled.
4092 * When the stack is not enabled we don't push the command but we do execute the command.
4093 * Most of such cases are when loading and opening a class. The operations performed at that time are not needed on the stack.
4094 * This is needed since we don't want to call clear on the stack.
4095 */
4096 if (isEnabled()) {
4097 /* If the stack is enabled then call the command redo function to check if the command fails or not.
4098 * If the command fails then delete it and don't push to the stack.
4099 * If the command doesn't fail then disable it and push to the stack. We need to disable it since QUndoStack::push() calls the
4100 * command redo function and we already called redo once so we don't want to call it here.
4101 * Enable the command after the push is done.
4102 */
4103 cmd->redoInternal();
4104 if (cmd->isFailed()) {
4105 delete cmd;
4106 } else {
4107 cmd->setEnabled(false);
4108 QUndoStack::push(cmd);
4109 cmd->setEnabled(true);
4110 }
4111 } else {
4112 cmd->redo();
4113 }
4114}
4115
4116ModelWidget::ModelWidget(LibraryTreeItem* pLibraryTreeItem, ModelWidgetContainer *pModelWidgetContainer)
4117 : QWidget(pModelWidgetContainer), mpModelWidgetContainer(pModelWidgetContainer), mpLibraryTreeItem(pLibraryTreeItem),
4118 mComponentsLoaded(false), mDiagramViewLoaded(false), mConnectionsLoaded(false), mCreateModelWidgetComponents(false),
4119 mExtendsModifiersLoaded(false), mDerivedClassModifiersLoaded(false)
4120{
4121 // create widgets based on library type
4122 if (mpLibraryTreeItem->getLibraryType() == LibraryTreeItem::Modelica) {
4123 // icon graphics framework
4124 mpIconGraphicsScene = new GraphicsScene(StringHandler::Icon, this);
4125 mpIconGraphicsView = new GraphicsView(StringHandler::Icon, this);
4126 mpIconGraphicsView->setScene(mpIconGraphicsScene);
4127 mpIconGraphicsView->hide();
4128 // diagram graphics framework
4129 mpDiagramGraphicsScene = new GraphicsScene(StringHandler::Diagram, this);
4130 mpDiagramGraphicsView = new GraphicsView(StringHandler::Diagram, this);
4131 mpDiagramGraphicsView->setScene(mpDiagramGraphicsScene);
4132 mpDiagramGraphicsView->hide();
4133 // Undo stack for model
4134 mpUndoStack = new UndoStack;
4135 connect(mpUndoStack, SIGNAL(canUndoChanged(bool))"2""canUndoChanged(bool)", SLOT(handleCanUndoChanged(bool))"1""handleCanUndoChanged(bool)");
4136 connect(mpUndoStack, SIGNAL(canRedoChanged(bool))"2""canRedoChanged(bool)", SLOT(handleCanRedoChanged(bool))"1""handleCanRedoChanged(bool)");
4137 if (MainWindow::instance()->isDebug()) {
4138 mpUndoView = new QUndoView(mpUndoStack);
4139 }
4140 mpEditor = 0;
4141 getModelInheritedClasses();
4142 drawModelInheritedClassShapes(this, StringHandler::Icon);
4143 getModelIconDiagramShapes(StringHandler::Icon);
4144 /* Ticket:2960
4145 * Just a workaround to make browsing faster.
4146 * We don't get the components here i.e items are shown without connectors in the Libraries Browser.
4147 * Fetch the components when we really need to draw them.
4148 */
4149 /*! @todo Uncomment the following code once we have new faster frontend and remove the flag mComponentsLoaded. */
4150 // drawModelInheritedClassComponents(this, StringHandler::Icon);
4151 // getModelComponents();
4152 // drawModelIconComponents();
4153 } else if (mpLibraryTreeItem->getLibraryType() == LibraryTreeItem::OMS) {
4154 // icon graphics framework
4155 if (mpLibraryTreeItem->isSystemElement() || mpLibraryTreeItem->isComponentElement()) {
4156 mpIconGraphicsScene = new GraphicsScene(StringHandler::Icon, this);
4157 mpIconGraphicsView = new GraphicsView(StringHandler::Icon, this);
4158 mpIconGraphicsView->setScene(mpIconGraphicsScene);
4159 mpIconGraphicsView->hide();
4160 } else {
4161 mpIconGraphicsScene = 0;
4162 mpIconGraphicsView = 0;
4163 }
4164 // diagram graphics framework
4165 mpDiagramGraphicsScene = new GraphicsScene(StringHandler::Diagram, this);
4166 mpDiagramGraphicsView = new GraphicsView(StringHandler::Diagram, this);
4167 mpDiagramGraphicsView->setScene(mpDiagramGraphicsScene);
4168 mpDiagramGraphicsView->hide();
4169 // Undo stack for model
4170 mpUndoStack = new UndoStack;
4171 connect(mpUndoStack, SIGNAL(canUndoChanged(bool))"2""canUndoChanged(bool)", SLOT(handleCanUndoChanged(bool))"1""handleCanUndoChanged(bool)");
4172 connect(mpUndoStack, SIGNAL(canRedoChanged(bool))"2""canRedoChanged(bool)", SLOT(handleCanRedoChanged(bool))"1""handleCanRedoChanged(bool)");
4173 if (MainWindow::instance()->isDebug()) {
4174 mpUndoView = new QUndoView(mpUndoStack);
4175 }
4176 mpEditor = 0;
4177 mpUndoStack->setEnabled(false);
4178 drawOMSModelIconElements();
4179 mpUndoStack->setEnabled(true);
4180 } else {
4181 // icon graphics framework
4182 mpIconGraphicsScene = 0;
4183 mpIconGraphicsView = 0;
4184 // diagram graphics framework
4185 mpDiagramGraphicsScene = 0;
4186 mpDiagramGraphicsView = 0;
4187 // undo stack for model
4188 mpUndoStack = 0;
4189 if (MainWindow::instance()->isDebug()) {
4190 mpUndoView = 0;
4191 }
4192 mpEditor = 0;
4193 }
4194 // Read the file for LibraryTreeItem::Text
4195 if (mpLibraryTreeItem->getLibraryType() == LibraryTreeItem::Text && !mpLibraryTreeItem->isFilePathValid()) {
4196 QString contents = "";
4197 QFile file(mpLibraryTreeItem->getFileName());
4198 if (!file.open(QIODevice::ReadOnly)) {
4199 // QMessageBox::critical(mpLibraryWidget->MainWindow::instance(), QString(Helper::applicationName).append(" - ").append(Helper::error),
4200 // GUIMessages::getMessage(GUIMessages::ERROR_OPENING_FILE).arg(pLibraryTreeItem->getFileName())
4201 // .arg(file.errorString()), Helper::ok);
4202 } else {
4203 contents = QString(file.readAll());
4204 file.close();
4205 }
4206 mpLibraryTreeItem->setClassText(contents);
4207 }
4208}
4209
4210/*!
4211 * \brief ModelWidget::getExtendsModifiersMap
4212 * Returns a extends modifier map for extends class
4213 * \param extendsClass
4214 * \return
4215 */
4216QMap<QString, QString> ModelWidget::getExtendsModifiersMap(QString extendsClass)
4217{
4218 if (!mExtendsModifiersLoaded) {
4219 foreach (LibraryTreeItem *pLibraryTreeItem, mInheritedClassesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mInheritedClassesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LibraryTreeItem
*pLibraryTreeItem = *_container_.i; _container_.control; _container_
.control = 0)
{
4220 fetchExtendsModifiers(pLibraryTreeItem->getNameStructure());
4221 }
4222 mExtendsModifiersLoaded = true;
4223 }
4224 return mExtendsModifiersMap.value(extendsClass);
4225}
4226
4227/*!
4228 * \brief ModelWidget::getDerivedClassModifiersMap
4229 * Returns a derived class modifiers map
4230 * \param derivedClass
4231 * \return
4232 */
4233QMap<QString, QString> ModelWidget::getDerivedClassModifiersMap()
4234{
4235 if (!mDerivedClassModifiersLoaded) {
4236 mDerivedClassModifiersMap.clear();
4237 OMCProxy *pOMCProxy = MainWindow::instance()->getOMCProxy();
4238 QStringList derivedClassModifierNames = pOMCProxy->getDerivedClassModifierNames(mpLibraryTreeItem->getNameStructure());
4239 foreach (QString derivedClassModifierName, derivedClassModifierNames)for (auto _container_ = QtPrivate::qMakeForeachContainer(derivedClassModifierNames
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QString derivedClassModifierName
= *_container_.i; _container_.control; _container_.control =
0)
{
4240 // if we have already read the record modifier then continue
4241 if (mDerivedClassModifiersMap.contains(derivedClassModifierName)) {
4242 continue;
4243 }
4244 mDerivedClassModifiersMap.insert(derivedClassModifierName, pOMCProxy->getDerivedClassModifierValue(mpLibraryTreeItem->getNameStructure(), derivedClassModifierName));
4245 }
4246 mDerivedClassModifiersLoaded = true;
4247 }
4248 return mDerivedClassModifiersMap;
4249}
4250
4251/*!
4252 * \brief ModelWidget::fetchExtendsModifiers
4253 * Gets the extends modifiers and their values.
4254 * \param extendsClass
4255 */
4256void ModelWidget::fetchExtendsModifiers(QString extendsClass)
4257{
4258 mExtendsModifiersMap.clear();
4259 OMCProxy *pOMCProxy = MainWindow::instance()->getOMCProxy();
4260 QStringList extendsModifiersList = pOMCProxy->getExtendsModifierNames(mpLibraryTreeItem->getNameStructure(), extendsClass);
4261 QMap<QString, QString> extendsModifiersMap;
4262 foreach (QString extendsModifier, extendsModifiersList)for (auto _container_ = QtPrivate::qMakeForeachContainer(extendsModifiersList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QString extendsModifier
= *_container_.i; _container_.control; _container_.control =
0)
{
4263 QString extendsModifierValue = pOMCProxy->getExtendsModifierValue(mpLibraryTreeItem->getNameStructure(), extendsClass, extendsModifier);
4264 extendsModifiersMap.insert(extendsModifier, extendsModifierValue);
4265 }
4266 mExtendsModifiersMap.insert(extendsClass, extendsModifiersMap);
4267}
4268
4269/*!
4270 * \brief ModelWidget::reDrawModelWidgetInheritedClasses
4271 * Redraws the class inherited classes shapes, components and connections.
4272 */
4273void ModelWidget::reDrawModelWidgetInheritedClasses()
4274{
4275 mpIconGraphicsView->removeInheritedClassShapes();
4276 drawModelInheritedClassShapes(this, StringHandler::Icon);
4277 mpIconGraphicsView->reOrderShapes();
4278 if (mComponentsLoaded) {
4279 mpIconGraphicsView->removeInheritedClassComponents();
4280 drawModelInheritedClassComponents(this, StringHandler::Icon);
4281 }
4282 if (mDiagramViewLoaded) {
4283 mpDiagramGraphicsView->removeInheritedClassShapes();
4284 drawModelInheritedClassShapes(this, StringHandler::Diagram);
4285 mpDiagramGraphicsView->reOrderShapes();
4286 mpDiagramGraphicsView->removeInheritedClassComponents();
4287 drawModelInheritedClassComponents(this, StringHandler::Diagram);
4288 }
4289 if (mConnectionsLoaded) {
4290 mpDiagramGraphicsView->removeInheritedClassConnections();
4291 drawModelInheritedClassConnections(this);
4292 }
4293}
4294
4295/*!
4296 * \brief ModelWidget::drawBaseCoOrdinateSystem
4297 * Draws the coordinate system from base class.
4298 * \param pModelWidget
4299 * \param pGraphicsView
4300 */
4301void ModelWidget::drawBaseCoOrdinateSystem(ModelWidget *pModelWidget, GraphicsView *pGraphicsView)
4302{
4303 foreach (LibraryTreeItem *pLibraryTreeItem, pModelWidget->getInheritedClassesList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pModelWidget
->getInheritedClassesList()); _container_.control &&
_container_.i != _container_.e; ++_container_.i, _container_
.control ^= 1) for (LibraryTreeItem *pLibraryTreeItem = *_container_
.i; _container_.control; _container_.control = 0)
{
4304 if (!pLibraryTreeItem->isNonExisting()) {
4305 GraphicsView *pInheritedGraphicsView;
4306 if (pGraphicsView->getViewType() == StringHandler::Icon) {
4307 pInheritedGraphicsView = pLibraryTreeItem->getModelWidget()->getIconGraphicsView();
4308 } else {
4309 pInheritedGraphicsView = pLibraryTreeItem->getModelWidget()->getDiagramGraphicsView();
4310 }
4311 if (pInheritedGraphicsView->mCoOrdinateSystem.isValid()) {
4312 qreal left = pInheritedGraphicsView->mCoOrdinateSystem.getExtent().at(0).x();
4313 qreal bottom = pInheritedGraphicsView->mCoOrdinateSystem.getExtent().at(0).y();
4314 qreal right = pInheritedGraphicsView->mCoOrdinateSystem.getExtent().at(1).x();
4315 qreal top = pInheritedGraphicsView->mCoOrdinateSystem.getExtent().at(1).y();
4316 pGraphicsView->setExtentRectangle(left, bottom, right, top);
4317 break;
4318 } else {
4319 drawBaseCoOrdinateSystem(pLibraryTreeItem->getModelWidget(), pGraphicsView);
4320 }
4321 }
4322 }
4323}
4324
4325/*!
4326 * \brief ModelWidget::drawModelIconDiagramShapes
4327 * Draws the model shapes.
4328 * \param shapes
4329 * \param pGraphicsView
4330 */
4331void ModelWidget::drawModelIconDiagramShapes(QStringList shapes, GraphicsView *pGraphicsView, bool select)
4332{
4333 foreach (QString shape, shapes)for (auto _container_ = QtPrivate::qMakeForeachContainer(shapes
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QString shape
= *_container_.i; _container_.control; _container_.control =
0)
{
4334 ShapeAnnotation *pShapeAnnotation = 0;
4335 if (shape.startsWith("Line")) {
4336 shape = shape.mid(QString("Line").length());
4337 shape = StringHandler::removeFirstLastParentheses(shape);
4338 pShapeAnnotation = new LineAnnotation(shape, pGraphicsView);
4339 } else if (shape.startsWith("Polygon")) {
4340 shape = shape.mid(QString("Polygon").length());
4341 shape = StringHandler::removeFirstLastParentheses(shape);
4342 pShapeAnnotation = new PolygonAnnotation(shape, pGraphicsView);
4343 } else if (shape.startsWith("Rectangle")) {
4344 shape = shape.mid(QString("Rectangle").length());
4345 shape = StringHandler::removeFirstLastParentheses(shape);
4346 pShapeAnnotation = new RectangleAnnotation(shape, pGraphicsView);
4347 } else if (shape.startsWith("Ellipse")) {
4348 shape = shape.mid(QString("Ellipse").length());
4349 shape = StringHandler::removeFirstLastParentheses(shape);
4350 pShapeAnnotation = new EllipseAnnotation(shape, pGraphicsView);
4351 } else if (shape.startsWith("Text")) {
4352 shape = shape.mid(QString("Text").length());
4353 shape = StringHandler::removeFirstLastParentheses(shape);
4354 pShapeAnnotation = new TextAnnotation(shape, pGraphicsView);
4355 } else if (shape.startsWith("Bitmap")) {
4356 /* create the bitmap shape */
4357 shape = shape.mid(QString("Bitmap").length());
4358 shape = StringHandler::removeFirstLastParentheses(shape);
4359 pShapeAnnotation = new BitmapAnnotation(mpLibraryTreeItem->mClassInformation.fileName, shape, pGraphicsView);
4360 }
4361 if (pShapeAnnotation) {
4362 pShapeAnnotation->initializeTransformation();
4363 pShapeAnnotation->drawCornerItems();
4364 pShapeAnnotation->setCornerItemsActiveOrPassive();
4365 mpUndoStack->push(new AddShapeCommand(pShapeAnnotation));
4366 if (select) {
4367 pShapeAnnotation->setSelected(true);
4368 }
4369 }
4370 }
4371}
4372
4373/*!
4374 * \brief ModelWidget::createNonExistingInheritedShape
4375 * Creates a red cross for non-existing inherited class shape.
4376 * \param pGraphicsView
4377 * \return
4378 */
4379ShapeAnnotation* ModelWidget::createNonExistingInheritedShape(GraphicsView *pGraphicsView)
4380{
4381 LineAnnotation *pLineAnnotation = new LineAnnotation(pGraphicsView);
4382 pLineAnnotation->initializeTransformation();
4383 pLineAnnotation->drawCornerItems();
4384 pLineAnnotation->setCornerItemsActiveOrPassive();
4385 return pLineAnnotation;
4386}
4387
4388/*!
4389 * \brief ModelWidget::createInheritedShape
4390 * Creates the inherited class shape.
4391 * \param pShapeAnnotation
4392 * \param pGraphicsView
4393 * \return
4394 */
4395ShapeAnnotation* ModelWidget::createInheritedShape(ShapeAnnotation *pShapeAnnotation, GraphicsView *pGraphicsView)
4396{
4397 if (dynamic_cast<LineAnnotation*>(pShapeAnnotation)) {
4398 LineAnnotation *pLineAnnotation = new LineAnnotation(pShapeAnnotation, pGraphicsView);
4399 pLineAnnotation->initializeTransformation();
4400 pLineAnnotation->drawCornerItems();
4401 pLineAnnotation->setCornerItemsActiveOrPassive();
4402 return pLineAnnotation;
4403 } else if (dynamic_cast<PolygonAnnotation*>(pShapeAnnotation)) {
4404 PolygonAnnotation *pPolygonAnnotation = new PolygonAnnotation(pShapeAnnotation, pGraphicsView);
4405 pPolygonAnnotation->initializeTransformation();
4406 pPolygonAnnotation->drawCornerItems();
4407 pPolygonAnnotation->setCornerItemsActiveOrPassive();
4408 return pPolygonAnnotation;
4409 } else if (dynamic_cast<RectangleAnnotation*>(pShapeAnnotation)) {
4410 RectangleAnnotation *pRectangleAnnotation = new RectangleAnnotation(pShapeAnnotation, pGraphicsView);
4411 pRectangleAnnotation->initializeTransformation();
4412 pRectangleAnnotation->drawCornerItems();
4413 pRectangleAnnotation->setCornerItemsActiveOrPassive();
4414 return pRectangleAnnotation;
4415 } else if (dynamic_cast<EllipseAnnotation*>(pShapeAnnotation)) {
4416 EllipseAnnotation *pEllipseAnnotation = new EllipseAnnotation(pShapeAnnotation, pGraphicsView);
4417 pEllipseAnnotation->initializeTransformation();
4418 pEllipseAnnotation->drawCornerItems();
4419 pEllipseAnnotation->setCornerItemsActiveOrPassive();
4420 return pEllipseAnnotation;
4421 } else if (dynamic_cast<TextAnnotation*>(pShapeAnnotation)) {
4422 TextAnnotation *pTextAnnotation = new TextAnnotation(pShapeAnnotation, pGraphicsView);
4423 pTextAnnotation->initializeTransformation();
4424 pTextAnnotation->drawCornerItems();
4425 pTextAnnotation->setCornerItemsActiveOrPassive();
4426 return pTextAnnotation;
4427 } else if (dynamic_cast<BitmapAnnotation*>(pShapeAnnotation)) {
4428 BitmapAnnotation *pBitmapAnnotation = new BitmapAnnotation(pShapeAnnotation, pGraphicsView);
4429 pBitmapAnnotation->initializeTransformation();
4430 pBitmapAnnotation->drawCornerItems();
4431 pBitmapAnnotation->setCornerItemsActiveOrPassive();
4432 return pBitmapAnnotation;
4433 }
4434 return 0;
4435}
4436
4437/*!
4438 * \brief ModelWidget::createInheritedComponent
4439 * Creates the inherited component.
4440 * \param pComponent
4441 * \param pGraphicsView
4442 * \return
4443 */
4444Component* ModelWidget::createInheritedComponent(Component *pComponent, GraphicsView *pGraphicsView)
4445{
4446 return new Component(pComponent, pGraphicsView);
4447}
4448
4449/*!
4450 * \brief ModelWidget::createInheritedConnection
4451 * Creates the inherited connection.
4452 * \param pConnectionLineAnnotation
4453 * \return
4454 */
4455LineAnnotation* ModelWidget::createInheritedConnection(LineAnnotation *pConnectionLineAnnotation)
4456{
4457 LineAnnotation *pInheritedConnectionLineAnnotation = new LineAnnotation(pConnectionLineAnnotation, mpDiagramGraphicsView);
4458 pInheritedConnectionLineAnnotation->setToolTip(QString("<b>connect</b>(%1, %2)<br /><br />%3 %4")
4459 .arg(pInheritedConnectionLineAnnotation->getStartComponentName())
4460 .arg(pInheritedConnectionLineAnnotation->getEndComponentName())
4461 .arg(tr("Connection declared in"))
4462 .arg(pConnectionLineAnnotation->getGraphicsView()->getModelWidget()->getLibraryTreeItem()->getNameStructure()));
4463 pInheritedConnectionLineAnnotation->drawCornerItems();
4464 pInheritedConnectionLineAnnotation->setCornerItemsActiveOrPassive();
4465 // Add the start component connection details.
4466 Component *pStartComponent = pInheritedConnectionLineAnnotation->getStartComponent();
4467 if (pStartComponent->getRootParentComponent()) {
4468 pStartComponent->getRootParentComponent()->addConnectionDetails(pInheritedConnectionLineAnnotation);
4469 } else {
4470 pStartComponent->addConnectionDetails(pInheritedConnectionLineAnnotation);
4471 }
4472 // Add the end component connection details.
4473 Component *pEndComponent = pInheritedConnectionLineAnnotation->getEndComponent();
4474 if (pEndComponent->getParentComponent()) {
4475 pEndComponent->getParentComponent()->addConnectionDetails(pInheritedConnectionLineAnnotation);
4476 } else {
4477 pEndComponent->addConnectionDetails(pInheritedConnectionLineAnnotation);
4478 }
4479 return pInheritedConnectionLineAnnotation;
4480}
4481
4482/*!
4483 * \brief ModelWidget::loadComponents
4484 * Loads the model components if they are not loaded before.
4485 */
4486void ModelWidget::loadComponents()
4487{
4488 if (!mComponentsLoaded) {
4489 drawModelInheritedClassComponents(this, StringHandler::Icon);
4490 if (mpLibraryTreeItem->getAccess() >= LibraryTreeItem::diagram) {
4491 getModelComponents();
4492 drawModelIconComponents();
4493 }
4494 mComponentsLoaded = true;
4495 }
4496}
4497
4498/*!
4499 * \brief ModelWidget::loadDiagramView
4500 * Loads the diagram view components if they are not loaded before.
4501 */
4502void ModelWidget::loadDiagramView()
4503{
4504 loadComponents();
4505 if (!mDiagramViewLoaded) {
4506 drawModelInheritedClassShapes(this, StringHandler::Diagram);
4507 getModelIconDiagramShapes(StringHandler::Diagram);
4508 drawModelInheritedClassComponents(this, StringHandler::Diagram);
4509 if (mpLibraryTreeItem->getAccess() >= LibraryTreeItem::diagram) {
4510 drawModelDiagramComponents();
4511 }
4512 mDiagramViewLoaded = true;
4513 /*! @note The following is not needed if we load the connectors alongwith the icon/diagram annotation.
4514 * We have disabled loading the connectors so user gets fast browsing of libraries.
4515 */
4516 mpLibraryTreeItem->handleIconUpdated();
4517 }
4518}
4519
4520/*!
4521 * \brief ModelWidget::loadConnections
4522 * Loads the model connections if they are not loaded before.
4523 */
4524void ModelWidget::loadConnections()
4525{
4526 if (!mConnectionsLoaded) {
4527 drawModelInheritedClassConnections(this);
4528 if (mpLibraryTreeItem->getAccess() >= LibraryTreeItem::diagram) {
4529 getModelConnections();
4530 getModelTransitions();
4531 getModelInitialStates();
4532 }
4533 mConnectionsLoaded = true;
4534 }
4535}
4536
4537/*!
4538 * \brief ModelWidget::getModelConnections
4539 * Gets the connections of the model and place them in the diagram GraphicsView.
4540 */
4541void ModelWidget::getModelConnections()
4542{
4543 // detect multiple declarations of a component instance
4544 detectMultipleDeclarations();
4545 // get the connections
4546 MainWindow *pMainWindow = MainWindow::instance();
4547 int connectionCount = pMainWindow->getOMCProxy()->getConnectionCount(mpLibraryTreeItem->getNameStructure());
4548 for (int i = 1 ; i <= connectionCount ; i++) {
4549 // get the connection from OMC
4550 QStringList connectionList = pMainWindow->getOMCProxy()->getNthConnection(mpLibraryTreeItem->getNameStructure(), i);
4551 QString connectionAnnotationString = pMainWindow->getOMCProxy()->getNthConnectionAnnotation(mpLibraryTreeItem->getNameStructure(), i);
4552 addConnection(connectionList, connectionAnnotationString, false, false);
4553 }
4554}
4555
4556void ModelWidget::addConnection(QStringList connectionList, QString connectionAnnotationString, bool addToOMC, bool select)
4557{
4558 MainWindow *pMainWindow = MainWindow::instance();
4559 LibraryTreeModel *pLibraryTreeModel = pMainWindow->getLibraryWidget()->getLibraryTreeModel();
4560 QString connectionString = QString("{%1}").arg(connectionList.join(","));
4561 // if the connectionString only contains two items then continue the loop,
4562 // because connection is not valid then
4563 if (connectionList.size() < 3) {
4564 return;
4565 }
4566 // get start and end components
4567 QStringList startComponentList = StringHandler::makeVariableParts(connectionList.at(0));
4568 QStringList endComponentList = StringHandler::makeVariableParts(connectionList.at(1));
4569 // get start component
4570 Component *pStartComponent = 0;
4571 if (startComponentList.size() > 0) {
4572 QString startComponentName = startComponentList.at(0);
4573 if (startComponentName.contains("[")) {
4574 startComponentName = startComponentName.mid(0, startComponentName.indexOf("["));
4575 }
4576 pStartComponent = mpDiagramGraphicsView->getComponentObject(startComponentName);
4577 }
4578 // get start connector
4579 Component *pStartConnectorComponent = 0;
4580 Component *pEndConnectorComponent = 0;
4581 if (pStartComponent) {
4582 // if a component type is connector then we only get one item in startComponentList
4583 // check the startcomponentlist
4584 if (startComponentList.size() < 2
4585 || (pStartComponent->getLibraryTreeItem()
4586 && pStartComponent->getLibraryTreeItem()->getRestriction() == StringHandler::ExpandableConnector)) {
4587 pStartConnectorComponent = pStartComponent;
4588 } else if (pStartComponent->getLibraryTreeItem()
4589 && !pLibraryTreeModel->findLibraryTreeItem(pStartComponent->getLibraryTreeItem()->getNameStructure())) {
4590 /* if class doesn't exist then connect with the red cross box */
4591 pStartConnectorComponent = pStartComponent;
4592 } else {
4593 // look for port from the parent component
4594 QString startComponentName = startComponentList.at(1);
4595 if (startComponentName.contains("[")) {
4596 startComponentName = startComponentName.mid(0, startComponentName.indexOf("["));
4597 }
4598 pStartConnectorComponent = getConnectorComponent(pStartComponent, startComponentName);
4599 }
4600 }
4601 // show error message if start component is not found.
4602 if (!pStartConnectorComponent) {
4603 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
4604 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_CONNECTION)
4605 .arg(connectionList.at(0)).arg(connectionString),
4606 Helper::scriptingKind, Helper::errorLevel));
4607 return;
4608 }
4609 // get end component
4610 Component *pEndComponent = 0;
4611 if (endComponentList.size() > 0) {
4612 QString endComponentName = endComponentList.at(0);
4613 if (endComponentName.contains("[")) {
4614 endComponentName = endComponentName.mid(0, endComponentName.indexOf("["));
4615 }
4616 pEndComponent = mpDiagramGraphicsView->getComponentObject(endComponentName);
4617 }
4618 // get the end connector
4619 if (pEndComponent) {
4620 // if a component type is connector then we only get one item in endComponentList
4621 // check the endcomponentlist
4622 if (endComponentList.size() < 2
4623 || (pEndComponent->getLibraryTreeItem()
4624 && pEndComponent->getLibraryTreeItem()->getRestriction() == StringHandler::ExpandableConnector)) {
4625 pEndConnectorComponent = pEndComponent;
4626 } else if (pEndComponent->getLibraryTreeItem()
4627 && !pLibraryTreeModel->findLibraryTreeItem(pEndComponent->getLibraryTreeItem()->getNameStructure())) {
4628 /* if class doesn't exist then connect with the red cross box */
4629 pEndConnectorComponent = pEndComponent;
4630 } else {
4631 QString endComponentName = endComponentList.at(1);
4632 if (endComponentName.contains("[")) {
4633 endComponentName = endComponentName.mid(0, endComponentName.indexOf("["));
4634 }
4635 pEndConnectorComponent = getConnectorComponent(pEndComponent, endComponentName);
4636 }
4637 }
4638 // show error message if end component is not found.
4639 if (!pEndConnectorComponent) {
4640 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
4641 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_CONNECTION)
4642 .arg(connectionList.at(1)).arg(connectionString),
4643 Helper::scriptingKind, Helper::errorLevel));
4644 return;
4645 }
4646 // connection annotation
4647 QStringList shapesList = StringHandler::getStrings(StringHandler::removeFirstLastCurlBrackets(connectionAnnotationString), '(', ')');
4648 // Now parse the shapes available in list
4649 QString lineShape = "";
4650 foreach (QString shape, shapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(shapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QString shape
= *_container_.i; _container_.control; _container_.control =
0)
{
4651 if (shape.startsWith("Line")) {
4652 lineShape = shape.mid(QString("Line").length());
4653 lineShape = StringHandler::removeFirstLastParentheses(lineShape);
4654 break; // break the loop once we have got the line annotation.
4655 }
4656 }
4657 LineAnnotation *pConnectionLineAnnotation;
4658 pConnectionLineAnnotation = new LineAnnotation(lineShape, pStartConnectorComponent, pEndConnectorComponent, mpDiagramGraphicsView);
4659 pConnectionLineAnnotation->setStartComponentName(connectionList.at(0));
4660 pConnectionLineAnnotation->setEndComponentName(connectionList.at(1));
4661 if (select) {
4662 pConnectionLineAnnotation->setSelected(true);
4663 }
4664 mpUndoStack->push(new AddConnectionCommand(pConnectionLineAnnotation, addToOMC));
4665}
4666
4667/*!
4668 * \brief ModelWidget::loadWidgetComponents
4669 * Creates the widgets for the ModelWidget.
4670 */
4671void ModelWidget::createModelWidgetComponents()
4672{
4673 if (!mCreateModelWidgetComponents) {
4674 // icon view tool button
4675 mpIconViewToolButton = new QToolButton;
4676 mpIconViewToolButton->setText(Helper::iconView);
4677 mpIconViewToolButton->setIcon(ResourceCache::getIcon(":/Resources/icons/model.svg"));
4678 mpIconViewToolButton->setToolTip(Helper::iconView);
4679 mpIconViewToolButton->setAutoRaise(true);
4680 mpIconViewToolButton->setCheckable(true);
4681 // diagram view tool button
4682 mpDiagramViewToolButton = new QToolButton;
4683 mpDiagramViewToolButton->setText(Helper::diagramView);
4684 mpDiagramViewToolButton->setIcon(ResourceCache::getIcon(":/Resources/icons/modeling.png"));
4685 mpDiagramViewToolButton->setToolTip(Helper::diagramView);
4686 mpDiagramViewToolButton->setAutoRaise(true);
4687 mpDiagramViewToolButton->setCheckable(true);
4688 // modelica text view tool button
4689 mpTextViewToolButton = new QToolButton;
4690 mpTextViewToolButton->setText(Helper::textView);
4691 mpTextViewToolButton->setIcon(ResourceCache::getIcon(":/Resources/icons/modeltext.svg"));
4692 mpTextViewToolButton->setToolTip(Helper::textView);
4693 mpTextViewToolButton->setAutoRaise(true);
4694 mpTextViewToolButton->setCheckable(true);
4695 // documentation view tool button
4696 mpDocumentationViewToolButton = new QToolButton;
4697 mpDocumentationViewToolButton->setText(Helper::documentationView);
4698 mpDocumentationViewToolButton->setIcon(ResourceCache::getIcon(":/Resources/icons/info-icon.svg"));
4699 mpDocumentationViewToolButton->setToolTip(Helper::documentationView);
4700 mpDocumentationViewToolButton->setAutoRaise(true);
4701 // view buttons box
4702 mpViewsButtonGroup = new QButtonGroup;
4703 mpViewsButtonGroup->setExclusive(true);
4704 mpViewsButtonGroup->addButton(mpDiagramViewToolButton);
4705 mpViewsButtonGroup->addButton(mpIconViewToolButton);
4706 mpViewsButtonGroup->addButton(mpTextViewToolButton);
4707 mpViewsButtonGroup->addButton(mpDocumentationViewToolButton);
4708 // frame to contain view buttons
4709 QFrame *pViewButtonsFrame = new QFrame;
4710 QHBoxLayout *pViewButtonsHorizontalLayout = new QHBoxLayout;
4711 pViewButtonsHorizontalLayout->setContentsMargins(0, 0, 0, 0);
4712 pViewButtonsHorizontalLayout->setSpacing(0);
4713 pViewButtonsFrame->setLayout(pViewButtonsHorizontalLayout);
4714 // set Project Status Bar lables
4715 mpReadOnlyLabel = mpLibraryTreeItem->isReadOnly() ? new Label(Helper::readOnly) : new Label(tr("Writable"));
4716 mpModelicaTypeLabel = new Label;
4717 mpViewTypeLabel = new Label;
4718 mpModelClassPathLabel = new Label(mpLibraryTreeItem->getNameStructure());
4719 mpModelFilePathLabel = new Label(mpLibraryTreeItem->getFileName());
4720 mpModelFilePathLabel->setElideMode(Qt::ElideMiddle);
4721 // documentation view tool button
4722 mpFileLockToolButton = new QToolButton;
4723 mpFileLockToolButton->setIcon(ResourceCache::getIcon(mpLibraryTreeItem->isReadOnly() ? ":/Resources/icons/lock.svg" : ":/Resources/icons/unlock.svg"));
4724 mpFileLockToolButton->setText(mpLibraryTreeItem->isReadOnly() ? tr("Make writable") : tr("File is writable"));
4725 mpFileLockToolButton->setToolTip(mpFileLockToolButton->text());
4726 mpFileLockToolButton->setEnabled(mpLibraryTreeItem->isReadOnly() && !mpLibraryTreeItem->isSystemLibrary());
4727 mpFileLockToolButton->setAutoRaise(true);
4728 connect(mpFileLockToolButton, SIGNAL(clicked())"2""clicked()", SLOT(makeFileWritAble())"1""makeFileWritAble()");
4729 // create project status bar
4730 mpModelStatusBar = new QStatusBar;
4731 mpModelStatusBar->setObjectName("ModelStatusBar");
4732 mpModelStatusBar->setSizeGripEnabled(false);
4733 mpModelStatusBar->addPermanentWidget(pViewButtonsFrame, 0);
4734 // create the main layout
4735 QVBoxLayout *pMainLayout = new QVBoxLayout;
4736 pMainLayout->setContentsMargins(0, 0, 0, 0);
4737 pMainLayout->setSpacing(4);
4738 pMainLayout->addWidget(mpModelStatusBar);
4739 setLayout(pMainLayout);
4740 MainWindow *pMainWindow = MainWindow::instance();
4741 // show hide widgets based on library type
4742 if (mpLibraryTreeItem->getLibraryType() == LibraryTreeItem::Modelica) {
4743 connect(mpIconViewToolButton, SIGNAL(toggled(bool))"2""toggled(bool)", SLOT(showIconView(bool))"1""showIconView(bool)");
4744 connect(mpDiagramViewToolButton, SIGNAL(toggled(bool))"2""toggled(bool)", SLOT(showDiagramView(bool))"1""showDiagramView(bool)");
4745 connect(mpTextViewToolButton, SIGNAL(toggled(bool))"2""toggled(bool)", SLOT(showTextView(bool))"1""showTextView(bool)");
4746 connect(mpDocumentationViewToolButton, SIGNAL(clicked())"2""clicked()", SLOT(showDocumentationView())"1""showDocumentationView()");
4747 pViewButtonsHorizontalLayout->addWidget(mpIconViewToolButton);
4748 pViewButtonsHorizontalLayout->addWidget(mpDiagramViewToolButton);
4749 pViewButtonsHorizontalLayout->addWidget(mpTextViewToolButton);
4750 pViewButtonsHorizontalLayout->addWidget(mpDocumentationViewToolButton);
4751 mpModelicaTypeLabel->setText(StringHandler::getModelicaClassType(mpLibraryTreeItem->getRestriction()));
4752 mpViewTypeLabel->setText(StringHandler::getViewType(StringHandler::Diagram));
4753 // modelica text editor
4754 mpEditor = new ModelicaEditor(this);
4755 ModelicaHighlighter *pModelicaTextHighlighter = new ModelicaHighlighter(OptionsDialog::instance()->getModelicaEditorPage(),
4756 mpEditor->getPlainTextEdit());
4757 ModelicaEditor *pModelicaEditor = dynamic_cast<ModelicaEditor*>(mpEditor);
4758 pModelicaEditor->setPlainText(mpLibraryTreeItem->getClassText(pMainWindow->getLibraryWidget()->getLibraryTreeModel()), false);
4759 mpEditor->hide(); // set it hidden so that Find/Replace action can get correct value.
4760 connect(OptionsDialog::instance(), SIGNAL(modelicaEditorSettingsChanged())"2""modelicaEditorSettingsChanged()", pModelicaTextHighlighter, SLOT(settingsChanged())"1""settingsChanged()");
4761 mpModelStatusBar->addPermanentWidget(mpReadOnlyLabel, 0);
4762 mpModelStatusBar->addPermanentWidget(mpModelicaTypeLabel, 0);
4763 mpModelStatusBar->addPermanentWidget(mpViewTypeLabel, 0);
4764 mpModelStatusBar->addPermanentWidget(mpModelClassPathLabel, 0);
4765 mpModelStatusBar->addPermanentWidget(mpModelFilePathLabel, 1);
4766 mpModelStatusBar->addPermanentWidget(mpFileLockToolButton, 0);
4767 // set layout
4768 if (MainWindow::instance()->isDebug()) {
4769 pMainLayout->addWidget(mpUndoView);
4770 }
4771 pMainLayout->addWidget(mpDiagramGraphicsView, 1);
4772 pMainLayout->addWidget(mpIconGraphicsView, 1);
4773 mpUndoStack->clear();
4774 } else if (mpLibraryTreeItem->getLibraryType() == LibraryTreeItem::Text) {
4775 pViewButtonsHorizontalLayout->addWidget(mpTextViewToolButton);
4776 QFileInfo fileInfo(mpLibraryTreeItem->getFileName());
4777 if (Utilities::isCFile(fileInfo.suffix())) {
4778 mpEditor = new CEditor(this);
4779 CHighlighter *pCHighlighter = new CHighlighter(OptionsDialog::instance()->getCEditorPage(), mpEditor->getPlainTextEdit());
4780 CEditor *pCEditor = dynamic_cast<CEditor*>(mpEditor);
4781 pCEditor->setPlainText(mpLibraryTreeItem->getClassText(pMainWindow->getLibraryWidget()->getLibraryTreeModel()));
4782 mpEditor->hide();
4783 connect(OptionsDialog::instance(), SIGNAL(cEditorSettingsChanged())"2""cEditorSettingsChanged()", pCHighlighter, SLOT(settingsChanged())"1""settingsChanged()");
4784 } else if (Utilities::isModelicaFile(fileInfo.suffix())) {
4785 mpEditor = new MetaModelicaEditor(this);
4786 MetaModelicaHighlighter *pMetaModelicaHighlighter;
4787 pMetaModelicaHighlighter = new MetaModelicaHighlighter(OptionsDialog::instance()->getMetaModelicaEditorPage(),
4788 mpEditor->getPlainTextEdit());
4789 MetaModelicaEditor *pMetaModelicaEditor = dynamic_cast<MetaModelicaEditor*>(mpEditor);
4790 pMetaModelicaEditor->setPlainText(mpLibraryTreeItem->getClassText(pMainWindow->getLibraryWidget()->getLibraryTreeModel()));
4791 mpEditor->hide();
4792 connect(OptionsDialog::instance(), SIGNAL(metaModelicaEditorSettingsChanged())"2""metaModelicaEditorSettingsChanged()", pMetaModelicaHighlighter, SLOT(settingsChanged())"1""settingsChanged()");
4793 } else {
4794 mpEditor = new TextEditor(this);
4795 TextEditor *pTextEditor = dynamic_cast<TextEditor*>(mpEditor);
4796 pTextEditor->setPlainText(mpLibraryTreeItem->getClassText(pMainWindow->getLibraryWidget()->getLibraryTreeModel()));
4797 mpEditor->hide();
4798 }
4799 mpModelStatusBar->addPermanentWidget(mpReadOnlyLabel, 0);
4800 mpModelStatusBar->addPermanentWidget(mpModelFilePathLabel, 1);
4801 mpModelStatusBar->addPermanentWidget(mpFileLockToolButton, 0);
4802 // set layout
4803 pMainLayout->addWidget(mpModelStatusBar);
4804 } else if (mpLibraryTreeItem->getLibraryType() == LibraryTreeItem::CompositeModel) {
4805 connect(mpDiagramViewToolButton, SIGNAL(toggled(bool))"2""toggled(bool)", SLOT(showDiagramView(bool))"1""showDiagramView(bool)");
4806 connect(mpTextViewToolButton, SIGNAL(toggled(bool))"2""toggled(bool)", SLOT(showTextView(bool))"1""showTextView(bool)");
4807 pViewButtonsHorizontalLayout->addWidget(mpDiagramViewToolButton);
4808 pViewButtonsHorizontalLayout->addWidget(mpTextViewToolButton);
4809 // diagram graphics framework
4810 mpDiagramGraphicsScene = new GraphicsScene(StringHandler::Diagram, this);
4811 mpDiagramGraphicsView = new GraphicsView(StringHandler::Diagram, this);
4812 mpDiagramGraphicsView->setScene(mpDiagramGraphicsScene);
4813 mpDiagramGraphicsView->hide();
4814 // Undo stack for model
4815 mpUndoStack = new UndoStack;
4816 connect(mpUndoStack, SIGNAL(canUndoChanged(bool))"2""canUndoChanged(bool)", SLOT(handleCanUndoChanged(bool))"1""handleCanUndoChanged(bool)");
4817 connect(mpUndoStack, SIGNAL(canRedoChanged(bool))"2""canRedoChanged(bool)", SLOT(handleCanRedoChanged(bool))"1""handleCanRedoChanged(bool)");
4818 if (MainWindow::instance()->isDebug()) {
4819 mpUndoView = new QUndoView(mpUndoStack);
4820 }
4821 // create an xml editor for CompositeModel
4822 mpEditor = new CompositeModelEditor(this);
4823 CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpEditor);
4824 if (mpLibraryTreeItem->getFileName().isEmpty()) {
4825 QString defaultCompositeModelText = QString("<?xml version='1.0' encoding='UTF-8'?>\n"
4826 "<!-- The root node is the composite-model -->\n"
4827 "<Model Name=\"%1\">\n"
4828 " <!-- List of connected sub-models -->\n"
4829 " <SubModels/>\n"
4830 " <!-- List of TLM connections -->\n"
4831 " <Connections/>\n"
4832 " <!-- Parameters for the simulation -->\n"
4833 " <SimulationParams StartTime=\"0\" StopTime=\"1\" />\n"
4834 "</Model>").arg(mpLibraryTreeItem->getName());
4835 pCompositeModelEditor->setPlainText(defaultCompositeModelText, false);
4836 mpLibraryTreeItem->setClassText(defaultCompositeModelText);
4837 } else {
4838 pCompositeModelEditor->setPlainText(mpLibraryTreeItem->getClassText(pMainWindow->getLibraryWidget()->getLibraryTreeModel()), false);
4839 }
4840 CompositeModelHighlighter *pCompositeModelHighlighter = new CompositeModelHighlighter(OptionsDialog::instance()->getCompositeModelEditorPage(),
4841 mpEditor->getPlainTextEdit());
4842 mpEditor->hide(); // set it hidden so that Find/Replace action can get correct value.
4843 connect(OptionsDialog::instance(), SIGNAL(compositeModelEditorSettingsChanged())"2""compositeModelEditorSettingsChanged()", pCompositeModelHighlighter, SLOT(settingsChanged())"1""settingsChanged()");
4844 // only get the TLM submodels and connectors if the we are not creating a new class.
4845 if (!mpLibraryTreeItem->getFileName().isEmpty()) {
4846 getCompositeModelSubModels();
4847 getCompositeModelConnections();
4848 }
4849 mpDiagramGraphicsScene->clearSelection();
4850 mpModelStatusBar->addPermanentWidget(mpReadOnlyLabel, 0);
4851 mpModelStatusBar->addPermanentWidget(mpViewTypeLabel, 0);
4852 mpModelStatusBar->addPermanentWidget(mpModelFilePathLabel, 1);
4853 mpModelStatusBar->addPermanentWidget(mpFileLockToolButton, 0);
4854 // set layout
4855 pMainLayout->addWidget(mpModelStatusBar);
4856 if (MainWindow::instance()->isDebug()) {
4857 pMainLayout->addWidget(mpUndoView);
4858 }
4859 pMainLayout->addWidget(mpDiagramGraphicsView, 1);
4860 mpUndoStack->clear();
4861 } else if (mpLibraryTreeItem->getLibraryType() == LibraryTreeItem::OMS) {
4862 if (mpLibraryTreeItem->isSystemElement() || mpLibraryTreeItem->isComponentElement()) {
4863 connect(mpIconViewToolButton, SIGNAL(toggled(bool))"2""toggled(bool)", SLOT(showIconView(bool))"1""showIconView(bool)");
4864 pViewButtonsHorizontalLayout->addWidget(mpIconViewToolButton);
4865 }
4866 connect(mpDiagramViewToolButton, SIGNAL(toggled(bool))"2""toggled(bool)", SLOT(showDiagramView(bool))"1""showDiagramView(bool)");
4867 pViewButtonsHorizontalLayout->addWidget(mpDiagramViewToolButton);
4868 // Only the top level OMSimualtor models or systems or components will have the editor.
4869 if (mpLibraryTreeItem->isTopLevel() || mpLibraryTreeItem->isSystemElement() || mpLibraryTreeItem->isComponentElement()) {
4870 connect(mpTextViewToolButton, SIGNAL(toggled(bool))"2""toggled(bool)", SLOT(showTextView(bool))"1""showTextView(bool)");
4871 pViewButtonsHorizontalLayout->addWidget(mpTextViewToolButton);
4872 // create an editor
4873 mpEditor = new OMSimulatorEditor(this);
4874 mpEditor->getPlainTextEdit()->setReadOnly(true);
4875 OMSimulatorEditor *pOMSimulatorEditor = dynamic_cast<OMSimulatorEditor*>(mpEditor);
4876 pOMSimulatorEditor->setPlainText(mpLibraryTreeItem->getClassText(pMainWindow->getLibraryWidget()->getLibraryTreeModel()), false);
4877 OMSimulatorHighlighter *pOMSimulatorHighlighter = new OMSimulatorHighlighter(OptionsDialog::instance()->getOMSimulatorEditorPage(),
4878 mpEditor->getPlainTextEdit());
4879 mpEditor->hide(); // set it hidden so that Find/Replace action can get correct value.
4880 connect(OptionsDialog::instance(), SIGNAL(omsimulatorEditorSettingsChanged())"2""omsimulatorEditorSettingsChanged()", pOMSimulatorHighlighter, SLOT(settingsChanged())"1""settingsChanged()");
4881 }
4882 mpUndoStack->setEnabled(false);
4883 drawOMSModelDiagramElements();
4884 drawOMSModelConnections();
4885 mpUndoStack->setEnabled(true);
4886 mpDiagramGraphicsScene->clearSelection();
4887 mpModelStatusBar->addPermanentWidget(mpReadOnlyLabel, 0);
4888 mpModelStatusBar->addPermanentWidget(mpViewTypeLabel, 0);
4889 mpModelStatusBar->addPermanentWidget(mpModelFilePathLabel, 1);
4890 mpModelStatusBar->addPermanentWidget(mpFileLockToolButton, 0);
4891 // set layout
4892 pMainLayout->addWidget(mpModelStatusBar);
4893 if (MainWindow::instance()->isDebug()) {
4894 pMainLayout->addWidget(mpUndoView);
4895 }
4896 pMainLayout->addWidget(mpDiagramGraphicsView, 1);
4897 if (mpLibraryTreeItem->isSystemElement() || mpLibraryTreeItem->isComponentElement()) {
4898 pMainLayout->addWidget(mpIconGraphicsView, 1);
4899 }
4900 }
4901 if (mpEditor) {
4902 connect(mpEditor->getPlainTextEdit()->document(), SIGNAL(undoAvailable(bool))"2""undoAvailable(bool)", SLOT(handleCanUndoChanged(bool))"1""handleCanUndoChanged(bool)");
4903 connect(mpEditor->getPlainTextEdit()->document(), SIGNAL(redoAvailable(bool))"2""redoAvailable(bool)", SLOT(handleCanRedoChanged(bool))"1""handleCanRedoChanged(bool)");
4904 pMainLayout->addWidget(mpEditor, 1);
4905 }
4906 mCreateModelWidgetComponents = true;
4907 }
4908}
4909
4910/*!
4911 * \brief ModelWidget::drawOMSModelElement
4912 * Draws the OMS model element i.e, system, FMU or table.
4913 */
4914ShapeAnnotation* ModelWidget::drawOMSModelElement()
4915{
4916 if (mpLibraryTreeItem->getOMSElement()->geometry && mpLibraryTreeItem->getOMSElement()->geometry->iconSource) {
4917 // Draw bitmap with icon source
4918 QUrl url(mpLibraryTreeItem->getOMSElement()->geometry->iconSource);
4919 QFileInfo fileInfo(url.toLocalFile());
4920 BitmapAnnotation *pBitmapAnnotation = new BitmapAnnotation(fileInfo.absoluteFilePath(), mpIconGraphicsView);
4921 pBitmapAnnotation->initializeTransformation();
4922 pBitmapAnnotation->drawCornerItems();
4923 pBitmapAnnotation->setCornerItemsActiveOrPassive();
4924 mpIconGraphicsView->addShapeToList(pBitmapAnnotation);
4925 mpIconGraphicsView->addItem(pBitmapAnnotation);
4926 return pBitmapAnnotation;
4927 } else {
4928 // Rectangle shape as base
4929 RectangleAnnotation *pRectangleAnnotation = new RectangleAnnotation(mpIconGraphicsView);
4930 pRectangleAnnotation->initializeTransformation();
4931 if (mpLibraryTreeItem->isSystemElement()) {
4932 pRectangleAnnotation->setLineColor(QColor(128, 128, 0));
4933 pRectangleAnnotation->setFillColor(Qt::white);
4934 } else if (mpLibraryTreeItem->isFMUComponent()) {
4935 pRectangleAnnotation->setFillColor(Qt::white);
4936 } else if (mpLibraryTreeItem->isTableComponent()) {
4937 pRectangleAnnotation->setLinePattern(StringHandler::LineNone);
4938 if (mpLibraryTreeItem->getSubModelPath().endsWith(".csv")) {
4939 pRectangleAnnotation->setFillColor(QColor(0, 148, 21));
4940 } else {
4941 pRectangleAnnotation->setFillColor(QColor(3, 75, 220));
4942 }
4943 }
4944 pRectangleAnnotation->drawCornerItems();
4945 pRectangleAnnotation->setCornerItemsActiveOrPassive();
4946 mpIconGraphicsView->addShapeToList(pRectangleAnnotation);
4947 mpIconGraphicsView->addItem(pRectangleAnnotation);
4948 // Text for name
4949 TextAnnotation *pTextAnnotation = new TextAnnotation(mpIconGraphicsView);
4950 pTextAnnotation->initializeTransformation();
4951 if (mpLibraryTreeItem->isSystemElement() || mpLibraryTreeItem->isFMUComponent()) {
4952 QList<QPointF> extents;
4953 extents << QPointF(-100, 80) << QPointF(100, 40);
4954 pTextAnnotation->setExtents(extents);
4955 if (mpLibraryTreeItem->isSystemElement()) {
4956 pTextAnnotation->setLineColor(QColor(128, 128, 0));
4957 }
4958 } else if (mpLibraryTreeItem->isTableComponent()) {
4959 pTextAnnotation->setLineColor(Qt::white);
4960 }
4961 pTextAnnotation->drawCornerItems();
4962 pTextAnnotation->setCornerItemsActiveOrPassive();
4963 mpIconGraphicsView->addShapeToList(pTextAnnotation);
4964 mpIconGraphicsView->addItem(pTextAnnotation);
4965 // Text for further information
4966 if (mpLibraryTreeItem->isSystemElement() || mpLibraryTreeItem->isFMUComponent()) {
4967 TextAnnotation *pInfoTextAnnotation = new TextAnnotation(mpIconGraphicsView);
4968 pInfoTextAnnotation->initializeTransformation();
4969 QList<QPointF> extents;
4970 extents << QPointF(-100, -40) << QPointF(100, -80);
4971 pInfoTextAnnotation->setExtents(extents);
4972 if (mpLibraryTreeItem->isSystemElement()) {
4973 pInfoTextAnnotation->setLineColor(QColor(128, 128, 0));
4974 pInfoTextAnnotation->setTextString(OMSProxy::getSystemTypeShortString(mpLibraryTreeItem->getSystemType()));
4975 } else {
4976 pInfoTextAnnotation->setTextString(QString("%1 %2").arg(OMSProxy::getFMUKindString(mpLibraryTreeItem->getFMUInfo()->fmiKind))
4977 .arg(QString(mpLibraryTreeItem->getFMUInfo()->fmiVersion)));
4978 }
4979 pInfoTextAnnotation->drawCornerItems();
4980 pInfoTextAnnotation->setCornerItemsActiveOrPassive();
4981 mpIconGraphicsView->addShapeToList(pInfoTextAnnotation);
4982 mpIconGraphicsView->addItem(pInfoTextAnnotation);
4983 }
4984 return pRectangleAnnotation;
4985 }
4986}
4987
4988/*!
4989 * \brief ModelWidget::getConnectorComponent
4990 * Finds the Port Component within the Component.
4991 * \param pConnectorComponent
4992 * \param connectorName
4993 * \return
4994 */
4995Component* ModelWidget::getConnectorComponent(Component *pConnectorComponent, QString connectorName)
4996{
4997 Component *pConnectorComponentFound = 0;
4998 foreach (Component *pComponent, pConnectorComponent->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pConnectorComponent
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pComponent = *_container_.i; _container_.control
; _container_.control = 0)
{
4999 if (pComponent->getName().compare(connectorName) == 0) {
5000 pConnectorComponentFound = pComponent;
5001 return pConnectorComponentFound;
5002 }
5003 foreach (Component *pInheritedComponent, pComponent->getInheritedComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pComponent
->getInheritedComponentsList()); _container_.control &&
_container_.i != _container_.e; ++_container_.i, _container_
.control ^= 1) for (Component *pInheritedComponent = *_container_
.i; _container_.control; _container_.control = 0)
{
5004 pConnectorComponentFound = getConnectorComponent(pInheritedComponent, connectorName);
5005 if (pConnectorComponentFound) {
5006 return pConnectorComponentFound;
5007 }
5008 }
5009 }
5010 /* if port is not found in components list then look into the inherited components list. */
5011 foreach (Component *pInheritedComponent, pConnectorComponent->getInheritedComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pConnectorComponent
->getInheritedComponentsList()); _container_.control &&
_container_.i != _container_.e; ++_container_.i, _container_
.control ^= 1) for (Component *pInheritedComponent = *_container_
.i; _container_.control; _container_.control = 0)
{
5012 pConnectorComponentFound = getConnectorComponent(pInheritedComponent, connectorName);
5013 if (pConnectorComponentFound) {
5014 return pConnectorComponentFound;
5015 }
5016 }
5017 return pConnectorComponentFound;
5018}
5019
5020void ModelWidget::clearGraphicsViews()
5021{
5022 /* remove everything from the icon view */
5023 if (mpIconGraphicsView) {
5024 mpIconGraphicsView->clearGraphicsView();
5025 }
5026 /* remove everything from the diagram view */
5027 if (mpDiagramGraphicsView) {
5028 mpDiagramGraphicsView->clearGraphicsView();
5029 }
5030}
5031
5032/*!
5033 * \brief ModelWidget::reDrawModelWidget
5034 * Redraws the ModelWidget.
5035 */
5036void ModelWidget::reDrawModelWidget()
5037{
5038 QApplication::setOverrideCursor(Qt::WaitCursor);
5039 clearGraphicsViews();
5040 /* get model components, connection and shapes. */
5041 if (getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel) {
5042 // read new CompositeModel name
5043 QString compositeModelName = getCompositeModelName();
5044 mpLibraryTreeItem->setName(compositeModelName);
5045 MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel()->updateLibraryTreeItem(mpLibraryTreeItem);
5046 setWindowTitle(compositeModelName);
5047 // get the submodels and connections
5048 getCompositeModelSubModels();
5049 getCompositeModelConnections();
5050 // clear the undo stack
5051 mpUndoStack->clear();
5052// if (mpEditor) {
5053// mpEditor->getPlainTextEdit()->document()->clearUndoRedoStacks();
5054// }
5055 } else if (getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
5056 MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel()->updateLibraryTreeItem(mpLibraryTreeItem);
5057 // get the submodels and connections
5058 drawOMSModelIconElements();
5059 drawOMSModelDiagramElements();
5060 drawOMSModelConnections();
5061 // clear the undo stack
5062 mpUndoStack->clear();
5063// if (mpEditor) {
5064// mpEditor->getPlainTextEdit()->document()->clearUndoRedoStacks();
5065// }
5066 } else {
5067 // Draw icon view
5068 mExtendsModifiersLoaded = false;
5069 mDerivedClassModifiersLoaded = false;
5070 // remove saved inherited classes
5071 clearInheritedClasses();
5072 // get inherited classes
5073 getModelInheritedClasses();
5074 // Draw Icon shapes and inherited shapes
5075 drawModelInheritedClassShapes(this, StringHandler::Icon);
5076 getModelIconDiagramShapes(StringHandler::Icon);
5077 // clear the components and their annotations
5078 mComponentsList.clear();
5079 mComponentsAnnotationsList.clear();
5080 mComponentsLoaded = false;
5081 // get the model components
5082 loadComponents();
5083 // invalidate the simulation options
5084 mpLibraryTreeItem->mSimulationOptions.setIsValid(false);
5085 // update the icon
5086 mpLibraryTreeItem->handleIconUpdated();
5087 // Draw diagram view
5088 if (mDiagramViewLoaded) {
5089 // reset flags
5090 mDiagramViewLoaded = false;
5091 loadDiagramView();
5092 mConnectionsLoaded = false;
5093 loadConnections();
5094 }
5095 // if documentation view is visible then update it
5096 if (MainWindow::instance()->getDocumentationDockWidget()->isVisible()) {
5097 MainWindow::instance()->getDocumentationWidget()->showDocumentation(getLibraryTreeItem());
5098 }
5099 // clear the undo stack
5100 mpUndoStack->clear();
5101// if (mpEditor) {
5102// mpEditor->getPlainTextEdit()->document()->clearUndoRedoStacks();
5103// }
5104 updateViewButtonsBasedOnAccess();
5105 // announce the change.
5106 mpLibraryTreeItem->emitLoaded();
5107 }
5108 QApplication::restoreOverrideCursor();
5109}
5110
5111/*!
5112 * \brief ModelWidget::validateText
5113 * Validates the text of the editor.
5114 * \param pLibraryTreeItem
5115 * \return Returns true if validation is successful otherwise return false.
5116 */
5117bool ModelWidget::validateText(LibraryTreeItem **pLibraryTreeItem)
5118{
5119 if (ModelicaEditor *pModelicaEditor = dynamic_cast<ModelicaEditor*>(mpEditor)) {
5120 return pModelicaEditor->validateText(pLibraryTreeItem);
5121 } else if (CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpEditor)) {
5122 return pCompositeModelEditor->validateText();
5123 } else if (OMSimulatorEditor *pOMSimulatorEditor = dynamic_cast<OMSimulatorEditor*>(mpEditor)) {
5124 return pOMSimulatorEditor->validateText();
5125 } else {
5126 return true;
5127 }
5128}
5129
5130/*!
5131 * \brief ModelWidget::modelicaEditorTextChanged
5132 * Called when Modelica text has been changed by user manually.\n
5133 * Updates the LibraryTreeItem and ModelWidget with new changes.
5134 * \param pLibraryTreeItem
5135 * \return
5136 * \sa ModelicaEditor::getClassNames()
5137 */
5138bool ModelWidget::modelicaEditorTextChanged(LibraryTreeItem **pLibraryTreeItem)
5139{
5140 QString errorString;
5141 ModelicaEditor *pModelicaEditor = dynamic_cast<ModelicaEditor*>(mpEditor);
5142 QStringList classNames = pModelicaEditor->getClassNames(&errorString);
5143 LibraryTreeModel *pLibraryTreeModel = MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel();
5144 OMCProxy *pOMCProxy = MainWindow::instance()->getOMCProxy();
5145 QString modelicaText = pModelicaEditor->getPlainText();
5146 QString stringToLoad;
5147 LibraryTreeItem *pParentLibraryTreeItem = pLibraryTreeModel->getContainingFileParentLibraryTreeItem(mpLibraryTreeItem);
5148 if (pParentLibraryTreeItem != mpLibraryTreeItem) {
5149 stringToLoad = mpLibraryTreeItem->getClassTextBefore() + StringHandler::trimmedEnd(modelicaText) + "\n" + mpLibraryTreeItem->getClassTextAfter();
5150 } else {
5151 stringToLoad = modelicaText;
5152 }
5153 if (classNames.size() == 0) {
5154 /* if the error is occured in P.M and package is saved in one file.
5155 * then update the package contents with new invalid code because we open P when user clicks on the error message.
5156 */
5157 if (mpLibraryTreeItem->isInPackageOneFile()) {
5158 if (!pParentLibraryTreeItem->getModelWidget()) {
5159 pLibraryTreeModel->showModelWidget(pParentLibraryTreeItem, false);
5160 }
5161 pParentLibraryTreeItem->getModelWidget()->createModelWidgetComponents();
5162 pParentLibraryTreeItem->setClassText(stringToLoad);
5163 }
5164 if (!errorString.isEmpty()) {
5165 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica, errorString, Helper::syntaxKind,
5166 Helper::errorLevel));
5167 }
5168 return false;
5169 }
5170 /* if no errors are found with the Modelica Text then load it in OMC */
5171 QString className = classNames.at(0);
5172 if (pParentLibraryTreeItem != mpLibraryTreeItem) {
5173 // only use OMCProxy::loadString merge when LibraryTreeItem::SaveFolderStructure i.e., package.mo
5174 if (!pOMCProxy->loadString(stringToLoad, pParentLibraryTreeItem->getFileName(), Helper::utf8, pParentLibraryTreeItem->getSaveContentsType() == LibraryTreeItem::SaveFolderStructure)) {
5175 return false;
5176 }
5177 } else {
5178 // only use OMCProxy::loadString merge when LibraryTreeItem::SaveFolderStructure i.e., package.mo
5179 if (!pOMCProxy->loadString(stringToLoad, mpLibraryTreeItem->getFileName(), Helper::utf8, mpLibraryTreeItem->getSaveContentsType() == LibraryTreeItem::SaveFolderStructure)) {
5180 return false;
5181 }
5182 }
5183 /* if user has changed the class contents then refresh it. */
5184 if (className.compare(mpLibraryTreeItem->getNameStructure()) == 0) {
5185 mpLibraryTreeItem->setClassInformation(pOMCProxy->getClassInformation(mpLibraryTreeItem->getNameStructure()));
5186 reDrawModelWidget();
5187 mpLibraryTreeItem->setClassText(modelicaText);
5188 if (mpLibraryTreeItem->isInPackageOneFile()) {
5189 pParentLibraryTreeItem->setClassText(stringToLoad);
5190 updateModelText();
5191 }
5192 // update child classes
5193 updateChildClasses(mpLibraryTreeItem);
5194 } else {
5195 /* if user has changed the class name then delete this class.
5196 * Update the LibraryTreeItem with new class name and then refresh it.
5197 */
5198 int row = mpLibraryTreeItem->row();
5199 /* if a class inside a package one file is renamed then it is already deleted by calling loadString using the whole package contents
5200 * so we tell unloadLibraryTreeItem to don't try deleteClass since it will only produce error
5201 */
5202 pLibraryTreeModel->unloadLibraryTreeItem(mpLibraryTreeItem, !mpLibraryTreeItem->isInPackageOneFile());
5203 mpLibraryTreeItem->setModelWidget(0);
5204 QString name = StringHandler::getLastWordAfterDot(className);
5205 LibraryTreeItem *pNewLibraryTreeItem = pLibraryTreeModel->createLibraryTreeItem(name, mpLibraryTreeItem->parent(), false, false, true, row);
5206 setWindowTitle(pNewLibraryTreeItem->getName() + (pNewLibraryTreeItem->isSaved() ? "" : "*"));
5207 setModelClassPathLabel(pNewLibraryTreeItem->getNameStructure());
5208 pNewLibraryTreeItem->setSaveContentsType(mpLibraryTreeItem->getSaveContentsType());
5209 pLibraryTreeModel->checkIfAnyNonExistingClassLoaded();
5210 // make the new created LibraryTreeItem selected
5211 QModelIndex modelIndex = pLibraryTreeModel->libraryTreeItemIndex(pNewLibraryTreeItem);
5212 LibraryTreeProxyModel *pLibraryTreeProxyModel = MainWindow::instance()->getLibraryWidget()->getLibraryTreeProxyModel();
5213 QModelIndex proxyIndex = pLibraryTreeProxyModel->mapFromSource(modelIndex);
5214 LibraryTreeView *pLibraryTreeView = MainWindow::instance()->getLibraryWidget()->getLibraryTreeView();
5215 pLibraryTreeView->selectionModel()->clearSelection();
5216 pLibraryTreeView->selectionModel()->select(proxyIndex, QItemSelectionModel::Select);
5217 // update class text
5218 pNewLibraryTreeItem->setModelWidget(this);
5219 pNewLibraryTreeItem->setClassText(modelicaText);
5220 setLibraryTreeItem(pNewLibraryTreeItem);
5221 setModelFilePathLabel(pNewLibraryTreeItem->getFileName());
5222 reDrawModelWidget();
5223 if (pNewLibraryTreeItem->isInPackageOneFile()) {
5224 pNewLibraryTreeItem->setClassText(stringToLoad);
5225 updateModelText();
5226 }
5227 *pLibraryTreeItem = pNewLibraryTreeItem;
5228 }
5229 return true;
5230}
5231
5232void ModelWidget::updateChildClasses(LibraryTreeItem *pLibraryTreeItem)
5233{
5234 MainWindow *pMainWindow = MainWindow::instance();
5235 LibraryTreeModel *pLibraryTreeModel = pMainWindow->getLibraryWidget()->getLibraryTreeModel();
5236 QStringList classNames = pMainWindow->getOMCProxy()->getClassNames(pLibraryTreeItem->getNameStructure());
5237 // first remove the classes that are removed by the user
5238 int i = 0;
5239 while(i != pLibraryTreeItem->childrenSize()) {
5240 LibraryTreeItem *pChildLibraryTreeItem = pLibraryTreeItem->child(i);
5241 if (!classNames.contains(pChildLibraryTreeItem->getName())) {
5242 pLibraryTreeModel->removeLibraryTreeItem(pChildLibraryTreeItem, LibraryTreeItem::Modelica);
5243 i = 0; //Restart iteration if list has changed
5244 } else {
5245 i++;
5246 }
5247 }
5248 // update and create any new classes
5249 int index = 0;
5250 foreach (QString className, classNames)for (auto _container_ = QtPrivate::qMakeForeachContainer(classNames
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QString className
= *_container_.i; _container_.control; _container_.control =
0)
{
5251 QString classNameStructure = QString("%1.%2").arg(pLibraryTreeItem->getNameStructure()).arg(className);
5252 LibraryTreeItem *pChildLibraryTreeItem = pLibraryTreeModel->findLibraryTreeItem(classNameStructure);
5253 // if the class already exists then we update it if needed.
5254 if (pChildLibraryTreeItem) {
5255 if (pChildLibraryTreeItem->isInPackageOneFile()) {
5256 // update the class information
5257 pChildLibraryTreeItem->setClassInformation(pMainWindow->getOMCProxy()->getClassInformation(pChildLibraryTreeItem->getNameStructure()));
5258 if (pLibraryTreeItem->isExpanded()) {
5259 if (pChildLibraryTreeItem->getModelWidget()) {
5260 pChildLibraryTreeItem->getModelWidget()->reDrawModelWidget();
5261 pLibraryTreeModel->readLibraryTreeItemClassText(pChildLibraryTreeItem);
5262 }
5263 updateChildClasses(pChildLibraryTreeItem);
5264 }
5265 }
5266 } else if (!pChildLibraryTreeItem) { // if the class doesn't exists then create one.
5267 pLibraryTreeModel->createLibraryTreeItem(className, pLibraryTreeItem, false, false, true, index);
5268 pLibraryTreeModel->checkIfAnyNonExistingClassLoaded();
5269 }
5270 index++;
5271 }
5272}
5273
5274/*!
5275 * \brief ModelWidget::omsimulatorEditorTextChanged
5276 * Called when OMSimulatorEditor text has been changed by user manually.\n
5277 * Updates the LibraryTreeItem and ModelWidget with new changes.
5278 * \return
5279 */
5280bool ModelWidget::omsimulatorEditorTextChanged()
5281{
5282 OMSimulatorEditor *pOMSimulatorEditor = dynamic_cast<OMSimulatorEditor*>(mpEditor);
5283 QFileInfo fileInfo(mpLibraryTreeItem->getFileName());
5284 if (fileInfo.exists()) {
5285 OMSProxy::instance()->setWorkingDirectory(fileInfo.absoluteDir().absolutePath());
5286 }
5287 QString modelName;
5288 bool success = false;
5289 if (OMSProxy::instance()->parseString(pOMSimulatorEditor->getPlainTextEdit()->toPlainText(), &modelName)) {
5290 if (mpLibraryTreeItem->getNameStructure().compare(modelName) != 0
5291 && MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel()->findLibraryTreeItemOneLevel(modelName)) {
5292 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
5293 GUIMessages::getMessage(GUIMessages::MODEL_ALREADY_EXISTS)
5294 .arg("Composite model").arg(modelName).arg("scope"),
5295 Helper::scriptingKind, Helper::errorLevel));
5296 return false;
5297 }
5298 success = OMSProxy::instance()->loadString(pOMSimulatorEditor->getPlainTextEdit()->toPlainText(), &modelName);
5299 }
5300 if (fileInfo.exists()) {
5301 OMSProxy::instance()->setWorkingDirectory(OptionsDialog::instance()->getOMSimulatorPage()->getWorkingDirectory());
5302 }
5303 if (success) {
5304 // model name has changed
5305 if (mpLibraryTreeItem->getNameStructure().compare(modelName) != 0) {
5306 // unload the old model from OMSimulator
5307 OMSProxy::instance()->omsDelete(mpLibraryTreeItem->getNameStructure());
5308 // Update to the new name
5309 mpLibraryTreeItem->setName(modelName);
5310 mpLibraryTreeItem->setNameStructure(modelName);
5311 setWindowTitle(mpLibraryTreeItem->getName() + (mpLibraryTreeItem->isSaved() ? "" : "*"));
5312 setModelClassPathLabel(mpLibraryTreeItem->getNameStructure());
5313 }
5314 // Update the OMS element
5315 oms_element_t *pOMSElement = 0;
5316 OMSProxy::instance()->getElement(mpLibraryTreeItem->getNameStructure(), &pOMSElement);
5317 mpLibraryTreeItem->setOMSElement(pOMSElement);
5318 // remove the children
5319 int i = 0;
5320 while (i < mpLibraryTreeItem->childrenSize()) {
5321 MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel()->removeLibraryTreeItem(mpLibraryTreeItem->child(i), LibraryTreeItem::OMS);
5322 i = 0; //Restart iteration
5323 }
5324 // create the children
5325 QModelIndex modelIndex = MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel()->libraryTreeItemIndex(mpLibraryTreeItem);
5326 QModelIndex proxyIndex = MainWindow::instance()->getLibraryWidget()->getLibraryTreeProxyModel()->mapFromSource(modelIndex);
5327 MainWindow::instance()->getLibraryWidget()->getLibraryTreeView()->collapse(proxyIndex);
5328 mpLibraryTreeItem->setExpanded(false);
5329 MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel()->createLibraryTreeItems(mpLibraryTreeItem);
5330 reDrawModelWidget();
5331 mpLibraryTreeItem->setClassText(pOMSimulatorEditor->getPlainTextEdit()->toPlainText());
5332 return true;
5333 } else {
5334 return false;
5335 }
5336}
5337
5338/*!
5339 * \brief ModelWidget::clearSelection
5340 * Clears the selection Icon and Diagram layers.
5341 */
5342void ModelWidget::clearSelection()
5343{
5344 if (mpIconGraphicsView) {
5345 mpIconGraphicsView->clearSelection();
5346 }
5347 if (mpDiagramGraphicsView) {
5348 mpDiagramGraphicsView->clearSelection();
5349 }
5350}
5351
5352/*!
5353 * \brief ModelWidget::updateClassAnnotationIfNeeded
5354 * Updates the class annotation for both icon and diagram views if needed.
5355 */
5356void ModelWidget::updateClassAnnotationIfNeeded()
5357{
5358 if (mpLibraryTreeItem->getLibraryType() == LibraryTreeItem::Modelica) {
5359 if (mpIconGraphicsView && mpIconGraphicsView->isAddClassAnnotationNeeded()) {
5360 mpIconGraphicsView->addClassAnnotation();
5361 mpIconGraphicsView->setAddClassAnnotationNeeded(false);
5362 }
5363 if (mpDiagramGraphicsView && mpDiagramGraphicsView->isAddClassAnnotationNeeded()) {
5364 mpDiagramGraphicsView->addClassAnnotation();
5365 mpDiagramGraphicsView->setAddClassAnnotationNeeded(false);
5366 }
5367 }
5368}
5369
5370/*!
5371 * \brief ModelWidget::updateModelText
5372 * Updates the Text of the class.
5373 */
5374void ModelWidget::updateModelText()
5375{
5376 LibraryTreeModel *pLibraryTreeModel = MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel();
5377 // Don't allow updating the child LibraryTreeItems of OMS model
5378 if (mpLibraryTreeItem->getLibraryType() == LibraryTreeItem::OMS && !mpLibraryTreeItem->isTopLevel()) {
5379 if (mpLibraryTreeItem->parent()->getModelWidget()) {
5380 mpLibraryTreeItem->parent()->getModelWidget()->updateModelText();
5381 } else {
5382 pLibraryTreeModel->updateLibraryTreeItemClassText(mpLibraryTreeItem->parent());
5383 }
5384 // set the library node not saved.
5385 mpLibraryTreeItem->setIsSaved(false);
5386 pLibraryTreeModel->updateLibraryTreeItem(mpLibraryTreeItem);
5387 if (mpLibraryTreeItem->isComponentElement()) {
5388 pLibraryTreeModel->updateOMSChildLibraryTreeItemClassText(mpLibraryTreeItem->parent());
5389 } else {
5390 pLibraryTreeModel->updateOMSChildLibraryTreeItemClassText(mpLibraryTreeItem);
5391 }
5392 return;
5393 }
5394 setWindowTitle(QString(mpLibraryTreeItem->getName()).append("*"));
5395 pLibraryTreeModel->updateLibraryTreeItemClassText(mpLibraryTreeItem);
5396#if !defined(WITHOUT_OSG)
5397 // update the ThreeDViewer Browser
5398 if (mpLibraryTreeItem->getLibraryType() == LibraryTreeItem::CompositeModel) {
5399 MainWindow::instance()->getModelWidgetContainer()->updateThreeDViewer(this);
5400 }
5401#endif
5402}
5403
5404/*!
5405 * \brief ModelWidget::updateModelicaTextManually
5406 * Updates the Parent Modelica class text after user has made changes manually in the text view.
5407 * \param contents
5408 */
5409void ModelWidget::updateModelicaTextManually(QString contents)
5410{
5411 setWindowTitle(QString(mpLibraryTreeItem->getName()).append("*"));
5412 LibraryTreeModel *pLibraryTreeModel = MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel();
5413 pLibraryTreeModel->updateLibraryTreeItemClassTextManually(mpLibraryTreeItem, contents);
5414}
5415
5416/*!
5417 * \brief ModelWidget::updateUndoRedoActions
5418 * Enables/disables the Undo/Redo actions based on the stack situation.
5419 */
5420void ModelWidget::updateUndoRedoActions()
5421{
5422 if (mpIconGraphicsView && mpIconGraphicsView->isVisible()) {
5423 MainWindow::instance()->getUndoAction()->setEnabled(mpUndoStack->canUndo());
5424 MainWindow::instance()->getRedoAction()->setEnabled(mpUndoStack->canRedo());
5425 } else if (mpDiagramGraphicsView && mpDiagramGraphicsView->isVisible()) {
5426 MainWindow::instance()->getUndoAction()->setEnabled(mpUndoStack->canUndo());
5427 MainWindow::instance()->getRedoAction()->setEnabled(mpUndoStack->canRedo());
5428 } else if (mpEditor && mpEditor->isVisible()) {
5429 MainWindow::instance()->getUndoAction()->setEnabled(mpEditor->getPlainTextEdit()->document()->isUndoAvailable());
5430 MainWindow::instance()->getRedoAction()->setEnabled(mpEditor->getPlainTextEdit()->document()->isRedoAvailable());
5431 } else {
5432 MainWindow::instance()->getUndoAction()->setEnabled(false);
5433 MainWindow::instance()->getRedoAction()->setEnabled(false);
5434 }
5435}
5436
5437/*!
5438 * \brief ModelWidget::writeCoSimulationResultFile
5439 * Writes the co-simulation csv result file for 3d viewer.
5440 * \param fileName
5441 */
5442bool ModelWidget::writeCoSimulationResultFile(QString fileName)
5443{
5444 // this function is only for meta-models
5445 if (mpLibraryTreeItem->getLibraryType() != LibraryTreeItem::CompositeModel) {
5446 return false;
5447 }
5448 // first remove the result file.
5449 if (QFile::exists(fileName)) {
5450 if (!QFile::remove(fileName)) {
5451 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
5452 GUIMessages::getMessage(GUIMessages::UNABLE_TO_DELETE_FILE).arg(fileName),
5453 Helper::scriptingKind, Helper::errorLevel));
5454 }
5455 }
5456 // write the result file.
5457 QFile file(fileName);
5458 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
5459 QTextStream resultFile(&file);
5460 // set to UTF-8
5461 resultFile.setCodec(Helper::utf8.toUtf8().constData());
5462 resultFile.setGenerateByteOrderMark(false);
5463 // write result file header
5464 resultFile << "\"" << "time\",";
5465 int nActiveInterfaces = 0;
5466 foreach (Component *pSubModelComponent, mpDiagramGraphicsView->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(mpDiagramGraphicsView
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pSubModelComponent = *_container_.i; _container_
.control; _container_.control = 0)
{
5467 foreach (Component *pInterfaceComponent, pSubModelComponent->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pSubModelComponent
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pInterfaceComponent = *_container_.i; _container_
.control; _container_.control = 0)
{
5468 QString name = QString("%1.%2").arg(pSubModelComponent->getName()).arg(pInterfaceComponent->getName());
5469 /*!
5470 * \note Don't check for connection.
5471 * If we check for connection then only connected submodels can be seen in the ThreeDViewer Browser.
5472 */
5473 // foreach (LineAnnotation *pConnectionLineAnnotation, mpDiagramGraphicsView->getConnectionsList()) {
5474 // if ((pConnectionLineAnnotation->getStartComponentName().compare(name) == 0) ||
5475 // (pConnectionLineAnnotation->getEndComponentName().compare(name) == 0)) {
5476 // Comma between interfaces
5477 if (nActiveInterfaces > 0) {
5478 resultFile << ",";
5479 }
5480 resultFile << "\"" << name << ".R[cG][cG](1) [m]\",\"" << name << ".R[cG][cG](2) [m]\",\"" << name << ".R[cG][cG](3) [m]\","; // Position vector
5481 resultFile << "\"" << name << ".A(1,1) [-]\",\"" << name << ".A(1,2) [-]\",\"" << name << ".A(1,3) [-]\",\""
5482 << name << ".A(2,1) [-]\",\"" << name << ".A(2,2) [-]\",\"" << name << ".A(2,3) [-]\",\""
5483 << name << ".A(3,1) [-]\",\"" << name << ".A(3,2) [-]\",\"" << name << ".A(3,3) [-]\""; // Transformation matrix
5484 nActiveInterfaces++;
5485 // }
5486 // }
5487 }
5488 }
5489 // write just single data for result file
5490 resultFile << "\n" << "0,";
5491 nActiveInterfaces = 0;
5492 foreach (Component *pSubModelComponent, mpDiagramGraphicsView->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(mpDiagramGraphicsView
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pSubModelComponent = *_container_.i; _container_
.control; _container_.control = 0)
{
5493 foreach (Component *pInterfaceComponent, pSubModelComponent->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pSubModelComponent
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pInterfaceComponent = *_container_.i; _container_
.control; _container_.control = 0)
{
5494 /*!
5495 * \note Don't check for connection.
5496 * If we check for connection then only connected submodels can be seen in the ThreeDViewer Browser.
5497 */
5498 // QString name = QString("%1.%2").arg(pSubModelComponent->getName()).arg(pInterfaceComponent->getName());
5499 // foreach (LineAnnotation *pConnectionLineAnnotation, mpDiagramGraphicsView->getConnectionsList()) {
5500 // if ((pConnectionLineAnnotation->getStartComponentName().compare(name) == 0) ||
5501 // (pConnectionLineAnnotation->getEndComponentName().compare(name) == 0)) {
5502 // Comma between interfaces
5503 if (nActiveInterfaces > 0) {
5504 resultFile << ",";
5505 }
5506
5507 // get the submodel position
5508 double values[] = {0.0, 0.0, 0.0};
5509 QGenericMatrix<3, 1, double> cX_R_cG_cG(values);
5510 QStringList subModelPositionList = pSubModelComponent->getComponentInfo()->getPosition().split(",", QString::SkipEmptyParts);
5511 if (subModelPositionList.size() > 2) {
5512 cX_R_cG_cG(0, 0) = subModelPositionList.at(0).toDouble();
5513 cX_R_cG_cG(0, 1) = subModelPositionList.at(1).toDouble();
5514 cX_R_cG_cG(0, 2) = subModelPositionList.at(2).toDouble();
5515 }
5516 // get the submodel angle
5517 double subModelPhi[3] = {0.0, 0.0, 0.0};
5518 QStringList subModelAngleList = pSubModelComponent->getComponentInfo()->getAngle321().split(",", QString::SkipEmptyParts);
5519 if (subModelAngleList.size() > 2) {
5520 subModelPhi[0] = subModelAngleList.at(0).toDouble();
5521 subModelPhi[1] = subModelAngleList.at(1).toDouble();
5522 subModelPhi[2] = subModelAngleList.at(2).toDouble();
5523 }
5524 QGenericMatrix<3, 3, double> cX_A_cG = Utilities::getRotationMatrix(QGenericMatrix<3, 1, double>(subModelPhi));
5525 // get the interface position
5526 QGenericMatrix<3, 1, double> ci_R_cX_cX(values);
5527 QStringList interfacePositionList = pInterfaceComponent->getComponentInfo()->getPosition().split(",", QString::SkipEmptyParts);
5528 if (interfacePositionList.size() > 2) {
5529 ci_R_cX_cX(0, 0) = interfacePositionList.at(0).toDouble();
5530 ci_R_cX_cX(0, 1) = interfacePositionList.at(1).toDouble();
5531 ci_R_cX_cX(0, 2) = interfacePositionList.at(2).toDouble();
5532 }
5533 // get the interface angle
5534 double interfacePhi[3] = {0.0, 0.0, 0.0};
5535 QStringList interfaceAngleList = pInterfaceComponent->getComponentInfo()->getAngle321().split(",", QString::SkipEmptyParts);
5536 if (interfaceAngleList.size() > 2) {
5537 interfacePhi[0] = interfaceAngleList.at(0).toDouble();
5538 interfacePhi[1] = interfaceAngleList.at(1).toDouble();
5539 interfacePhi[2] = interfaceAngleList.at(2).toDouble();
5540 }
5541 QGenericMatrix<3, 3, double> ci_A_cX = Utilities::getRotationMatrix(QGenericMatrix<3, 1, double>(interfacePhi));
5542
5543 QGenericMatrix<3, 1, double> ci_R_cG_cG = cX_R_cG_cG + ci_R_cX_cX*cX_A_cG;
5544 QGenericMatrix<3, 3, double> ci_A_cG = ci_A_cX*cX_A_cG;
5545
5546 // write data
5547 resultFile << ci_R_cG_cG(0, 0) << "," << ci_R_cG_cG(0, 1) << "," << ci_R_cG_cG(0, 2) << ","; // Position vector
5548 resultFile << ci_A_cG(0, 0) << "," << ci_A_cG(0, 1) << "," << ci_A_cG(0, 2) << ","
5549 << ci_A_cG(1, 0) << "," << ci_A_cG(1, 1) << "," << ci_A_cG(1, 2) << ","
5550 << ci_A_cG(2, 0) << "," << ci_A_cG(2, 1) << "," << ci_A_cG(2, 2); // Transformation matrix
5551 nActiveInterfaces++;
5552 // }
5553 // }
5554 }
5555 }
5556 file.close();
5557 return true;
5558 } else {
5559 QString msg = GUIMessages::getMessage(GUIMessages::ERROR_OCCURRED).arg(GUIMessages::getMessage(GUIMessages::UNABLE_TO_SAVE_FILE)
5560 .arg(fileName).arg(file.errorString()));
5561 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica, msg, Helper::scriptingKind,
5562 Helper::errorLevel));
5563 return false;
5564 }
5565}
5566
5567/*!
5568 * \brief ModelWidget::writeVisualXMLFile
5569 * Writes the visual xml file for 3d visualization.
5570 * \param fileName
5571 * \param canWriteVisualXMLFile
5572 * \return
5573 */
5574bool ModelWidget::writeVisualXMLFile(QString fileName, bool canWriteVisualXMLFile)
5575{
5576 // this function is only for meta-models
5577 if (mpLibraryTreeItem->getLibraryType() != LibraryTreeItem::CompositeModel) {
5578 return false;
5579 }
5580 // first remove the visual xml file.
5581 if (QFile::exists(fileName)) {
5582 if (!QFile::remove(fileName)) {
5583 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
5584 GUIMessages::getMessage(GUIMessages::UNABLE_TO_DELETE_FILE).arg(fileName),
5585 Helper::scriptingKind, Helper::errorLevel));
5586 }
5587 }
5588 // can we write visual xml file.
5589 if (!canWriteVisualXMLFile) {
5590 foreach (Component *pSubModelComponent, mpDiagramGraphicsView->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(mpDiagramGraphicsView
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pSubModelComponent = *_container_.i; _container_
.control; _container_.control = 0)
{
5591 if (!pSubModelComponent->getComponentInfo()->getGeometryFile().isEmpty()) {
5592 canWriteVisualXMLFile = true;
5593 }
5594 }
5595 if (!canWriteVisualXMLFile) {
5596 return false;
5597 }
5598 }
5599 // write the visual xml file.
5600 QFile file(fileName);
5601 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
5602 QTextStream visualFile(&file);
5603 // set to UTF-8
5604 visualFile.setCodec(Helper::utf8.toUtf8().constData());
5605 visualFile.setGenerateByteOrderMark(false);
5606
5607 visualFile << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
5608 visualFile << "<visualization>\n";
5609 visualFile << " <shape>\n";
5610 visualFile << " <ident>x-axis</ident>\n";
5611 visualFile << " <type>cylinder</type>\n";
5612 visualFile << " <T>\n";
5613 visualFile << " <exp>1.0</exp>\n";
5614 visualFile << " <exp>0.0</exp>\n";
5615 visualFile << " <exp>0.0</exp>\n";
5616 visualFile << " <exp>0.0</exp>\n";
5617 visualFile << " <exp>1.0</exp>\n";
5618 visualFile << " <exp>0.0</exp>\n";
5619 visualFile << " <exp>0.0</exp>\n";
5620 visualFile << " <exp>0.0</exp>\n";
5621 visualFile << " <exp>1.0</exp>\n";
5622 visualFile << " </T>\n";
5623 visualFile << " <r>\n";
5624 visualFile << " <exp>0.0</exp>\n";
5625 visualFile << " <exp>0.0</exp>\n";
5626 visualFile << " <exp>0.0</exp>\n";
5627 visualFile << " </r>\n";
5628 visualFile << " <r_shape>\n";
5629 visualFile << " <exp>0.0</exp>\n";
5630 visualFile << " <exp>0.0</exp>\n";
5631 visualFile << " <exp>0.0</exp>\n";
5632 visualFile << " </r_shape>\n";
5633 visualFile << " <lengthDir>\n";
5634 visualFile << " <exp>1.0</exp>\n";
5635 visualFile << " <exp>0.0</exp>\n";
5636 visualFile << " <exp>0.0</exp>\n";
5637 visualFile << " </lengthDir>\n";
5638 visualFile << " <widthDir>\n";
5639 visualFile << " <exp>0.0</exp>\n";
5640 visualFile << " <exp>1.0</exp>\n";
5641 visualFile << " <exp>0.0</exp>\n";
5642 visualFile << " </widthDir>\n";
5643 visualFile << " <length><exp>1.0</exp></length>\n";
5644 visualFile << " <width><exp>0.0025</exp></width>\n";
5645 visualFile << " <height><exp>0.0025</exp></height>\n";
5646 visualFile << " <extra><exp>0.0</exp></extra>\n";
5647 visualFile << " <color>\n";
5648 visualFile << " <exp>255.0</exp>\n";
5649 visualFile << " <exp>0.0</exp>\n";
5650 visualFile << " <exp>0.0</exp>\n";
5651 visualFile << " </color>\n";
5652 visualFile << " <specCoeff><exp>0.7</exp></specCoeff>\n";
5653 visualFile << " </shape>\n";
5654
5655 visualFile << " <shape>\n";
5656 visualFile << " <ident>y-axis</ident>\n";
5657 visualFile << " <type>cylinder</type>\n";
5658 visualFile << " <T>\n";
5659 visualFile << " <exp>1.0</exp>\n";
5660 visualFile << " <exp>0.0</exp>\n";
5661 visualFile << " <exp>0.0</exp>\n";
5662 visualFile << " <exp>0.0</exp>\n";
5663 visualFile << " <exp>1.0</exp>\n";
5664 visualFile << " <exp>0.0</exp>\n";
5665 visualFile << " <exp>0.0</exp>\n";
5666 visualFile << " <exp>0.0</exp>\n";
5667 visualFile << " <exp>1.0</exp>\n";
5668 visualFile << " </T>\n";
5669 visualFile << " <r>\n";
5670 visualFile << " <exp>0.0</exp>\n";
5671 visualFile << " <exp>0.0</exp>\n";
5672 visualFile << " <exp>0.0</exp>\n";
5673 visualFile << " </r>\n";
5674 visualFile << " <r_shape>\n";
5675 visualFile << " <exp>0.0</exp>\n";
5676 visualFile << " <exp>0.0</exp>\n";
5677 visualFile << " <exp>0.0</exp>\n";
5678 visualFile << " </r_shape>\n";
5679 visualFile << " <lengthDir>\n";
5680 visualFile << " <exp>0.0</exp>\n";
5681 visualFile << " <exp>1.0</exp>\n";
5682 visualFile << " <exp>0.0</exp>\n";
5683 visualFile << " </lengthDir>\n";
5684 visualFile << " <widthDir>\n";
5685 visualFile << " <exp>1.0</exp>\n";
5686 visualFile << " <exp>0.0</exp>\n";
5687 visualFile << " <exp>0.0</exp>\n";
5688 visualFile << " </widthDir>\n";
5689 visualFile << " <length><exp>1.0</exp></length>\n";
5690 visualFile << " <width><exp>0.0025</exp></width>\n";
5691 visualFile << " <height><exp>0.0025</exp></height>\n";
5692 visualFile << " <extra><exp>0.0</exp></extra>\n";
5693 visualFile << " <color>\n";
5694 visualFile << " <exp>0.0</exp>\n";
5695 visualFile << " <exp>255.0</exp>\n";
5696 visualFile << " <exp>0.0</exp>\n";
5697 visualFile << " </color>\n";
5698 visualFile << " <specCoeff><exp>0.7</exp></specCoeff>\n";
5699 visualFile << " </shape>\n";
5700
5701 visualFile << " <shape>\n";
5702 visualFile << " <ident>z-axis</ident>\n";
5703 visualFile << " <type>cylinder</type>\n";
5704 visualFile << " <T>\n";
5705 visualFile << " <exp>1.0</exp>\n";
5706 visualFile << " <exp>0.0</exp>\n";
5707 visualFile << " <exp>0.0</exp>\n";
5708 visualFile << " <exp>0.0</exp>\n";
5709 visualFile << " <exp>1.0</exp>\n";
5710 visualFile << " <exp>0.0</exp>\n";
5711 visualFile << " <exp>0.0</exp>\n";
5712 visualFile << " <exp>0.0</exp>\n";
5713 visualFile << " <exp>1.0</exp>\n";
5714 visualFile << " </T>\n";
5715 visualFile << " <r>\n";
5716 visualFile << " <exp>0.0</exp>\n";
5717 visualFile << " <exp>0.0</exp>\n";
5718 visualFile << " <exp>0.0</exp>\n";
5719 visualFile << " </r>\n";
5720 visualFile << " <r_shape>\n";
5721 visualFile << " <exp>0.0</exp>\n";
5722 visualFile << " <exp>0.0</exp>\n";
5723 visualFile << " <exp>0.0</exp>\n";
5724 visualFile << " </r_shape>\n";
5725 visualFile << " <lengthDir>\n";
5726 visualFile << " <exp>0.0</exp>\n";
5727 visualFile << " <exp>0.0</exp>\n";
5728 visualFile << " <exp>1.0</exp>\n";
5729 visualFile << " </lengthDir>\n";
5730 visualFile << " <widthDir>\n";
5731 visualFile << " <exp>0.0</exp>\n";
5732 visualFile << " <exp>1.0</exp>\n";
5733 visualFile << " <exp>0.0</exp>\n";
5734 visualFile << " </widthDir>\n";
5735 visualFile << " <length><exp>1.0</exp></length>\n";
5736 visualFile << " <width><exp>0.0025</exp></width>\n";
5737 visualFile << " <height><exp>0.0025</exp></height>\n";
5738 visualFile << " <extra><exp>0.0</exp></extra>\n";
5739 visualFile << " <color>\n";
5740 visualFile << " <exp>0.0</exp>\n";
5741 visualFile << " <exp>0.0</exp>\n";
5742 visualFile << " <exp>255.0</exp>\n";
5743 visualFile << " </color>\n";
5744 visualFile << " <specCoeff><exp>0.7</exp></specCoeff>\n";
5745 visualFile << " </shape>\n";
5746
5747 QList<QColor> colorsList;
5748 colorsList.append(QColor(Qt::red));
5749 colorsList.append(QColor(85,170,0)); // green
5750 colorsList.append(QColor(Qt::blue));
5751 colorsList.append(QColor(Qt::lightGray));
5752 colorsList.append(QColor(Qt::magenta));
5753 colorsList.append(QColor(Qt::yellow));
5754 colorsList.append(QColor(Qt::darkRed));
5755 colorsList.append(QColor(Qt::darkBlue));
5756 colorsList.append(QColor(Qt::darkGreen));
5757 colorsList.append(QColor(Qt::darkCyan));
5758 colorsList.append(QColor(Qt::darkMagenta));
5759 colorsList.append(QColor(Qt::darkYellow));
5760 // selected color
5761 QColor selectedColor(255, 192, 203); // pink
5762 int i = 0;
5763
5764 foreach (Component *pSubModelComponent, mpDiagramGraphicsView->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(mpDiagramGraphicsView
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pSubModelComponent = *_container_.i; _container_
.control; _container_.control = 0)
{
5765 // if no geometry file then continue.
5766 if (pSubModelComponent->getComponentInfo()->getGeometryFile().isEmpty()) {
5767 continue;
5768 }
5769 bool visited = false;
5770 foreach (Component *pInterfaceComponent, pSubModelComponent->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pSubModelComponent
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pInterfaceComponent = *_container_.i; _container_
.control; _container_.control = 0)
{
5771 QString name = QString("%1.%2").arg(pSubModelComponent->getName()).arg(pInterfaceComponent->getName());
5772
5773
5774
5775
5776 //Draw interface vectors
5777 bool interfaceSelected=false;
5778 foreach(LineAnnotation* pConnection, pInterfaceComponent->getGraphicsView()->getConnectionsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pInterfaceComponent
->getGraphicsView()->getConnectionsList()); _container_
.control && _container_.i != _container_.e; ++_container_
.i, _container_.control ^= 1) for (LineAnnotation* pConnection
= *_container_.i; _container_.control; _container_.control =
0)
{
5779 if(pConnection->isSelected()) {
5780 if(pConnection->getStartComponent() == pInterfaceComponent ||
5781 pConnection->getEndComponent() == pInterfaceComponent) {
5782 interfaceSelected = true;
5783 }
5784 }
5785 }
5786
5787 //Draw X-axis
5788 visualFile << " <shape>\n";
5789 visualFile << " <ident>" << name << ".x</ident>\n";
5790 visualFile << " <type>cylinder</type>\n";
5791 visualFile << " <T>\n";
5792 visualFile << " <cref>" << name << ".A(1,1) [-]</cref>\n";
5793 visualFile << " <cref>" << name << ".A(1,2) [-]</cref>\n";
5794 visualFile << " <cref>" << name << ".A(1,3) [-]</cref>\n";
5795 visualFile << " <cref>" << name << ".A(2,1) [-]</cref>\n";
5796 visualFile << " <cref>" << name << ".A(2,2) [-]</cref>\n";
5797 visualFile << " <cref>" << name << ".A(2,3) [-]</cref>\n";
5798 visualFile << " <cref>" << name << ".A(3,1) [-]</cref>\n";
5799 visualFile << " <cref>" << name << ".A(3,2) [-]</cref>\n";
5800 visualFile << " <cref>" << name << ".A(3,3) [-]</cref>\n";
5801 visualFile << " </T>\n";
5802 visualFile << " <r>\n";
5803 visualFile << " <cref>" << name << ".R[cG][cG](1) [m]</cref>\n";
5804 visualFile << " <cref>" << name << ".R[cG][cG](2) [m]</cref>\n";
5805 visualFile << " <cref>" << name << ".R[cG][cG](3) [m]</cref>\n";
5806 visualFile << " </r>\n";
5807 visualFile << " <r_shape>\n";
5808 visualFile << " <exp>0</exp>\n";
5809 visualFile << " <exp>0</exp>\n";
5810 visualFile << " <exp>0</exp>\n";
5811 visualFile << " </r_shape>\n";
5812 visualFile << " <lengthDir>\n";
5813 visualFile << " <exp>1</exp>\n";
5814 visualFile << " <exp>0</exp>\n";
5815 visualFile << " <exp>0</exp>\n";
5816 visualFile << " </lengthDir>\n";
5817 visualFile << " <widthDir>\n";
5818 visualFile << " <exp>0</exp>\n";
5819 visualFile << " <exp>1</exp>\n";
5820 visualFile << " <exp>0</exp>\n";
5821 visualFile << " </widthDir>\n";
5822 visualFile << " <length><exp>0.5</exp></length>\n";
5823 visualFile << " <width><exp>0.0025</exp></width>\n";
5824 visualFile << " <height><exp>0.0025</exp></height>\n";
5825 visualFile << " <extra><exp>0.0</exp></extra>\n";
5826 visualFile << " <color>\n";
5827 if(interfaceSelected) {
5828 visualFile << " <exp>" << selectedColor.red() << "</exp>\n";
5829 visualFile << " <exp>" << selectedColor.green() << "</exp>\n";
5830 visualFile << " <exp>" << selectedColor.blue() << "</exp>\n";
5831 } else {
5832 visualFile << " <exp>255</exp>\n";
5833 visualFile << " <exp>0</exp>\n";
5834 visualFile << " <exp>0</exp>\n";
5835 }
5836 visualFile << " </color>\n";
5837 visualFile << " <specCoeff><exp>0.7</exp></specCoeff>\n";
5838 visualFile << " </shape>\n";
5839
5840 //Draw Y-axis
5841 visualFile << " <shape>\n";
5842 visualFile << " <ident>" << name << ".x</ident>\n";
5843 visualFile << " <type>cylinder</type>\n";
5844 visualFile << " <T>\n";
5845 visualFile << " <cref>" << name << ".A(1,1) [-]</cref>\n";
5846 visualFile << " <cref>" << name << ".A(1,2) [-]</cref>\n";
5847 visualFile << " <cref>" << name << ".A(1,3) [-]</cref>\n";
5848 visualFile << " <cref>" << name << ".A(2,1) [-]</cref>\n";
5849 visualFile << " <cref>" << name << ".A(2,2) [-]</cref>\n";
5850 visualFile << " <cref>" << name << ".A(2,3) [-]</cref>\n";
5851 visualFile << " <cref>" << name << ".A(3,1) [-]</cref>\n";
5852 visualFile << " <cref>" << name << ".A(3,2) [-]</cref>\n";
5853 visualFile << " <cref>" << name << ".A(3,3) [-]</cref>\n";
5854 visualFile << " </T>\n";
5855 visualFile << " <r>\n";
5856 visualFile << " <cref>" << name << ".R[cG][cG](1) [m]</cref>\n";
5857 visualFile << " <cref>" << name << ".R[cG][cG](2) [m]</cref>\n";
5858 visualFile << " <cref>" << name << ".R[cG][cG](3) [m]</cref>\n";
5859 visualFile << " </r>\n";
5860 visualFile << " <r_shape>\n";
5861 visualFile << " <exp>0</exp>\n";
5862 visualFile << " <exp>0</exp>\n";
5863 visualFile << " <exp>0</exp>\n";
5864 visualFile << " </r_shape>\n";
5865 visualFile << " <lengthDir>\n";
5866 visualFile << " <exp>0</exp>\n";
5867 visualFile << " <exp>1</exp>\n";
5868 visualFile << " <exp>0</exp>\n";
5869 visualFile << " </lengthDir>\n";
5870 visualFile << " <widthDir>\n";
5871 visualFile << " <exp>0</exp>\n";
5872 visualFile << " <exp>0</exp>\n";
5873 visualFile << " <exp>1</exp>\n";
5874 visualFile << " </widthDir>\n";
5875 visualFile << " <length><exp>0.5</exp></length>\n";
5876 visualFile << " <width><exp>0.0025</exp></width>\n";
5877 visualFile << " <height><exp>0.0025</exp></height>\n";
5878 visualFile << " <extra><exp>0.0</exp></extra>\n";
5879 visualFile << " <color>\n";
5880 if(interfaceSelected) {
5881 visualFile << " <exp>" << selectedColor.red() << "</exp>\n";
5882 visualFile << " <exp>" << selectedColor.green() << "</exp>\n";
5883 visualFile << " <exp>" << selectedColor.blue() << "</exp>\n";
5884 } else {
5885 visualFile << " <exp>0</exp>\n";
5886 visualFile << " <exp>255</exp>\n";
5887 visualFile << " <exp>0</exp>\n";
5888 }
5889 visualFile << " </color>\n";
5890 visualFile << " <specCoeff><exp>0.7</exp></specCoeff>\n";
5891 visualFile << " </shape>\n";
5892
5893 //Draw Z-axis
5894 visualFile << " <shape>\n";
5895 visualFile << " <ident>" << name << ".x</ident>\n";
5896 visualFile << " <type>cylinder</type>\n";
5897 visualFile << " <T>\n";
5898 visualFile << " <cref>" << name << ".A(1,1) [-]</cref>\n";
5899 visualFile << " <cref>" << name << ".A(1,2) [-]</cref>\n";
5900 visualFile << " <cref>" << name << ".A(1,3) [-]</cref>\n";
5901 visualFile << " <cref>" << name << ".A(2,1) [-]</cref>\n";
5902 visualFile << " <cref>" << name << ".A(2,2) [-]</cref>\n";
5903 visualFile << " <cref>" << name << ".A(2,3) [-]</cref>\n";
5904 visualFile << " <cref>" << name << ".A(3,1) [-]</cref>\n";
5905 visualFile << " <cref>" << name << ".A(3,2) [-]</cref>\n";
5906 visualFile << " <cref>" << name << ".A(3,3) [-]</cref>\n";
5907 visualFile << " </T>\n";
5908 visualFile << " <r>\n";
5909 visualFile << " <cref>" << name << ".R[cG][cG](1) [m]</cref>\n";
5910 visualFile << " <cref>" << name << ".R[cG][cG](2) [m]</cref>\n";
5911 visualFile << " <cref>" << name << ".R[cG][cG](3) [m]</cref>\n";
5912 visualFile << " </r>\n";
5913 visualFile << " <r_shape>\n";
5914 visualFile << " <exp>0</exp>\n";
5915 visualFile << " <exp>0</exp>\n";
5916 visualFile << " <exp>0</exp>\n";
5917 visualFile << " </r_shape>\n";
5918 visualFile << " <lengthDir>\n";
5919 visualFile << " <exp>0</exp>\n";
5920 visualFile << " <exp>0</exp>\n";
5921 visualFile << " <exp>1</exp>\n";
5922 visualFile << " </lengthDir>\n";
5923 visualFile << " <widthDir>\n";
5924 visualFile << " <exp>1</exp>\n";
5925 visualFile << " <exp>0</exp>\n";
5926 visualFile << " <exp>0</exp>\n";
5927 visualFile << " </widthDir>\n";
5928 visualFile << " <length><exp>0.5</exp></length>\n";
5929 visualFile << " <width><exp>0.0025</exp></width>\n";
5930 visualFile << " <height><exp>0.0025</exp></height>\n";
5931 visualFile << " <extra><exp>0.0</exp></extra>\n";
5932 visualFile << " <color>\n";
5933 if(interfaceSelected) {
5934 visualFile << " <exp>" << selectedColor.red() << "</exp>\n";
5935 visualFile << " <exp>" << selectedColor.green() << "</exp>\n";
5936 visualFile << " <exp>" << selectedColor.blue() << "</exp>\n";
5937 } else {
5938 visualFile << " <exp>0</exp>\n";
5939 visualFile << " <exp>0</exp>\n";
5940 visualFile << " <exp>255</exp>\n";
5941 }
5942 visualFile << " </color>\n";
5943 visualFile << " <specCoeff><exp>0.7</exp></specCoeff>\n";
5944 visualFile << " </shape>\n";
5945 //End new code
5946
5947 if (visited) {
5948 break;
5949 }
5950 /*!
5951 * \note Don't check for connection.
5952 * If we check for connection then only connected submodels can be seen in the ThreeDViewer Browser.
5953 */
5954 // foreach (LineAnnotation *pConnectionLineAnnotation, mpDiagramGraphicsView->getConnectionsList()) {
5955 // if ((pConnectionLineAnnotation->getStartComponentName().compare(name) == 0) ||
5956 // (pConnectionLineAnnotation->getEndComponentName().compare(name) == 0)) {
5957 // get the angle
5958 double phi[3] = {0.0, 0.0, 0.0};
5959 QStringList angleList = pInterfaceComponent->getComponentInfo()->getAngle321().split(",", QString::SkipEmptyParts);
5960 if (angleList.size() > 2) {
5961 phi[0] = -angleList.at(0).toDouble();
5962 phi[1] = -angleList.at(1).toDouble();
5963 phi[2] = -angleList.at(2).toDouble();
5964 }
5965 QGenericMatrix<3, 3, double> T = Utilities::getRotationMatrix(QGenericMatrix<3, 1, double>(phi));
5966 // get the position
5967 double position[3] = {0.0, 0.0, 0.0};
5968 QStringList positionList = pInterfaceComponent->getComponentInfo()->getPosition().split(",", QString::SkipEmptyParts);
5969 if (positionList.size() > 2) {
5970 position[0] = positionList.at(0).toDouble();
5971 position[1] = positionList.at(1).toDouble();
5972 position[2] = positionList.at(2).toDouble();
5973 }
5974 QGenericMatrix<3, 1, double> r_shape;
5975 r_shape(0, 0) = -position[0];
5976 r_shape(0, 1) = -position[1];
5977 r_shape(0, 2) = -position[2];
5978 r_shape = r_shape*(T);
5979 double lengthDirArr[3] = {1.0, 0.0, 0.0};
5980 QGenericMatrix<3, 1, double> lengthDir(lengthDirArr);
5981 lengthDir = lengthDir*(T);
5982 double widthDirArr[3] = {0.0, 1.0, 0.0};
5983 QGenericMatrix<3, 1, double> widthDir(widthDirArr);
5984 widthDir = widthDir*(T);
5985
5986 visualFile << " <shape>\n";
5987 visualFile << " <ident>" << name << "</ident>\n";
5988 visualFile << " <type>file://" << pSubModelComponent->getComponentInfo()->getGeometryFile() << "</type>\n";
5989 visualFile << " <T>\n";
5990 visualFile << " <cref>" << name << ".A(1,1) [-]</cref>\n";
5991 visualFile << " <cref>" << name << ".A(1,2) [-]</cref>\n";
5992 visualFile << " <cref>" << name << ".A(1,3) [-]</cref>\n";
5993 visualFile << " <cref>" << name << ".A(2,1) [-]</cref>\n";
5994 visualFile << " <cref>" << name << ".A(2,2) [-]</cref>\n";
5995 visualFile << " <cref>" << name << ".A(2,3) [-]</cref>\n";
5996 visualFile << " <cref>" << name << ".A(3,1) [-]</cref>\n";
5997 visualFile << " <cref>" << name << ".A(3,2) [-]</cref>\n";
5998 visualFile << " <cref>" << name << ".A(3,3) [-]</cref>\n";
5999 visualFile << " </T>\n";
6000 visualFile << " <r>\n";
6001 visualFile << " <cref>" << name << ".R[cG][cG](1) [m]</cref>\n";
6002 visualFile << " <cref>" << name << ".R[cG][cG](2) [m]</cref>\n";
6003 visualFile << " <cref>" << name << ".R[cG][cG](3) [m]</cref>\n";
6004 visualFile << " </r>\n";
6005 visualFile << " <r_shape>\n";
6006 visualFile << " <exp>" << r_shape(0, 0) << "</exp>\n";
6007 visualFile << " <exp>" << r_shape(0, 1) << "</exp>\n";
6008 visualFile << " <exp>" << r_shape(0, 2) << "</exp>\n";
6009 visualFile << " </r_shape>\n";
6010 visualFile << " <lengthDir>\n";
6011 visualFile << " <exp>" << lengthDir(0, 0) << "</exp>\n";
6012 visualFile << " <exp>" << lengthDir(0, 1) << "</exp>\n";
6013 visualFile << " <exp>" << lengthDir(0, 2) << "</exp>\n";
6014 visualFile << " </lengthDir>\n";
6015 visualFile << " <widthDir>\n";
6016 visualFile << " <exp>" << widthDir(0, 0) << "</exp>\n";
6017 visualFile << " <exp>" << widthDir(0, 1) << "</exp>\n";
6018 visualFile << " <exp>" << widthDir(0, 2) << "</exp>\n";
6019 visualFile << " </widthDir>\n";
6020 visualFile << " <length><exp>0.0</exp></length>\n";
6021 visualFile << " <width><exp>0.0</exp></width>\n";
6022 visualFile << " <height><exp>0.0</exp></height>\n";
6023 visualFile << " <extra><exp>0.0</exp></extra>\n";
6024 visualFile << " <color>\n";
6025 if (pSubModelComponent->isSelected()) {
6026 visualFile << " <exp>" << selectedColor.red() << "</exp>\n";
6027 visualFile << " <exp>" << selectedColor.green() << "</exp>\n";
6028 visualFile << " <exp>" << selectedColor.blue() << "</exp>\n";
6029 } else {
6030 visualFile << " <exp>" << colorsList.at(i % colorsList.size()).red() << "</exp>\n";
6031 visualFile << " <exp>" << colorsList.at(i % colorsList.size()).green() << "</exp>\n";
6032 visualFile << " <exp>" << colorsList.at(i % colorsList.size()).blue() << "</exp>\n";
6033 }
6034 visualFile << " </color>\n";
6035 visualFile << " <specCoeff><exp>0.7</exp></specCoeff>\n";
6036 visualFile << " </shape>\n";
6037 // set the visited flag to true.
6038 visited = true;
6039 i++;
6040 break;
6041 // }
6042 // }
6043 }
6044 }
6045
6046 visualFile << "</visualization>\n";
6047 file.close();
6048 return true;
6049 } else {
6050 QString msg = GUIMessages::getMessage(GUIMessages::ERROR_OCCURRED).arg(GUIMessages::getMessage(GUIMessages::UNABLE_TO_SAVE_FILE)
6051 .arg(fileName).arg(file.errorString()));
6052 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica, msg, Helper::scriptingKind,
6053 Helper::errorLevel));
6054 return false;
6055 }
6056}
6057
6058/*!
6059 * \brief ModelWidget::beginMacro
6060 * Tells the undo stack to consider all coming commands as one.\n
6061 * Also tells the text editor to mark all changes as one.
6062 * \param text
6063 */
6064void ModelWidget::beginMacro(const QString &text)
6065{
6066 mpUndoStack->beginMacro(text);
6067 if (mpEditor) {
6068 QTextCursor textCursor = mpEditor->getPlainTextEdit()->textCursor();
6069 textCursor.beginEditBlock();
6070 }
6071}
6072
6073/*!
6074 * \brief ModelWidget::endMacro
6075 * Tells the undo stack and text editor that the batch editing is finished.
6076 */
6077void ModelWidget::endMacro()
6078{
6079 mpUndoStack->endMacro();
6080 if (mpEditor) {
6081 mpEditor->setForceSetPlainText(true);
6082 QTextCursor textCursor = mpEditor->getPlainTextEdit()->textCursor();
6083 textCursor.endEditBlock();
6084 mpEditor->setForceSetPlainText(false);
6085 }
6086}
6087
6088/*!
6089 * \brief ModelWidget::updateViewButtonsBasedOnAccess
6090 * Update the view buttons i.e., icon, diagram and text based on the Access annotation.
6091 */
6092void ModelWidget::updateViewButtonsBasedOnAccess()
6093{
6094 if (mCreateModelWidgetComponents) {
6095 LibraryTreeItem::Access access = mpLibraryTreeItem->getAccess();
6096 switch (access) {
6097 case LibraryTreeItem::icon:
6098 mpIconViewToolButton->setChecked(true);
6099 mpDiagramViewToolButton->setEnabled(false);
6100 mpTextViewToolButton->setEnabled(false);
6101 mpDocumentationViewToolButton->setEnabled(false);
6102 break;
6103 case LibraryTreeItem::documentation:
6104 mpIconViewToolButton->setChecked(true);
6105 mpDiagramViewToolButton->setEnabled(false);
6106 mpTextViewToolButton->setEnabled(false);
6107 mpDocumentationViewToolButton->setEnabled(true);
6108 break;
6109 case LibraryTreeItem::diagram:
6110 if (mpTextViewToolButton->isChecked()) {
6111 mpDiagramViewToolButton->setChecked(true);
6112 }
6113 mpTextViewToolButton->setEnabled(false);
6114 mpDocumentationViewToolButton->setEnabled(true);
6115 break;
6116 case LibraryTreeItem::nonPackageText:
6117 case LibraryTreeItem::nonPackageDuplicate:
6118 if (mpLibraryTreeItem->getRestriction() == StringHandler::Package) {
6119 if (mpTextViewToolButton->isChecked()) {
6120 mpDiagramViewToolButton->setChecked(true);
6121 }
6122 mpTextViewToolButton->setEnabled(false);
6123 } else {
6124 mpDiagramViewToolButton->setEnabled(true);
6125 mpTextViewToolButton->setEnabled(true);
6126 }
6127 mpDocumentationViewToolButton->setEnabled(true);
6128 break;
6129 default:
6130 mpDiagramViewToolButton->setEnabled(true);
6131 mpTextViewToolButton->setEnabled(true);
6132 mpDocumentationViewToolButton->setEnabled(true);
6133 break;
6134 }
6135 }
6136}
6137
6138/*!
6139 * \brief ModelWidget::associateBusWithConnector
6140 * Associates the bus component with the connector component.
6141 * \param busName
6142 * \param connectorName
6143 */
6144void ModelWidget::associateBusWithConnector(QString busName, QString connectorName)
6145{
6146 associateBusWithConnector(busName, connectorName, mpIconGraphicsView);
6147 associateBusWithConnector(busName, connectorName, mpDiagramGraphicsView);
6148 // get the connector component
6149 Component *pConnectorComponent = mpIconGraphicsView->getComponentObject(connectorName);
6150 if (pConnectorComponent) {
6151 pConnectorComponent->emitDeleted();
6152 }
6153}
6154
6155/*!
6156 * \brief ModelWidget::dissociateBusWithConnector
6157 * Dissociate the bus component with the connector component.
6158 * \param busName
6159 * \param connectorName
6160 */
6161void ModelWidget::dissociateBusWithConnector(QString busName, QString connectorName)
6162{
6163 dissociateBusWithConnector(busName, connectorName, mpIconGraphicsView);
6164 dissociateBusWithConnector(busName, connectorName, mpDiagramGraphicsView);
6165 // get the connector component
6166 Component *pConnectorComponent = mpIconGraphicsView->getComponentObject(connectorName);
6167 if (pConnectorComponent) {
6168 pConnectorComponent->emitAdded();
6169 }
6170}
6171
6172/*!
6173 * \brief ModelWidget::associateBusWithConnectors
6174 * Associates the bus component with each of its connector component.
6175 * \param busName
6176 */
6177void ModelWidget::associateBusWithConnectors(QString busName)
6178{
6179 // get the bus component
6180 Component *pIconBusComponent = mpIconGraphicsView->getComponentObject(busName);
6181 associateBusWithConnectors(pIconBusComponent, mpIconGraphicsView);
6182 Component *pDiagramBusComponent = mpDiagramGraphicsView->getComponentObject(busName);
6183 associateBusWithConnectors(pDiagramBusComponent, mpDiagramGraphicsView);
6184}
6185
6186/*!
6187 * \brief ModelWidget::toOMSensJson
6188 * Creates a list of QVariant containing the model information needed by OMSens.
6189 * \return
6190 */
6191QList<QVariant> ModelWidget::toOMSensData()
6192{
6193 QStringList inputVariables;
6194 QStringList outputVariables;
6195 QStringList parameters;
6196 QStringList auxVariables;
6197
6198 if (mpDiagramGraphicsView) {
6199 foreach (Component *pComponent, mpDiagramGraphicsView->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(mpDiagramGraphicsView
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pComponent = *_container_.i; _container_.control
; _container_.control = 0)
{
6200 ComponentInfo *pComponentInfo = pComponent->getComponentInfo();
6201 if ((pComponentInfo->getCausality().compare("input") == 0) && ((pComponentInfo->getClassName().compare("Real") == 0)
6202 || (pComponentInfo->getClassName().compare("Modelica.Blocks.Interfaces.RealInput") == 0))) {
6203 inputVariables.append(pComponentInfo->getName());
6204 } else if ((pComponentInfo->getCausality().compare("output") == 0) && ((pComponentInfo->getClassName().compare("Real") == 0)
6205 || (pComponentInfo->getClassName().compare("Modelica.Blocks.Interfaces.RealOutput") == 0))) {
6206 outputVariables.append(pComponentInfo->getName());
6207 } else if ((pComponentInfo->getVariablity().compare("parameter") == 0) && (pComponentInfo->getClassName().compare("Real") == 0)) {
6208 parameters.append(pComponentInfo->getName());
6209 } else if (pComponentInfo->getClassName().compare("Real") == 0) {
6210 auxVariables.append(pComponentInfo->getName());
6211 }
6212 }
6213 }
6214
6215 QList<QVariant> omSensData;
6216 omSensData << inputVariables << outputVariables << auxVariables << parameters << mpLibraryTreeItem->getFileName() << mpLibraryTreeItem->getNameStructure();
6217 return omSensData;
6218}
6219
6220/*!
6221 * \brief ModelWidget::getIconDiagramMap
6222 * Parses the IconMap/DiagramMap annotation and returns the IconDiagramMap object.
6223 * \param mapAnnotation
6224 * \return
6225 */
6226IconDiagramMap ModelWidget::getIconDiagramMap(QString mapAnnotation)
6227{
6228 IconDiagramMap map;
6229 QStringList mapAnnotationValues = StringHandler::getStrings(StringHandler::removeFirstLastCurlBrackets(mapAnnotation));
6230 if (mapAnnotationValues.length() == 6) {
6231 QPointF point1, point2;
6232 point1.setX(mapAnnotationValues.at(1).toFloat());
6233 point1.setY(mapAnnotationValues.at(2).toFloat());
6234 point2.setX(mapAnnotationValues.at(3).toFloat());
6235 point2.setY(mapAnnotationValues.at(4).toFloat());
6236 map.mExtent.clear();
6237 map.mExtent.append(point1);
6238 map.mExtent.append(point2);
6239 map.mPrimitivesVisible = mapAnnotationValues.at(5).compare("true") == 0;
6240 }
6241 return map;
6242}
6243
6244/*!
6245 * \brief ModelWidget::getModelInheritedClasses
6246 * Gets the class inherited classes.
6247 */
6248void ModelWidget::getModelInheritedClasses()
6249{
6250 MainWindow *pMainWindow = MainWindow::instance();
6251 LibraryTreeModel *pLibraryTreeModel = pMainWindow->getLibraryWidget()->getLibraryTreeModel();
6252 // get the inherited classes of the class
6253 QList<QString> inheritedClasses = pMainWindow->getOMCProxy()->getInheritedClasses(mpLibraryTreeItem->getNameStructure());
6254 int index = 1;
6255 foreach (QString inheritedClass, inheritedClasses)for (auto _container_ = QtPrivate::qMakeForeachContainer(inheritedClasses
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QString inheritedClass
= *_container_.i; _container_.control; _container_.control =
0)
{
6256 /* If the inherited class is one of the builtin type such as Real we can
6257 * stop here, because the class can not contain any classes, etc.
6258 * Also check for cyclic loops.
6259 */
6260 if (!(pMainWindow->getOMCProxy()->isBuiltinType(inheritedClass) || inheritedClass.compare(mpLibraryTreeItem->getNameStructure()) == 0)) {
6261 LibraryTreeItem *pInheritedLibraryTreeItem = pLibraryTreeModel->findLibraryTreeItem(inheritedClass);
6262 if (!pInheritedLibraryTreeItem) {
6263 pInheritedLibraryTreeItem = pLibraryTreeModel->createNonExistingLibraryTreeItem(inheritedClass);
6264 }
6265 if (!pInheritedLibraryTreeItem->isNonExisting() && !pInheritedLibraryTreeItem->getModelWidget()) {
6266 pLibraryTreeModel->showModelWidget(pInheritedLibraryTreeItem, false);
6267 }
6268 mpLibraryTreeItem->addInheritedClass(pInheritedLibraryTreeItem);
6269 addInheritedClass(pInheritedLibraryTreeItem);
6270 // get the icon and diagram map of inherited class
6271 IconDiagramMap iconMap = getIconDiagramMap(pMainWindow->getOMCProxy()->getNthInheritedClassIconMapAnnotation(mpLibraryTreeItem->getNameStructure(), index));
6272 mInheritedClassesIconMap.insert(index, iconMap);
6273 IconDiagramMap diagramMap = getIconDiagramMap(pMainWindow->getOMCProxy()->getNthInheritedClassDiagramMapAnnotation(mpLibraryTreeItem->getNameStructure(), index));
6274 mInheritedClassesDiagramMap.insert(index, diagramMap);
6275 }
6276 index++;
6277 }
6278}
6279
6280/*!
6281 * \brief ModelWidget::parseModelInheritedClass
6282 * Parses the inherited class shape and draws its items on the appropriate view.
6283 * \param pModelWidget
6284 * \param viewType
6285 */
6286void ModelWidget::drawModelInheritedClassShapes(ModelWidget *pModelWidget, StringHandler::ViewType viewType)
6287{
6288 int index = 1;
6289 foreach (LibraryTreeItem *pLibraryTreeItem, pModelWidget->getInheritedClassesList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pModelWidget
->getInheritedClassesList()); _container_.control &&
_container_.i != _container_.e; ++_container_.i, _container_
.control ^= 1) for (LibraryTreeItem *pLibraryTreeItem = *_container_
.i; _container_.control; _container_.control = 0)
{
6290 if (!pLibraryTreeItem->isNonExisting()) {
6291 if (!pLibraryTreeItem->getModelWidget()) {
6292 MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel()->showModelWidget(pLibraryTreeItem, false);
6293 }
6294 drawModelInheritedClassShapes(pLibraryTreeItem->getModelWidget(), viewType);
6295 }
6296 GraphicsView *pInheritedGraphicsView, *pGraphicsView;
6297 if (pLibraryTreeItem->isNonExisting()) {
6298 if (viewType == StringHandler::Icon) {
6299 mpIconGraphicsView->addInheritedShapeToList(createNonExistingInheritedShape(mpIconGraphicsView));
6300 } else {
6301 mpDiagramGraphicsView->addInheritedShapeToList(createNonExistingInheritedShape(mpDiagramGraphicsView));
6302 }
6303 } else {
6304 bool primitivesVisible = true;
6305 if (viewType == StringHandler::Icon) {
6306 pInheritedGraphicsView = pLibraryTreeItem->getModelWidget()->getIconGraphicsView();
6307 pGraphicsView = mpIconGraphicsView;
6308 primitivesVisible = pModelWidget->getInheritedClassIconMap().value(index).mPrimitivesVisible;
6309 } else {
6310 pLibraryTreeItem->getModelWidget()->loadDiagramView();
6311 pInheritedGraphicsView = pLibraryTreeItem->getModelWidget()->getDiagramGraphicsView();
6312 pGraphicsView = mpDiagramGraphicsView;
6313 primitivesVisible = pModelWidget->getInheritedClassDiagramMap().value(index).mPrimitivesVisible;
6314 }
6315 // loop through the inherited class shapes
6316 foreach (ShapeAnnotation *pShapeAnnotation, pInheritedGraphicsView->getShapesList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pInheritedGraphicsView
->getShapesList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (ShapeAnnotation *pShapeAnnotation = *_container_.i; _container_
.control; _container_.control = 0)
{
6317 if (primitivesVisible) {
6318 pGraphicsView->addInheritedShapeToList(createInheritedShape(pShapeAnnotation, pGraphicsView));
6319 }
6320 }
6321 }
6322 index++;
6323 }
6324}
6325
6326/*!
6327 * \brief ModelWidget::getModelIconDiagramShapes
6328 * Gets the Modelica model icon & diagram shapes.
6329 * Parses the Modelica icon/diagram annotation and creates shapes for it on appropriate GraphicsView.
6330 * \param viewType
6331 */
6332void ModelWidget::getModelIconDiagramShapes(StringHandler::ViewType viewType)
6333{
6334 OMCProxy *pOMCProxy = MainWindow::instance()->getOMCProxy();
6335 GraphicsView *pGraphicsView = 0;
6336 QString annotationString;
6337 if (viewType == StringHandler::Icon) {
6338 pGraphicsView = mpIconGraphicsView;
6339 if (mpLibraryTreeItem->getAccess() >= LibraryTreeItem::icon) {
6340 annotationString = pOMCProxy->getIconAnnotation(mpLibraryTreeItem->getNameStructure());
6341 }
6342 } else {
6343 pGraphicsView = mpDiagramGraphicsView;
6344 if (mpLibraryTreeItem->getAccess() >= LibraryTreeItem::diagram) {
6345 annotationString = pOMCProxy->getDiagramAnnotation(mpLibraryTreeItem->getNameStructure());
6346 }
6347 }
6348 annotationString = StringHandler::removeFirstLastCurlBrackets(annotationString);
6349 if (annotationString.isEmpty()) {
6350 drawBaseCoOrdinateSystem(this, pGraphicsView);
6351 return;
6352 }
6353 QStringList list = StringHandler::getStrings(annotationString);
6354 // read the coordinate system
6355 if (list.size() < 8) {
6356 drawBaseCoOrdinateSystem(this, pGraphicsView);
6357 return;
6358 }
6359
6360 qreal left = qMin(list.at(0).toFloat(), list.at(2).toFloat());
6361 qreal bottom = qMin(list.at(1).toFloat(), list.at(3).toFloat());
6362 qreal right = qMax(list.at(0).toFloat(), list.at(2).toFloat());
6363 qreal top = qMax(list.at(1).toFloat(), list.at(3).toFloat());
6364 QList<QPointF> extent;
6365 extent << QPointF(left, bottom) << QPointF(right, top);
6366 pGraphicsView->mCoOrdinateSystem.setExtent(extent);
6367 pGraphicsView->mCoOrdinateSystem.setPreserveAspectRatio((list.at(4).compare("true") == 0) ? true : false);
6368 pGraphicsView->mCoOrdinateSystem.setInitialScale(list.at(5).toFloat());
6369 qreal horizontal = list.at(6).toFloat();
6370 qreal vertical = list.at(7).toFloat();
6371 pGraphicsView->mCoOrdinateSystem.setGrid(QPointF(horizontal, vertical));
6372 pGraphicsView->mCoOrdinateSystem.setValid(true);
6373 pGraphicsView->setExtentRectangle(left, bottom, right, top);
6374 pGraphicsView->resize(pGraphicsView->size());
6375 // read the shapes
6376 if (list.size() < 9)
6377 return;
6378 QStringList shapesList = StringHandler::getStrings(StringHandler::removeFirstLastCurlBrackets(list.at(8)), '(', ')');
6379 drawModelIconDiagramShapes(shapesList, pGraphicsView, false);
6380}
6381
6382/*!
6383 * \brief ModelWidget::drawModelInheritedClassComponents
6384 * Loops through the class inhertited classes and draws the components for all.
6385 * \param pModelWidget
6386 * \param viewType
6387 */
6388void ModelWidget::drawModelInheritedClassComponents(ModelWidget *pModelWidget, StringHandler::ViewType viewType)
6389{
6390 foreach (LibraryTreeItem *pLibraryTreeItem, pModelWidget->getInheritedClassesList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pModelWidget
->getInheritedClassesList()); _container_.control &&
_container_.i != _container_.e; ++_container_.i, _container_
.control ^= 1) for (LibraryTreeItem *pLibraryTreeItem = *_container_
.i; _container_.control; _container_.control = 0)
{
6391 if (!pLibraryTreeItem->isNonExisting()) {
6392 drawModelInheritedClassComponents(pLibraryTreeItem->getModelWidget(), viewType);
6393 GraphicsView *pInheritedGraphicsView, *pGraphicsView;
6394 if (viewType == StringHandler::Icon) {
6395 pLibraryTreeItem->getModelWidget()->loadComponents();
6396 pInheritedGraphicsView = pLibraryTreeItem->getModelWidget()->getIconGraphicsView();
6397 pGraphicsView = mpIconGraphicsView;
6398 } else {
6399 pLibraryTreeItem->getModelWidget()->loadDiagramView();
6400 pInheritedGraphicsView = pLibraryTreeItem->getModelWidget()->getDiagramGraphicsView();
6401 pGraphicsView = mpDiagramGraphicsView;
6402 }
6403 foreach (Component *pInheritedComponent, pInheritedGraphicsView->getComponentsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pInheritedGraphicsView
->getComponentsList()); _container_.control && _container_
.i != _container_.e; ++_container_.i, _container_.control ^= 1
) for (Component *pInheritedComponent = *_container_.i; _container_
.control; _container_.control = 0)
{
6404 pGraphicsView->addInheritedComponentToList(createInheritedComponent(pInheritedComponent, pGraphicsView));
6405 }
6406 }
6407 }
6408}
6409
6410/*!
6411 * \brief ModelWidget::getModelComponents
6412 * Gets the components of the model and their annotations.
6413 */
6414void ModelWidget::getModelComponents()
6415{
6416 MainWindow *pMainWindow = MainWindow::instance();
6417 // get the components
6418 mComponentsList = pMainWindow->getOMCProxy()->getComponents(mpLibraryTreeItem->getNameStructure());
6419 // get the components annotations
6420 if (!mComponentsList.isEmpty()) {
6421 mComponentsAnnotationsList = pMainWindow->getOMCProxy()->getComponentAnnotations(mpLibraryTreeItem->getNameStructure());
6422 }
6423}
6424
6425/*!
6426 * \brief ModelWidget::drawModelIconComponents
6427 * Draw the components for icon view and place them in the icon GraphicsView.
6428 */
6429void ModelWidget::drawModelIconComponents()
6430{
6431 MainWindow *pMainWindow = MainWindow::instance();
6432 int i = 0;
6433 foreach (ComponentInfo *pComponentInfo, mComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (ComponentInfo
*pComponentInfo = *_container_.i; _container_.control; _container_
.control = 0)
{
6434 // if the component type is one of the builtin type then don't try to load it here. we load it when loading diagram view.
6435 if (pMainWindow->getOMCProxy()->isBuiltinType(pComponentInfo->getClassName())) {
6436 i++;
6437 continue;
6438 }
6439 LibraryTreeItem *pLibraryTreeItem = 0;
6440 LibraryTreeModel *pLibraryTreeModel = pMainWindow->getLibraryWidget()->getLibraryTreeModel();
6441 pLibraryTreeItem = pLibraryTreeModel->findLibraryTreeItem(pComponentInfo->getClassName());
6442 if (!pLibraryTreeItem) {
6443 pLibraryTreeItem = pLibraryTreeModel->createNonExistingLibraryTreeItem(pComponentInfo->getClassName());
6444 }
6445 // we only load and draw connectors here. Other components are drawn when loading diagram view.
6446 if (pLibraryTreeItem->isConnector()) {
6447 if (!pLibraryTreeItem->isNonExisting() && !pLibraryTreeItem->getModelWidget()) {
6448 pLibraryTreeModel->showModelWidget(pLibraryTreeItem, false);
6449 }
6450 QString annotation = mComponentsAnnotationsList.size() > i ? mComponentsAnnotationsList.at(i) : "";
6451 if (StringHandler::getPlacementAnnotation(annotation).isEmpty()) {
6452 annotation = StringHandler::removeFirstLastCurlBrackets(annotation);
6453 annotation = QString("{%1, Placement(false,0.0,0.0,-10.0,-10.0,10.0,10.0,0.0,-,-,-,-,-,-,)}").arg(annotation);
6454 }
6455 mpIconGraphicsView->addComponentToView(pComponentInfo->getName(), pLibraryTreeItem, annotation, QPointF(0, 0), pComponentInfo, false, true, false);
6456 }
6457 i++;
6458 }
6459}
6460
6461/*!
6462 * \brief ModelWidget::drawModelDiagramComponents
6463 * Draw the components for diagram view and place them in the diagram GraphicsView.
6464 */
6465void ModelWidget::drawModelDiagramComponents()
6466{
6467 MainWindow *pMainWindow = MainWindow::instance();
6468 int i = 0;
6469 foreach (ComponentInfo *pComponentInfo, mComponentsList)for (auto _container_ = QtPrivate::qMakeForeachContainer(mComponentsList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (ComponentInfo
*pComponentInfo = *_container_.i; _container_.control; _container_
.control = 0)
{
6470 LibraryTreeItem *pLibraryTreeItem = 0;
6471 // if the component type is one of the builtin type then don't try to load it.
6472 if (!pMainWindow->getOMCProxy()->isBuiltinType(pComponentInfo->getClassName())) {
6473 LibraryTreeModel *pLibraryTreeModel = pMainWindow->getLibraryWidget()->getLibraryTreeModel();
6474 pLibraryTreeItem = pLibraryTreeModel->findLibraryTreeItem(pComponentInfo->getClassName());
6475 if (!pLibraryTreeItem) {
6476 pLibraryTreeItem = pLibraryTreeModel->createNonExistingLibraryTreeItem(pComponentInfo->getClassName());
6477 }
6478 // we only load and draw non-connectors here. Connector components are drawn in drawModelIconComponents().
6479 if (pLibraryTreeItem->isConnector()) {
6480 i++;
6481 continue;
6482 }
6483 if (!pLibraryTreeItem->isNonExisting() && !pLibraryTreeItem->getModelWidget()) {
6484 pLibraryTreeModel->showModelWidget(pLibraryTreeItem, false);
6485 }
6486 }
6487 QString annotation = mComponentsAnnotationsList.size() > i ? mComponentsAnnotationsList.at(i) : "";
6488 if (StringHandler::getPlacementAnnotation(annotation).isEmpty()) {
6489 annotation = StringHandler::removeFirstLastCurlBrackets(annotation);
6490 annotation = QString("{%1, Placement(false,0.0,0.0,-10.0,-10.0,10.0,10.0,0.0,-,-,-,-,-,-,)}").arg(annotation);
6491 }
6492 mpDiagramGraphicsView->addComponentToView(pComponentInfo->getName(), pLibraryTreeItem, annotation, QPointF(0, 0), pComponentInfo, false, true, false);
6493 i++;
6494 }
6495}
6496
6497/*!
6498 * \brief ModelWidget::drawModelInheritedClassConnections
6499 * Loops through the class inhertited classes and draws the connections for all.
6500 * \param pModelWidget
6501 */
6502void ModelWidget::drawModelInheritedClassConnections(ModelWidget *pModelWidget)
6503{
6504 foreach (LibraryTreeItem *pLibraryTreeItem, pModelWidget->getInheritedClassesList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pModelWidget
->getInheritedClassesList()); _container_.control &&
_container_.i != _container_.e; ++_container_.i, _container_
.control ^= 1) for (LibraryTreeItem *pLibraryTreeItem = *_container_
.i; _container_.control; _container_.control = 0)
{
6505 if (!pLibraryTreeItem->isNonExisting()) {
6506 drawModelInheritedClassConnections(pLibraryTreeItem->getModelWidget());
6507 pLibraryTreeItem->getModelWidget()->loadConnections();
6508 foreach (LineAnnotation *pConnectionLineAnnotation, pLibraryTreeItem->getModelWidget()->getDiagramGraphicsView()->getConnectionsList())for (auto _container_ = QtPrivate::qMakeForeachContainer(pLibraryTreeItem
->getModelWidget()->getDiagramGraphicsView()->getConnectionsList
()); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (LineAnnotation
*pConnectionLineAnnotation = *_container_.i; _container_.control
; _container_.control = 0)
{
6509 mpDiagramGraphicsView->addInheritedConnectionToList(createInheritedConnection(pConnectionLineAnnotation));
6510 }
6511 }
6512 }
6513}
6514
6515/*!
6516 * \brief ModelWidget::getModelTransitions
6517 * Gets the transitions of the model and place them in the diagram GraphicsView.
6518 */
6519void ModelWidget::getModelTransitions()
6520{
6521 QList<QList<QString>> transitions = MainWindow::instance()->getOMCProxy()->getTransitions(mpLibraryTreeItem->getNameStructure());
6522 for (int i = 0 ; i < transitions.size() ; i++) {
6523 QStringList transition = transitions.at(i);
6524 // get start component
6525 Component *pStartComponent = mpDiagramGraphicsView->getComponentObject(transition.at(0));
6526 // show error message if start component is not found.
6527 if (!pStartComponent) {
6528 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
6529 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_TRANSITION)
6530 .arg(transition.at(0)).arg(transition.join(",")),
6531 Helper::scriptingKind, Helper::errorLevel));
6532 continue;
6533 }
6534 // get end component
6535 Component *pEndComponent = mpDiagramGraphicsView->getComponentObject(transition.at(1));
6536 // show error message if end component is not found.
6537 if (!pEndComponent) {
6538 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
6539 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_TRANSITION)
6540 .arg(transition.at(1)).arg(transition.join(",")),
6541 Helper::scriptingKind, Helper::errorLevel));
6542 continue;
6543 }
6544 // get the transition annotations
6545 QStringList shapesList = StringHandler::getStrings(transition.at(7), '(', ')');
6546 // Now parse the shapes available in list
6547 QString lineShape, textShape = "";
6548 foreach (QString shape, shapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(shapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QString shape
= *_container_.i; _container_.control; _container_.control =
0)
{
6549 if (shape.startsWith("Line")) {
6550 lineShape = shape.mid(QString("Line").length());
6551 lineShape = StringHandler::removeFirstLastParentheses(lineShape);
6552 } else if (shape.startsWith("Text")) {
6553 textShape = shape.mid(QString("Text").length());
6554 textShape = StringHandler::removeFirstLastParentheses(textShape);
6555 }
6556 }
6557 LineAnnotation *pTransitionLineAnnotation;
6558 pTransitionLineAnnotation = new LineAnnotation(lineShape, textShape, pStartComponent, pEndComponent, transition.at(2), transition.at(3),
6559 transition.at(4), transition.at(5), transition.at(6), mpDiagramGraphicsView);
6560 pTransitionLineAnnotation->setStartComponentName(transition.at(0));
6561 pTransitionLineAnnotation->setEndComponentName(transition.at(1));
6562 mpUndoStack->push(new AddTransitionCommand(pTransitionLineAnnotation, false));
6563 }
6564}
6565
6566/*!
6567 * \brief ModelWidget::getModelInitialStates
6568 * Gets the initial states of the model and place them in the diagram GraphicsView.
6569 */
6570void ModelWidget::getModelInitialStates()
6571{
6572 QList<QList<QString>> initialStates = MainWindow::instance()->getOMCProxy()->getInitialStates(mpLibraryTreeItem->getNameStructure());
6573 for (int i = 0 ; i < initialStates.size() ; i++) {
6574 QStringList initialState = initialStates.at(i);
6575 // get initial state component
6576 Component *pInitialStateComponent = mpDiagramGraphicsView->getComponentObject(initialState.at(0));
6577 // show error message if initial state component is not found.
6578 if (!pInitialStateComponent) {
6579 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
6580 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_INITIALSTATE)
6581 .arg(initialState.at(0)).arg(initialState.join(",")),
6582 Helper::scriptingKind, Helper::errorLevel));
6583 continue;
6584 }
6585 // get the transition annotations
6586 QStringList shapesList = StringHandler::getStrings(initialState.at(1), '(', ')');
6587 // Now parse the shapes available in list
6588 QString lineShape = "";
6589 foreach (QString shape, shapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(shapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QString shape
= *_container_.i; _container_.control; _container_.control =
0)
{
6590 if (shape.startsWith("Line")) {
6591 lineShape = shape.mid(QString("Line").length());
6592 lineShape = StringHandler::removeFirstLastParentheses(lineShape);
6593 }
6594 }
6595 LineAnnotation *pInitialStateLineAnnotation;
6596 pInitialStateLineAnnotation = new LineAnnotation(lineShape, pInitialStateComponent, mpDiagramGraphicsView);
6597 pInitialStateLineAnnotation->setStartComponentName(initialState.at(0));
6598 pInitialStateLineAnnotation->setEndComponentName("");
6599 mpUndoStack->push(new AddInitialStateCommand(pInitialStateLineAnnotation, false));
6600 }
6601}
6602
6603/*!
6604 * \brief ModelWidget::getMetaModelSubModels
6605 * \brief ModelWidget::detectMultipleDeclarations
6606 * detect multiple declarations of a component instance
6607 */
6608void ModelWidget::detectMultipleDeclarations()
6609{
6610 for (int i = 0 ; i < mComponentsList.size() ; i++) {
6611 for (int j = 0 ; j < mComponentsList.size() ; j++) {
6612 if (i == j) {
6613 j++;
6614 continue;
6615 }
6616 if (mComponentsList[i]->getName().compare(mComponentsList[j]->getName()) == 0) {
6617 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica,
6618 GUIMessages::getMessage(GUIMessages::MULTIPLE_DECLARATIONS_COMPONENT)
6619 .arg(mComponentsList[i]->getName()),
6620 Helper::scriptingKind, Helper::errorLevel));
6621 return;
6622 }
6623 }
6624 }
6625}
6626
6627/*!
6628 * \brief ModelWidget::getCompositeModelName
6629 * Gets the CompositeModel name.
6630 * \return
6631 */
6632QString ModelWidget::getCompositeModelName()
6633{
6634 CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpEditor);
6635 return pCompositeModelEditor->getCompositeModelName();
6636}
6637
6638/*!
6639 * \brief ModelWidget::getCompositeModelSubModels
6640 * Gets the submodels of the TLM and place them in the diagram GraphicsView.
6641 */
6642void ModelWidget::getCompositeModelSubModels()
6643{
6644 QFileInfo fileInfo(mpLibraryTreeItem->getFileName());
6645 CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpEditor);
6646 if (pCompositeModelEditor) {
6647 QDomNodeList subModels = pCompositeModelEditor->getSubModels();
6648 for (int i = 0; i < subModels.size(); i++) {
6649 QString transformation;
6650 QDomElement subModel = subModels.at(i).toElement();
6651 QDomNodeList subModelChildren = subModel.childNodes();
6652 for (int j = 0 ; j < subModelChildren.size() ; j++) {
6653 QDomElement annotationElement = subModelChildren.at(j).toElement();
6654 if (annotationElement.tagName().compare("Annotation") == 0) {
6655 transformation = "Placement(";
6656 transformation.append(annotationElement.attribute("Visible")).append(",");
6657 transformation.append(StringHandler::removeFirstLastCurlBrackets(annotationElement.attribute("Origin"))).append(",");
6658 transformation.append(StringHandler::removeFirstLastCurlBrackets(annotationElement.attribute("Extent"))).append(",");
6659 transformation.append(StringHandler::removeFirstLastCurlBrackets(annotationElement.attribute("Rotation"))).append(",");
6660 transformation.append("-,-,-,-,-,-,");
6661 }
6662 }
6663 // add the component to the the diagram view.
6664 LibraryTreeModel *pLibraryTreeModel = MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel();
6665 LibraryTreeItem *pLibraryTreeItem = pLibraryTreeModel->findLibraryTreeItem(subModel.attribute("Name"));
6666 // get the attibutes of the submodel
6667 ComponentInfo *pComponentInfo = new ComponentInfo;
6668 pComponentInfo->setName(subModel.attribute("Name"));
6669 pComponentInfo->setStartCommand(subModel.attribute("StartCommand"));
6670 bool exactStep;
6671 if ((subModel.attribute("ExactStep").toLower().compare("1") == 0)
6672 || (subModel.attribute("ExactStep").toLower().compare("true") == 0)) {
6673 exactStep = true;
6674 } else {
6675 exactStep = false;
6676 }
6677 pComponentInfo->setExactStep(exactStep);
6678 pComponentInfo->setModelFile(subModel.attribute("ModelFile"));
6679 QString absoluteModelFilePath = QString("%1/%2/%3").arg(fileInfo.absolutePath()).arg(subModel.attribute("Name"))
6680 .arg(subModel.attribute("ModelFile"));
6681 // if ModelFile doesn't exist
6682 if (!QFile::exists(absoluteModelFilePath)) {
6683 QString msg = tr("Unable to find ModelFile <b>%1</b> for SubModel <b>%2</b>. The file location should be <b>%3</b>.")
6684 .arg(subModel.attribute("ModelFile")).arg(subModel.attribute("Name")).arg(absoluteModelFilePath);
6685 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica, msg, Helper::scriptingKind,
6686 Helper::errorLevel));
6687 }
6688 // Geometry File
6689 if (!subModel.attribute("GeometryFile").isEmpty()) {
6690 QString absoluteGeometryFilePath = QString("%1/%2/%3").arg(fileInfo.absolutePath()).arg(subModel.attribute("Name"))
6691 .arg(subModel.attribute("GeometryFile"));
6692 pComponentInfo->setGeometryFile(absoluteGeometryFilePath);
6693 // if GeometryFile doesn't exist
6694 if (!QFile::exists(absoluteGeometryFilePath)) {
6695 QString msg = tr("Unable to find GeometryFile <b>%1</b> for SubModel <b>%2</b>. The file location should be <b>%3</b>.")
6696 .arg(subModel.attribute("GeometryFile")).arg(subModel.attribute("Name")).arg(absoluteGeometryFilePath);
6697 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::Modelica, msg, Helper::scriptingKind,
6698 Helper::errorLevel));
6699 }
6700 }
6701 pComponentInfo->setPosition(subModel.attribute("Position"));
6702 pComponentInfo->setAngle321(subModel.attribute("Angle321"));
6703 // add submodel as component to view.
6704 mpDiagramGraphicsView->addComponentToView(subModel.attribute("Name"), pLibraryTreeItem, transformation, QPointF(0.0, 0.0), pComponentInfo, false, true, false);
6705 }
6706 }
6707}
6708
6709/*!
6710 * \brief ModelWidget::getCompositeModelConnections
6711 * Reads the TLM connections and draws them.
6712 */
6713void ModelWidget::getCompositeModelConnections()
6714{
6715 MessagesWidget *pMessagesWidget = MessagesWidget::instance();
6716 CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpEditor);
6717 QDomNodeList connections = pCompositeModelEditor->getConnections();
6718 for (int i = 0; i < connections.size(); i++) {
6719 QDomElement connection = connections.at(i).toElement();
6720 // get start submodel
6721 QStringList startConnectionList = connection.attribute("From").split(".");
6722 if (startConnectionList.size() < 2) {
6723 continue;
6724 }
6725 Component *pStartSubModelComponent = mpDiagramGraphicsView->getComponentObject(startConnectionList.at(0));
6726 if (!pStartSubModelComponent) {
6727 pMessagesWidget->addGUIMessage(MessageItem(MessageItem::Modelica,
6728 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_CONNECTION).arg(startConnectionList.at(0))
6729 .arg(connection.attribute("From")), Helper::scriptingKind, Helper::errorLevel));
6730 continue;
6731 }
6732 // get start interface point
6733 Component *pStartInterfacePointComponent = getConnectorComponent(pStartSubModelComponent, startConnectionList.at(1));
6734 if (!pStartInterfacePointComponent) {
6735 pMessagesWidget->addGUIMessage(MessageItem(MessageItem::Modelica,
6736 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_CONNECTION).arg(startConnectionList.at(1))
6737 .arg(connection.attribute("From")), Helper::scriptingKind, Helper::errorLevel));
6738 continue;
6739 }
6740 // get end submodel
6741 QStringList endConnectionList = connection.attribute("To").split(".");
6742 if (endConnectionList.size() < 2) {
6743 continue;
6744 }
6745 Component *pEndSubModelComponent = mpDiagramGraphicsView->getComponentObject(endConnectionList.at(0));
6746 if (!pEndSubModelComponent) {
6747 pMessagesWidget->addGUIMessage(MessageItem(MessageItem::Modelica,
6748 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_CONNECTION).arg(endConnectionList.at(0))
6749 .arg(connection.attribute("To")), Helper::scriptingKind, Helper::errorLevel));
6750 continue;
6751 }
6752 // get end interface point
6753 Component *pEndInterfacePointComponent = getConnectorComponent(pEndSubModelComponent, endConnectionList.at(1));
6754 if (!pEndInterfacePointComponent) {
6755 pMessagesWidget->addGUIMessage(MessageItem(MessageItem::Modelica,
6756 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_CONNECTION).arg(endConnectionList.at(1))
6757 .arg(connection.attribute("To")), Helper::scriptingKind, Helper::errorLevel));
6758 continue;
6759 }
6760 // default connection annotation
6761 QString annotation = QString("{Line(true,{0.0,0.0},0,%1,{0,0,0},LinePattern.Solid,0.25,{Arrow.None,Arrow.None},3,Smooth.None)}");
6762 QStringList shapesList;
6763 bool annotationFound = false;
6764 // check if connection has annotaitons defined
6765 QDomNodeList connectionChildren = connection.childNodes();
6766 for (int j = 0 ; j < connectionChildren.size() ; j++) {
6767 QDomElement annotationElement = connectionChildren.at(j).toElement();
6768 if (annotationElement.tagName().compare("Annotation") == 0) {
6769 annotationFound = true;
6770 shapesList = StringHandler::getStrings(StringHandler::removeFirstLastCurlBrackets(QString(annotation).arg(annotationElement.attribute("Points"))), '(', ')');
6771 }
6772 }
6773 if (!annotationFound) {
6774 QString point = QString("{%1,%2}");
6775 QStringList points;
6776 QPointF startPoint = pStartInterfacePointComponent->mapToScene(pStartInterfacePointComponent->boundingRect().center());
6777 points.append(point.arg(startPoint.x()).arg(startPoint.y()));
6778 QPointF endPoint = pEndInterfacePointComponent->mapToScene(pEndInterfacePointComponent->boundingRect().center());
6779 points.append(point.arg(endPoint.x()).arg(endPoint.y()));
6780 QString pointsString = QString("{%1}").arg(points.join(","));
6781 shapesList = StringHandler::getStrings(StringHandler::removeFirstLastCurlBrackets(QString(annotation).arg(pointsString)), '(', ')');
6782 }
6783 // Now parse the shapes available in list
6784 QString lineShape = "";
6785 foreach (QString shape, shapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(shapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QString shape
= *_container_.i; _container_.control; _container_.control =
0)
{
6786 if (shape.startsWith("Line")) {
6787 lineShape = shape.mid(QString("Line").length());
6788 lineShape = StringHandler::removeFirstLastParentheses(lineShape);
6789 break; // break the loop once we have got the line annotation.
6790 }
6791 }
6792 LineAnnotation *pConnectionLineAnnotation = new LineAnnotation(lineShape, pStartInterfacePointComponent, pEndInterfacePointComponent,
6793 mpDiagramGraphicsView);
6794 pConnectionLineAnnotation->setStartComponentName(connection.attribute("From"));
6795 pConnectionLineAnnotation->setEndComponentName(connection.attribute("To"));
6796 pConnectionLineAnnotation->setDelay(connection.attribute("Delay"));
6797 pConnectionLineAnnotation->setZf(connection.attribute("Zf"));
6798 pConnectionLineAnnotation->setZfr(connection.attribute("Zfr"));
6799 pConnectionLineAnnotation->setAlpha(connection.attribute("alpha"));
6800 // check if interfaces are aligned
6801 bool aligned = pCompositeModelEditor->interfacesAligned(pConnectionLineAnnotation->getStartComponentName(),
6802 pConnectionLineAnnotation->getEndComponentName());
6803 pConnectionLineAnnotation->setAligned(aligned);
6804
6805 CompositeModelEditor *pEditor = dynamic_cast<CompositeModelEditor*>(mpEditor);
6806 if(pEditor->getInterfaceCausality(pConnectionLineAnnotation->getEndComponentName()) ==
6807 StringHandler::getTLMCausality(StringHandler::TLMInput)) {
6808 pConnectionLineAnnotation->setLinePattern(StringHandler::LineDash);
6809 pConnectionLineAnnotation->setEndArrow(StringHandler::ArrowFilled);
6810 //pConnectionLineAnnotation->update();
6811 //pConnectionLineAnnotation->handleComponentMoved();
6812 }
6813 else if(pEditor->getInterfaceCausality(pConnectionLineAnnotation->getEndComponentName()) ==
6814 StringHandler::getTLMCausality(StringHandler::TLMOutput)) {
6815 pConnectionLineAnnotation->setLinePattern(StringHandler::LineDash);
6816 pConnectionLineAnnotation->setStartArrow(StringHandler::ArrowFilled);
6817 //pConnectionLineAnnotation->update();
6818 //pConnectionLineAnnotation->handleComponentMoved();
6819 }
6820
6821 mpUndoStack->push(new AddConnectionCommand(pConnectionLineAnnotation, false));
6822 }
6823}
6824
6825void ModelWidget::drawOMSModelIconElements()
6826{
6827 if (mpLibraryTreeItem->isTopLevel()) {
6828 return;
6829 } else if (mpLibraryTreeItem->isSystemElement() || mpLibraryTreeItem->isComponentElement()) {
6830 drawOMSModelElement();
6831 // draw connectors
6832 for (int i = 0 ; i < mpLibraryTreeItem->childrenSize() ; i++) {
6833 LibraryTreeItem *pChildLibraryTreeItem = mpLibraryTreeItem->childAt(i);
6834 if (pChildLibraryTreeItem->getOMSConnector()
6835 && (pChildLibraryTreeItem->getOMSConnector()->causality == oms_causality_input
6836 || pChildLibraryTreeItem->getOMSConnector()->causality == oms_causality_output)) {
6837 double x = 0.5;
6838 double y = 0.5;
6839 if (pChildLibraryTreeItem->getOMSConnector()->geometry) {
6840 x = pChildLibraryTreeItem->getOMSConnector()->geometry->x;
6841 y = pChildLibraryTreeItem->getOMSConnector()->geometry->y;
6842 }
6843 QString annotation = QString("Placement(true,%1,%2,-10.0,-10.0,10.0,10.0,0,%1,%2,-10.0,-10.0,10.0,10.0,)")
6844 .arg(Utilities::mapToCoOrdinateSystem(x, 0, 1, -100, 100))
6845 .arg(Utilities::mapToCoOrdinateSystem(y, 0, 1, -100, 100));
6846 AddConnectorCommand *pAddConnectorCommand = new AddConnectorCommand(pChildLibraryTreeItem->getName(), pChildLibraryTreeItem,
6847 annotation, mpIconGraphicsView, true,
6848 pChildLibraryTreeItem->getOMSConnector()->causality,
6849 pChildLibraryTreeItem->getOMSConnector()->type);
6850 mpUndoStack->push(pAddConnectorCommand);
6851 } else if (pChildLibraryTreeItem->getOMSBusConnector()) {
6852 double x = 0.5;
6853 double y = 0.5;
6854 if (pChildLibraryTreeItem->getOMSBusConnector()->geometry) {
6855 x = pChildLibraryTreeItem->getOMSBusConnector()->geometry->x;
6856 y = pChildLibraryTreeItem->getOMSBusConnector()->geometry->y;
6857 }
6858 QString annotation = QString("Placement(true,%1,%2,-10.0,-10.0,10.0,10.0,0,%1,%2,-10.0,-10.0,10.0,10.0,)")
6859 .arg(Utilities::mapToCoOrdinateSystem(x, 0, 1, -100, 100))
6860 .arg(Utilities::mapToCoOrdinateSystem(y, 0, 1, -100, 100));
6861 AddBusCommand *pAddBusCommand = new AddBusCommand(pChildLibraryTreeItem->getName(), pChildLibraryTreeItem,
6862 annotation, mpIconGraphicsView, true);
6863 mpUndoStack->push(pAddBusCommand);
6864 // assoicated the bus component with each of its connector component
6865 associateBusWithConnectors(pChildLibraryTreeItem->getName());
6866 } else if (pChildLibraryTreeItem->getOMSTLMBusConnector()) {
6867 double x = 0.5;
6868 double y = 0.5;
6869 if (pChildLibraryTreeItem->getOMSTLMBusConnector()->geometry) {
6870 x = pChildLibraryTreeItem->getOMSTLMBusConnector()->geometry->x;
6871 y = pChildLibraryTreeItem->getOMSTLMBusConnector()->geometry->y;
6872 }
6873 QString annotation = QString("Placement(true,%1,%2,-10.0,-10.0,10.0,10.0,0,%1,%2,-10.0,-10.0,10.0,10.0,)")
6874 .arg(Utilities::mapToCoOrdinateSystem(x, 0, 1, -100, 100))
6875 .arg(Utilities::mapToCoOrdinateSystem(y, 0, 1, -100, 100));
6876 AddTLMBusCommand *pAddTLMBusCommand = new AddTLMBusCommand(pChildLibraryTreeItem->getName(), pChildLibraryTreeItem,
6877 annotation, mpIconGraphicsView, true,
6878 pChildLibraryTreeItem->getOMSTLMBusConnector()->domain,
6879 pChildLibraryTreeItem->getOMSTLMBusConnector()->dimensions,
6880 pChildLibraryTreeItem->getOMSTLMBusConnector()->interpolation);
6881 mpUndoStack->push(pAddTLMBusCommand);
6882 // assoicated the bus component with each of its connector component
6883 associateBusWithConnectors(pChildLibraryTreeItem->getName());
6884 }
6885 }
6886 }
6887}
6888
6889void ModelWidget::drawOMSModelDiagramElements()
6890{
6891 if (mpLibraryTreeItem->isTopLevel() || mpLibraryTreeItem->isSystemElement()) {
6892 for (int i = 0 ; i < mpLibraryTreeItem->childrenSize() ; i++) {
6893 LibraryTreeItem *pChildLibraryTreeItem = mpLibraryTreeItem->childAt(i);
6894 /* We only draw the elements here
6895 * Connectors are already drawn as part of ModelWidget::drawOMSModelIconElements();
6896 */
6897 if (pChildLibraryTreeItem->getOMSElement() && pChildLibraryTreeItem->getOMSElement()->geometry) {
6898 // check if we have zero width and height
6899 double x1, y1, x2, y2;
6900 x1 = pChildLibraryTreeItem->getOMSElement()->geometry->x1;
6901 y1 = pChildLibraryTreeItem->getOMSElement()->geometry->y1;
6902 x2 = pChildLibraryTreeItem->getOMSElement()->geometry->x2;
6903 y2 = pChildLibraryTreeItem->getOMSElement()->geometry->y2;
6904 double width = x2 - x1;
6905 double height = y2 - y1;
6906 if (width <= 0 && height <= 0) {
6907 x1 = -10.0;
6908 y1 = -10.0;
6909 x2 = 10.0;
6910 y2 = 10.0;
6911 }
6912 // Load the ModelWidget if not loaded already
6913 if (!pChildLibraryTreeItem->getModelWidget()) {
6914 MainWindow::instance()->getLibraryWidget()->getLibraryTreeModel()->showModelWidget(pChildLibraryTreeItem, false);
6915 }
6916
6917 QString annotation = QString("Placement(true,-,-,%1,%2,%3,%4,%5,-,-,-,-,-,-,)")
6918 .arg(x1).arg(y1)
6919 .arg(x2).arg(y2)
6920 .arg(pChildLibraryTreeItem->getOMSElement()->geometry->rotation);
6921
6922 if (pChildLibraryTreeItem->isSystemElement()) {
6923 AddSystemCommand *pAddSystemCommand = new AddSystemCommand(pChildLibraryTreeItem->getName(), pChildLibraryTreeItem,
6924 annotation, mpDiagramGraphicsView, true,
6925 pChildLibraryTreeItem->getSystemType());
6926 mpUndoStack->push(pAddSystemCommand);
6927 } else if (pChildLibraryTreeItem->isComponentElement()) {
6928 AddSubModelCommand *pAddSubModelCommand = new AddSubModelCommand(pChildLibraryTreeItem->getName(), "", "", pChildLibraryTreeItem,
6929 annotation, true, mpDiagramGraphicsView);
6930 mpUndoStack->push(pAddSubModelCommand);
6931 }
6932 }
6933 }
6934 }
6935}
6936
6937/*!
6938 * \brief ModelWidget::drawOMSModelConnections
6939 * Gets the OMSimulator model connections and draws them.
6940 */
6941void ModelWidget::drawOMSModelConnections()
6942{
6943 if (mpLibraryTreeItem->isSystemElement()) {
6944 MessagesWidget *pMessagesWidget = MessagesWidget::instance();
6945 oms_connection_t** pConnections = NULL__null;
6946 if (OMSProxy::instance()->getConnections(mpLibraryTreeItem->getNameStructure(), &pConnections)) {
6947 for (int i = 0 ; pConnections[i] ; i++) {
6948 // get start component
6949 QStringList startConnectionList = StringHandler::makeVariableParts(QString(pConnections[i]->conA));
6950 if (startConnectionList.size() < 1) {
6951 continue;
6952 }
6953 Component *pStartComponent = mpDiagramGraphicsView->getComponentObject(startConnectionList.at(0));
6954 if (!pStartComponent) {
6955 pMessagesWidget->addGUIMessage(MessageItem(MessageItem::Modelica,
6956 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_CONNECTION)
6957 .arg(startConnectionList.at(0)).arg(pConnections[i]->conA),
6958 Helper::scriptingKind, Helper::errorLevel));
6959 continue;
6960 }
6961 Component *pStartConnectorComponent, *pStartBusConnectorComponent;
6962 if (startConnectionList.size() > 1) {
6963 // get start connector component
6964 QString startConnectorName = StringHandler::removeFirstWordAfterDot(QString(pConnections[i]->conA));
6965 pStartConnectorComponent = getConnectorComponent(pStartComponent, startConnectorName);
6966 if (!pStartConnectorComponent) {
6967 pMessagesWidget->addGUIMessage(MessageItem(MessageItem::Modelica,
6968 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_CONNECTION)
6969 .arg(startConnectorName).arg(pConnections[i]->conA),
6970 Helper::scriptingKind, Helper::errorLevel));
6971 continue;
6972 }
6973 pStartBusConnectorComponent = pStartConnectorComponent;
6974 // if the connector is part of a bus connector
6975 if (pStartConnectorComponent->isInBus()) {
6976 pStartBusConnectorComponent = getConnectorComponent(pStartComponent, pStartConnectorComponent->getBusComponent()->getName());
6977 }
6978 } else {
6979 pStartConnectorComponent = pStartComponent;
6980 pStartBusConnectorComponent = pStartConnectorComponent;
6981 // if the connector is part of a bus connector
6982 if (pStartConnectorComponent->isInBus()) {
6983 pStartBusConnectorComponent = pStartConnectorComponent->getBusComponent();
6984 }
6985 }
6986
6987 // get end component
6988 QStringList endConnectionList = StringHandler::makeVariableParts(QString(pConnections[i]->conB));
6989 if (endConnectionList.size() < 1) {
6990 continue;
6991 }
6992 Component *pEndComponent = mpDiagramGraphicsView->getComponentObject(endConnectionList.at(0));
6993 if (!pEndComponent) {
6994 pMessagesWidget->addGUIMessage(MessageItem(MessageItem::Modelica,
6995 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_CONNECTION)
6996 .arg(endConnectionList.at(0)).arg(pConnections[i]->conB),
6997 Helper::scriptingKind, Helper::errorLevel));
6998 continue;
6999 }
7000 Component *pEndConnectorComponent, *pEndBusConnectorComponent;
7001 if (endConnectionList.size() > 1) {
7002 // get end connector component
7003 QString endConnectorName = StringHandler::removeFirstWordAfterDot(QString(pConnections[i]->conB));
7004 pEndConnectorComponent = getConnectorComponent(pEndComponent, endConnectorName);
7005 if (!pEndConnectorComponent) {
7006 pMessagesWidget->addGUIMessage(MessageItem(MessageItem::Modelica,
7007 GUIMessages::getMessage(GUIMessages::UNABLE_FIND_COMPONENT_IN_CONNECTION)
7008 .arg(endConnectorName).arg(pConnections[i]->conB),
7009 Helper::scriptingKind, Helper::errorLevel));
7010 continue;
7011 }
7012 pEndBusConnectorComponent = pEndConnectorComponent;
7013 // if the connector is part of a bus connector
7014 if (pEndConnectorComponent->isInBus()) {
7015 pEndBusConnectorComponent = getConnectorComponent(pEndComponent, pEndConnectorComponent->getBusComponent()->getName());
7016 }
7017 } else {
7018 pEndConnectorComponent = pEndComponent;
7019 pEndBusConnectorComponent = pEndConnectorComponent;
7020 // if the connector is part of a bus connector
7021 if (pEndConnectorComponent->isInBus()) {
7022 pEndBusConnectorComponent = pEndConnectorComponent->getBusComponent();
7023 }
7024 }
7025
7026 // default connection annotation
7027 QString annotation = QString("{Line(true,{0.0,0.0},0,%1,{0,0,0},LinePattern.Solid,0.25,{Arrow.None,Arrow.None},3,Smooth.None)}");
7028 QStringList shapesList;
7029 QString point = QString("{%1,%2}");
7030 QStringList points;
7031 if (pConnections[i]->geometry && pConnections[i]->geometry->n > 0) {
7032 for (unsigned int j = 0 ; j < pConnections[i]->geometry->n ; j++) {
7033 points.append(point.arg(pConnections[i]->geometry->pointsX[j]).arg(pConnections[i]->geometry->pointsY[j]));
7034 }
7035 }
7036 QPointF startPoint = pStartBusConnectorComponent->mapToScene(pStartBusConnectorComponent->boundingRect().center());
7037 points.prepend(point.arg(startPoint.x()).arg(startPoint.y()));
7038 QPointF endPoint = pEndBusConnectorComponent->mapToScene(pEndBusConnectorComponent->boundingRect().center());
7039 points.append(point.arg(endPoint.x()).arg(endPoint.y()));
7040 QString pointsString = QString("{%1}").arg(points.join(","));
7041 shapesList = StringHandler::getStrings(StringHandler::removeFirstLastCurlBrackets(QString(annotation).arg(pointsString)), '(', ')');
7042 // Now parse the shapes available in list
7043 QString lineShape = "";
7044 foreach (QString shape, shapesList)for (auto _container_ = QtPrivate::qMakeForeachContainer(shapesList
); _container_.control && _container_.i != _container_
.e; ++_container_.i, _container_.control ^= 1) for (QString shape
= *_container_.i; _container_.control; _container_.control =
0)
{
7045 if (shape.startsWith("Line")) {
7046 lineShape = shape.mid(QString("Line").length());
7047 lineShape = StringHandler::removeFirstLastParentheses(lineShape);
7048 break; // break the loop once we have got the line annotation.
7049 }
7050 }
7051
7052 LineAnnotation *pConnectionLineAnnotation = new LineAnnotation(lineShape, pStartBusConnectorComponent,
7053 pEndBusConnectorComponent, mpDiagramGraphicsView);
7054 if (pStartConnectorComponent->getLibraryTreeItem()) {
7055 pConnectionLineAnnotation->setStartComponentName(pStartConnectorComponent->getLibraryTreeItem()->getNameStructure());
7056 }
7057 if (pEndConnectorComponent->getLibraryTreeItem()) {
7058 pConnectionLineAnnotation->setEndComponentName(pEndConnectorComponent->getLibraryTreeItem()->getNameStructure());
7059 }
7060 pConnectionLineAnnotation->setOMSConnectionType(pConnections[i]->type);
7061 mpUndoStack->push(new AddConnectionCommand(pConnectionLineAnnotation, false));
7062 // Check if the connectors of the connection belongs to a bus
7063 if (pStartConnectorComponent->isInBus() && pEndConnectorComponent->isInBus()) {
7064 pConnectionLineAnnotation->setVisible(false);
7065 }
7066 // Check if bus connection
7067 if (pConnections[i]->type == oms_connection_bus || pConnections[i]->type == oms_connection_tlm) {
7068 pConnectionLineAnnotation->setLineThickness(0.5);
7069 }
7070 }
7071 }
7072 }
7073}
7074
7075/*!
7076 * \brief ModelWidget::associateBusWithConnector
7077 * Helper function for ModelWidget::associateBusWithConnector(busName, connectorName)
7078 * \param busName
7079 * \param connectorName
7080 * \param pGraphicsView
7081 */
7082void ModelWidget::associateBusWithConnector(QString busName, QString connectorName, GraphicsView *pGraphicsView)
7083{
7084 // get the bus component
7085 Component *pBusComponent = pGraphicsView->getComponentObject(busName);
7086 // get the connector component
7087 Component *pConnectorComponent = pGraphicsView->getComponentObject(connectorName);
7088 if (pBusComponent && pConnectorComponent) {
7089 pConnectorComponent->setBusComponent(pBusComponent);
7090 }
7091}
7092
7093/*!
7094 * \brief ModelWidget::dissociateBusWithConnector
7095 * Helper function for ModelWidget::dissociateBusWithConnector(busName, connectorName)
7096 * \param busName
7097 * \param connectorName
7098 * \param pGraphicsView
7099 */
7100void ModelWidget::dissociateBusWithConnector(QString busName, QString connectorName, GraphicsView *pGraphicsView)
7101{
7102 // get the bus component
7103 Component *pBusComponent = pGraphicsView->getComponentObject(busName);
7104 Component *pConnectorComponent = pGraphicsView->getComponentObject(connectorName);
7105 if (pBusComponent && pConnectorComponent) {
7106 pConnectorComponent->setBusComponent(0);
7107 }
7108}
7109
7110/*!
7111 * \brief ModelWidget::associateBusWithConnectors
7112 * Helper function for ModelWidget::associateBusWithConnectors(busName)
7113 * \param pBusComponent
7114 * \param pGraphicsView
7115 */
7116void ModelWidget::associateBusWithConnectors(Component *pBusComponent, GraphicsView *pGraphicsView)
7117{
7118 if (pBusComponent && pBusComponent->getLibraryTreeItem() && pBusComponent->getLibraryTreeItem()->getOMSBusConnector()) {
7119 oms_busconnector_t *pBusConnector = pBusComponent->getLibraryTreeItem()->getOMSBusConnector();
7120 if (pBusConnector->connectors) {
7121 for (int i = 0 ; pBusConnector->connectors[i] ; i++) {
7122 Component *pConnectorComponent = pGraphicsView->getComponentObject(QString(pBusConnector->connectors[i]));
7123 if (pConnectorComponent) {
7124 pConnectorComponent->setBusComponent(pBusComponent);
7125 }
7126 }
7127 }
7128 } else if (pBusComponent && pBusComponent->getLibraryTreeItem() && pBusComponent->getLibraryTreeItem()->getOMSTLMBusConnector()) {
7129 oms_tlmbusconnector_t *pTLMBusConnector = pBusComponent->getLibraryTreeItem()->getOMSTLMBusConnector();
7130 if (pTLMBusConnector->connectornames) {
7131 for (int i = 0 ; pTLMBusConnector->connectornames[i] ; i++) {
7132 Component *pConnectorComponent = pGraphicsView->getComponentObject(QString(pTLMBusConnector->connectornames[i]));
7133 if (pConnectorComponent) {
7134 pConnectorComponent->setBusComponent(pBusComponent);
7135 }
7136 }
7137 }
7138 }
7139}
7140
7141/*!
7142 * \brief ModelWidget::showIconView
7143 * \param checked
7144 * Slot activated when mpIconViewToolButton toggled SIGNAL is raised. Shows the icon view.
7145 */
7146void ModelWidget::showIconView(bool checked)
7147{
7148 // validate the modelica text before switching to icon view
7149 if (checked) {
7150 if (!validateText(&mpLibraryTreeItem)) {
7151 mpTextViewToolButton->setChecked(true);
7152 return;
7153 }
7154 }
7155 QMdiSubWindow *pSubWindow = mpModelWidgetContainer->getCurrentMdiSubWindow();
7156 if (pSubWindow) {
7157 pSubWindow->setWindowIcon(ResourceCache::getIcon(":/Resources/icons/model.svg"));
7158 }
7159 mpModelWidgetContainer->currentModelWidgetChanged(mpModelWidgetContainer->getCurrentMdiSubWindow());
7160 mpIconGraphicsView->setFocus(Qt::ActiveWindowFocusReason);
7161 if (!checked || (checked && mpIconGraphicsView->isVisible())) {
7162 return;
7163 }
7164 mpViewTypeLabel->setText(StringHandler::getViewType(StringHandler::Icon));
7165 mpDiagramGraphicsView->hide();
7166 if (mpEditor) {
7167 mpEditor->hide();
7168 }
7169 mpIconGraphicsView->show();
7170 mpIconGraphicsView->setFocus();
7171 mpModelWidgetContainer->setPreviousViewType(StringHandler::Icon);
7172 updateUndoRedoActions();
7173 MainWindow::instance()->getPositionLabel()->clear();
7174}
7175
7176/*!
7177 * \brief ModelWidget::showDiagramView
7178 * \param checked
7179 * Slot activated when mpDiagramViewToolButton toggled SIGNAL is raised. Shows the diagram view.
7180 */
7181void ModelWidget::showDiagramView(bool checked)
7182{
7183 // validate the modelica text before switching to diagram view
7184 if (checked) {
7185 if (!validateText(&mpLibraryTreeItem)) {
7186 mpTextViewToolButton->setChecked(true);
7187 return;
7188 }
7189 }
7190 QMdiSubWindow *pSubWindow = mpModelWidgetContainer->getCurrentMdiSubWindow();
7191 if (pSubWindow) {
7192 pSubWindow->setWindowIcon(ResourceCache::getIcon(":/Resources/icons/modeling.png"));
7193 }
7194 mpModelWidgetContainer->currentModelWidgetChanged(mpModelWidgetContainer->getCurrentMdiSubWindow());
7195 mpDiagramGraphicsView->setFocus(Qt::ActiveWindowFocusReason);
7196 if (!checked || (checked && mpDiagramGraphicsView->isVisible())) {
7197 return;
7198 }
7199 mpViewTypeLabel->setText(StringHandler::getViewType(StringHandler::Diagram));
7200 if (mpIconGraphicsView) {
7201 mpIconGraphicsView->hide();
7202 }
7203 if (mpEditor) {
7204 mpEditor->hide();
7205 }
7206 mpDiagramGraphicsView->show();
7207 mpDiagramGraphicsView->setFocus();
7208 mpModelWidgetContainer->setPreviousViewType(StringHandler::Diagram);
7209 updateUndoRedoActions();
7210 MainWindow::instance()->getPositionLabel()->clear();
7211}
7212
7213/*!
7214 * \brief ModelWidget::showTextView
7215 * \param checked
7216 * Slot activated when mpTextViewToolButton toggled SIGNAL is raised. Shows the text view.
7217 */
7218void ModelWidget::showTextView(bool checked)
7219{
7220 if (!checked || (checked && mpEditor->isVisible())) {
7221 return;
7222 }
7223 if (QMdiSubWindow *pSubWindow = mpModelWidgetContainer->getCurrentMdiSubWindow()) {
7224 pSubWindow->setWindowIcon(ResourceCache::getIcon(":/Resources/icons/modeltext.svg"));
7225 }
7226 mpModelWidgetContainer->currentModelWidgetChanged(mpModelWidgetContainer->getCurrentMdiSubWindow());
7227 mpViewTypeLabel->setText(StringHandler::getViewType(StringHandler::ModelicaText));
7228 if (mpIconGraphicsView) {
7229 mpIconGraphicsView->hide();
7230 }
7231 mpDiagramGraphicsView->hide();
7232 if (mpEditor) {
7233 mpEditor->show();
7234 mpEditor->getPlainTextEdit()->setFocus(Qt::ActiveWindowFocusReason);
7235 mpEditor->getPlainTextEdit()->updateCursorPosition();
7236 }
7237 mpModelWidgetContainer->setPreviousViewType(StringHandler::ModelicaText);
7238 updateUndoRedoActions();
7239}
7240
7241void ModelWidget::makeFileWritAble()
7242{
7243 const QString &fileName = mpLibraryTreeItem->getFileName();
7244 const bool permsOk = QFile::setPermissions(fileName, QFile::permissions(fileName) | QFile::WriteUser);
7245 if (!permsOk)
7246 QMessageBox::warning(this, tr("Cannot Set Permissions"), tr("Cannot set permissions to writable."));
7247 else
7248 {
7249 mpLibraryTreeItem->setReadOnly(false);
7250 mpFileLockToolButton->setText(tr("File is writable"));
7251 mpFileLockToolButton->setIcon(ResourceCache::getIcon(":/Resources/icons/unlock.svg"));
7252 mpFileLockToolButton->setEnabled(false);
7253 mpFileLockToolButton->setToolTip(mpFileLockToolButton->text());
7254 }
7255}
7256
7257void ModelWidget::showDocumentationView()
7258{
7259 // validate the modelica text before switching to documentation view
7260 if (!validateText(&mpLibraryTreeItem)) {
7261 mpTextViewToolButton->setChecked(true);
7262 return;
7263 }
7264 MainWindow::instance()->getDocumentationWidget()->showDocumentation(getLibraryTreeItem());
7265 bool state = MainWindow::instance()->getDocumentationDockWidget()->blockSignals(true);
7266 MainWindow::instance()->getDocumentationDockWidget()->show();
7267 MainWindow::instance()->getDocumentationDockWidget()->blockSignals(state);
7268}
7269
7270/*!
7271 * \brief ModelWidget::compositeModelEditorTextChanged
7272 * Called when CompositeModelEditor text has been changed by user manually.\n
7273 * Updates the LibraryTreeItem and ModelWidget with new changes.
7274 * \return
7275 */
7276bool ModelWidget::compositeModelEditorTextChanged()
7277{
7278 MessageHandler *pMessageHandler = new MessageHandler;
7279 Utilities::parseCompositeModelText(pMessageHandler, mpEditor->getPlainTextEdit()->toPlainText());
7280 if (pMessageHandler->isFailed()) {
7281 MessagesWidget::instance()->addGUIMessage(MessageItem(MessageItem::CompositeModel, getLibraryTreeItem()->getName(), false,
7282 pMessageHandler->line(), pMessageHandler->column(), 0, 0,
7283 pMessageHandler->statusMessage(), Helper::syntaxKind, Helper::errorLevel));
7284 delete pMessageHandler;
7285 return false;
7286 }
7287 delete pMessageHandler;
7288 // update the xml document with new accepted text.
7289 CompositeModelEditor *pCompositeModelEditor = dynamic_cast<CompositeModelEditor*>(mpEditor);
7290 pCompositeModelEditor->setXmlDocumentContent(mpEditor->getPlainTextEdit()->toPlainText());
7291 /* get the model components and connectors */
7292 reDrawModelWidget();
7293 return true;
7294}
7295
7296/*!
7297 * \brief ModelWidget::handleCanUndoChanged
7298 * Enables/disables the Edit menu Undo action depending on the stack situation.
7299 * \param canUndo
7300 */
7301void ModelWidget::handleCanUndoChanged(bool canUndo)
7302{
7303 Q_UNUSED(canUndo)(void)canUndo;;
7304 updateUndoRedoActions();
7305}
7306
7307/*!
7308 * \brief ModelWidget::handleCanRedoChanged
7309 * Enables/disables the Edit menu Redo action depending on the stack situation.
7310 * \param canRedo
7311 */
7312void ModelWidget::handleCanRedoChanged(bool canRedo)
7313{
7314 Q_UNUSED(canRedo)(void)canRedo;;
7315 updateUndoRedoActions();
7316}
7317
7318void ModelWidget::closeEvent(QCloseEvent *event)
7319{
7320 Q_UNUSED(event)(void)event;;
7321 mpModelWidgetContainer->removeSubWindow(this);
7322}
7323
7324/*!
7325 * \brief addCloseActionsToSubWindowSystemMenu
7326 * Adds the "Close All Windows" and "Close All Windows But This" actions to QMdiSubWindow system menu.
7327 */
7328void addCloseActionsToSubWindowSystemMenu(QMdiSubWindow *pMdiSubWindow)
7329{
7330 /* ticket:3295 Add the "Close All Windows" and "Close All Windows But This" to system menu. */
7331 QMenu *pMenu = pMdiSubWindow->systemMenu();
7332 pMenu->addAction(MainWindow::instance()->getCloseAllWindowsAction());
7333 pMenu->addAction(MainWindow::instance()->getCloseAllWindowsButThisAction());
7334}
7335
7336ModelWidgetContainer::ModelWidgetContainer(QWidget *pParent)
7337 : QMdiArea(pParent), mPreviousViewType(StringHandler::NoView), mShowGridLines(true)
7338{
7339 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
7340 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
7341 setActivationOrder(QMdiArea::ActivationHistoryOrder);
7342 setDocumentMode(true);
7343#if QT_VERSION((5<<16)|(9<<8)|(5)) >= 0x040800
7344 setTabsClosable(true);
7345#endif
7346 if (OptionsDialog::instance()->getGeneralSettingsPage()->getModelingViewMode().compare(Helper::subWindow) == 0) {
7347 setViewMode(QMdiArea::SubWindowView);
7348 } else {
7349 setViewMode(QMdiArea::TabbedView);
7350 }
7351 // create a Model Swicther Dialog
7352 mpModelSwitcherDialog = new QDialog(this, Qt::Popup);
7353 mpRecentModelsList = new QListWidget(this);
7354 mpRecentModelsList->setItemDelegate(new ItemDelegate(mpRecentModelsList));
7355 mpRecentModelsList->setTextElideMode(Qt::ElideMiddle);
7356 mpRecentModelsList->setViewMode(QListView::ListMode);
7357 mpRecentModelsList->setMovement(QListView::Static);
7358 connect(mpRecentModelsList, SIGNAL(itemClicked(QListWidgetItem*))"2""itemClicked(QListWidgetItem*)", SLOT(openRecentModelWidget(QListWidgetItem*))"1""openRecentModelWidget(QListWidgetItem*)");
7359 QGridLayout *pModelSwitcherLayout = new QGridLayout;
7360 pModelSwitcherLayout->setContentsMargins(0, 0, 0, 0);
7361 pModelSwitcherLayout->addWidget(mpRecentModelsList, 0, 0);
7362 mpModelSwitcherDialog->setLayout(pModelSwitcherLayout);
7363 mpLastActiveSubWindow = 0;
7364 // install QApplication event filter to handle the ctrl+tab and ctrl+shift+tab
7365 QApplication::instance()->installEventFilter(this);
7366 connect(this, SIGNAL(subWindowActivated(QMdiSubWindow*))"2""subWindowActivated(QMdiSubWindow*)", SLOT(currentModelWidgetChanged(QMdiSubWindow*))"1""currentModelWidgetChanged(QMdiSubWindow*)");
7367 connect(this, SIGNAL(subWindowActivated(QMdiSubWindow*))"2""subWindowActivated(QMdiSubWindow*)", MainWindow::instance(), SLOT(updateModelSwitcherMenu(QMdiSubWindow*))"1""updateModelSwitcherMenu(QMdiSubWindow*)");
7368 connect(this, SIGNAL(subWindowActivated(QMdiSubWindow*))"2""subWindowActivated(QMdiSubWindow*)", SLOT(updateThreeDViewer(QMdiSubWindow*))"1""updateThreeDViewer(QMdiSubWindow*)");
7369 // add actions
7370 connect(MainWindow::instance()->getSaveAction(), SIGNAL(triggered())"2""triggered()", SLOT(saveModelWidget())"1""saveModelWidget()");
7371 connect(MainWindow::instance()->getSaveAsAction(), SIGNAL(triggered())"2""triggered()", SLOT(saveAsModelWidget())"1""saveAsModelWidget()");
7372 connect(MainWindow::instance()->getSaveTotalAction(), SIGNAL(triggered())"2""triggered()", SLOT(saveTotalModelWidget())"1""saveTotalModelWidget()");
7373 connect(MainWindow::instance()->getPrintModelAction(), SIGNAL(triggered())"2""triggered()", SLOT(printModel())"1""printModel()");
7374 connect(MainWindow::instance()->getSimulationParamsAction(), SIGNAL(triggered())"2""triggered()", SLOT(showSimulationParams())"1""showSimulationParams()");
7375 connect(MainWindow::instance()->getAlignInterfacesAction(), SIGNAL(triggered())"2""triggered()", SLOT(alignInterfaces())"1""alignInterfaces()");
7376 connect(MainWindow::instance()->getAddSystemAction(), SIGNAL(triggered())"2""triggered()", SLOT(addSystem())"1""addSystem()");
7377 connect(MainWindow::instance()->getAddOrEditIconAction(), SIGNAL(triggered())"2""triggered()", SLOT(addOrEditIcon())"1""addOrEditIcon()");
7378 connect(MainWindow::instance()->getDeleteIconAction(), SIGNAL(triggered())"2""triggered()", SLOT(deleteIcon())"1""deleteIcon()");
7379 connect(MainWindow::instance()->getAddConnectorAction(), SIGNAL(triggered())"2""triggered()", SLOT(addConnector())"1""addConnector()");
7380 connect(MainWindow::instance()->getAddBusAction(), SIGNAL(triggered())"2""triggered()", SLOT(addBus())"1""addBus()");
7381 connect(MainWindow::instance()->getAddTLMBusAction(), SIGNAL(triggered())"2""triggered()", SLOT(addTLMBus())"1""addTLMBus()");
7382 connect(MainWindow::instance()->getAddSubModelAction(), SIGNAL(triggered())"2""triggered()", SLOT(addSubModel())"1""addSubModel()");
7383}
7384
7385void ModelWidgetContainer::addModelWidget(ModelWidget *pModelWidget, bool checkPreferedView)
7386{
7387 bool hasModelWidget = false;
7388 QList<QMdiSubWindow*> subWindowsList = subWindowList(QMdiArea::ActivationHistoryOrder);
7389 for (int i = subWindowsList.size() - 1 ; i >= 0 ; i--) {
7390 ModelWidget *pSubModelWidget = qobject_cast<ModelWidget*>(subWindowsList.at(i)->widget());
7391 if (pSubModelWidget == pModelWidget) {
7392 if (pModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
7393 pModelWidget->loadDiagramView();
7394 pModelWidget->loadConnections();
7395 }
7396 pModelWidget->createModelWidgetComponents();
7397 pModelWidget->show();
7398 setActiveSubWindow(subWindowsList.at(i));
7399 hasModelWidget = true;
7400 break;
7401 }
7402 }
7403 if (!hasModelWidget) {
7404 int subWindowsSize = subWindowList(QMdiArea::ActivationHistoryOrder).size();
7405 QMdiSubWindow *pSubWindow = addSubWindow(pModelWidget);
7406 addCloseActionsToSubWindowSystemMenu(pSubWindow);
7407 pSubWindow->setWindowIcon(ResourceCache::getIcon(":/Resources/icons/modeling.png"));
7408 if (pModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Modelica) {
7409 pModelWidget->loadDiagramView();
7410 pModelWidget->loadConnections();
7411 }
7412 pModelWidget->createModelWidgetComponents();
7413 pModelWidget->show();
7414 if (subWindowsSize == 0 || MainWindow::instance()->isPlottingPerspectiveActive()) {
7415 pModelWidget->setWindowState(Qt::WindowMaximized);
7416 }
7417 setActiveSubWindow(pSubWindow);
7418 if (pModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::OMS) {
7419 pModelWidget->getDiagramViewToolButton()->setChecked(true);
7420 }
7421 }
7422 if (pModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::Text) {
7423 pModelWidget->getTextViewToolButton()->setChecked(true);
7424 if (!pModelWidget->getEditor()->isVisible()) {
7425 pModelWidget->getEditor()->show();
7426 }
7427 pModelWidget->getEditor()->getPlainTextEdit()->setFocus(Qt::ActiveWindowFocusReason);
7428 } else if (pModelWidget->getLibraryTreeItem()->getLibraryType() == LibraryTreeItem::CompositeModel) {
7429 if (pModelWidget->getModelWidgetContainer()->getPreviousViewType() != StringHandler::NoView) {
7430 loadPreviousViewType(pModelWidget);
7431 } else {
7432 pModelWidget->getDiagramViewToolButton()->setChecked(true);
7433 }
7434 }
7435 pModelWidget->updateViewButtonsBasedOnAccess();
7436 if (!checkPreferedView || pModelWidget->getLibraryTreeItem()->getLibraryType() != LibraryTreeItem::Modelica) {
7437 return;
7438 }
7439 // get the preferred view to display
7440 QString preferredView = pModelWidget->getLibraryTreeItem()->mClassInformation.preferredView;
7441 if (!preferredView.isEmpty()) {
7442 if (preferredView.compare("text") == 0) {
7443 pModelWidget->getTextViewToolButton()->setChecked(true);
7444 } else {
7445 pModelWidget->getDiagramViewToolButton()->setChecked(true);
7446 }
7447 } else if (pModelWidget->getModelWidgetContainer()->getPreviousViewType() != StringHandler::NoView) {
7448 loadPreviousViewType(pModelWidget);
7449 } else {
7450 QString defaultView = OptionsDialog::instance()->getGeneralSettingsPage()->getDefaultView();
7451 if (defaultView.compare(Helper::iconView) == 0) {
7452 pModelWidget->getIconViewToolButton()->setChecked(true);
7453 } else if (defaultView.compare(Helper::textView) == 0) {
7454 pModelWidget->getTextViewToolButton()->setChecked(true);
7455 } else {
7456 pModelWidget->getDiagramViewToolButton()->setChecked(true);
7457 }
7458 }
7459 pModelWidget->updateViewButtonsBasedOnAccess();
7460}
7461
7462/*!
7463