Date:2010-10-22 03:31:51 (13 years 5 months ago)
Author:Juan64Bits
Commit:32a206d1b00a98d3b9591ae566f0e62028b081eb
Message:First commit for sie code generator project.

Files: Software/sie_cg/arrow.cpp (1 diff)
Software/sie_cg/arrow.h (1 diff)
Software/sie_cg/block_editor/arrow.cpp (1 diff)
Software/sie_cg/block_editor/arrow.h (1 diff)
Software/sie_cg/block_editor/diagramitem.o (0 diffs)
Software/sie_cg/block_editor/diagramscene.cpp (1 diff)
Software/sie_cg/block_editor/diagramscene.h (1 diff)
Software/sie_cg/block_editor/diagramscene.pro (1 diff)
Software/sie_cg/block_editor/diagramscene.pro.user (1 diff)
Software/sie_cg/block_editor/diagramscene.qrc (1 diff)
Software/sie_cg/block_editor/diagramtextitem.cpp (1 diff)
Software/sie_cg/block_editor/diagramtextitem.h (1 diff)
Software/sie_cg/block_editor/lineitem.cpp (1 diff)
Software/sie_cg/block_editor/lineitem.h (1 diff)
Software/sie_cg/block_editor/main.cpp (1 diff)
Software/sie_cg/block_editor/mainwindow.cpp (1 diff)
Software/sie_cg/block_editor/mainwindow.h (1 diff)
Software/sie_cg/block_editor/test_block1.die (1 diff)
Software/sie_cg/block_editor/test_block2.die (1 diff)
Software/sie_cg/block_editor/test_block3.die (1 diff)
Software/sie_cg/block_editor/test_block4.die (1 diff)
Software/sie_cg/diagramitem.cpp (1 diff)
Software/sie_cg/diagramitem.h (1 diff)
Software/sie_cg/diagramscene.cpp (1 diff)
Software/sie_cg/diagramscene.h (1 diff)
Software/sie_cg/diagramscene.pro (1 diff)
Software/sie_cg/diagramscene.pro.user (1 diff)
Software/sie_cg/diagramscene.qrc (1 diff)
Software/sie_cg/diagramtextitem.cpp (1 diff)
Software/sie_cg/diagramtextitem.h (1 diff)
Software/sie_cg/images/background1.png (0 diffs)
Software/sie_cg/images/background2.png (0 diffs)
Software/sie_cg/images/background3.png (0 diffs)
Software/sie_cg/images/background4.png (0 diffs)
Software/sie_cg/images/bold.png (0 diffs)
Software/sie_cg/images/bringtofront.png (0 diffs)
Software/sie_cg/images/delete.png (0 diffs)
Software/sie_cg/images/exit.png (0 diffs)
Software/sie_cg/images/floodfill.png (0 diffs)
Software/sie_cg/images/italic.png (0 diffs)
Software/sie_cg/images/linecolor.png (0 diffs)
Software/sie_cg/images/linepointer.png (0 diffs)
Software/sie_cg/images/lower1.png (0 diffs)
Software/sie_cg/images/new.png (0 diffs)
Software/sie_cg/images/no.png (0 diffs)
Software/sie_cg/images/open.png (0 diffs)
Software/sie_cg/images/pointer.png (0 diffs)
Software/sie_cg/images/preview.png (0 diffs)
Software/sie_cg/images/raise1.png (0 diffs)
Software/sie_cg/images/save.png (0 diffs)
Software/sie_cg/images/save_as.png (0 diffs)
Software/sie_cg/images/sendtoback.png (0 diffs)
Software/sie_cg/images/textpointer.png (0 diffs)
Software/sie_cg/images/underline.png (0 diffs)
Software/sie_cg/images/yes.png (0 diffs)
Software/sie_cg/images/zoom_in.png (0 diffs)
Software/sie_cg/images/zoom_out.png (0 diffs)
Software/sie_cg/librarydialog.o (0 diffs)
Software/sie_cg/librarydialog.ui (1 diff)
Software/sie_cg/lineitem.cpp (1 diff)
Software/sie_cg/lineitem.h (1 diff)
Software/sie_cg/main.cpp (1 diff)
Software/sie_cg/mainwindow.cpp (1 diff)
Software/sie_cg/mainwindow.h (1 diff)
Software/sie_cg/moc_librarydialog.cpp (1 diff)
Software/sie_cg/moc_librarydialog.o (0 diffs)
Software/sie_cg/test.sie (1 diff)

Change Details

Software/sie_cg/arrow.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43
44#include "arrow.h"
45#include <math.h>
46
47const qreal Pi = 3.14;
48
49Arrow::Arrow(DiagramTextItem *startItem, DiagramTextItem *endItem,
50         QGraphicsItem *parent, QGraphicsScene *scene)
51    : QGraphicsPathItem(parent, scene)
52{
53    myStartItem = startItem;
54    myEndItem = endItem;
55    arrowSize = 10;
56    moving=0;
57    //setFlag(QGraphicsItem::ItemIsMovable, true);
58    setFlag(QGraphicsItem::ItemIsSelectable, true);
59    myColor = Qt::black;
60    setPen(QPen(myColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
61    myOwnerScene = scene;
62    lineItem *newLine= new lineItem(QPointF(0,0),QPointF(0,0),this);
63    myOwnerScene->addItem(newLine);
64    addLine(newLine);
65}
66
67void Arrow::removeLine(lineItem *line)
68{
69    int index = myLines.indexOf(line);
70    int cIndex = myCLines.indexOf(line);
71    if(cIndex!=-1) index = cIndex; //Prevent segmentation fault
72
73    if (index != -1){
74        //Adjust the corners
75        if(myLines.count()>1)
76        {
77            if(index==0)
78            {
79                myCorners.removeAt(0);
80                myOwnerScene->removeItem(myCLines.at(0));
81                myCLines.removeAt(0);
82            }
83            else if(index>0)
84            {
85                myCorners.removeAt(index-1);
86                myOwnerScene->removeItem(myCLines.at(index-1));
87                myCLines.removeAt(index-1);
88            }
89        }
90        myLines.removeAt(index);
91    }
92
93    //If lines is empty the arrow is removed
94    if (myLines.isEmpty())
95    {
96        this->startItem()->ownerItem()->removeArrow(this);
97        this->endItem()->ownerItem()->removeArrow(this);
98        this->myOwnerScene->removeItem(this);
99    }
100}
101
102void Arrow::removeLines()
103{
104    foreach (lineItem *line, myLines) {
105        scene()->removeItem(line);
106        delete line;
107    }
108    foreach (lineItem *line, myCLines) {
109        scene()->removeItem(line);
110        delete line;
111    }
112}
113
114bool Arrow::addLine(lineItem *line)
115{
116        myLines.append(line);
117        return 1;
118}
119
120QRectF Arrow::boundingRect() const
121{
122    qreal extra = (pen().width() + arrowSize*2) / 2.0;
123
124    return QGraphicsPathItem::boundingRect()
125           .normalized()
126           .adjusted(-extra, -extra, extra, extra);
127}
128
129QPainterPath Arrow::shape() const
130{
131    QPainterPath path = QGraphicsPathItem::shape();
132    return path; //FIXME, Arrow heads must to be include
133}
134
135void Arrow::updatePosition()
136{
137    QPainterPath myPath;
138    myPath.moveTo(myStartItem->ownerItem()->pos()+myStartItem->offset()+
139                  QPointF(arrowSize,0));
140    if(!myCorners.isEmpty())
141        foreach(QPointF corner, myCorners){
142            myPath.lineTo(corner);
143        }
144    myPath.lineTo(myEndItem->ownerItem()->pos()+myEndItem->offset()-
145                  QPointF(arrowSize,0));
146
147    setPath(myPath);
148
149}
150//! [3]
151
152void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
153          QWidget *)
154{
155    QPen myPen = pen();
156    myPen.setColor(myColor);
157    painter->setPen(myPen);
158    painter->setBrush(myColor);
159
160    QPointF endPos=myEndItem->ownerItem()->pos()+myEndItem->offset()-
161                   QPointF(arrowSize,0);
162    QPointF startPos=myStartItem->ownerItem()->pos()+myStartItem->offset()+
163                     QPointF(arrowSize,0);
164
165    if(myCorners.isEmpty())
166    {
167        myLines.first()->setLine(QLineF(startPos,endPos));
168    }
169    else
170    {
171        myLines.first()->setLine(QLineF(startPos,myCorners.first()));
172        for(int i=0; i<myCorners.count()-1;i++)
173          myLines.at(i+1)->setLine(QLineF(myCorners.at(i),myCorners.at(i+1)));
174        myLines.last()->setLine(QLineF(myCorners.last(),endPos));
175    }
176
177    //Drawing arrow selected
178    for(int i=0; i<myLines.count();i++)
179        if (isSelected())
180        {
181            painter->setPen(QPen(Qt::gray, 2, Qt::SolidLine));
182            QLineF myLine = myLines.at(i)->line();
183            painter->drawLine(myLine);
184            foreach (lineItem *line, myLines) { line->setColor(Qt::gray);}
185            foreach (lineItem *line, myCLines) { line->setColor(Qt::gray);}
186        }
187        else
188        {
189            foreach (lineItem *line, myLines) { line->setColor(myColor);}
190            foreach (lineItem *line, myCLines) { line->setColor(myColor);}
191        }
192
193    //End arrow head
194    QPointF arrowP1=QPointF(endPos+QPointF(0,arrowSize));
195    QPointF arrowP2=QPointF(endPos+QPointF(0,-arrowSize));
196
197    arrowHeadEnd.clear();
198    arrowHeadEnd << endPos+QPointF(arrowSize,0) << arrowP1 << arrowP2;
199
200    painter->drawPolygon(arrowHeadEnd);
201    //Start arrow head
202    arrowP1=QPointF(startPos+QPointF(-arrowSize,arrowSize));
203    arrowP2=QPointF(startPos+QPointF(-arrowSize,-arrowSize));
204
205    arrowHeadStart.clear();
206    arrowHeadStart << startPos << arrowP1 << arrowP2;
207    painter->drawPolygon(arrowHeadStart);
208
209    //Set visible corners
210    bool anySelected = 0;
211
212    foreach(lineItem *line,myLines){ if(line->isSelected())anySelected=1;}
213    foreach(lineItem *line,myCLines){ if(line->isSelected())anySelected=1;}
214    if(isSelected()) anySelected=1;
215
216    if(anySelected)
217        setVisibleCorners(1);
218    else
219        setVisibleCorners(0);
220}
221
222void Arrow::createCorner(QPointF cornerPos, lineItem *inLine)
223{
224    createCorner(cornerPos,myLines.indexOf(inLine));
225}
226
227void Arrow::createCorner(QPointF cornerPos, int index)
228{
229    if (index != -1)
230    {
231            myCorners.insert(index,cornerPos);
232            lineItem *newLine= new lineItem(QPointF(0,0),QPointF(0,0),this);
233            myOwnerScene->addItem(newLine);
234            newLine->setZValue(this->zValue());
235            addLine(newLine);
236            newLine= new lineItem(cornerPos+QPointF(-0.5,-0.5) ,
237                                  cornerPos+QPointF(0.5,0.5),this,6,1);
238            myOwnerScene->addItem(newLine);
239            newLine->setZValue(this->zValue()+0.1);
240            myCLines.insert(index,newLine);
241    }
242}
243
244void Arrow::moveCorner(QPointF cornerPos, lineItem *inLine)
245{
246    int index = myCLines.indexOf(inLine);
247
248    if (index != -1)
249    {
250            cornerPos=mapFromItem(inLine,cornerPos);
251            myCorners.replace(index,cornerPos);
252            updatePosition();
253    }
254}
255
256void Arrow::setVisibleCorners(bool visible)
257{
258    foreach (lineItem *line, myCLines) {
259        line->setVisible(visible);
260    }
261}
262
263QDomElement Arrow::toXml(QDomDocument &document,
264                          QList<DiagramItem*> sceneItems) const
265{
266        QDomElement diagramArrow = document.createElement("Arrow");
267
268        //Set attibutes; startItem
269        diagramArrow.setAttribute("start-x",startOffset().x());
270        diagramArrow.setAttribute("start-y",startOffset().y());
271        diagramArrow.setAttribute("start-Owner",
272                                  sceneItems.indexOf(startOwner()));
273        diagramArrow.setAttribute("start-ID",this->startItem()->textID());
274
275        //Set attibutes; endItem
276        diagramArrow.setAttribute("end-x",endOffset().x());
277        diagramArrow.setAttribute("end-y",endOffset().y());
278        diagramArrow.setAttribute("end-Owner",
279                                  sceneItems.indexOf(endOwner()));
280        diagramArrow.setAttribute("end-ID",this->endItem()->textID());
281
282        diagramArrow.setAttribute("color",myColor.name());
283
284        //Corners list
285        int i=0;
286        if(!myCorners.isEmpty())
287        {
288            QDomElement arrowCorners = document.createElement("arrowCorners");
289            foreach(QPointF corner, myCorners)
290            {
291                QDomElement arrowCorner = document.createElement("arrowCorner");
292                arrowCorner.setAttribute("x",corner.x());
293                arrowCorner.setAttribute("y",corner.y());
294                i++;
295                arrowCorners.appendChild(arrowCorner);
296            }
297
298            diagramArrow.appendChild(arrowCorners);
299        }
300        return (diagramArrow);
301}
302
303void Arrow::snapToGrid(QGraphicsSceneMouseEvent *event)
304{
305    //TODO implement polygon drag
306    QPointF diffPos= event->scenePos()-previousPos;
307    //Update corners:
308    for(int i=0; i < myCorners.count();i++)
309    {
310        myCLines.at(i)->setLine(QLineF(myCLines.at(i)->line().p1()+diffPos,
311                                       myCLines.at(i)->line().p2()+diffPos));
312        QPointF itemPos = myCLines.at(i)->line().p1()+QPointF(0.5,0.5);
313        moveCorner(itemPos,myCLines.at(i));
314    }
315    updatePosition();
316}
317
318void Arrow::mousePressEvent(QGraphicsSceneMouseEvent *event)
319{
320    //if(this->isSelected())
321    {
322        previousPos = event->scenePos();
323        moving=1;
324    }
325    QGraphicsPathItem::mousePressEvent(event);
326}
327
328void Arrow::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
329{
330    if(moving && isSelected())
331    {
332        snapToGrid(event);
333        previousPos = event->scenePos();
334    }
335    moving=0;
336    QGraphicsPathItem::mouseReleaseEvent(event);
337}
338
339void Arrow::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
340{
341    if(moving && isSelected())
342    {
343        snapToGrid(event);
344        previousPos = event->scenePos();
345    }
346    QGraphicsPathItem::mouseMoveEvent(event);
347}
Software/sie_cg/arrow.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef ARROW_H
43#define ARROW_H
44
45#include <QGraphicsLineItem>
46#include <QtXml>
47#include "diagramtextitem.h"
48#include "lineitem.h"
49#include "diagramitem.h"
50
51QT_BEGIN_NAMESPACE
52class QGraphicsPolygonItem;
53class QGraphicsLineItem;
54class QGraphicsPathItem;
55class QGraphicsScene;
56class QRectF;
57class QGraphicsSceneMouseEvent;
58class QPainterPath;
59QT_END_NAMESPACE
60
61class lineItem;
62
63class Arrow : public QGraphicsPathItem
64{
65public:
66    enum { Type = UserType + 32 };
67
68    Arrow(DiagramTextItem *startItem, DiagramTextItem *endItem,
69      QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);
70
71    int type() const
72        { return Type; }
73    QRectF boundingRect() const;
74    QPainterPath shape() const;
75    void setColor(const QColor &color)
76        { myColor=color; }
77    DiagramTextItem *startItem() const
78        { return myStartItem; }
79    DiagramTextItem *endItem() const
80        { return myEndItem; }
81
82    void removeLine(lineItem *line);
83    void removeLines();
84    bool addLine(lineItem *line);
85
86    void createCorner(QPointF cornerPos, lineItem *inLine);
87    void createCorner(QPointF cornerPos, int index);
88    void moveCorner(QPointF cornerPos, lineItem *inLine);
89
90    void setVisibleCorners(bool visible);
91
92    void snapToGrid(QGraphicsSceneMouseEvent *event);
93
94    QDomDocument toXmlFormat();
95
96    QPointF startOffset() const
97        { return myStartItem->offset();}
98
99    QPointF endOffset() const
100        { return myEndItem->offset();}
101
102    DiagramItem *startOwner() const
103        { return myStartItem->ownerItem();}
104    DiagramItem *endOwner() const
105        { return myEndItem->ownerItem();}
106
107    QDomElement toXml(QDomDocument &,QList<DiagramItem*>) const;
108
109public slots:
110    void updatePosition();
111
112protected:
113    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
114               QWidget *widget = 0);
115    void mousePressEvent(QGraphicsSceneMouseEvent *event);
116    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
117    void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
118
119private:
120    DiagramTextItem *myStartItem;
121    DiagramTextItem *myEndItem;
122    QColor myColor;
123    QPolygonF arrowHeadEnd;
124    QPolygonF arrowHeadStart;
125    QList<lineItem *> myLines;
126    QList<lineItem *> myCLines;
127    QList<QPointF> myCorners;
128    QGraphicsScene *myOwnerScene;
129    qreal arrowSize;
130    bool moving;
131    QPointF previousPos;
132};
133
134#endif
Software/sie_cg/block_editor/arrow.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43
44#include "arrow.h"
45#include "lineitem.h"
46#include <math.h>
47
48const qreal Pi = 3.14;
49
50Arrow::Arrow( QPointF startP,QPointF endP,
51              QGraphicsItem *parent, QGraphicsScene *scene)
52    : QGraphicsPathItem(parent, scene)
53{
54    startPoint=startP;
55    endPoint=endP;
56    arrowSize = 10;
57    moving=0;
58    //setFlag(QGraphicsItem::ItemIsMovable, true);
59    setFlag(QGraphicsItem::ItemIsSelectable, true);
60    myColor = Qt::black;
61    setPen(QPen(myColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
62    //setZValue(0.0);
63    myOwnerScene = scene;
64    lineItem *newLine= new lineItem(QPointF(0,0),QPointF(0,0),this);
65    myOwnerScene->addItem(newLine);
66    addLine(newLine);
67
68    updatePosition();
69}
70
71void Arrow::removeLine(lineItem *line)
72{
73    int index = myLines.indexOf(line);
74
75    if (index != -1){
76        //Adjust the corners
77        if(myLines.count()>1)
78        {
79            if(index==0)
80            {
81                myCorners.removeAt(0);
82                myOwnerScene->removeItem(myCLines.at(0));
83                myCLines.removeAt(0);
84            }
85            else if(index>0)
86            {
87                myCorners.removeAt(index-1);
88                myOwnerScene->removeItem(myCLines.at(index-1));
89                myCLines.removeAt(index-1);
90            }
91        }
92        myLines.removeAt(index);
93    }
94
95    //If lines is empty the arrow is removed
96    if (myLines.count()<3)
97    {
98        removeLines();
99        myOwnerScene->removeItem(this);
100    }
101}
102
103void Arrow::removeLines()
104{
105    foreach (lineItem *line, myLines) {
106        scene()->removeItem(line);
107        delete line;
108    }
109    foreach (lineItem *line, myCLines) {
110        scene()->removeItem(line);
111        delete line;
112    }
113    if(myOwnerScene->items().indexOf(SECLine)!=-1)
114    {
115        scene()->removeItem(SECLine);
116        delete SECLine;
117    }
118}
119
120bool Arrow::addLine(lineItem *line)
121{
122        myLines.append(line);
123        return 1;
124}
125
126QRectF Arrow::boundingRect() const
127{
128    qreal extra = (pen().width() + arrowSize*2) / 2.0;
129
130    return QGraphicsPathItem::boundingRect()
131           .normalized()
132           .adjusted(-extra, -extra, extra, extra);
133}
134
135QPainterPath Arrow::shape() const
136{
137    QPainterPath path = QGraphicsPathItem::shape();
138    return path;
139}
140
141void Arrow::updatePosition()
142{
143    QPainterPath myPath;
144    myPath.moveTo(startPoint);
145    if(!myCorners.isEmpty())
146        foreach(QPointF corner, myCorners){
147            myPath.lineTo(corner);
148        }
149    myPath.lineTo(endPoint);
150
151    setPath(myPath);
152}
153
154void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
155          QWidget *)
156{
157    //Update line positions
158    QPen myPen = pen();
159    myPen.setColor(myColor);
160    painter->setPen(myPen);
161    painter->setBrush(myColor);
162
163    QPointF endPos=endPoint;
164    QPointF startPos=startPoint;
165
166    if(myCorners.isEmpty())
167    {
168        myLines.first()->setLine(QLineF(startPos,endPos));
169    }
170    else
171    {
172        myLines.first()->setLine(QLineF(startPos,myCorners.first()));
173        for(int i=0; i<myCorners.count()-1;i++)
174          myLines.at(i+1)->setLine(QLineF(myCorners.at(i),myCorners.at(i+1)));
175        myLines.last()->setLine(QLineF(myCorners.last(),endPos));
176    }
177
178    //Drawing arrow selected
179    for(int i=0; i<myLines.count();i++)
180    {
181        if (isSelected())
182        {
183            painter->setPen(QPen(Qt::gray, 2, Qt::SolidLine));
184            QLineF myLine = myLines.at(i)->line();
185            painter->drawLine(myLine);
186            foreach (lineItem *line, myLines) { line->setColor(Qt::gray);}
187            foreach (lineItem *line, myCLines) { line->setColor(Qt::gray);}
188            if(myOwnerScene->items().indexOf(SECLine)!=-1)
189                SECLine->setColor(Qt::gray);
190        }
191        else
192        {
193            foreach (lineItem *line, myLines) { line->setColor(myColor);}
194            foreach (lineItem *line, myCLines) { line->setColor(myColor);}
195            if(myOwnerScene->items().indexOf(SECLine)!=-1)
196                SECLine->setColor(myColor);
197        }
198    }
199    setSelectedArrows();
200}
201
202void Arrow::setSelectedArrows()
203{
204    bool anySelected = 0;
205
206    foreach(lineItem *line,myLines){ if(line->isSelected())anySelected=1;}
207    foreach(lineItem *line,myCLines){ if(line->isSelected())anySelected=1;}
208    if(isSelected()) anySelected=1;
209
210    if(anySelected)
211        setVisibleCorners(1);
212    else
213        setVisibleCorners(0);
214}
215
216void Arrow::createCorner(QPointF cornerPos, lineItem *inLine)
217{
218    createCorner(cornerPos,myLines.indexOf(inLine));
219}
220
221void Arrow::createCorner(QPointF cornerPos, int index)
222{
223    if (index != -1)
224    {
225            myCorners.insert(index,cornerPos);
226            lineItem *newLine= new lineItem(cornerPos,cornerPos,this);
227            myOwnerScene->addItem(newLine);
228            newLine->setZValue(this->zValue());
229            addLine(newLine);
230            newLine= new lineItem(cornerPos+QPointF(-0.5,-0.5) ,
231                                  cornerPos+QPointF(0.5,0.5),this,6,1);
232            myOwnerScene->addItem(newLine);
233            newLine->setZValue(this->zValue()+0.1);
234            myCLines.insert(index,newLine);
235    }
236    updatePosition();
237}
238void Arrow::createFirstCorner()
239{
240    if(myOwnerScene->items().indexOf(SECLine)==-1)
241    {
242        SECLine = new lineItem(startPoint+QPointF(-0.5,-0.5) ,
243                               startPoint+QPointF(0.5,0.5),this,6,1);
244        myOwnerScene->addItem(SECLine);
245        SECLine->setVisible(1);
246        SECLine->setZValue(this->zValue()+0.1);
247    }
248    updatePosition();
249}
250
251void Arrow::moveCorner(QPointF cornerPos, lineItem *inLine, bool relative)
252{
253    int index = myCLines.indexOf(inLine);
254    if(relative) cornerPos=mapFromItem(inLine,cornerPos);
255
256    if (index != -1)
257    {
258        myCorners.replace(index,cornerPos);
259    }
260    else if (inLine == SECLine)
261    {
262        startPoint=cornerPos;
263        endPoint=cornerPos;
264    }
265    updatePosition();
266}
267
268void Arrow::setVisibleCorners(bool visible)
269{
270    foreach (lineItem *line, myCLines) {
271        line->setVisible(visible);
272    }
273    if(myOwnerScene->items().indexOf(SECLine)!=-1)
274    {
275        SECLine->setVisible(1);
276    }
277    updatePosition();
278}
279
280void Arrow::snapToGrid(QGraphicsSceneMouseEvent *event)
281{
282    //TODO implement polygon drag
283    QPointF diffPos= event->scenePos()-previousPos;
284    printf("diff[%f|%f]\n",diffPos.x(),diffPos.y()); fflush(stdout);
285    //Update corners:
286    for(int i=0; i < myCorners.count();i++)
287    {
288        myCLines.at(i)->setLine(QLineF(myCLines.at(i)->line().p1()+diffPos,
289                                       myCLines.at(i)->line().p2()+diffPos));
290        QPointF itemPos = myCLines.at(i)->line().p1()+QPointF(0.5,0.5);
291        moveCorner(itemPos,myCLines.at(i));
292    }
293    if(myOwnerScene->items().indexOf(SECLine)!=-1)
294    {
295        SECLine->setLine(QLineF(SECLine->line().p1()+diffPos,
296                                 SECLine->line().p2()+diffPos));
297        QPointF itemPos = SECLine->line().p1()+QPointF(0.5,0.5);
298        moveCorner(itemPos,SECLine);
299    }
300    updatePosition();
301}
302
303void Arrow::mousePressEvent(QGraphicsSceneMouseEvent *event)
304{
305    //if(this->isSelected())
306    {
307        previousPos = event->scenePos();
308        moving=1;
309    }
310    QGraphicsPathItem::mousePressEvent(event);
311}
312
313void Arrow::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
314{
315    if(moving && isSelected())
316    {
317        snapToGrid(event);
318        previousPos = event->scenePos();
319    }
320    moving=0;
321    QGraphicsPathItem::mouseReleaseEvent(event);
322}
323
324void Arrow::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
325{
326    if(moving && isSelected())
327    {
328        snapToGrid(event);
329        previousPos = event->scenePos();
330    }
331    QGraphicsPathItem::mouseMoveEvent(event);
332}
333
334QDomElement Arrow::toXml(QDomDocument &document) const
335{
336        QDomElement diagramArrow = document.createElement("Polygon");
337        //Point list
338        if(!myCorners.isEmpty())
339        {
340            QDomElement arrowCorner;
341            //start point
342            arrowCorner = document.createElement("Point");
343            arrowCorner.setAttribute("x",(startPoint-QPointF(500,500)).x());
344            arrowCorner.setAttribute("y",(startPoint-QPointF(500,500)).y());
345            diagramArrow.appendChild(arrowCorner);
346            //corner points
347            foreach(QPointF corner, myCorners)
348            {
349                arrowCorner = document.createElement("Point");
350                arrowCorner.setAttribute("x",(corner-QPointF(500,500)).x());
351                arrowCorner.setAttribute("y",(corner-QPointF(500,500)).y());
352                diagramArrow.appendChild(arrowCorner);
353            }
354        }
355        return (diagramArrow);
356}
Software/sie_cg/block_editor/arrow.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef ARROW_H
43#define ARROW_H
44
45#include <QGraphicsLineItem>
46#include <QtXml>
47#include "diagramtextitem.h"
48#include "diagramscene.h"
49
50QT_BEGIN_NAMESPACE
51class QGraphicsPolygonItem;
52class QGraphicsLineItem;
53class QGraphicsPathItem;
54class QGraphicsScene;
55class QRectF;
56class QGraphicsSceneMouseEvent;
57class QPainterPath;
58QT_END_NAMESPACE
59
60class lineItem;
61class DiagramScene;
62
63class Arrow : public QGraphicsPathItem
64{
65public:
66    enum { Type = UserType + 32 };
67
68    Arrow(QPointF startPoint,QPointF endPoint,
69          QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);
70
71    int type() const
72        { return Type; }
73    QRectF boundingRect() const;
74    QPainterPath shape() const;
75    void setColor(const QColor &color)
76        { myColor=color; }
77
78    void removeLine(lineItem *line);
79    void removeLines();
80    bool addLine(lineItem *line);
81    void setStartPoint(QPointF point){startPoint=point;}
82    void setEndPoint(QPointF point){endPoint=point;}
83
84    QPointF getStartPoint(){return startPoint;}
85    QPointF getEndPoint(){return endPoint;}
86
87    void createCorner(QPointF cornerPos, lineItem *inLine);
88    void createCorner(QPointF cornerPos, int index);
89    void moveCorner(QPointF cornerPos, lineItem *inLine, bool relative = 1);
90
91    void setVisibleCorners(bool visible);
92
93    void snapToGrid(QGraphicsSceneMouseEvent *event);
94
95    QDomDocument toXmlFormat();
96    QDomElement toXml(QDomDocument &) const;
97    void createFirstCorner();
98    void setSelectedArrows();
99
100public slots:
101    void updatePosition();
102
103protected:
104    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
105               QWidget *widget = 0);
106    void mousePressEvent(QGraphicsSceneMouseEvent *event);
107    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
108    void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
109
110private:
111    QColor myColor;
112    QList<lineItem *> myLines;
113    QList<lineItem *> myCLines;
114    lineItem *SECLine;
115    QPointF startPoint;
116    QPointF endPoint;
117    QList<QPointF> myCorners;
118    QGraphicsScene *myOwnerScene;
119    qreal arrowSize;
120    bool moving;
121    QPointF previousPos;
122};
123
124#endif
Software/sie_cg/block_editor/diagramitem.o
Software/sie_cg/block_editor/diagramscene.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43#include <QHash>
44#include "diagramscene.h"
45
46DiagramScene::DiagramScene(QMenu *itemMenu, QObject *parent)
47    : QGraphicsScene(parent)
48{
49    myItemMenu = itemMenu;
50    myMode = MoveItem;
51
52    line = 0;
53    textItem = 0;
54    myItemColor = Qt::white;
55    myTextColor = Qt::black;
56    myLineColor = Qt::black;
57    snapToGrid=1;
58    myGrid=10;
59    myPolygonPath=0;
60    myCorners=0;
61
62    TitleText = new DiagramTextItem(0,0,1,0xFFF,255,"BLOCK NAME HERE (not visible)",
63                                    QPointF(250,250));
64    addItem(TitleText);
65
66}
67
68void DiagramScene::editorLostFocus(DiagramTextItem *item)
69{
70    QTextCursor cursor = item->textCursor();
71    cursor.clearSelection();
72    item->setTextCursor(cursor);
73
74    if (item->toPlainText().isEmpty()) {
75        removeItem(item);
76        item->deleteLater();
77    }
78}
79
80void DiagramScene::drawBackground(QPainter *p, const QRectF &r)
81{
82    p -> save();
83
84    p -> setRenderHint(QPainter::Antialiasing, false);
85    p -> setRenderHint(QPainter::TextAntialiasing, true);
86    p -> setRenderHint(QPainter::SmoothPixmapTransform, false);
87
88    p -> setPen(Qt::NoPen);
89    p -> setBrush(Qt::white);
90    p -> drawRect(r);
91
92
93        p -> setPen(Qt::gray);
94        p -> setBrush(Qt::NoBrush);
95        qreal limite_x = r.x() + r.width();
96        qreal limite_y = r.y() + r.height();
97
98        int g_x = (int)ceil(r.x());
99        while (g_x % myGrid) ++ g_x;
100        int g_y = (int)ceil(r.y());
101        while (g_y % myGrid) ++ g_y;
102
103        QPolygon points;
104        for (int gx = g_x ; gx < limite_x ; gx += myGrid) {
105            for (int gy = g_y ; gy < limite_y ; gy += myGrid) {
106                points << QPoint(gx, gy);
107            }
108        }
109        p -> drawPoints(points);
110
111    p->drawLine(500,0,500,1000);
112    p->drawLine(0,500,1000,500);
113
114    p -> restore();
115}
116
117void DiagramScene::doSnapToGrid(QGraphicsSceneMouseEvent *mouseEvent)
118{
119    if(snapToGrid){
120        mouseEvent->setScenePos(QPointF(
121                                int(mouseEvent->scenePos().x()/myGrid)*myGrid,
122                                int(mouseEvent->scenePos().y()/myGrid)*myGrid
123                                ));
124    }
125}
126
127void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
128{
129    doSnapToGrid(mouseEvent);
130    QString Text;
131
132    if (mouseEvent->button() != Qt::LeftButton)
133        return;
134
135    switch (myMode)
136    {
137        case InsertText:
138            //TODO: limit text items to 255 maximum
139            if(myTextType<256)
140                if(myTextType & 0b10000000)
141                    Text = "IN " +myTypeString;
142                else
143                    Text = "OUT " +myTypeString;
144            else
145                Text = myTypeString;
146
147            textItem = new DiagramTextItem(0,0,1,myTextType,0,Text,
148                                           mouseEvent->scenePos());
149            if(addTextItem(textItem))
150            {
151                textItem->setZValue(1000.0);
152                connect(textItem, SIGNAL(lostFocus(DiagramTextItem*)),
153                        this, SLOT(editorLostFocus(DiagramTextItem*)));
154                addItem(textItem);
155            }
156            else
157            {
158                delete(textItem);
159                QMessageBox::warning(0,"Full","The block can only have only"
160                                     "255 text items");
161            }
162            emit textInserted(textItem);
163            break;
164        case EditPolygon:
165            if(line == 0 && items().indexOf(myPolygonPath)==-1)
166            {
167                line = new QGraphicsLineItem(QLineF(mouseEvent->scenePos(),
168                                            mouseEvent->scenePos()));
169                line->setPen(QPen(Qt::blue, 2));
170                line->setZValue(1000.0);
171                addItem(line);
172            }
173            else if(line != 0 && items().indexOf(myPolygonPath)==-1 &&
174                    line->line().length()>5)
175            {
176                myPolygonPath = new Arrow(line->line().p1(),line->line().p2(),
177                                          0,this);
178                QLineF newLine(line->line().p2(),line->line().p2());
179                line->setLine(newLine);
180            }
181            else if(line != 0 && items().indexOf(myPolygonPath)!=-1 &&
182                    line->line().length()>5)
183            {
184                myPolygonPath->createCorner(line->line().p1(),myCorners);
185                myPolygonPath->setEndPoint(line->line().p2());
186                myPolygonPath->updatePosition();
187                QLineF newLine(line->line().p2(),line->line().p2());
188                line->setLine(newLine);
189
190                myCorners++;
191            }
192
193        case MoveItem:
194            QGraphicsScene::mousePressEvent(mouseEvent);
195            break;
196        default: ;
197    }
198
199}
200
201void DiagramScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
202{
203    doSnapToGrid(mouseEvent);
204    if (myMode == EditPolygon && line != 0 )
205    {
206        QLineF newLine(line->line().p1(), mouseEvent->scenePos());
207        line->setLine(newLine);
208    }
209
210        QGraphicsScene::mouseMoveEvent(mouseEvent);
211
212}
213
214void DiagramScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
215{
216    doSnapToGrid(mouseEvent);
217    if (myMode == EditPolygon && line != 0 && myCorners>0)
218    {
219        if(myPolygonPath->getStartPoint()!=line->line().p2())
220            myPolygonPath->createCorner(line->line().p2(),myCorners);
221
222        myPolygonPath->setEndPoint(myPolygonPath->getStartPoint());
223        myPolygonPath->createFirstCorner();
224        myPolygonPath->updatePosition();
225        myCorners=0;
226        removeItem(line);
227        line = 0;
228        myMode = MoveItem;
229        emit textInserted(textItem);//Is the same for all buttons
230    }
231    else if (myMode != EditPolygon)
232    {
233       QGraphicsScene::mouseDoubleClickEvent(mouseEvent);
234    }
235}
236
237void DiagramScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
238{
239    doSnapToGrid(mouseEvent);
240   if (myMode != EditPolygon && line == 0)
241        QGraphicsScene::mouseReleaseEvent(mouseEvent);
242}
243
244bool DiagramScene::isItemChange(int type)
245{
246    foreach (QGraphicsItem *item, selectedItems()) {
247        if (item->type() == type)
248            return true;
249    }
250    return false;
251}
252
253QDomDocument DiagramScene::toXmlFormat()
254{
255    QDomDocument document;
256    QDomComment initialComments=document.createComment(
257        "File for SIE Code Generator. Custmos Blocks");
258    document.appendChild(initialComments);
259    QDomElement diagram = document.createElement("CustomItem");
260    diagram.setAttribute("BlockName",TitleText->toPlainText());
261    document.appendChild(diagram);
262    //Lists of items
263    QList<DiagramTextItem *> Items;
264    QList<Arrow *> Arrows;
265    foreach(QGraphicsItem *item, items())
266    {
267        if(item->type() == DiagramTextItem::Type)
268            Items.append(qgraphicsitem_cast<DiagramTextItem *>(item));
269        else if(item->type() == Arrow::Type)
270            Arrows.append(qgraphicsitem_cast<Arrow *>(item));
271    }
272
273    if(Arrows.count()>1) {printf("Something is wrong.\n"); fflush(stdout);}
274
275    //Create the XML structure
276    diagram.appendChild(myPolygonPath->toXml(document));
277
278    QDomElement element;
279    if(Items.count()>0)
280    {
281        QDomElement textItems = document.createElement("TextItems");
282        foreach(DiagramTextItem *item, Items)
283        {
284            if(item->styleIO() != 0xFFF)
285            {
286                element = item->toXml(document);
287                element.setAttribute("ID",textItemsByID.key(item));
288                textItems.appendChild(element);
289            }
290        }
291        diagram.appendChild(textItems);
292    }
293
294    return(document);
295}
296
297int DiagramScene::fromXmlFormat(QDomDocument document)
298{
299    //Read items TODO: in future... add multi items on same file
300    QDomNodeList customsItems = document.elementsByTagName("CustomItem");
301    if(!customsItems.at(0).isElement())
302        return -1;
303    //Load the first item in the document
304    QDomElement customItem = customsItems.at(0).toElement();
305    if(customItem.attribute("BlockName")=="")
306        TitleText->setPlainText("Please set Block Name");
307    else
308        TitleText->setPlainText(customItem.attribute("BlockName"));
309    TitleText->updatePosition();
310    for (QDomNode node = customItem.firstChild() ;
311         !node.isNull() ;
312         node = node.nextSibling())
313    {
314        QDomElement element = node.toElement();
315        if(element.tagName()=="Polygon")
316        {
317            QList<QPointF> points;
318            for (QDomNode node = element.firstChild() ;
319                             !node.isNull() ;
320                             node = node.nextSibling())
321            {
322                QDomElement point = node.toElement();
323                if(point.tagName()!="Point")
324                    return -1;
325                points.append(QPointF((QPointF(point.attribute("x").toFloat(),0)
326                                              +QPointF(500,500)).x(),
327                                     (QPointF(0,point.attribute("y").toFloat())
328                                              +QPointF(500,500)).y()));
329            }
330
331            if(points.count()>0)
332            {
333                myPolygonPath = new Arrow(points.at(0),points.at(0),0,this);
334                for(int i=1; i< points.count();i++)
335                {
336                     myPolygonPath->createCorner(points.at(i),i-1);
337                }
338                myPolygonPath->createFirstCorner();
339                myPolygonPath->updatePosition();
340            }
341        }
342        else if(element.tagName()=="TextItems")
343        {
344            for (QDomNode node = element.firstChild() ;
345                             !node.isNull() ;
346                             node = node.nextSibling())
347            {
348                QDomElement textItemE = node.toElement();
349                if(textItemE.tagName()!="TextItem")
350                    return -1;
351
352                int myStyleIO = textItemE.attribute("myStyleIO").toInt();
353                int myID = textItemE.attribute("ID").toInt();
354                bool editableItem = textItemE.attribute("editableItem").toInt();
355                QPointF posOffset=
356                        QPointF((QPointF(textItemE.attribute("posOffset-x")
357                                         .toFloat(),0)+QPointF(500,500)).x(),
358                               (-QPointF(0,textItemE.attribute("posOffset-y")
359                                         .toFloat())+QPointF(500,500)).y());
360                QString itemString=textItemE.attribute("text");
361
362                if(myStyleIO==0)
363                {
364                    if(!editableItem)
365                        myStyleIO=256;
366                    else
367                        myStyleIO=257;
368                }
369
370                DiagramTextItem * newTextItem =
371                 new DiagramTextItem(0,0,1,myStyleIO,myID,itemString,posOffset);
372                newTextItem->setZValue(1000.0);
373                connect(newTextItem, SIGNAL(lostFocus(DiagramTextItem*)),
374                 this, SLOT(editorLostFocus(DiagramTextItem*)));
375                addItem(newTextItem);
376                textItemsByID.insert(myID,newTextItem);
377            }
378        }
379    }
380
381    return 1;
382}
383
384void DiagramScene::cleanScene()
385{
386    //Lists of items
387    QList<DiagramTextItem *> Items;
388    foreach(QGraphicsItem *item, items())
389    {
390        if(item->type() == DiagramTextItem::Type)
391            Items.append(qgraphicsitem_cast<DiagramTextItem *>(item));
392    }
393    //Remove Diagram Text Items
394    foreach(DiagramTextItem *item, Items)
395    {
396        if(item->styleIO() != 0xFFF)
397        {
398            removeItem(item);
399            delete(item);
400        }
401    }
402    //Remove Polygon Path
403    if(items().indexOf(myPolygonPath)!=-1)
404    {
405        myPolygonPath->removeLines();
406        removeItem(myPolygonPath);
407        delete(myPolygonPath);
408    }
409    TitleText->setPlainText("BLOCK NAME HERE (not visible)");
410    TitleText->updatePosition();
411}
412
413int DiagramScene::addTextItem(DiagramTextItem * textItem)
414{
415    for(int i=0; i<255; i++)
416    {
417        QHash<int,DiagramTextItem *>::iterator iter= textItemsByID.find(i);
418        if(iter==textItemsByID.end())
419        {
420            textItemsByID.insert(i,textItem);
421            return 1;
422        }
423    }
424    return 0;
425}
426
427void DiagramScene::removeTextItem(DiagramTextItem * textItem)
428{
429    textItemsByID.remove(textItemsByID.key(textItem));
430}
Software/sie_cg/block_editor/diagramscene.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef DIAGRAMSCENE_H
43#define DIAGRAMSCENE_H
44
45#include <QGraphicsScene>
46#include <QDesktopServices>
47#include <QtXml>
48#include "diagramtextitem.h"
49#include "arrow.h"
50
51QT_BEGIN_NAMESPACE
52class QGraphicsSceneMouseEvent;
53class QMenu;
54class QPointF;
55class QGraphicsLineItem;
56class QFont;
57class QGraphicsTextItem;
58class QColor;
59QT_END_NAMESPACE
60
61class Arrow;
62class DiagramTextItem;
63
64class DiagramScene : public QGraphicsScene
65{
66    Q_OBJECT
67
68public:
69    enum Mode { MoveItem , EditPolygon, InsertText };
70
71    DiagramScene(QMenu *itemMenu, QObject *parent = 0);
72
73    QDomDocument toXmlFormat();
74    int fromXmlFormat(QDomDocument xmlDocument);
75    void cleanScene();
76    void setTextType(int type,QString text){myTextType=type;myTypeString=text;}
77    void resetMyPolygon(){myPolygonPath=0;}
78
79    QHash<int,DiagramTextItem*> getTextItemsByID;
80
81    int addTextItem(DiagramTextItem * textItem);
82    void removeTextItem(DiagramTextItem * textItem);
83
84public slots:
85    void setMode(Mode mode){myMode=mode;}
86    void editorLostFocus(DiagramTextItem *item);
87
88signals:
89    void textInserted(QGraphicsTextItem *item);
90
91protected:
92    void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
93    void mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent);
94    void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent);
95    void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
96    void drawBackground(QPainter *p, const QRectF &r);
97
98private:
99    bool isItemChange(int type);
100    void doSnapToGrid(QGraphicsSceneMouseEvent *mouseEvent);
101    QMenu *myItemMenu;
102    Mode myMode;
103    int myTextType;
104    QString myTypeString;
105    bool leftButtonDown;
106    QPointF startPoint;
107    QGraphicsLineItem *line;
108    Arrow *myPolygonPath;
109    QFont myFont;
110    DiagramTextItem *textItem;
111    DiagramTextItem *TitleText;
112    QColor myTextColor;
113    QColor myItemColor;
114    QColor myLineColor;
115    bool snapToGrid;
116    short int myGrid;
117    int myCorners;
118    QHash<int,DiagramTextItem*> textItemsByID;
119};
120
121#endif
Software/sie_cg/block_editor/diagramscene.pro
1HEADERS = mainwindow.h \
2    diagramscene.h \
3    arrow.h \
4    diagramtextitem.h \
5    lineitem.h
6SOURCES = mainwindow.cpp \
7    main.cpp \
8    arrow.cpp \
9    diagramtextitem.cpp \
10    diagramscene.cpp \
11    lineitem.cpp
12RESOURCES = diagramscene.qrc
13
14TARGET = blockeditor
15
16# install
17target.path = $$[QT_INSTALL_EXAMPLES]/graphicsview/diagramscene
18sources.files = $$SOURCES \
19    $$HEADERS \
20    $$RESOURCES \
21    $$FORMS \
22    diagramscene.pro \
23    images
24sources.path = $$[QT_INSTALL_EXAMPLES]/graphicsview/diagramscene
25INSTALLS += target \
26    sources
27symbian:include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri)
28QT += xml \
29    svg \
30    network
Software/sie_cg/block_editor/diagramscene.pro.user
1<!DOCTYPE QtCreatorProject>
2<qtcreator>
3 <data>
4  <variable>RunConfiguration0-BaseEnvironmentBase</variable>
5  <value type="int">2</value>
6 </data>
7 <data>
8  <variable>RunConfiguration0-CommandLineArguments</variable>
9  <valuelist type="QVariantList"/>
10 </data>
11 <data>
12  <variable>RunConfiguration0-ProFile</variable>
13  <value type="QString">diagramscene.pro</value>
14 </data>
15 <data>
16  <variable>RunConfiguration0-RunConfiguration.name</variable>
17  <value type="QString">diagramscene</value>
18 </data>
19 <data>
20  <variable>RunConfiguration0-UseDyldImageSuffix</variable>
21  <value type="bool">false</value>
22 </data>
23 <data>
24  <variable>RunConfiguration0-UseTerminal</variable>
25  <value type="bool">false</value>
26 </data>
27 <data>
28  <variable>RunConfiguration0-UserEnvironmentChanges</variable>
29  <valuelist type="QVariantList"/>
30 </data>
31 <data>
32  <variable>RunConfiguration0-UserSetName</variable>
33  <value type="bool">false</value>
34 </data>
35 <data>
36  <variable>RunConfiguration0-UserSetWorkingDirectory</variable>
37  <value type="bool">false</value>
38 </data>
39 <data>
40  <variable>RunConfiguration0-UserWorkingDirectory</variable>
41  <value type="QString"></value>
42 </data>
43 <data>
44  <variable>RunConfiguration0-type</variable>
45  <value type="QString">Qt4ProjectManager.Qt4RunConfiguration</value>
46 </data>
47 <data>
48  <variable>activeRunConfiguration</variable>
49  <value type="int">0</value>
50 </data>
51 <data>
52  <variable>activebuildconfiguration</variable>
53  <value type="QString">Debug</value>
54 </data>
55 <data>
56  <variable>buildConfiguration-Debug</variable>
57  <valuemap type="QVariantMap">
58   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Debug</value>
59   <value key="QtVersionId" type="int">0</value>
60   <value key="ToolChain" type="int">0</value>
61   <value key="addQDumper" type=""></value>
62   <value key="buildConfiguration" type="int">2</value>
63  </valuemap>
64 </data>
65 <data>
66  <variable>buildConfiguration-Release</variable>
67  <valuemap type="QVariantMap">
68   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Release</value>
69   <value key="QtVersionId" type="int">0</value>
70   <value key="addQDumper" type=""></value>
71   <value key="buildConfiguration" type="int">0</value>
72  </valuemap>
73 </data>
74 <data>
75  <variable>buildconfiguration-Debug-buildstep0</variable>
76  <valuemap type="QVariantMap">
77   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Debug</value>
78   <valuelist key="abstractProcess.Environment" type="QVariantList">
79    <value type="QString">DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-MI4KrAyPP5,guid=5c5c5e6146195c74b6ad266d4cc07afd</value>
80    <value type="QString">DEFAULTS_PATH=/usr/share/gconf/gnome.default.path</value>
81    <value type="QString">DESKTOP_SESSION=gnome</value>
82    <value type="QString">DISPLAY=:0.0</value>
83    <value type="QString">GDMSESSION=gnome</value>
84    <value type="QString">GDM_KEYBOARD_LAYOUT=es</value>
85    <value type="QString">GDM_LANG=en_US.utf8</value>
86    <value type="QString">GNOME_DESKTOP_SESSION_ID=this-is-deprecated</value>
87    <value type="QString">GNOME_KEYRING_CONTROL=/tmp/keyring-CFAuJK</value>
88    <value type="QString">GNOME_KEYRING_PID=1516</value>
89    <value type="QString">GTK_MODULES=canberra-gtk-module</value>
90    <value type="QString">HOME=/home/juan64bits</value>
91    <value type="QString">LANG=en_US.utf8</value>
92    <value type="QString">LD_LIBRARY_PATH=/usr/lib/qtcreator</value>
93    <value type="QString">LOGNAME=juan64bits</value>
94    <value type="QString">MANDATORY_PATH=/usr/share/gconf/gnome.mandatory.path</value>
95    <value type="QString">ORBIT_SOCKETDIR=/tmp/orbit-juan64bits</value>
96    <value type="QString">PATH=/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games</value>
97    <value type="QString">PWD=/home/juan64bits</value>
98    <value type="QString">QTDIR=/usr/share/qt4</value>
99    <value type="QString">SESSION_MANAGER=local/Maximus:@/tmp/.ICE-unix/1534,unix/Maximus:/tmp/.ICE-unix/1534</value>
100    <value type="QString">SHELL=/bin/bash</value>
101    <value type="QString">SPEECHD_PORT=7560</value>
102    <value type="QString">SSH_AGENT_PID=1570</value>
103    <value type="QString">SSH_AUTH_SOCK=/tmp/keyring-CFAuJK/ssh</value>
104    <value type="QString">USER=juan64bits</value>
105    <value type="QString">USERNAME=juan64bits</value>
106    <value type="QString">XAUTHORITY=/var/run/gdm/auth-for-juan64bits-V4ry7M/database</value>
107    <value type="QString">XDG_CONFIG_DIRS=/etc/xdg/xdg-gnome:/etc/xdg</value>
108    <value type="QString">XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/</value>
109    <value type="QString">XDG_SESSION_COOKIE=b9a7fbc4d869fc15bd6cdd474bcc9a28-1287682812.550485-1725059380</value>
110   </valuelist>
111   <valuelist key="abstractProcess.arguments" type="QVariantList">
112    <value type="QString">/home/juan64bits/QT/diagramscene/block_editor/diagramscene.pro</value>
113    <value type="QString">-spec</value>
114    <value type="QString">linux-g++</value>
115    <value type="QString">-r</value>
116    <value type="QString">CONFIG+=debug</value>
117   </valuelist>
118   <value key="abstractProcess.command" type="QString">/usr/bin/qmake-qt4</value>
119   <value key="abstractProcess.enabled" type="bool">false</value>
120   <value key="abstractProcess.workingDirectory" type="QString">/home/juan64bits/QT/diagramscene/block_editor</value>
121  </valuemap>
122 </data>
123 <data>
124  <variable>buildconfiguration-Debug-buildstep1</variable>
125  <valuemap type="QVariantMap">
126   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Debug</value>
127   <valuelist key="abstractProcess.Environment" type="QVariantList">
128    <value type="QString">DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-MI4KrAyPP5,guid=5c5c5e6146195c74b6ad266d4cc07afd</value>
129    <value type="QString">DEFAULTS_PATH=/usr/share/gconf/gnome.default.path</value>
130    <value type="QString">DESKTOP_SESSION=gnome</value>
131    <value type="QString">DISPLAY=:0.0</value>
132    <value type="QString">GDMSESSION=gnome</value>
133    <value type="QString">GDM_KEYBOARD_LAYOUT=es</value>
134    <value type="QString">GDM_LANG=en_US.utf8</value>
135    <value type="QString">GNOME_DESKTOP_SESSION_ID=this-is-deprecated</value>
136    <value type="QString">GNOME_KEYRING_CONTROL=/tmp/keyring-CFAuJK</value>
137    <value type="QString">GNOME_KEYRING_PID=1516</value>
138    <value type="QString">GTK_MODULES=canberra-gtk-module</value>
139    <value type="QString">HOME=/home/juan64bits</value>
140    <value type="QString">LANG=en_US.utf8</value>
141    <value type="QString">LD_LIBRARY_PATH=/usr/lib/qtcreator</value>
142    <value type="QString">LOGNAME=juan64bits</value>
143    <value type="QString">MANDATORY_PATH=/usr/share/gconf/gnome.mandatory.path</value>
144    <value type="QString">ORBIT_SOCKETDIR=/tmp/orbit-juan64bits</value>
145    <value type="QString">PATH=/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games</value>
146    <value type="QString">PWD=/home/juan64bits</value>
147    <value type="QString">QTDIR=/usr/share/qt4</value>
148    <value type="QString">SESSION_MANAGER=local/Maximus:@/tmp/.ICE-unix/1534,unix/Maximus:/tmp/.ICE-unix/1534</value>
149    <value type="QString">SHELL=/bin/bash</value>
150    <value type="QString">SPEECHD_PORT=7560</value>
151    <value type="QString">SSH_AGENT_PID=1570</value>
152    <value type="QString">SSH_AUTH_SOCK=/tmp/keyring-CFAuJK/ssh</value>
153    <value type="QString">USER=juan64bits</value>
154    <value type="QString">USERNAME=juan64bits</value>
155    <value type="QString">XAUTHORITY=/var/run/gdm/auth-for-juan64bits-V4ry7M/database</value>
156    <value type="QString">XDG_CONFIG_DIRS=/etc/xdg/xdg-gnome:/etc/xdg</value>
157    <value type="QString">XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/</value>
158    <value type="QString">XDG_SESSION_COOKIE=b9a7fbc4d869fc15bd6cdd474bcc9a28-1287682812.550485-1725059380</value>
159   </valuelist>
160   <value key="abstractProcess.IgnoreReturnValue" type="bool">false</value>
161   <valuelist key="abstractProcess.arguments" type="QVariantList">
162    <value type="QString">-w</value>
163   </valuelist>
164   <value key="abstractProcess.command" type="QString">/usr/bin/make</value>
165   <value key="abstractProcess.enabled" type="bool">true</value>
166   <value key="abstractProcess.workingDirectory" type="QString">/home/juan64bits/QT/diagramscene/block_editor</value>
167  </valuemap>
168 </data>
169 <data>
170  <variable>buildconfiguration-Debug-cleanstep0</variable>
171  <valuemap type="QVariantMap">
172   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Debug</value>
173   <value key="cleanConfig" type="bool">true</value>
174   <valuelist key="makeargs" type="QVariantList">
175    <value type="QString">clean</value>
176   </valuelist>
177  </valuemap>
178 </data>
179 <data>
180  <variable>buildconfiguration-Release-buildstep0</variable>
181  <valuemap type="QVariantMap">
182   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Release</value>
183  </valuemap>
184 </data>
185 <data>
186  <variable>buildconfiguration-Release-buildstep1</variable>
187  <valuemap type="QVariantMap">
188   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Release</value>
189  </valuemap>
190 </data>
191 <data>
192  <variable>buildconfiguration-Release-cleanstep0</variable>
193  <valuemap type="QVariantMap">
194   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Release</value>
195  </valuemap>
196 </data>
197 <data>
198  <variable>buildconfigurations</variable>
199  <valuelist type="QVariantList">
200   <value type="QString">Debug</value>
201   <value type="QString">Release</value>
202  </valuelist>
203 </data>
204 <data>
205  <variable>buildstep0</variable>
206  <valuemap type="QVariantMap">
207   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString"></value>
208   <value key="mkspec" type="QString"></value>
209  </valuemap>
210 </data>
211 <data>
212  <variable>buildstep1</variable>
213  <valuemap type="QVariantMap">
214   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString"></value>
215  </valuemap>
216 </data>
217 <data>
218  <variable>buildsteps</variable>
219  <valuelist type="QVariantList">
220   <value type="QString">trolltech.qt4projectmanager.qmake</value>
221   <value type="QString">trolltech.qt4projectmanager.make</value>
222  </valuelist>
223 </data>
224 <data>
225  <variable>cleanstep0</variable>
226  <valuemap type="QVariantMap">
227   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString"></value>
228   <value key="clean" type="bool">true</value>
229  </valuemap>
230 </data>
231 <data>
232  <variable>cleansteps</variable>
233  <valuelist type="QVariantList">
234   <value type="QString">trolltech.qt4projectmanager.make</value>
235  </valuelist>
236 </data>
237 <data>
238  <variable>defaultFileEncoding</variable>
239  <value type="QByteArray">System</value>
240 </data>
241 <data>
242  <variable>project</variable>
243  <valuemap type="QVariantMap"/>
244 </data>
245</qtcreator>
Software/sie_cg/block_editor/diagramscene.qrc
1<RCC>
2    <qresource prefix="/">
3        <file>../images/pointer.png</file>
4        <file>../images/linepointer.png</file>
5        <file>../images/textpointer.png</file>
6        <file>../images/bold.png</file>
7        <file>../images/italic.png</file>
8        <file>../images/underline.png</file>
9        <file>../images/floodfill.png</file>
10        <file>../images/bringtofront.png</file>
11        <file>../images/delete.png</file>
12        <file>../images/sendtoback.png</file>
13        <file>../images/linecolor.png</file>
14        <file>../images/background1.png</file>
15        <file>../images/background2.png</file>
16        <file>../images/background3.png</file>
17        <file>../images/background4.png</file>
18        <file>../images/exit.png</file>
19        <file>../images/new.png</file>
20        <file>../images/no.png</file>
21        <file>../images/open.png</file>
22        <file>../images/save.png</file>
23        <file>../images/save_as.png</file>
24        <file>../images/yes.png</file>
25        <file>../images/zoom_in.png</file>
26        <file>../images/zoom_out.png</file>
27    </qresource>
28</RCC>
Software/sie_cg/block_editor/diagramtextitem.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43
44#include "diagramtextitem.h"
45#include "diagramscene.h"
46
47DiagramTextItem::DiagramTextItem(
48                    QGraphicsItem *parent, QGraphicsScene *scene,
49                    bool editable, int styleIO,
50                    unsigned char ID, QString defaultText, QPointF offset)
51    : QGraphicsTextItem(parent, scene)
52{
53    myOwnerScene=scene;
54    myStyleIO = styleIO;
55    myID=ID;
56    editableItem=editable;
57    setPlainText(defaultText);
58    posOffset=offset;
59    //setFlag(QGraphicsItem::ItemIsMovable,0);
60    if(editable)
61        setFlag(QGraphicsItem::ItemIsSelectable,1);
62    else
63        setFlag(QGraphicsItem::ItemIsFocusable,0);
64
65    updatePosition();
66    moving=0;
67}
68
69void DiagramTextItem::updatePosition()
70{
71        if(myStyleIO>255)
72            setPos(posOffset+QPointF(-boundingRect().width()/2,
73                                                -boundingRect().height()/2));
74        else if(myStyleIO & 0b10000000)
75            setPos(posOffset+QPointF(0,-boundingRect().height()/2));
76        else //OUT
77            setPos(posOffset+QPointF(-boundingRect().width(),
78                                                -boundingRect().height()/2));
79}
80
81QVariant DiagramTextItem::itemChange(GraphicsItemChange change,
82                     const QVariant &value)
83{
84    if (change == QGraphicsItem::ItemSelectedHasChanged)
85        emit selectedChange(this);
86
87    return value;
88}
89
90void DiagramTextItem::focusOutEvent(QFocusEvent *event)
91{
92    if(editableItem)
93    {
94        if(toPlainText()=="") setPlainText("?");
95        //updatePosition();
96        setTextInteractionFlags(Qt::NoTextInteraction);
97        emit lostFocus(this);
98        QGraphicsTextItem::focusOutEvent(event);
99    }
100}
101
102void DiagramTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
103{
104    if(editableItem)
105    {
106        if (textInteractionFlags() == Qt::NoTextInteraction)
107            setTextInteractionFlags(Qt::TextEditorInteraction);
108    }
109     QGraphicsTextItem::mouseDoubleClickEvent(event);
110}
111
112void DiagramTextItem::snapToGrid(QGraphicsSceneMouseEvent *event)
113{
114    if(myStyleIO!=0xFFF)
115        setOffset(event->scenePos());
116    updatePosition();
117}
118
119void DiagramTextItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
120{
121    moving=1;
122    //snapToGrid(event);
123    QGraphicsTextItem::mousePressEvent(event);
124}
125
126void DiagramTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
127{
128    moving=0;
129    QGraphicsTextItem::mouseReleaseEvent(event);
130}
131
132void DiagramTextItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
133{
134    if(moving)
135        snapToGrid(event);
136
137    QGraphicsTextItem::mouseMoveEvent(event);
138}
139
140QDomElement DiagramTextItem::toXml(QDomDocument &document) const
141{
142        QDomElement textItem = document.createElement("TextItem");
143        textItem.setAttribute("text",toPlainText());
144        if(myStyleIO<256)
145        {
146            textItem.setAttribute("myStyleIO",myStyleIO);
147            textItem.setAttribute("editableItem",0);
148        }
149        else if (myStyleIO==256)
150        {
151            textItem.setAttribute("myStyleIO",0);
152            textItem.setAttribute("editableItem",0);
153        }
154        else if (myStyleIO==257)
155        {
156            textItem.setAttribute("myStyleIO",0);
157            textItem.setAttribute("editableItem",1);
158        }
159        textItem.setAttribute("posOffset-x",
160                              QPointF(posOffset-QPointF(500,500)).x());
161        textItem.setAttribute("posOffset-y",
162                              -QPointF(posOffset-QPointF(500,500)).y());
163        return (textItem);
164}
165
Software/sie_cg/block_editor/diagramtextitem.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef DIAGRAMTEXTITEM_H
43#define DIAGRAMTEXTITEM_H
44
45#include <QGraphicsTextItem>
46#include <QPen>
47#include "diagramscene.h"
48
49QT_BEGIN_NAMESPACE
50class QFocusEvent;
51class QGraphicsItem;
52class QGraphicsScene;
53class QGraphicsSceneMouseEvent;
54QT_END_NAMESPACE
55
56class DiagramTextItem : public QGraphicsTextItem
57{
58    Q_OBJECT
59
60public:
61    enum { Type = UserType + 3 };
62
63    DiagramTextItem(
64          QGraphicsItem *parent = 0, QGraphicsScene *scene = 0,
65          bool editable =1, int styleIO = 0,
66          unsigned char ID=0, QString defaultText="<text>",
67          QPointF offset=QPointF(0,0));
68
69    int type() const
70        { return Type;}
71
72    int styleIO()
73        { return myStyleIO;}
74
75    unsigned char ID()
76        { return myID;}
77
78    unsigned char textID() const
79        { return myID;}
80
81    QPointF offset() const
82        { return posOffset;}
83
84    void setOffset(QPointF offset)
85        { posOffset=offset;}
86
87    bool isEditable()
88        { return editableItem;}
89
90    void snapToGrid(QGraphicsSceneMouseEvent *event);
91
92    QDomElement toXml(QDomDocument &document) const;
93
94public slots:
95    void updatePosition();
96
97signals:
98    void lostFocus(DiagramTextItem *item);
99    void selectedChange(QGraphicsItem *item);
100
101protected:
102    QVariant itemChange(GraphicsItemChange change, const QVariant &value);
103    void focusOutEvent(QFocusEvent *event);
104    void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
105    void mousePressEvent(QGraphicsSceneMouseEvent *event);
106    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
107    void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
108
109private:
110    bool editableItem;
111    QPointF posOffset;
112    int myStyleIO;
113    unsigned char myID;
114    QGraphicsScene *myOwnerScene;
115    bool moving;
116};
117
118#endif
Software/sie_cg/block_editor/lineitem.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43
44#include "lineitem.h"
45#include <math.h>
46
47lineItem::lineItem(QPointF startPoint, QPointF endItem, Arrow *ownerArrow,
48    int wt, bool movable, QGraphicsItem *parent, QGraphicsScene *scene)
49    : QGraphicsLineItem(parent, scene)
50{
51    isMovable=movable;
52    if(isMovable)
53    {
54        setFlag(QGraphicsItem::ItemIsMovable, true);
55    }
56
57    setFlag(QGraphicsItem::ItemIsSelectable, true);
58
59    myColor = Qt::black;
60    setPen(QPen(myColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
61    setLine(QLineF(startPoint,endItem));
62    myOwnerArrow = ownerArrow;
63    pWidth=wt;
64    moveItem=0;
65}
66
67QRectF lineItem::boundingRect() const
68{
69    qreal extra = (pen().width() + 20) / 2.0;
70
71    return QRectF(line().p1(), QSizeF(line().p2().x() - line().p1().x(),
72                                      line().p2().y() - line().p1().y()))
73        .normalized()
74        .adjusted(-extra, -extra, extra, extra);
75}
76
77QPainterPath lineItem::shape() const
78{
79    QPainterPath path = QGraphicsLineItem::shape();
80    return path;
81}
82
83void lineItem::updatePos()
84{
85    QPointF itemPos = this->line().p1()+QPointF(0.5,0.5);
86    myOwnerArrow->moveCorner(itemPos,this);
87}
88
89void lineItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
90          QWidget *)
91{
92    QPen myPen = pen();
93    myPen.setColor(myColor);
94    myPen.setWidth(pWidth);
95    painter->setPen(myPen);
96    painter->setBrush(myColor);
97
98    setLine(line());
99        painter->drawLine(line());
100
101        //Drawing arrow selected
102        if (isSelected()) {
103            painter->setPen(QPen(Qt::gray, pWidth, Qt::SolidLine));
104            QLineF myLine = line();
105            painter->drawLine(myLine);
106        }
107}
108
109void lineItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
110{
111    if(!isMovable)
112    {
113        myOwnerArrow->createCorner(mouseEvent->scenePos(),this);
114    }
115    QGraphicsLineItem::mouseDoubleClickEvent(mouseEvent);
116}
117
118
119void lineItem::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
120{
121    QGraphicsLineItem::mousePressEvent(mouseEvent);
122}
123
124void lineItem::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
125{
126    if(isMovable)
127    {
128        updatePos();
129    }
130    QGraphicsLineItem::mouseMoveEvent(mouseEvent);
131}
132
133void lineItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
134{
135    if(isMovable)
136    {
137        updatePos();
138    }
139    QGraphicsLineItem::mouseReleaseEvent(mouseEvent);
140}
Software/sie_cg/block_editor/lineitem.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef LINEITEM_H
43#define LINEITEM_H
44
45#include <QGraphicsLineItem>
46#include "arrow.h"
47
48QT_BEGIN_NAMESPACE
49class QGraphicsPolygonItem;
50class QGraphicsLineItem;
51class QGraphicsScene;
52class QRectF;
53class QGraphicsSceneMouseEvent;
54class QPainterPath;
55QT_END_NAMESPACE
56
57class lineItem : public QGraphicsLineItem
58{
59public:
60    enum { Type = UserType + 4 };
61
62    lineItem(QPointF startPoint, QPointF endItem, Arrow *ownerArrow, int wt=2,
63        bool movable = 0, QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);
64
65    int type() const
66        { return Type;}
67    QRectF boundingRect() const;
68    QPainterPath shape() const;
69    void setColor(const QColor &color)
70        { myColor=color; }
71
72    Arrow * myOwner()
73        { return myOwnerArrow;}
74
75    bool itemIsMovable() {return isMovable;}
76
77public slots:
78    void updatePos();
79
80protected:
81    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
82               QWidget *widget = 0);
83    void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
84    void mousePressEvent(QGraphicsSceneMouseEvent *event);
85    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
86    void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
87
88private:
89    QColor myColor;
90    int pWidth;
91    Arrow *myOwnerArrow;
92    int moveItem;
93    bool isMovable;
94};
95
96#endif
Software/sie_cg/block_editor/main.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43
44#include "mainwindow.h"
45
46int main(int argv, char *args[])
47{
48    Q_INIT_RESOURCE(diagramscene);
49
50    QApplication app(argv, args);
51    MainWindow mainWindow;
52    mainWindow.setGeometry(100, 100, 1024, 640);
53    mainWindow.show();
54    return app.exec();
55}
Software/sie_cg/block_editor/mainwindow.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43#include <QLabel>
44
45#include "mainwindow.h"
46
47const int InsertTextButton = 10;
48
49MainWindow::MainWindow()
50{
51    createActions();
52    createToolBox();
53    createMenus();
54
55    scene = new DiagramScene(itemMenu);
56    scene->setSceneRect(QRectF(0, 0, 1000, 1000));
57    connect(scene, SIGNAL(textInserted(QGraphicsTextItem*)),
58        this, SLOT(textInserted(QGraphicsTextItem*)));
59
60    createToolbars();
61
62    QHBoxLayout *layout = new QHBoxLayout;
63    layout->addWidget(toolBox);
64    view = new QGraphicsView(scene);
65    layout->addWidget(view);
66
67    QWidget *widget = new QWidget;
68    widget->setLayout(layout);
69
70    setCentralWidget(widget);
71    setWindowTitle(tr("SIE Code Generator (Block Editor)"));
72    setUnifiedTitleAndToolBarOnMac(true);
73    myFilePath = "";
74
75    if(QApplication::argc()>1)
76        {newDiagram(QString(QApplication::argv()[1]));}
77}
78
79void MainWindow::deleteItem()
80{
81    foreach (QGraphicsItem *item, scene->selectedItems())
82    {
83        if (item->type() == Arrow::Type) {
84           qgraphicsitem_cast<Arrow *>(item)->removeLines();
85           scene->removeItem(item);
86           delete(item);
87        }
88        //If line is deleted then is romoved from the arrow owner
89        else if (item->type() == lineItem::Type &&
90                 !qgraphicsitem_cast<lineItem *>(item)->itemIsMovable()) {
91
92           qgraphicsitem_cast<lineItem *>(item)->myOwner()->removeLine(
93                                    qgraphicsitem_cast<lineItem *>(item));
94           qgraphicsitem_cast<lineItem *>(item)->myOwner()->updatePosition();
95           scene->removeItem(item);
96           delete(item);
97       }
98       else if (item->type() == DiagramTextItem::Type) {
99           if(qgraphicsitem_cast<DiagramTextItem *>(item)->styleIO()!=0xFFF)
100           {
101               scene->removeTextItem(qgraphicsitem_cast
102                                     <DiagramTextItem *>(item));
103               scene->removeItem(item);
104               delete(item);
105           }
106       }
107    }
108}
109
110void MainWindow::textInserted(QGraphicsTextItem*)
111{
112    buttonGroup->button(selectedButton)->setChecked(false);
113    scene->setMode(DiagramScene::MoveItem);
114}
115
116
117void MainWindow::sceneScaleChanged(const QString &scale)
118{
119    double newScale = scale.left(scale.indexOf(tr("%"))).toDouble() / 100.0;
120    QMatrix oldMatrix = view->matrix();
121    view->resetMatrix();
122    view->translate(oldMatrix.dx(), oldMatrix.dy());
123    view->scale(newScale, newScale);
124}
125
126void MainWindow::about()
127{
128    QMessageBox::question(this, tr("About SIE Code Generator"),
129                       tr("TODO <b>:)</b>"));
130}
131
132QWidget *MainWindow::createToolButton(int ID, QString type, QIcon icon)
133{
134    QToolButton *button = new QToolButton;
135    button->setIcon(icon);
136    button->setIconSize(QSize(50, 50));
137    button->setCheckable(true);
138    button->setText(type);
139    buttonGroup->addButton(button,ID);
140
141    QGridLayout *layout = new QGridLayout;
142    layout->addWidget(button, 0, 0, Qt::AlignHCenter);
143    layout->addWidget(new QLabel(type), 1, 0, Qt::AlignCenter);
144
145    QWidget *widget = new QWidget;
146    widget->setLayout(layout);
147
148    return widget;
149}
150
151void MainWindow::createToolBox()
152{
153    buttonGroup = new QButtonGroup;
154    buttonGroup->setExclusive(false);
155    connect(buttonGroup, SIGNAL(buttonClicked(int)),
156            this, SLOT(buttonGroupClicked(int)));
157
158    QGridLayout *layout = new QGridLayout;
159    //INPUTS
160    int i=0;
161    layout->addWidget(createToolButton(129+i,tr("Bool"),
162                      QIcon(":/images/background1.png")),++i,0);
163    layout->addWidget(createToolButton(129+i,tr("Char"),
164                      QIcon(":/images/background1.png")),++i,0);
165    layout->addWidget(createToolButton(129+i,tr("Integer"),
166                      QIcon(":/images/background1.png")),++i,0);
167    layout->addWidget(createToolButton(129+i,tr("Double"),
168                      QIcon(":/images/background1.png")),++i,0);
169    layout->addWidget(createToolButton(129+i,tr("Float"),
170                      QIcon(":/images/background1.png")),++i,0);
171
172    //OUTPUTS
173    i=0;
174    layout->addWidget(createToolButton(i,tr("Bool"),
175                      QIcon(":/images/background3.png")),++i,1);
176    layout->addWidget(createToolButton(i,tr("Char"),
177                      QIcon(":/images/background3.png")),++i,1);
178    layout->addWidget(createToolButton(i,tr("Integer"),
179                      QIcon(":/images/background3.png")),++i,1);
180    layout->addWidget(createToolButton(i,tr("Double"),
181                      QIcon(":/images/background3.png")),++i,1);
182    layout->addWidget(createToolButton(i,tr("Float"),
183                      QIcon(":/images/background3.png")),++i,1);
184
185    layout->setRowStretch(3, 10);
186    layout->setColumnStretch(2, 10);
187    QWidget *ioWidget = new QWidget;
188    ioWidget->setLayout(layout);
189
190    layout = new QGridLayout;
191    //Labels
192    layout->addWidget(createToolButton(256,tr("Label"),
193                      QIcon(":/images/background4.png")),0,0);
194    //Values
195    layout->addWidget(createToolButton(257,tr("Value"),
196                      QIcon(":/images/background4.png")),0,1);
197
198    //Polygon
199    layout->addWidget(createToolButton(258,tr("Polygon"),
200                      QIcon(":/images/background2.png")),1,0);
201
202    layout->setRowStretch(3, 10);
203    layout->setColumnStretch(2, 10);
204    QWidget *labelWidget = new QWidget;
205    labelWidget->setLayout(layout);
206
207
208    toolBox = new QToolBox;
209    toolBox->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Ignored));
210    toolBox->setMinimumWidth(labelWidget->sizeHint().width());
211    toolBox->addItem(labelWidget, tr("Basic draw"));
212    toolBox->addItem(ioWidget, tr("Inputs/Outputs"));
213
214}
215
216void MainWindow::buttonGroupClicked(int id)
217{
218    QList<QAbstractButton *> buttons = buttonGroup->buttons();
219    foreach (QAbstractButton *button, buttons)
220        {if (buttonGroup->button(id) != button) button->setChecked(false);}
221    selectedButton=id;
222
223    if(id==258)
224    { //Polygon edition
225        scene->setMode(DiagramScene::EditPolygon);
226    } else {
227        scene->setMode(DiagramScene::InsertText);
228    }
229
230    scene->setTextType(id,buttonGroup->button(id)->text());
231
232}
233
234void MainWindow::createActions()
235{
236
237    deleteAction = new QAction(QIcon(":/images/delete.png"),
238                               tr("&Delete"), this);
239    deleteAction->setShortcut(tr("Ctrl+Delete"));
240    deleteAction->setStatusTip(tr("Delete item from diagram"));
241    connect(deleteAction, SIGNAL(triggered()),
242        this, SLOT(deleteItem()));
243
244
245    newAction = new QAction(QIcon(":/images/new.png"),tr("&New"),this);
246    newAction->setShortcuts(QKeySequence::New);
247    newAction->setStatusTip("New diagram");
248    connect(newAction,SIGNAL(triggered()),this,SLOT(newDiagram()));
249
250    saveAction = new QAction(QIcon(":/images/save.png"),tr("&Save"),this);
251    saveAction->setShortcuts(QKeySequence::Save);
252    saveAction->setStatusTip("Save current diagram");
253    connect(saveAction,SIGNAL(triggered()),this,SLOT(saveDiagram()));
254
255    saveAsAction = new QAction(QIcon(":/images/save_as.png"),
256                               tr("Save &As..."),this);
257    saveAsAction->setShortcuts(QKeySequence::SaveAs);
258    saveAsAction->setStatusTip("Save current diagram with another name");
259    connect(saveAsAction,SIGNAL(triggered()),this,SLOT(saveAsDiagram()));
260
261    openAction = new QAction(QIcon(":/images/open.png"),tr("&Open"),this);
262    openAction->setShortcuts(QKeySequence::Open);
263    openAction->setStatusTip("Open diagram");
264    connect(openAction,SIGNAL(triggered()),this,SLOT(openDiagram()));
265
266    exitAction = new QAction(tr("E&xit"), this);
267    exitAction->setShortcuts(QKeySequence::Quit);
268    exitAction->setStatusTip(tr("Quit diagram editor"));
269    connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));
270
271    aboutAction = new QAction(tr("A&bout"), this);
272    aboutAction->setShortcut(tr("Ctrl+B"));
273    connect(aboutAction, SIGNAL(triggered()),
274            this, SLOT(about()));
275}
276
277void MainWindow::createMenus()
278{
279    fileMenu = menuBar()->addMenu(tr("&File"));
280    fileMenu->addAction(newAction);
281    fileMenu->addAction(openAction);
282    fileMenu->addSeparator();
283    fileMenu->addAction(saveAction);
284    fileMenu->addAction(saveAsAction);
285    fileMenu->addSeparator();
286    fileMenu->addAction(exitAction);
287
288    itemMenu = menuBar()->addMenu(tr("&Item"));
289    itemMenu->addAction(deleteAction);
290
291    aboutMenu = menuBar()->addMenu(tr("&Help"));
292    aboutMenu->addAction(aboutAction);
293}
294
295void MainWindow::createToolbars()
296{
297    fileToolBar = addToolBar(tr("File"));
298    fileToolBar->addAction(newAction);
299    fileToolBar->addAction(openAction);
300    fileToolBar->addAction(saveAction);
301
302    editToolBar = addToolBar(tr("Edit"));
303    editToolBar->addAction(deleteAction);
304
305    sceneScaleCombo = new QComboBox;
306    QStringList scales;
307    scales << tr("75%") << tr("100%") << tr("125%") << tr("150%") << tr("175%");
308    sceneScaleCombo->addItems(scales);
309    sceneScaleCombo->setCurrentIndex(1);
310    connect(sceneScaleCombo, SIGNAL(currentIndexChanged(QString)),
311            this, SLOT(sceneScaleChanged(QString)));
312
313    editToolBar->addWidget(sceneScaleCombo);
314}
315
316bool MainWindow::newDiagram(QString filePath)
317{
318    saveIfNeeded();
319    scene->cleanScene();
320    myFilePath="";
321
322    if(filePath=="")
323        return 0;
324
325    myFilePath=filePath;
326    QFile file(myFilePath);
327    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
328    {
329        QDomDocument document;
330        bool parsing=document.setContent(&file);
331        file.close();
332        if(!parsing)
333        {
334            QMessageBox::warning(this,"Aborting","Failed to parse file, "
335                                 "wrong format or encoding.");
336            return 0;
337        }
338        scene->fromXmlFormat(document);
339        return 1;
340    }
341    else
342        QMessageBox::critical(this,"Error","Could not open file for read.");
343
344    return 0;
345
346}
347
348void MainWindow::saveIfNeeded()
349{
350    if(myFilePath!="" || scene->items().count()>0)
351    {}//TODO save opened or modified diagram
352}
353
354bool MainWindow::openDiagram()
355{
356    QString
357    filePath = QFileDialog::getOpenFileName(this,"Open",
358               currentDir(),"Custom item for SIE code generator (*.die)");
359
360    if(filePath.isEmpty())
361        return 0;
362
363    if(!QFileInfo(filePath).isReadable())
364    {
365        QMessageBox::critical(this,"Error","File is not readable "
366                                           " or not exists.");
367        return 0;
368    }
369
370    newDiagram(filePath);
371    return 0;
372}
373
374bool MainWindow::saveDiagram()
375{
376    if(myFilePath=="")
377    {
378        saveAsDiagram();
379        return 0;
380    }
381    if(!QFileInfo(myFilePath).isWritable() && QFileInfo(myFilePath).exists())
382    {
383        QMessageBox::critical(this,"Error","File is not writable.");
384        return 0;
385    }
386    QFile file(myFilePath);
387    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
388    {
389        QDomDocument document = scene->toXmlFormat();
390        QTextStream out(&file);
391        out.setCodec("UTF-8");
392        out << document.toString(4);
393        file.close();
394        return 1;
395    }
396    else
397        QMessageBox::critical(this,"Error","Could not open file for write.");
398    return 0;
399}
400
401bool MainWindow::saveAsDiagram()
402{
403    QString filePath = QFileDialog::getSaveFileName(this,"Save as...",
404                 currentDir(),"Custom item for SIE code generator (*.die)");
405
406    if(!filePath.isEmpty())
407    {
408        myFilePath = filePath;
409        saveDiagram();
410        return 1;
411    }
412    return 0;
413}
Software/sie_cg/block_editor/mainwindow.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef MAINWINDOW_H
43#define MAINWINDOW_H
44
45#include <QMainWindow>
46#include <QDir>
47#include <QtXml>
48
49#include "diagramscene.h"
50#include "diagramtextitem.h"
51#include "lineitem.h"
52#include "arrow.h"
53
54class DiagramScene;
55
56QT_BEGIN_NAMESPACE
57class QAction;
58class QToolBox;
59class QSpinBox;
60class QComboBox;
61class QFontComboBox;
62class QButtonGroup;
63class QLineEdit;
64class QGraphicsTextItem;
65class QFont;
66class QToolButton;
67class QAbstractButton;
68class QGraphicsView;
69QT_END_NAMESPACE
70
71class MainWindow : public QMainWindow
72{
73    Q_OBJECT
74
75public:
76   MainWindow();
77   QString filePath() const
78       { return myFilePath;}
79   QString currentDir() const
80   { return QDir::currentPath();}
81
82   void saveIfNeeded();
83
84private slots:
85    void deleteItem();
86    void sceneScaleChanged(const QString &scale);
87    void about();
88    bool newDiagram(QString pathFile="");
89    bool openDiagram();
90    bool saveDiagram();
91    bool saveAsDiagram();
92    void buttonGroupClicked(int id);
93    void textInserted(QGraphicsTextItem*);
94
95private:
96    void createToolBox();
97    void createActions();
98    void createMenus();
99    void createToolbars();
100    QWidget *createToolButton(int ID, QString type,QIcon icon);
101
102    DiagramScene *scene;
103    QGraphicsView *view;
104
105    QAction *newAction;
106    QAction *saveAction;
107    QAction *saveAsAction;
108    QAction *openAction;
109
110    QAction *exitAction;
111    QAction *addAction;
112    QAction *deleteAction;
113
114    QAction *aboutAction;
115
116    QMenu *fileMenu;
117    QMenu *itemMenu;
118    QMenu *aboutMenu;
119
120    QToolBar *fileToolBar;
121    QToolBar *editToolBar;
122
123    QToolBox *toolBox;
124
125    QComboBox *sceneScaleCombo;
126
127    QButtonGroup *buttonGroup;
128
129    int selectedButton;
130
131    QString myFilePath;
132
133};
134
135
136#endif
Software/sie_cg/block_editor/test_block1.die
1<!--File for SIE Code Generator. Custmos Blocks-->
2<CustomItem BlockName="Test Block 1">
3    <Polygon>
4        <Point x="-120" y="0"/>
5        <Point x="-70" y="-50"/>
6        <Point x="90" y="-50"/>
7        <Point x="140" y="0"/>
8        <Point x="90" y="50"/>
9        <Point x="-70" y="50"/>
10    </Polygon>
11    <TextItems>
12        <TextItem myStyleIO="0" posOffset-y="-30" editableItem="0" ID="0" text="Value" posOffset-x="-40"/>
13        <TextItem myStyleIO="0" posOffset-y="-30" editableItem="1" ID="1" text="0.001" posOffset-x="40"/>
14        <TextItem myStyleIO="2" posOffset-y="-0" editableItem="0" ID="3" text="OUT Char " posOffset-x="140"/>
15        <TextItem myStyleIO="130" posOffset-y="-0" editableItem="0" ID="4" text=" IN Bool" posOffset-x="-120"/>
16        <TextItem myStyleIO="0" posOffset-y="30" editableItem="0" ID="2" text="Test Block 1" posOffset-x="0"/>
17    </TextItems>
18</CustomItem>
Software/sie_cg/block_editor/test_block2.die
1<!--File for SIE Code Generator. Custmos Blocks-->
2<CustomItem BlockName="Test Block 2">
3    <Polygon>
4        <Point x="-50" y="-20"/>
5        <Point x="-30" y="0"/>
6        <Point x="-50" y="20"/>
7        <Point x="30" y="20"/>
8        <Point x="60" y="0"/>
9        <Point x="40" y="-20"/>
10    </Polygon>
11    <TextItems>
12        <TextItem myStyleIO="130" posOffset-y="-0" editableItem="0" ID="1" text=" IN Bool" posOffset-x="-30"/>
13        <TextItem myStyleIO="0" posOffset-y="30" editableItem="0" ID="0" text="Test Block 2" posOffset-x="-10"/>
14    </TextItems>
15</CustomItem>
Software/sie_cg/block_editor/test_block3.die
1<!--File for SIE Code Generator. Custmos Blocks-->
2<CustomItem BlockName="Test Block 3">
3    <Polygon>
4        <Point x="-30" y="0"/>
5        <Point x="-50" y="20"/>
6        <Point x="50" y="20"/>
7        <Point x="70" y="0"/>
8        <Point x="50" y="-20"/>
9        <Point x="-50" y="-20"/>
10    </Polygon>
11    <TextItems>
12        <TextItem myStyleIO="0" posOffset-y="30" editableItem="0" ID="1" text="Test Block 3" posOffset-x="0"/>
13        <TextItem myStyleIO="1" posOffset-y="-0" editableItem="0" ID="0" text="OUT Bool " posOffset-x="60"/>
14    </TextItems>
15</CustomItem>
Software/sie_cg/block_editor/test_block4.die
1<!--File for SIE Code Generator. Custmos Blocks-->
2<CustomItem BlockName="BLOCK NAME HERE (not visible)">
3    <Polygon>
4        <Point x="-60" y="100"/>
5        <Point x="100" y="100"/>
6        <Point x="100" y="60"/>
7        <Point x="50" y="60"/>
8        <Point x="50" y="20"/>
9        <Point x="100" y="20"/>
10        <Point x="100" y="-10"/>
11        <Point x="100" y="-20"/>
12        <Point x="50" y="-20"/>
13        <Point x="50" y="-40"/>
14        <Point x="50" y="-60"/>
15        <Point x="100" y="-60"/>
16        <Point x="100" y="-100"/>
17        <Point x="-60" y="-100"/>
18        <Point x="-60" y="-20"/>
19        <Point x="-100" y="-20"/>
20        <Point x="-100" y="20"/>
21        <Point x="-60" y="20"/>
22    </Polygon>
23    <TextItems>
24        <TextItem myStyleIO="1" posOffset-y="-80" editableItem="0" ID="8" text="OUT Bool" posOffset-x="100"/>
25        <TextItem myStyleIO="1" posOffset-y="-0" editableItem="0" ID="1" text="OUT Bool" posOffset-x="100"/>
26        <TextItem myStyleIO="1" posOffset-y="80" editableItem="0" ID="6" text="OUT Bool" posOffset-x="100"/>
27        <TextItem myStyleIO="130" posOffset-y="-0" editableItem="0" ID="5" text="IN Bool" posOffset-x="-100"/>
28    </TextItems>
29</CustomItem>
Software/sie_cg/diagramitem.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43
44#include "diagramitem.h"
45#include "arrow.h"
46#include "diagramtextitem.h"
47#include "lineitem.h"
48
49DiagramItem::DiagramItem(
50                            QMenu *contextMenu,
51                            QString diagramType,
52                            QDomElement *domElement,
53                            QGraphicsItem *parent, QGraphicsScene *scene,
54                            QPointF position, double zV)
55    : QGraphicsPolygonItem(parent, scene)
56{
57    myDiagramType = diagramType;
58    myContextMenu = contextMenu;
59    myOwnerScene = scene;
60    myDomElement=domElement;
61    setPos(position);
62    setZValue(zV);
63    myColor = Qt::white;
64
65    for (QDomNode node = myDomElement->firstChild() ;
66         !node.isNull() ;
67         node = node.nextSibling())
68    {
69        QDomElement element = node.toElement();
70        if(element.tagName()=="Polygon")
71        {
72            //READING POLYGON POINTS
73            QList<QPointF> points;
74            for (QDomNode node = element.firstChild() ;
75                             !node.isNull() ;
76                             node = node.nextSibling())
77            {
78                QDomElement point = node.toElement();
79                if(point.tagName()=="Point")
80                    points.append(QPointF(
81                                  point.attribute("x").toFloat(),
82                                  point.attribute("y").toFloat()));
83            }
84            //CREATING POLYGON
85            if(points.count()>0)
86                foreach(QPointF p, points)
87                    myPolygon << p;
88
89        }
90        else if(element.tagName()=="TextItems" && myOwnerScene!=0)
91        {
92            for (QDomNode node = element.firstChild() ;
93                             !node.isNull() ;
94                             node = node.nextSibling())
95            {
96                QDomElement textItemE = node.toElement();
97            if(textItemE.tagName()=="TextItem")
98            {
99                int myStyleIO = textItemE.attribute("myStyleIO").
100                                toInt();
101                int myID = textItemE.attribute("ID").toInt();
102                bool editableItem = textItemE.attribute("editableItem").
103                                    toInt();
104                QPointF posOffset=
105                        QPointF(textItemE.attribute("posOffset-x").
106                                toFloat(),
107                                -textItemE.attribute("posOffset-y").
108                                toFloat());
109                QString itemString=textItemE.attribute("text");
110
111                DiagramTextItem * newTextItem =
112                 new DiagramTextItem(0,0,editableItem,this,myStyleIO,
113                                    myID,itemString,posOffset);
114                myOwnerScene->addItem(newTextItem);
115                addText(newTextItem);
116            }
117
118            }
119        }
120    }
121
122    setPolygon(myPolygon);
123    setFlag(QGraphicsItem::ItemIsMovable, true);
124    setFlag(QGraphicsItem::ItemIsSelectable, true);
125}
126
127bool DiagramItem::setValue(unsigned char ID, QString value)
128{
129    foreach(DiagramTextItem *item, textItems)
130    {
131        if(item->isEditable())
132        {
133            if(item->textID()==ID)
134                item->setPlainText(value);
135        }
136    }
137    return 1;
138}
139
140DiagramTextItem *DiagramItem::pointerText(unsigned char ID)
141{
142    foreach(DiagramTextItem *item, textItems)
143    {
144            if(item->textID()==ID)
145                return item;
146    }
147    return 0;
148}
149
150unsigned char DiagramItem::existArrow(DiagramTextItem *startItem,
151                                     DiagramTextItem *endItem)
152{
153    foreach (Arrow *arrow, arrows) {
154        if(arrow->startItem() == startItem &&
155           arrow->endItem() == endItem)
156            return 1; //Already exist
157        else if(arrow->endItem()== endItem)
158            return 1; //End item (INPOUT) already connected
159    }
160    return 0;
161}
162
163void DiagramItem::removeArrow(Arrow *arrow)
164{
165    int index = arrows.indexOf(arrow);
166
167    if (index != -1)
168        arrows.removeAt(index);
169}
170
171void DiagramItem::removeArrows()
172{
173    foreach (Arrow *arrow, arrows) {
174        arrow->startItem()->ownerItem()->removeArrow(arrow);
175        arrow->endItem()->ownerItem()->removeArrow(arrow);
176        arrow->removeLines();
177        scene()->removeItem(arrow);
178        delete arrow;
179    }
180}
181
182void DiagramItem::addArrow(Arrow *arrow)
183{
184    arrows.append(arrow);
185}
186
187void DiagramItem::removeTextItem(DiagramTextItem *textItem)
188{
189    int index = textItems.indexOf(textItem);
190
191    if (index != -1)
192        textItems.removeAt(index);
193}
194
195void DiagramItem::removeTextItems()
196{
197    foreach (DiagramTextItem *textItem, textItems) {
198        textItem->ownerItem()->removeTextItem(textItem);
199        scene()->removeItem(textItem);
200        delete textItem;
201    }
202}
203
204QPixmap DiagramItem::image() const
205{
206    QSize mySize=this->boundingRect().size().toSize()*1.4;
207    QPixmap pixmap(mySize);
208    pixmap.fill(Qt::transparent);
209    QPainter painter(&pixmap);
210    int penWidth;
211    if(mySize.width()>mySize.height())
212        penWidth = int(mySize.width()/32);
213    else
214        penWidth = int(mySize.height()/32);
215
216    painter.setPen(QPen(Qt::black, penWidth));
217    painter.translate(mySize.width()/2, mySize.height()/2);
218    QPolygonF Polygon = myPolygon;
219    Polygon = Polygon << Polygon.first(); //Adjust the last segment
220    painter.drawPolyline(Polygon);
221    //TODO text on icon may be interesting
222    return pixmap;
223}
224
225void DiagramItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
226{
227    scene()->clearSelection();
228    setSelected(true);
229    myContextMenu->exec(event->screenPos());
230}
231
232QVariant DiagramItem::itemChange(GraphicsItemChange change,
233                     const QVariant &value)
234{
235    if (change == QGraphicsItem::ItemPositionChange) {
236        foreach (Arrow *arrow, arrows) {
237            arrow->updatePosition();
238        }
239
240    }
241    return value;
242}
243
244void DiagramItem::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
245{
246    foreach (DiagramTextItem *texts, textItems) {
247        texts->updatePosition();
248    }
249    foreach (Arrow *arrow, arrows) {
250        arrow->updatePosition();
251    }
252    QGraphicsPolygonItem::mouseMoveEvent(mouseEvent);
253}
254
255void DiagramItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
256{
257    foreach (DiagramTextItem *texts, textItems) {
258        texts->updatePosition();
259    }
260    foreach (Arrow *arrow, arrows) {
261        arrow->updatePosition();
262    }
263    QGraphicsPolygonItem::mouseReleaseEvent(mouseEvent);
264}
265
266QDomElement DiagramItem::toXml(QDomDocument &document) const
267{
268        QDomElement diagramItem = document.createElement("DiagramItem");
269
270        //Set attibutes; type and position
271        diagramItem.setAttribute("type",diagramType());
272        diagramItem.setAttribute("x",pos().x());
273        diagramItem.setAttribute("y",pos().y());
274        diagramItem.setAttribute("z",zValue());
275        diagramItem.setAttribute("color",myColor.name());
276
277        //Lists of values (text on editable labels)
278        int i=0;
279        QDomElement diagramValues = document.createElement("diagramValues");
280        foreach(DiagramTextItem *item, textItems)
281        {
282            if(item->isEditable())
283            {
284                QDomElement diagramValue = document.createElement("diagramValue");
285                diagramValue.setAttribute("value", item->toPlainText());
286                diagramValue.setAttribute("ID", item->textID());
287                i++;
288                diagramValues.appendChild(diagramValue);
289            }
290        }
291        diagramItem.appendChild(diagramValues);
292
293        return (diagramItem);
294}
295
Software/sie_cg/diagramitem.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef DIAGRAMITEM_H
43#define DIAGRAMITEM_H
44
45#include <QGraphicsPixmapItem>
46#include <QGraphicsSimpleTextItem>
47#include <QList>
48#include <QtXml>
49#include <stdio.h>
50
51QT_BEGIN_NAMESPACE
52class QPixmap;
53class QGraphicsItem;
54class QGraphicsScene;
55class QTextEdit;
56class QGraphicsSceneMouseEvent;
57class QMenu;
58class QGraphicsSceneContextMenuEvent;
59class QPainter;
60class QStyleOptionGraphicsItem;
61class QWidget;
62class QPolygonF;
63QT_END_NAMESPACE
64
65class QObject;
66
67class Arrow;
68class DiagramTextItem;
69
70class DiagramItem : public QGraphicsPolygonItem
71{
72public:
73    enum { Type = UserType + 15 };
74
75    DiagramItem(QMenu *contextMenu,
76                QString diagramType,
77                QDomElement *domElement,
78                QGraphicsItem *parent = 0, QGraphicsScene *scene = 0,
79                QPointF position = QPointF(0,0), double zV=500);
80
81    void removeArrow(Arrow *arrow);
82    void removeArrows();
83    void addArrow(Arrow *arrow);
84
85    void addText(DiagramTextItem *externalTextItem)
86        { textItems.append(externalTextItem);}
87
88    void removeTextItem(DiagramTextItem *textItem);
89    void removeTextItems();
90
91    QString diagramType() const
92        { return myDiagramType; }
93
94    QPolygonF polygon() const
95        { return myPolygon; }
96
97    QDomElement *getDomElement()
98        {return myDomElement;}
99
100    QPixmap image() const;
101
102    int type() const
103        { return Type;}
104
105    QList<DiagramTextItem *> getTextItems() const
106        { return textItems;}
107
108    unsigned char existArrow(DiagramTextItem *startItem,
109                             DiagramTextItem *endItem);
110
111
112    void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
113        {QGraphicsPolygonItem::mousePressEvent(mouseEvent);}
114    void mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent);
115    void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent);
116
117    QDomElement toXml(QDomDocument &) const;
118
119    bool setValue(unsigned char ioID, QString value);
120    DiagramTextItem * pointerText(unsigned char ID);
121
122    void setColor(const QColor &color)
123        { myColor=color; setBrush(color); }
124
125protected:
126    void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
127    QVariant itemChange(GraphicsItemChange change, const QVariant &value);
128
129private:
130    QString myDiagramType;
131    QPolygonF myPolygon;
132    QMenu *myContextMenu;
133    QList<Arrow *> arrows;
134    QList<DiagramTextItem *> textItems;
135    QGraphicsScene *myOwnerScene;
136    DiagramTextItem *textItem;
137    QColor myColor;
138    QDomElement *myDomElement;
139};
140
141#endif
Software/sie_cg/diagramscene.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43#include <QHash>
44#include "diagramscene.h"
45#include "arrow.h"
46
47DiagramScene::DiagramScene(QMenu *itemMenu, MainWindow *ownerWindow,
48                           QObject *parent)
49    : QGraphicsScene(parent)
50{
51    myItemMenu = itemMenu;
52    myMode = MoveItem;
53    myItemType = "";
54    line = 0;
55    textItem = 0;
56    myItemColor = Qt::white;
57    myTextColor = Qt::black;
58    myLineColor = Qt::black;
59    snapToGrid=1;
60    myGrid=10;
61    drawGrid=1;
62    myOwnerWindow=ownerWindow;
63}
64
65void DiagramScene::setLineColor(const QColor &color)
66{
67    myLineColor = color;
68    if (isItemChange(Arrow::Type)) {
69        Arrow *item =
70            qgraphicsitem_cast<Arrow *>(selectedItems().first());
71        item->setColor(myLineColor);
72        update();
73    }
74}
75
76void DiagramScene::setTextColor(const QColor &color)
77{
78    myTextColor = color;
79    if (isItemChange(DiagramTextItem::Type)) {
80        DiagramTextItem *item =
81            qgraphicsitem_cast<DiagramTextItem *>(selectedItems().first());
82        item->setDefaultTextColor(myTextColor);
83    }
84}
85
86void DiagramScene::setItemColor(const QColor &color)
87{
88    myItemColor = color;
89    if (isItemChange(DiagramItem::Type)) {
90        DiagramItem *item =
91            qgraphicsitem_cast<DiagramItem *>(selectedItems().first());
92        item->setColor(myItemColor);
93    }
94}
95
96void DiagramScene::setFont(const QFont &font)
97{
98    myFont = font;
99
100    if (isItemChange(DiagramTextItem::Type)) {
101        QGraphicsTextItem *item =
102            qgraphicsitem_cast<DiagramTextItem *>(selectedItems().first());
103        //At this point the selection can change so the first selected item might not be a DiagramTextItem
104        if (item)
105            item->setFont(myFont);
106    }
107}
108
109void DiagramScene::setMode(Mode mode)
110{
111    myMode = mode;
112}
113
114void DiagramScene::setItemType(QString type)
115{
116    myItemType = type;
117}
118
119void DiagramScene::editorLostFocus(DiagramTextItem *item)
120{
121    QTextCursor cursor = item->textCursor();
122    cursor.clearSelection();
123    item->setTextCursor(cursor);
124
125    if (item->toPlainText().isEmpty()) {
126        removeItem(item);
127        item->deleteLater();
128    }
129}
130
131void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
132{
133    doSnapToGrid(mouseEvent);
134
135    if (mouseEvent->button() != Qt::LeftButton)
136        return;
137
138    DiagramItem *item;
139    switch (myMode) {
140        case InsertItem:
141            item = new DiagramItem(myItemMenu,myItemType,
142                                   domElementsByName.value(myItemType),0,this);
143            item->setColor(myItemColor);
144            addItem(item);
145            item->setPos(mouseEvent->scenePos());
146            emit itemInserted(item);
147            break;
148        case InsertLine:
149            line = new QGraphicsLineItem(QLineF(mouseEvent->scenePos(),
150                                        mouseEvent->scenePos()));
151            line->setPen(QPen(myLineColor, 2));
152            line->setZValue(1000.0);
153            addItem(line);
154            snapToGrid=0;
155            break;
156        case InsertText:
157            textItem = new DiagramTextItem();
158            textItem->setFont(myFont);
159            textItem->setTextInteractionFlags(Qt::TextEditorInteraction);
160            textItem->setZValue(1000.0);
161            connect(textItem, SIGNAL(lostFocus(DiagramTextItem*)),
162                    this, SLOT(editorLostFocus(DiagramTextItem*)));
163            connect(textItem, SIGNAL(selectedChange(QGraphicsItem*)),
164                    this, SIGNAL(itemSelected(QGraphicsItem*)));
165            addItem(textItem);
166            textItem->setDefaultTextColor(myTextColor);
167            textItem->setPos(mouseEvent->scenePos());
168            emit textInserted(textItem);
169    default:
170        ;
171    }
172    QGraphicsScene::mousePressEvent(mouseEvent);
173}
174
175void DiagramScene::doSnapToGrid(QGraphicsSceneMouseEvent *mouseEvent)
176{
177    if(snapToGrid){
178        mouseEvent->setScenePos(QPointF(
179                                int(mouseEvent->scenePos().x()/myGrid)*myGrid,
180                                int(mouseEvent->scenePos().y()/myGrid)*myGrid
181                                ));
182    }
183}
184
185void DiagramScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
186{
187    doSnapToGrid(mouseEvent);
188    if (myMode == InsertLine && line != 0) {
189        QLineF newLine(line->line().p1(), mouseEvent->scenePos());
190        line->setLine(newLine);
191    } else if (myMode == MoveItem) {
192        QGraphicsScene::mouseMoveEvent(mouseEvent);
193    }
194}
195
196void DiagramScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
197{
198    doSnapToGrid(mouseEvent);
199    QGraphicsScene::mouseDoubleClickEvent(mouseEvent);
200}
201
202void DiagramScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
203{
204    doSnapToGrid(mouseEvent);
205    if (line != 0 && myMode == InsertLine) {
206        QList<QGraphicsItem *> startItems = items(line->line().p1());
207        if (startItems.count() && startItems.first() == line)
208            startItems.removeFirst();
209        QList<QGraphicsItem *> endItems = items(line->line().p2());
210        if (endItems.count() && endItems.first() == line)
211            endItems.removeFirst();
212
213        removeItem(line);
214        delete line;
215        //Diferents items and valid type
216        if (startItems.count() > 0 && endItems.count() > 0 &&
217            startItems.first()->type() == DiagramTextItem::Type &&
218            endItems.first()->type() == DiagramTextItem::Type &&
219            startItems.first() != endItems.first())
220        {
221            DiagramTextItem *startItem_ =
222                qgraphicsitem_cast<DiagramTextItem *>(startItems.first());
223            DiagramTextItem *endItem_ =
224                qgraphicsitem_cast<DiagramTextItem *>(endItems.first());
225
226            //Real first and end item
227            DiagramTextItem *startItem = startItem_;
228            DiagramTextItem *endItem = endItem_;
229            if(startItem_->styleIO()>>7)
230            {
231                startItem = endItem_;
232                endItem = startItem_;
233            }
234
235            //Inputs to outputs and diferent owner diagram item
236            if(startItem->styleIO()>0 &&
237               endItem->styleIO()>0 &&
238              (startItem->styleIO()>>7 != endItem->styleIO()>>7) &&
239              (startItem->ownerItem() != endItem->ownerItem()) &&
240               !endItem->ownerItem()->existArrow(startItem,endItem)
241              )
242            {
243                Arrow *arrow = new Arrow(startItem, endItem,0,this);
244                arrow->setColor(myLineColor);
245                startItem->ownerItem()->addArrow(arrow);
246                endItem->ownerItem()->addArrow(arrow);
247                arrow->setZValue(0.0);
248                addItem(arrow);
249                arrow->updatePosition();
250            }
251        }
252    }
253    line = 0;
254    snapToGrid=1;
255    QGraphicsScene::mouseReleaseEvent(mouseEvent);
256}
257
258bool DiagramScene::isItemChange(int type)
259{
260    foreach (QGraphicsItem *item, selectedItems()) {
261        if (item->type() == type)
262            return true;
263    }
264    return false;
265}
266
267QDomDocument DiagramScene::toXmlFormat()
268{
269    QDomDocument document;
270    QDomComment initialComments=document.createComment(
271        "\nFile for SIE Code Generator.\n"
272        "**WARNING**If you are going to edit this file note that:\n"
273        "In order to segmentation faults prevention the load process \n"
274        "is started loading the libraries, then items and finally arrows.\n"
275        "Arrows depend of items, and items depend of libraries!!!!\n");
276    document.appendChild(initialComments);
277    QDomElement diagram = document.createElement("Diagram");
278    document.appendChild(diagram);
279
280    //Lists of items
281    QList<DiagramItem *> Items;
282    QList<Arrow *> Arrows;
283    foreach(QGraphicsItem *item, items())
284    {
285        if(item->type() == DiagramItem::Type)
286            Items.append(qgraphicsitem_cast<DiagramItem *>(item));
287        else if(item->type() == Arrow::Type)
288            Arrows.append(qgraphicsitem_cast<Arrow *>(item));
289    }
290    //Create the XML structure
291    QDomElement element;
292    if(!libraryList.isEmpty())
293    {
294        QDomElement libraries = document.createElement("Libraries");
295        foreach(QString lib, libraryList)
296        {
297            element = document.createElement("Library");
298            element.setAttribute("Dir",lib);
299            libraries.appendChild(element);
300        }
301        diagram.appendChild(libraries);
302
303    }
304    if(!Items.isEmpty())
305    {
306        QDomElement diagramItems = document.createElement("DiagramItems");
307        foreach(DiagramItem *item, Items)
308        {
309            element = item->toXml(document);
310            element.setAttribute("ID",Items.indexOf(item)); //save index
311            diagramItems.appendChild(element);
312        }
313        diagram.appendChild(diagramItems);
314    }
315    if(!Arrows.isEmpty())
316    {
317        QDomElement arrowItems = document.createElement("Arrows");
318        foreach(Arrow *item, Arrows)
319        {
320            element = item->toXml(document,Items);
321            element.setAttribute("ID",Arrows.indexOf(item)); //save index
322            arrowItems.appendChild(element);
323        }
324        diagram.appendChild(arrowItems);
325    }
326    return(document);
327}
328
329int DiagramScene::fromXmlFormat(QDomDocument document)
330{
331    //Read diagrams TODO: in future... add multi projects functionality
332    QHash<int , DiagramItem *> DiagramsID;
333    QDomNodeList diagrams = document.elementsByTagName("Diagram");
334    if(!diagrams.at(0).isElement())
335        return 0;
336    //Load the first diagram in the document
337    QDomElement diagram = diagrams.at(0).toElement();
338    //In order to segmentation faults prevention the load process
339    //is started loading the libraries, then items and finally arrows.
340    //Arrows depend of items, and items depend of libraries!!!
341    //TODO: rewrite this process for reading in the order specified
342    for (QDomNode node = diagram.firstChild() ;
343         !node.isNull() ;
344         node = node.nextSibling())
345    {
346        QDomElement element = node.toElement();
347        if(element.tagName()=="Libraries")
348        {
349            libraryList.clear();
350            for (QDomNode node = element.firstChild() ;
351                !node.isNull() ;
352                node = node.nextSibling())
353            {
354                //Load library directory
355                QDomElement Library = node.toElement();
356                if(Library.tagName()!="Library")
357                    return 0;
358                libraryList.append(Library.attribute("Dir"));
359            }
360            myOwnerWindow->updateLibraries();
361        }
362        else if(element.tagName()=="DiagramItems") //Load diagram items
363        {
364            for (QDomNode node = element.firstChild() ;
365                 !node.isNull() ;
366                 node = node.nextSibling())
367            {
368                //Load diagram item and add to scene
369                QDomElement diagramItem = node.toElement();
370                if(diagramItem.tagName()!="DiagramItem")
371                    return 0;
372
373                QPointF position = QPointF(diagramItem.attribute("x").toFloat(),
374                                          diagramItem.attribute("y").toFloat());
375                //PREVENT Segmentation faults:
376                if(!domElementsByName.contains(
377                   diagramItem.attribute("type")))
378                {
379                    QMessageBox::critical(0,"Error",QObject::tr(
380                                          "Diagram can't be loaded, because the"
381                                          " library for block [") +
382                                          diagramItem.attribute("type") +tr(
383                                          "] can't be found."));
384                    return 0;
385                }
386
387                DiagramItem *newItem=new DiagramItem(
388                        myItemMenu,
389                        diagramItem.attribute("type"),
390                        domElementsByName.value(diagramItem.attribute("type")),
391                        0,this, position,
392                        diagramItem.attribute("z").toDouble());
393
394                newItem->setColor(QColor(diagramItem.attribute("color")));
395
396                addItem(newItem);
397                DiagramsID.insert(diagramItem.attribute("ID").toInt(),newItem);
398                for (QDomNode node = diagramItem.firstChild() ;
399                     !node.isNull() ;
400                     node = node.nextSibling())
401                {
402                    //Load diagram text values and set on diagram item
403                    QDomElement diagramValues = node.toElement();
404                    if(diagramValues.tagName()!="diagramValues")
405                        return 0;
406
407                    for (QDomNode node = diagramValues.firstChild() ;
408                         !node.isNull() ;
409                         node = node.nextSibling())
410                    {
411                        QDomElement diagramValue = node.toElement();
412                        if(diagramValue.tagName()!="diagramValue")
413                            return 0;
414                        newItem->setValue(diagramValue.attribute("ID").toInt(),
415                                          diagramValue.attribute("value"));
416                    }
417                }
418            }
419        }
420        else if(element.tagName()=="Arrows")
421        {
422
423            for (QDomNode node = element.firstChild() ;
424                 !node.isNull() ;
425                 node = node.nextSibling())
426            {
427                //Load arrow item and add to scene
428                QDomElement arrow = node.toElement();
429                if(arrow.tagName()!="Arrow")
430                    return 0;
431
432                DiagramTextItem *startItem=
433                        DiagramsID.value(arrow.attribute("start-Owner").toInt())
434                        ->pointerText(arrow.attribute("start-ID").toInt());
435                DiagramTextItem *endItem=
436                        DiagramsID.value(arrow.attribute("end-Owner").toInt())
437                        ->pointerText(arrow.attribute("end-ID").toInt());
438
439                Arrow *newArrow = new Arrow(startItem, endItem,0,this);
440                newArrow->setColor(QColor(arrow.attribute("color")));
441                startItem->ownerItem()->addArrow(newArrow);
442                endItem->ownerItem()->addArrow(newArrow);
443                newArrow->setZValue(0.0);
444                addItem(newArrow);
445                newArrow->updatePosition();
446
447                for (QDomNode node = arrow.firstChild() ;
448                     !node.isNull() ;
449                     node = node.nextSibling())
450                {
451                    //Load diagram text values and set on diagram item
452                    QDomElement arrowCorners = node.toElement();
453                    if(arrowCorners.tagName()!="arrowCorners")
454                        return 0;
455                    int i=0;
456                    for (QDomNode node = arrowCorners.firstChild() ;
457                         !node.isNull() ;
458                         node = node.nextSibling())
459                    {
460                        QDomElement arrowCorner = node.toElement();
461                        if(arrowCorner.tagName()!="arrowCorner")
462                            return 0;
463
464                        QPointF cornerPos =
465                                QPointF(arrowCorner.attribute("x").toFloat(),
466                                        arrowCorner.attribute("y").toFloat());
467
468                        newArrow->createCorner(cornerPos,++i);
469                    }
470                }
471
472            }
473        }
474    }
475
476    return 1;
477}
478
479void DiagramScene::cleanScene()
480{
481    //Lists of items
482    QList<DiagramItem *> Items;
483    QList<Arrow *> Arrows;
484    foreach(QGraphicsItem *item, items())
485    {
486        if(item->type() == DiagramItem::Type)
487            Items.append(qgraphicsitem_cast<DiagramItem *>(item));
488        else if(item->type() == Arrow::Type)
489            Arrows.append(qgraphicsitem_cast<Arrow *>(item));
490    }
491    //Delete only DiagramItems: When a diagramitem is deleted his arrows and
492    //textitems have to be deleted too, so if we delete only diagramitems then
493    //we are deleting all items in the scene. This is in order to prevent
494    //segmentation faults.
495    foreach(DiagramItem *item, Items)
496    {
497        item->removeArrows();
498        item->removeTextItems();
499        removeItem(item);
500        delete(item);
501    }
502    //Delete the text items without parents
503    foreach(QGraphicsItem *item, items())
504    {
505        removeItem(item);
506        delete(item);
507    }
508}
509
510void DiagramScene::drawBackground(QPainter *p, const QRectF &r)
511{
512    QGraphicsScene::drawBackground(p,r);
513    if(drawGrid)
514    {
515        p -> save();
516
517        p -> setRenderHint(QPainter::Antialiasing, false);
518        p -> setRenderHint(QPainter::TextAntialiasing, true);
519        p -> setRenderHint(QPainter::SmoothPixmapTransform, false);
520
521        p -> setPen(Qt::NoPen);
522        p -> setBrush(Qt::white);
523        p -> drawRect(r);
524
525
526        p -> setPen(Qt::black);
527        p -> setBrush(Qt::NoBrush);
528        qreal limite_x = r.x() + r.width();
529        qreal limite_y = r.y() + r.height();
530
531        int g_x = (int)ceil(r.x());
532        while (g_x % myGrid) ++ g_x;
533        int g_y = (int)ceil(r.y());
534        while (g_y % myGrid) ++ g_y;
535
536        QPolygon points;
537        for (int gx = g_x ; gx < limite_x ; gx += myGrid) {
538            for (int gy = g_y ; gy < limite_y ; gy += myGrid) {
539                points << QPoint(gx, gy);
540            }
541        }
542        p -> drawPoints(points);
543        p -> restore();
544    }
545}
Software/sie_cg/diagramscene.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef DIAGRAMSCENE_H
43#define DIAGRAMSCENE_H
44
45#include <QGraphicsScene>
46#include <QDesktopServices>
47#include <QtXml>
48#include "diagramitem.h"
49#include "diagramtextitem.h"
50#include "mainwindow.h"
51
52QT_BEGIN_NAMESPACE
53class QGraphicsSceneMouseEvent;
54class QMenu;
55class QPointF;
56class QGraphicsLineItem;
57class QFont;
58class QGraphicsTextItem;
59class QColor;
60QT_END_NAMESPACE
61class MainWindow;
62
63class DiagramScene : public QGraphicsScene
64{
65    Q_OBJECT
66
67public:
68    enum Mode { InsertItem, InsertLine, InsertText, MoveItem };
69
70    DiagramScene(QMenu *itemMenu, MainWindow *ownerWindow = 0,
71                 QObject *parent = 0);
72
73    QFont font() const
74        { return myFont; }
75    QColor textColor() const
76        { return myTextColor; }
77    QColor itemColor() const
78        { return myItemColor; }
79    QColor lineColor() const
80        { return myLineColor; }
81    void setLineColor(const QColor &color);
82    void setTextColor(const QColor &color);
83    void setItemColor(const QColor &color);
84    void setFont(const QFont &font);
85    void setDawGrid(bool value) {drawGrid=value;}
86
87    QDomDocument toXmlFormat();
88    int fromXmlFormat(QDomDocument xmlDocument);
89    void cleanScene();
90
91    QStringList getLibList(){return libraryList;}
92    void setLibList(QStringList list)
93        {libraryList=list;}
94
95    void setDomElementsByName(QHash<QString , QDomElement*> hash)
96        {domElementsByName=hash;}
97
98    void setButtonIdByName(QHash<QString , int> hash)
99        {buttonIdByName=hash;}
100
101
102public slots:
103    void setMode(Mode mode);
104    void setItemType(QString type);
105    void editorLostFocus(DiagramTextItem *item);
106
107signals:
108    void itemInserted(DiagramItem *item);
109    void textInserted(QGraphicsTextItem *item);
110    void itemSelected(QGraphicsItem *item);
111
112protected:
113    void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
114    void mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent);
115    void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent);
116    void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent);
117    void drawBackground(QPainter *p, const QRectF &r);
118
119private:
120    bool isItemChange(int type);
121    void doSnapToGrid(QGraphicsSceneMouseEvent *mouseEvent);
122    QString myItemType;
123    QMenu *myItemMenu;
124    Mode myMode;
125    bool leftButtonDown;
126    QPointF startPoint;
127    QGraphicsLineItem *line;
128    QFont myFont;
129    DiagramTextItem *textItem;
130    QColor myTextColor;
131    QColor myItemColor;
132    QColor myLineColor;
133    bool snapToGrid;
134    bool drawGrid;
135    short int myGrid;
136    QStringList libraryList;
137    QHash<QString , QDomElement*> domElementsByName;
138    QHash<QString , int> buttonIdByName;
139    MainWindow *myOwnerWindow;
140};
141
142#endif
Software/sie_cg/diagramscene.pro
1HEADERS = mainwindow.h \
2    diagramitem.h \
3    diagramscene.h \
4    arrow.h \
5    diagramtextitem.h \
6    lineitem.h
7SOURCES = mainwindow.cpp \
8    diagramitem.cpp \
9    main.cpp \
10    arrow.cpp \
11    diagramtextitem.cpp \
12    diagramscene.cpp \
13    lineitem.cpp
14RESOURCES = diagramscene.qrc
15
16TARGET = diagrameditor
17
18# install
19target.path = $$[QT_INSTALL_EXAMPLES]/graphicsview/diagramscene
20sources.files = $$SOURCES \
21    $$HEADERS \
22    $$RESOURCES \
23    $$FORMS \
24    diagramscene.pro \
25    images
26sources.path = $$[QT_INSTALL_EXAMPLES]/graphicsview/diagramscene
27INSTALLS += target \
28    sources
29symbian:include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri)
30QT += xml \
31    svg \
32    network
33FORMS += librarydialog.ui
Software/sie_cg/diagramscene.pro.user
1<!DOCTYPE QtCreatorProject>
2<qtcreator>
3 <data>
4  <variable>RunConfiguration0-BaseEnvironmentBase</variable>
5  <value type="int">2</value>
6 </data>
7 <data>
8  <variable>RunConfiguration0-CommandLineArguments</variable>
9  <valuelist type="QVariantList"/>
10 </data>
11 <data>
12  <variable>RunConfiguration0-ProFile</variable>
13  <value type="QString">diagramscene.pro</value>
14 </data>
15 <data>
16  <variable>RunConfiguration0-RunConfiguration.name</variable>
17  <value type="QString">diagramscene</value>
18 </data>
19 <data>
20  <variable>RunConfiguration0-UseDyldImageSuffix</variable>
21  <value type="bool">false</value>
22 </data>
23 <data>
24  <variable>RunConfiguration0-UseTerminal</variable>
25  <value type="bool">false</value>
26 </data>
27 <data>
28  <variable>RunConfiguration0-UserEnvironmentChanges</variable>
29  <valuelist type="QVariantList"/>
30 </data>
31 <data>
32  <variable>RunConfiguration0-UserSetName</variable>
33  <value type="bool">false</value>
34 </data>
35 <data>
36  <variable>RunConfiguration0-UserSetWorkingDirectory</variable>
37  <value type="bool">false</value>
38 </data>
39 <data>
40  <variable>RunConfiguration0-UserWorkingDirectory</variable>
41  <value type="QString"></value>
42 </data>
43 <data>
44  <variable>RunConfiguration0-type</variable>
45  <value type="QString">Qt4ProjectManager.Qt4RunConfiguration</value>
46 </data>
47 <data>
48  <variable>activeRunConfiguration</variable>
49  <value type="int">0</value>
50 </data>
51 <data>
52  <variable>activebuildconfiguration</variable>
53  <value type="QString">Debug</value>
54 </data>
55 <data>
56  <variable>buildConfiguration-Debug</variable>
57  <valuemap type="QVariantMap">
58   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Debug</value>
59   <value key="QtVersionId" type="int">0</value>
60   <value key="ToolChain" type="int">0</value>
61   <value key="addQDumper" type=""></value>
62   <value key="buildConfiguration" type="int">2</value>
63  </valuemap>
64 </data>
65 <data>
66  <variable>buildConfiguration-Release</variable>
67  <valuemap type="QVariantMap">
68   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Release</value>
69   <value key="QtVersionId" type="int">0</value>
70   <value key="addQDumper" type=""></value>
71   <value key="buildConfiguration" type="int">0</value>
72  </valuemap>
73 </data>
74 <data>
75  <variable>buildconfiguration-Debug-buildstep0</variable>
76  <valuemap type="QVariantMap">
77   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Debug</value>
78   <valuelist key="abstractProcess.Environment" type="QVariantList">
79    <value type="QString">DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-MI4KrAyPP5,guid=5c5c5e6146195c74b6ad266d4cc07afd</value>
80    <value type="QString">DEFAULTS_PATH=/usr/share/gconf/gnome.default.path</value>
81    <value type="QString">DESKTOP_SESSION=gnome</value>
82    <value type="QString">DISPLAY=:0.0</value>
83    <value type="QString">GDMSESSION=gnome</value>
84    <value type="QString">GDM_KEYBOARD_LAYOUT=es</value>
85    <value type="QString">GDM_LANG=en_US.utf8</value>
86    <value type="QString">GNOME_DESKTOP_SESSION_ID=this-is-deprecated</value>
87    <value type="QString">GNOME_KEYRING_CONTROL=/tmp/keyring-CFAuJK</value>
88    <value type="QString">GNOME_KEYRING_PID=1516</value>
89    <value type="QString">GTK_MODULES=canberra-gtk-module</value>
90    <value type="QString">HOME=/home/juan64bits</value>
91    <value type="QString">LANG=en_US.utf8</value>
92    <value type="QString">LANGUAGE=</value>
93    <value type="QString">LD_LIBRARY_PATH=/usr/lib/qtcreator</value>
94    <value type="QString">LOGNAME=juan64bits</value>
95    <value type="QString">MANDATORY_PATH=/usr/share/gconf/gnome.mandatory.path</value>
96    <value type="QString">ORBIT_SOCKETDIR=/tmp/orbit-juan64bits</value>
97    <value type="QString">PATH=/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games</value>
98    <value type="QString">PWD=/home/juan64bits</value>
99    <value type="QString">QTDIR=/usr/share/qt4</value>
100    <value type="QString">SESSION_MANAGER=local/Maximus:@/tmp/.ICE-unix/1534,unix/Maximus:/tmp/.ICE-unix/1534</value>
101    <value type="QString">SHELL=/bin/bash</value>
102    <value type="QString">SPEECHD_PORT=7560</value>
103    <value type="QString">SSH_AGENT_PID=1570</value>
104    <value type="QString">SSH_AUTH_SOCK=/tmp/keyring-CFAuJK/ssh</value>
105    <value type="QString">USER=juan64bits</value>
106    <value type="QString">USERNAME=juan64bits</value>
107    <value type="QString">XAUTHORITY=/var/run/gdm/auth-for-juan64bits-V4ry7M/database</value>
108    <value type="QString">XDG_CONFIG_DIRS=/etc/xdg/xdg-gnome:/etc/xdg</value>
109    <value type="QString">XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/</value>
110    <value type="QString">XDG_SESSION_COOKIE=b9a7fbc4d869fc15bd6cdd474bcc9a28-1287682812.550485-1725059380</value>
111   </valuelist>
112   <valuelist key="abstractProcess.arguments" type="QVariantList">
113    <value type="QString">/home/juan64bits/QT/diagramscene/diagramscene.pro</value>
114    <value type="QString">-spec</value>
115    <value type="QString">linux-g++</value>
116    <value type="QString">-r</value>
117    <value type="QString">CONFIG+=debug</value>
118   </valuelist>
119   <value key="abstractProcess.command" type="QString">/usr/bin/qmake-qt4</value>
120   <value key="abstractProcess.enabled" type="bool">false</value>
121   <value key="abstractProcess.workingDirectory" type="QString">/home/juan64bits/QT/diagramscene</value>
122  </valuemap>
123 </data>
124 <data>
125  <variable>buildconfiguration-Debug-buildstep1</variable>
126  <valuemap type="QVariantMap">
127   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Debug</value>
128   <valuelist key="abstractProcess.Environment" type="QVariantList">
129    <value type="QString">DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-MI4KrAyPP5,guid=5c5c5e6146195c74b6ad266d4cc07afd</value>
130    <value type="QString">DEFAULTS_PATH=/usr/share/gconf/gnome.default.path</value>
131    <value type="QString">DESKTOP_SESSION=gnome</value>
132    <value type="QString">DISPLAY=:0.0</value>
133    <value type="QString">GDMSESSION=gnome</value>
134    <value type="QString">GDM_KEYBOARD_LAYOUT=es</value>
135    <value type="QString">GDM_LANG=en_US.utf8</value>
136    <value type="QString">GNOME_DESKTOP_SESSION_ID=this-is-deprecated</value>
137    <value type="QString">GNOME_KEYRING_CONTROL=/tmp/keyring-CFAuJK</value>
138    <value type="QString">GNOME_KEYRING_PID=1516</value>
139    <value type="QString">GTK_MODULES=canberra-gtk-module</value>
140    <value type="QString">HOME=/home/juan64bits</value>
141    <value type="QString">LANG=en_US.utf8</value>
142    <value type="QString">LANGUAGE=</value>
143    <value type="QString">LD_LIBRARY_PATH=/usr/lib/qtcreator</value>
144    <value type="QString">LOGNAME=juan64bits</value>
145    <value type="QString">MANDATORY_PATH=/usr/share/gconf/gnome.mandatory.path</value>
146    <value type="QString">ORBIT_SOCKETDIR=/tmp/orbit-juan64bits</value>
147    <value type="QString">PATH=/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games</value>
148    <value type="QString">PWD=/home/juan64bits</value>
149    <value type="QString">QTDIR=/usr/share/qt4</value>
150    <value type="QString">SESSION_MANAGER=local/Maximus:@/tmp/.ICE-unix/1534,unix/Maximus:/tmp/.ICE-unix/1534</value>
151    <value type="QString">SHELL=/bin/bash</value>
152    <value type="QString">SPEECHD_PORT=7560</value>
153    <value type="QString">SSH_AGENT_PID=1570</value>
154    <value type="QString">SSH_AUTH_SOCK=/tmp/keyring-CFAuJK/ssh</value>
155    <value type="QString">USER=juan64bits</value>
156    <value type="QString">USERNAME=juan64bits</value>
157    <value type="QString">XAUTHORITY=/var/run/gdm/auth-for-juan64bits-V4ry7M/database</value>
158    <value type="QString">XDG_CONFIG_DIRS=/etc/xdg/xdg-gnome:/etc/xdg</value>
159    <value type="QString">XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/</value>
160    <value type="QString">XDG_SESSION_COOKIE=b9a7fbc4d869fc15bd6cdd474bcc9a28-1287682812.550485-1725059380</value>
161   </valuelist>
162   <value key="abstractProcess.IgnoreReturnValue" type="bool">false</value>
163   <valuelist key="abstractProcess.arguments" type="QVariantList">
164    <value type="QString">-w</value>
165   </valuelist>
166   <value key="abstractProcess.command" type="QString">/usr/bin/make</value>
167   <value key="abstractProcess.enabled" type="bool">true</value>
168   <value key="abstractProcess.workingDirectory" type="QString">/home/juan64bits/QT/diagramscene</value>
169  </valuemap>
170 </data>
171 <data>
172  <variable>buildconfiguration-Debug-cleanstep0</variable>
173  <valuemap type="QVariantMap">
174   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Debug</value>
175   <value key="cleanConfig" type="bool">true</value>
176   <valuelist key="makeargs" type="QVariantList">
177    <value type="QString">clean</value>
178   </valuelist>
179  </valuemap>
180 </data>
181 <data>
182  <variable>buildconfiguration-Release-buildstep0</variable>
183  <valuemap type="QVariantMap">
184   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Release</value>
185  </valuemap>
186 </data>
187 <data>
188  <variable>buildconfiguration-Release-buildstep1</variable>
189  <valuemap type="QVariantMap">
190   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Release</value>
191  </valuemap>
192 </data>
193 <data>
194  <variable>buildconfiguration-Release-cleanstep0</variable>
195  <valuemap type="QVariantMap">
196   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString">Release</value>
197  </valuemap>
198 </data>
199 <data>
200  <variable>buildconfigurations</variable>
201  <valuelist type="QVariantList">
202   <value type="QString">Debug</value>
203   <value type="QString">Release</value>
204  </valuelist>
205 </data>
206 <data>
207  <variable>buildstep0</variable>
208  <valuemap type="QVariantMap">
209   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString"></value>
210   <value key="mkspec" type="QString"></value>
211  </valuemap>
212 </data>
213 <data>
214  <variable>buildstep1</variable>
215  <valuemap type="QVariantMap">
216   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString"></value>
217  </valuemap>
218 </data>
219 <data>
220  <variable>buildsteps</variable>
221  <valuelist type="QVariantList">
222   <value type="QString">trolltech.qt4projectmanager.qmake</value>
223   <value type="QString">trolltech.qt4projectmanager.make</value>
224  </valuelist>
225 </data>
226 <data>
227  <variable>cleanstep0</variable>
228  <valuemap type="QVariantMap">
229   <value key="ProjectExplorer.BuildConfiguration.DisplayName" type="QString"></value>
230   <value key="clean" type="bool">true</value>
231  </valuemap>
232 </data>
233 <data>
234  <variable>cleansteps</variable>
235  <valuelist type="QVariantList">
236   <value type="QString">trolltech.qt4projectmanager.make</value>
237  </valuelist>
238 </data>
239 <data>
240  <variable>defaultFileEncoding</variable>
241  <value type="QByteArray">System</value>
242 </data>
243 <data>
244  <variable>project</variable>
245  <valuemap type="QVariantMap"/>
246 </data>
247</qtcreator>
Software/sie_cg/diagramscene.qrc
1<RCC>
2    <qresource prefix="/">
3        <file>images/pointer.png</file>
4        <file>images/linepointer.png</file>
5        <file>images/textpointer.png</file>
6        <file>images/bold.png</file>
7        <file>images/italic.png</file>
8        <file>images/underline.png</file>
9        <file>images/floodfill.png</file>
10        <file>images/bringtofront.png</file>
11        <file>images/delete.png</file>
12        <file>images/sendtoback.png</file>
13        <file>images/linecolor.png</file>
14        <file>images/background1.png</file>
15        <file>images/background2.png</file>
16        <file>images/background3.png</file>
17        <file>images/background4.png</file>
18        <file>images/exit.png</file>
19        <file>images/new.png</file>
20        <file>images/no.png</file>
21        <file>images/open.png</file>
22        <file>images/save.png</file>
23        <file>images/save_as.png</file>
24        <file>images/yes.png</file>
25        <file>images/zoom_in.png</file>
26        <file>images/zoom_out.png</file>
27    </qresource>
28</RCC>
Software/sie_cg/diagramtextitem.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43
44#include "diagramtextitem.h"
45#include "diagramscene.h"
46
47DiagramTextItem::DiagramTextItem(QGraphicsItem *parent, QGraphicsScene *scene,
48                 bool editable, DiagramItem *ownerItem, unsigned char styleIO,
49                 unsigned char ID, QString defaultText, QPointF offset)
50    : QGraphicsTextItem(parent, scene)
51{
52    myOwnerItem = ownerItem;
53    myStyleIO = styleIO;
54    myID=ID;
55    editableItem=editable;
56    if(myOwnerItem==0)
57        setZValue(1000.0);
58    else
59        setZValue(myOwnerItem->zValue());
60
61    setPlainText(defaultText);
62    posOffset=offset;
63
64    if(editable)
65    {
66        if (myOwnerItem==0)
67            setFlag(QGraphicsItem::ItemIsMovable);
68        setFlag(QGraphicsItem::ItemIsSelectable);
69    }
70    else
71        setFlag(QGraphicsItem::ItemIsFocusable,0);
72
73        updatePosition();
74}
75
76void DiagramTextItem::updatePosition()
77{
78        QPointF myOwnerPos;
79
80
81        if(myOwnerItem!=0)
82        {
83            setZValue(myOwnerItem->zValue());
84            myOwnerPos= myOwnerItem->pos();
85        }
86        else
87        {
88            setZValue(1000.0);
89            myOwnerPos=pos();
90        }
91
92        if(myStyleIO==0)
93            setPos(myOwnerPos+posOffset+QPointF(-boundingRect().width()/2,
94                                                -boundingRect().height()/2));
95        else if(myStyleIO & 0b10000000)
96            setPos(myOwnerPos+posOffset+QPointF(0,-boundingRect().height()/2));
97        else //OUT
98            setPos(myOwnerPos+posOffset+QPointF(-boundingRect().width(),
99                                                -boundingRect().height()/2));
100}
101
102QVariant DiagramTextItem::itemChange(GraphicsItemChange change,
103                     const QVariant &value)
104{
105    if (change == QGraphicsItem::ItemSelectedHasChanged)
106        emit selectedChange(this);
107
108    return value;
109}
110
111void DiagramTextItem::focusOutEvent(QFocusEvent *event)
112{
113    if(editableItem)
114    {
115        if(toPlainText()=="") setPlainText("?");
116        if(myOwnerItem!=0) updatePosition();
117        setTextInteractionFlags(Qt::NoTextInteraction);
118        emit lostFocus(this);
119        QGraphicsTextItem::focusOutEvent(event);
120    }
121}
122
123void DiagramTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
124{
125    if(editableItem)
126    {
127        if (textInteractionFlags() == Qt::NoTextInteraction)
128            setTextInteractionFlags(Qt::TextEditorInteraction);
129        QGraphicsTextItem::mouseDoubleClickEvent(event);
130    }
131}
132
133void DiagramTextItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
134{
135        if (myOwnerItem!=0)
136        {
137            setSelected(0);
138            myOwnerItem->mousePressEvent(event);
139        }
140        else
141            QGraphicsTextItem::mousePressEvent(event);
142}
143
144void DiagramTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
145{
146        if (myOwnerItem!=0)
147        {
148            myOwnerItem->mouseReleaseEvent(event);
149        }
150        else
151            QGraphicsTextItem::mouseReleaseEvent(event);
152}
153
154void DiagramTextItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
155{
156        if (myOwnerItem!=0)
157        {
158            myOwnerItem->mouseMoveEvent(event);
159        }
160        else
161            QGraphicsTextItem::mouseMoveEvent(event);
162}
Software/sie_cg/diagramtextitem.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef DIAGRAMTEXTITEM_H
43#define DIAGRAMTEXTITEM_H
44
45#include <QGraphicsTextItem>
46#include <QPen>
47#include "diagramitem.h"
48
49QT_BEGIN_NAMESPACE
50class QFocusEvent;
51class QGraphicsItem;
52class QGraphicsScene;
53class QGraphicsSceneMouseEvent;
54QT_END_NAMESPACE
55
56class DiagramTextItem : public QGraphicsTextItem
57{
58    Q_OBJECT
59
60public:
61    enum { Type = UserType + 3 };
62
63    DiagramTextItem(
64          QGraphicsItem *parent = 0, QGraphicsScene *scene = 0,
65          bool editable =1, DiagramItem *ownerItem=0, unsigned char styleIO = 0,
66          unsigned char ID=0, QString defaultText="<text>",
67          QPointF offset=QPointF(0,0));
68
69    int type() const
70        { return Type;}
71
72    unsigned char styleIO() const
73        { return myStyleIO;}
74
75    unsigned char textID() const
76        { return myID;}
77
78    QPointF offset() const
79        { return posOffset;}
80
81    DiagramItem *ownerItem() const
82        { return myOwnerItem; }
83
84    bool isEditable()
85        { return editableItem;}
86
87public slots:
88    void updatePosition();
89
90signals:
91    void lostFocus(DiagramTextItem *item);
92    void selectedChange(QGraphicsItem *item);
93
94protected:
95    QVariant itemChange(GraphicsItemChange change, const QVariant &value);
96    void focusOutEvent(QFocusEvent *event);
97    void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
98    void mousePressEvent(QGraphicsSceneMouseEvent *event);
99    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
100    void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
101
102private:
103    bool editableItem;
104    DiagramItem *myOwnerItem;
105    QPointF posOffset;
106    unsigned char myStyleIO;
107    unsigned char myID;
108};
109
110#endif
Software/sie_cg/images/background1.png
Software/sie_cg/images/background2.png
Software/sie_cg/images/background3.png
Software/sie_cg/images/background4.png
Software/sie_cg/images/bold.png
Software/sie_cg/images/bringtofront.png
Software/sie_cg/images/delete.png
Software/sie_cg/images/exit.png
Software/sie_cg/images/floodfill.png
Software/sie_cg/images/italic.png
Software/sie_cg/images/linecolor.png
Software/sie_cg/images/linepointer.png
Software/sie_cg/images/lower1.png
Software/sie_cg/images/new.png
Software/sie_cg/images/no.png
Software/sie_cg/images/open.png
Software/sie_cg/images/pointer.png
Software/sie_cg/images/preview.png
Software/sie_cg/images/raise1.png
Software/sie_cg/images/save.png
Software/sie_cg/images/save_as.png
Software/sie_cg/images/sendtoback.png
Software/sie_cg/images/textpointer.png
Software/sie_cg/images/underline.png
Software/sie_cg/images/yes.png
Software/sie_cg/images/zoom_in.png
Software/sie_cg/images/zoom_out.png
Software/sie_cg/librarydialog.o
Software/sie_cg/librarydialog.ui
1<?xml version="1.0" encoding="UTF-8"?>
2<ui version="4.0">
3 <class>libraryDialog</class>
4 <widget class="QDialog" name="libraryDialog">
5  <property name="geometry">
6   <rect>
7    <x>0</x>
8    <y>0</y>
9    <width>333</width>
10    <height>341</height>
11   </rect>
12  </property>
13  <property name="windowTitle">
14   <string>Dialog</string>
15  </property>
16  <layout class="QVBoxLayout" name="verticalLayout">
17   <item>
18    <widget class="QListWidget" name="listLib"/>
19   </item>
20   <item>
21    <layout class="QHBoxLayout" name="horizontalLayout">
22     <item>
23      <widget class="QPushButton" name="addLib">
24       <property name="text">
25        <string>&amp;Add Library</string>
26       </property>
27      </widget>
28     </item>
29     <item>
30      <widget class="QPushButton" name="delLib">
31       <property name="text">
32        <string>&amp;Remove library</string>
33       </property>
34      </widget>
35     </item>
36     <item>
37      <widget class="QPushButton" name="editLib">
38       <property name="text">
39        <string>&amp;Edit library</string>
40       </property>
41      </widget>
42     </item>
43    </layout>
44   </item>
45   <item>
46    <widget class="Line" name="line">
47     <property name="orientation">
48      <enum>Qt::Horizontal</enum>
49     </property>
50    </widget>
51   </item>
52   <item>
53    <widget class="QDialogButtonBox" name="buttonBox">
54     <property name="orientation">
55      <enum>Qt::Horizontal</enum>
56     </property>
57     <property name="standardButtons">
58      <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
59     </property>
60    </widget>
61   </item>
62  </layout>
63 </widget>
64 <resources/>
65 <connections>
66  <connection>
67   <sender>buttonBox</sender>
68   <signal>rejected()</signal>
69   <receiver>libraryDialog</receiver>
70   <slot>reject()</slot>
71   <hints>
72    <hint type="sourcelabel">
73     <x>316</x>
74     <y>260</y>
75    </hint>
76    <hint type="destinationlabel">
77     <x>286</x>
78     <y>274</y>
79    </hint>
80   </hints>
81  </connection>
82  <connection>
83   <sender>buttonBox</sender>
84   <signal>accepted()</signal>
85   <receiver>libraryDialog</receiver>
86   <slot>accept()</slot>
87   <hints>
88    <hint type="sourcelabel">
89     <x>248</x>
90     <y>254</y>
91    </hint>
92    <hint type="destinationlabel">
93     <x>157</x>
94     <y>274</y>
95    </hint>
96   </hints>
97  </connection>
98 </connections>
99</ui>
Software/sie_cg/lineitem.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43
44#include "lineitem.h"
45#include <math.h>
46
47lineItem::lineItem(QPointF startPoint, QPointF endItem, Arrow *ownerArrow,
48    int wt, bool movable, QGraphicsItem *parent, QGraphicsScene *scene)
49    : QGraphicsLineItem(parent, scene)
50{
51    isMovable=movable;
52    if(isMovable) setFlag(QGraphicsItem::ItemIsMovable, true);
53
54    setFlag(QGraphicsItem::ItemIsSelectable, true);
55
56    myColor = Qt::black;
57    setPen(QPen(myColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
58    setLine(QLineF(startPoint,endItem));
59    myOwnerArrow = ownerArrow;
60    pWidth=wt;
61    moveItem=0;
62}
63
64QRectF lineItem::boundingRect() const
65{
66    qreal extra = (pen().width() + 20) / 2.0;
67
68    return QRectF(line().p1(), QSizeF(line().p2().x() - line().p1().x(),
69                                      line().p2().y() - line().p1().y()))
70        .normalized()
71        .adjusted(-extra, -extra, extra, extra);
72}
73
74QPainterPath lineItem::shape() const
75{
76    QPainterPath path = QGraphicsLineItem::shape();
77    return path;
78}
79
80void lineItem::updatePos()
81{
82    QPointF itemPos = this->line().p1();
83    myOwnerArrow->moveCorner(itemPos,this);
84}
85
86void lineItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
87          QWidget *)
88{
89    QPen myPen = pen();
90    myPen.setColor(myColor);
91    myPen.setWidth(pWidth);
92    painter->setPen(myPen);
93    painter->setBrush(myColor);
94
95    setLine(line());
96        painter->drawLine(line());
97
98        //Drawing arrow selected
99        if (isSelected()) {
100            painter->setPen(QPen(Qt::gray, pWidth, Qt::SolidLine));
101            QLineF myLine = line();
102            painter->drawLine(myLine);
103        }
104}
105
106void lineItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
107{
108    if(!isMovable)
109    {
110        myOwnerArrow->createCorner(mouseEvent->pos(),this);
111    }
112    QGraphicsLineItem::mouseDoubleClickEvent(mouseEvent);
113}
114
115
116void lineItem::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
117{
118    QGraphicsLineItem::mousePressEvent(mouseEvent);
119}
120
121void lineItem::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
122{
123    if(isMovable)
124    {
125        updatePos();
126    }
127    QGraphicsLineItem::mouseMoveEvent(mouseEvent);
128}
129
130void lineItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
131{
132    if(isMovable)
133    {
134        updatePos();
135    }
136    QGraphicsLineItem::mouseReleaseEvent(mouseEvent);
137}
Software/sie_cg/lineitem.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef LINEITEM_H
43#define LINEITEM_H
44
45#include <QGraphicsLineItem>
46
47#include "diagramitem.h"
48#include "arrow.h"
49
50QT_BEGIN_NAMESPACE
51class QGraphicsPolygonItem;
52class QGraphicsLineItem;
53class QGraphicsScene;
54class QRectF;
55class QGraphicsSceneMouseEvent;
56class QPainterPath;
57QT_END_NAMESPACE
58
59class lineItem : public QGraphicsLineItem
60{
61public:
62    enum { Type = UserType + 4 };
63
64    lineItem(QPointF startPoint, QPointF endItem, Arrow *ownerArrow, int wt=2,
65        bool movable = 0, QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);
66
67    int type() const
68        { return Type;}
69    QRectF boundingRect() const;
70    QPainterPath shape() const;
71    void setColor(const QColor &color)
72        { myColor=color; }
73
74    Arrow * myOwner()
75        { return myOwnerArrow;}
76
77    bool itemIsMovable() {return isMovable;}
78
79public slots:
80    void updatePos();
81
82protected:
83    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
84               QWidget *widget = 0);
85    void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
86    void mousePressEvent(QGraphicsSceneMouseEvent *event);
87    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
88    void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
89
90private:
91    QColor myColor;
92    int pWidth;
93    Arrow *myOwnerArrow;
94    int moveItem;
95    bool isMovable;
96};
97
98#endif
Software/sie_cg/main.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43
44#include "mainwindow.h"
45
46int main(int argv, char *args[])
47{
48    Q_INIT_RESOURCE(diagramscene);
49
50    QApplication app(argv, args);
51    MainWindow mainWindow;
52    mainWindow.setGeometry(100, 100, 1024, 640);
53    mainWindow.show();
54    return app.exec();
55}
Software/sie_cg/mainwindow.cpp
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <QtGui>
43#include <QLabel>
44
45#include "mainwindow.h"
46
47const int InsertTextButton = 100000;
48
49MainWindow::MainWindow()
50{
51    buttonGroup=0;
52    toolBox=0;
53
54    createActions();
55    createMenus();
56    scene = new DiagramScene(itemMenu,this);
57    scene->setSceneRect(QRectF(0, 0, 5000, 5000));
58    connect(scene, SIGNAL(itemInserted(DiagramItem*)),
59            this, SLOT(itemInserted(DiagramItem*)));
60    connect(scene, SIGNAL(textInserted(QGraphicsTextItem*)),
61        this, SLOT(textInserted(QGraphicsTextItem*)));
62    connect(scene, SIGNAL(itemSelected(QGraphicsItem*)),
63        this, SLOT(itemSelected(QGraphicsItem*)));
64    createToolBox();
65    createToolbars();
66
67    setWindowTitle(tr("SIE Code Generator (Diagram Editor)"));
68    setUnifiedTitleAndToolBarOnMac(true);
69    myFilePath = "";
70    libDialog=0;
71
72    if(QApplication::argc()>1)
73        {newDiagram(QString(QApplication::argv()[1]));}
74}
75
76void MainWindow::backgroundButtonGroupClicked(QAbstractButton *button)
77{
78    QList<QAbstractButton *> buttons = backgroundButtonGroup->buttons();
79    foreach (QAbstractButton *myButton, buttons) {
80    if (myButton != button)
81        button->setChecked(false);
82    }
83    QString text = button->text();
84    if (text == tr("Blue Grid"))
85        scene->setBackgroundBrush(QPixmap(":/images/background1.png"));
86    else if (text == tr("White Grid"))
87        scene->setBackgroundBrush(QPixmap(":/images/background2.png"));
88    else if (text == tr("Gray Grid"))
89        scene->setBackgroundBrush(QPixmap(":/images/background3.png"));
90    else
91        scene->setBackgroundBrush(QPixmap(":/images/background4.png"));
92
93    scene->update();
94    view->update();
95}
96
97void MainWindow::buttonGroupClicked(int id)
98{
99    QList<QAbstractButton *> buttons = buttonGroup->buttons();
100    foreach (QAbstractButton *button, buttons) {
101    if (buttonGroup->button(id) != button)
102        button->setChecked(false);
103    }
104    if (id == InsertTextButton) {
105        scene->setMode(DiagramScene::InsertText);
106    } else {
107        scene->setItemType(buttonGroup->button(id)->text()); //Block name
108        scene->setMode(DiagramScene::InsertItem);
109    }
110}
111
112void MainWindow::deleteItem()
113{
114    foreach (QGraphicsItem *item, scene->selectedItems()) {
115        if (item->type() == DiagramItem::Type) {
116            qgraphicsitem_cast<DiagramItem *>(item)->removeArrows();
117            qgraphicsitem_cast<DiagramItem *>(item)->removeTextItems();
118            scene->removeItem(item);
119            delete(item);
120        }
121        //If arrow is deleted then is romoved from diagram owner
122        else if (item->type() == Arrow::Type) {
123           qgraphicsitem_cast<Arrow *>(item)->removeLines();
124           qgraphicsitem_cast<Arrow *>(item)->startItem()->ownerItem()
125                            ->removeArrow(qgraphicsitem_cast<Arrow *>(item));
126           qgraphicsitem_cast<Arrow *>(item)->endItem()->ownerItem()
127                            ->removeArrow(qgraphicsitem_cast<Arrow *>(item));
128           scene->removeItem(item);
129           delete(item);
130        }
131        //If line is deleted then is romoved from the arrow owner
132        else if (item->type() == lineItem::Type &&
133                 !qgraphicsitem_cast<lineItem *>(item)->itemIsMovable()) {
134
135           qgraphicsitem_cast<lineItem *>(item)->myOwner()->removeLine(
136                                    qgraphicsitem_cast<lineItem *>(item));
137           qgraphicsitem_cast<lineItem *>(item)->myOwner()->updatePosition();
138           scene->removeItem(item);
139           delete(item);
140       }
141
142    }
143}
144
145void MainWindow::pointerGroupClicked(int)
146{
147    scene->setMode(DiagramScene::Mode(pointerTypeGroup->checkedId()));
148}
149
150void MainWindow::bringToFront()
151{
152    sendTo(1);
153}
154
155void MainWindow::sendToBack()
156{
157    sendTo(0);
158}
159
160void MainWindow::sendTo(bool value)
161{
162    if (scene->selectedItems().isEmpty())
163        return;
164
165    QGraphicsItem *selectedItem = scene->selectedItems().first();
166    QList<QGraphicsItem *> overlapItems = selectedItem->collidingItems();
167
168    qreal zValue = 0;
169    foreach (QGraphicsItem *item, overlapItems) {
170        if (item->zValue() <= zValue &&
171            item->type() == DiagramItem::Type)
172        {
173            if(value)
174                zValue = item->zValue() + 0.1;
175            else
176                zValue = item->zValue() - 0.1;
177        }
178    }
179    selectedItem->setZValue(zValue);
180    if(selectedItem->type() == DiagramItem::Type)
181        foreach (DiagramTextItem *texts,
182                qgraphicsitem_cast<DiagramItem *>(selectedItem)->getTextItems())
183        {
184            texts->updatePosition();
185        }
186
187}
188
189void MainWindow::itemInserted(DiagramItem *item)
190{
191    pointerTypeGroup->button(int(DiagramScene::MoveItem))->setChecked(true);
192    scene->setMode(DiagramScene::Mode(pointerTypeGroup->checkedId()));
193    buttonGroup->button(buttonIdByName.value(item->diagramType()))->setChecked(false);
194}
195
196void MainWindow::textInserted(QGraphicsTextItem *)
197{
198    buttonGroup->button(InsertTextButton)->setChecked(false);
199    scene->setMode(DiagramScene::Mode(pointerTypeGroup->checkedId()));
200}
201
202void MainWindow::currentFontChanged(const QFont &)
203{
204    handleFontChange();
205}
206
207void MainWindow::fontSizeChanged(const QString &)
208{
209    handleFontChange();
210}
211
212void MainWindow::sceneScaleChanged(const QString &scale)
213{
214    double newScale = scale.left(scale.indexOf(tr("%"))).toDouble() / 100.0;
215    QMatrix oldMatrix = view->matrix();
216    view->resetMatrix();
217    view->translate(oldMatrix.dx(), oldMatrix.dy());
218    view->scale(newScale, newScale);
219}
220
221void MainWindow::textColorChanged()
222{
223    textAction = qobject_cast<QAction *>(sender());
224    fontColorToolButton->setIcon(createColorToolButtonIcon(
225                ":/images/textpointer.png",
226                qVariantValue<QColor>(textAction->data())));
227    textButtonTriggered();
228}
229
230void MainWindow::itemColorChanged()
231{
232    fillAction = qobject_cast<QAction *>(sender());
233    fillColorToolButton->setIcon(createColorToolButtonIcon(
234                 ":/images/floodfill.png",
235                 qVariantValue<QColor>(fillAction->data())));
236    fillButtonTriggered();
237}
238
239void MainWindow::lineColorChanged()
240{
241    lineAction = qobject_cast<QAction *>(sender());
242    lineColorToolButton->setIcon(createColorToolButtonIcon(
243                 ":/images/linecolor.png",
244                 qVariantValue<QColor>(lineAction->data())));
245    lineButtonTriggered();
246}
247
248void MainWindow::textButtonTriggered()
249{
250    scene->setTextColor(qVariantValue<QColor>(textAction->data()));
251}
252
253void MainWindow::fillButtonTriggered()
254{
255    scene->setItemColor(qVariantValue<QColor>(fillAction->data()));
256}
257
258void MainWindow::lineButtonTriggered()
259{
260    scene->setLineColor(qVariantValue<QColor>(lineAction->data()));
261}
262
263void MainWindow::handleFontChange()
264{
265    QFont font = fontCombo->currentFont();
266    font.setPointSize(fontSizeCombo->currentText().toInt());
267    font.setWeight(boldAction->isChecked() ? QFont::Bold : QFont::Normal);
268    font.setItalic(italicAction->isChecked());
269    font.setUnderline(underlineAction->isChecked());
270
271    scene->setFont(font);
272}
273
274void MainWindow::itemSelected(QGraphicsItem *item)
275{
276    DiagramTextItem *textItem =
277    qgraphicsitem_cast<DiagramTextItem *>(item);
278
279    QFont font = textItem->font();
280    QColor color = textItem->defaultTextColor();
281    fontCombo->setCurrentFont(font);
282    fontSizeCombo->setEditText(QString().setNum(font.pointSize()));
283    boldAction->setChecked(font.weight() == QFont::Bold);
284    italicAction->setChecked(font.italic());
285    underlineAction->setChecked(font.underline());
286}
287
288void MainWindow::about()
289{
290    QMessageBox::question(this, tr("About SIE Code Generator"),
291                       tr("TODO <b>:)</b>"));
292}
293
294void MainWindow::addLibrariesButtons(QGridLayout *layout)
295{
296    int i=1;
297    domElementsByName.clear(); buttonIdByName.clear();
298    QDomDocument customItems;
299    foreach(QString filepath, libraryList)
300    {
301        customItems = parseDocument(filepath);
302        for (QDomNode node = customItems.firstChild() ;
303             !node.isNull() ;
304             node = node.nextSibling())
305        {
306            QDomElement *customItem = new QDomElement(node.toElement());
307            if(customItem->tagName()=="CustomItem")
308            {
309                if(domElementsByName.contains(
310                        customItem->attribute("BlockName")))
311                {
312                    QMessageBox::warning(this,"Block name in use.",
313                                         "The library " + filepath +
314                                         " has one block called" +
315                                         customItem->attribute("BlockName") +
316                                         " that is already in use. Only the "
317                                         " first Block loaded can be used, this"
318                                         " library will be ignored.");
319                }
320                else
321                {
322                    domElementsByName.insert(customItem->attribute("BlockName"),
323                                             customItem);
324                    buttonIdByName.insert(customItem->attribute("BlockName"),i-1);
325
326                    scene->setDomElementsByName(domElementsByName);
327                    scene->setButtonIdByName(buttonIdByName);
328
329                    layout->addWidget(createCellWidget(
330                            customItem->attribute("BlockName"),
331                            domElementsByName.
332                            value(customItem->attribute("BlockName"))),i/2,i&1);
333                    i++;
334                }
335            }
336        }
337    }
338}
339
340
341
342void MainWindow::createToolBox()
343{
344    if(buttonGroup!=0) delete(buttonGroup);
345    if(toolBox!=0) delete(toolBox);
346    buttonGroup = new QButtonGroup;
347    buttonGroup->setExclusive(false);
348    connect(buttonGroup, SIGNAL(buttonClicked(int)),
349            this, SLOT(buttonGroupClicked(int)));
350
351    QGridLayout *layout = new QGridLayout;
352
353    addLibrariesButtons(layout);
354
355    QToolButton *textButton = new QToolButton;
356    textButton->setCheckable(true);
357    buttonGroup->addButton(textButton, InsertTextButton);
358    textButton->setIcon(QIcon(QPixmap(":/images/textpointer.png")
359                        .scaled(30, 30)));
360    textButton->setIconSize(QSize(50, 50));
361    QGridLayout *textLayout = new QGridLayout;
362    textLayout->addWidget(textButton, 0, 0, Qt::AlignHCenter);
363    textLayout->addWidget(new QLabel(tr("Text")), 1, 0, Qt::AlignCenter);
364    QWidget *textWidget = new QWidget;
365    textWidget->setLayout(textLayout);
366    layout->addWidget(textWidget, 0, 0);
367
368    layout->setRowStretch(3, 10);
369    layout->setColumnStretch(2, 10);
370
371    QWidget *itemWidget = new QWidget;
372    itemWidget->setLayout(layout);
373
374    toolBox = new QToolBox;
375    toolBox->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Ignored));
376    toolBox->setMinimumWidth(itemWidget->sizeHint().width());
377    toolBox->addItem(itemWidget, tr("Basic Flowchart Shapes"));
378    //toolBox->addItem(backgroundWidget, tr("Backgrounds"));
379
380    //Add tool box to window
381    QHBoxLayout *newLayout = new QHBoxLayout;
382    newLayout->addWidget(toolBox);
383    view = new QGraphicsView(scene);
384    newLayout->addWidget(view);
385
386    QWidget *widget = new QWidget;
387    widget->setLayout(newLayout);
388
389    setCentralWidget(widget);
390}
391
392void MainWindow::createActions()
393{
394    toFrontAction = new QAction(QIcon(":/images/bringtofront.png"),
395                                tr("Bring to &Front"), this);
396    toFrontAction->setShortcut(tr("Ctrl+F"));
397    toFrontAction->setStatusTip(tr("Bring item to front"));
398    connect(toFrontAction, SIGNAL(triggered()),
399            this, SLOT(bringToFront()));
400
401    sendBackAction = new QAction(QIcon(":/images/sendtoback.png"),
402                                 tr("Send to &Back"), this);
403    sendBackAction->setShortcut(tr("Ctrl+B"));
404    sendBackAction->setStatusTip(tr("Send item to back"));
405    connect(sendBackAction, SIGNAL(triggered()),
406        this, SLOT(sendToBack()));
407
408    deleteAction = new QAction(QIcon(":/images/delete.png"),
409                               tr("&Delete"), this);
410    deleteAction->setShortcut(tr("Ctrl+Delete"));
411    deleteAction->setStatusTip(tr("Delete item from diagram"));
412    connect(deleteAction, SIGNAL(triggered()),
413        this, SLOT(deleteItem()));
414
415
416    newAction = new QAction(QIcon(":/images/new.png"),tr("&New"),this);
417    newAction->setShortcuts(QKeySequence::New);
418    newAction->setStatusTip("New diagram");
419    connect(newAction,SIGNAL(triggered()),this,SLOT(newDiagram()));
420
421    saveAction = new QAction(QIcon(":/images/save.png"),tr("&Save"),this);
422    saveAction->setShortcuts(QKeySequence::Save);
423    saveAction->setStatusTip("Save current diagram");
424    connect(saveAction,SIGNAL(triggered()),this,SLOT(saveDiagram()));
425
426    saveAsAction = new QAction(QIcon(":/images/save_as.png"),
427                               tr("Save &As..."),this);
428    saveAsAction->setShortcuts(QKeySequence::SaveAs);
429    saveAsAction->setStatusTip("Save current diagram with another name");
430    connect(saveAsAction,SIGNAL(triggered()),this,SLOT(saveAsDiagram()));
431
432    openAction = new QAction(QIcon(":/images/open.png"),tr("&Open"),this);
433    openAction->setShortcuts(QKeySequence::Open);
434    openAction->setStatusTip("Open diagram");
435    connect(openAction,SIGNAL(triggered()),this,SLOT(openDiagram()));
436
437    exportImgAction = new QAction(tr("&Export to ..."),this);
438    exportImgAction->setStatusTip("Export current diagram to picture");
439    connect(exportImgAction,SIGNAL(triggered()),this,SLOT(exportDiagram()));
440
441    exitAction = new QAction(tr("E&xit"), this);
442    exitAction->setShortcuts(QKeySequence::Quit);
443    exitAction->setStatusTip(tr("Quit diagram editor"));
444    connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));
445
446    boldAction = new QAction(QIcon(":/images/bold.png"),tr("Bold"), this);
447    boldAction->setCheckable(true);
448    boldAction->setShortcut(tr("Ctrl+B"));
449    connect(boldAction, SIGNAL(triggered()),
450            this, SLOT(handleFontChange()));
451
452    italicAction = new QAction(QIcon(":/images/italic.png"),
453                               tr("Italic"), this);
454    italicAction->setCheckable(true);
455    italicAction->setShortcut(tr("Ctrl+I"));
456    connect(italicAction, SIGNAL(triggered()),
457            this, SLOT(handleFontChange()));
458
459    underlineAction = new QAction(QIcon(":/images/underline.png"),
460                                  tr("Underline"), this);
461    underlineAction->setCheckable(true);
462    underlineAction->setShortcut(tr("Ctrl+U"));
463    connect(underlineAction, SIGNAL(triggered()),
464            this, SLOT(handleFontChange()));
465
466
467
468    libraryAction = new QAction(tr("&Library..."),this);
469    connect(libraryAction, SIGNAL(triggered()),
470            this, SLOT(libraryForm()));
471
472    optionsAction = new QAction(tr("&Options"),this);
473    optionsAction->setShortcuts(QKeySequence::Preferences);
474    connect(optionsAction, SIGNAL(triggered()),
475            this, SLOT(optionsForm()));
476
477    aboutAction = new QAction(tr("A&bout"), this);
478    aboutAction->setShortcut(tr("Ctrl+B"));
479    connect(aboutAction, SIGNAL(triggered()),
480            this, SLOT(about()));
481}
482
483void MainWindow::createMenus()
484{
485    fileMenu = menuBar()->addMenu(tr("&File"));
486    fileMenu->addAction(newAction);
487    fileMenu->addAction(openAction);
488    fileMenu->addSeparator();
489    fileMenu->addAction(saveAction);
490    fileMenu->addAction(saveAsAction);
491    fileMenu->addAction(exportImgAction);
492    fileMenu->addSeparator();
493    fileMenu->addAction(exitAction);
494
495    itemMenu = menuBar()->addMenu(tr("&Item"));
496    itemMenu->addAction(deleteAction);
497    itemMenu->addSeparator();
498    itemMenu->addAction(toFrontAction);
499    itemMenu->addAction(sendBackAction);
500
501    preferencesMenu= menuBar()->addMenu(tr("&Preferences"));
502    preferencesMenu->addAction(libraryAction);
503    preferencesMenu->addAction(optionsAction);
504
505    aboutMenu = menuBar()->addMenu(tr("&Help"));
506    aboutMenu->addAction(aboutAction);
507}
508
509void MainWindow::createToolbars()
510{
511    fileToolBar = addToolBar(tr("File"));
512    fileToolBar->addAction(newAction);
513    fileToolBar->addAction(openAction);
514    fileToolBar->addAction(saveAction);
515
516    editToolBar = addToolBar(tr("Edit"));
517    editToolBar->addAction(deleteAction);
518    editToolBar->addAction(toFrontAction);
519    editToolBar->addAction(sendBackAction);
520
521    fontCombo = new QFontComboBox();
522    fontSizeCombo = new QComboBox();
523    connect(fontCombo, SIGNAL(currentFontChanged(QFont)),
524            this, SLOT(currentFontChanged(QFont)));
525
526    fontSizeCombo = new QComboBox;
527    fontSizeCombo->setEditable(true);
528    for (int i = 8; i < 30; i = i + 2)
529        fontSizeCombo->addItem(QString().setNum(i));
530    QIntValidator *validator = new QIntValidator(2, 64, this);
531    fontSizeCombo->setValidator(validator);
532    connect(fontSizeCombo, SIGNAL(currentIndexChanged(QString)),
533            this, SLOT(fontSizeChanged(QString)));
534
535    fontColorToolButton = new QToolButton;
536    fontColorToolButton->setPopupMode(QToolButton::MenuButtonPopup);
537    fontColorToolButton->setMenu(createColorMenu(SLOT(textColorChanged()),
538                                                 Qt::black));
539    textAction = fontColorToolButton->menu()->defaultAction();
540    fontColorToolButton->setIcon(createColorToolButtonIcon(
541    ":/images/textpointer.png", Qt::black));
542    fontColorToolButton->setAutoFillBackground(true);
543    connect(fontColorToolButton, SIGNAL(clicked()),
544            this, SLOT(textButtonTriggered()));
545
546    fillColorToolButton = new QToolButton;
547    fillColorToolButton->setPopupMode(QToolButton::MenuButtonPopup);
548    fillColorToolButton->setMenu(createColorMenu(SLOT(itemColorChanged()),
549                         Qt::white));
550    fillAction = fillColorToolButton->menu()->defaultAction();
551    fillColorToolButton->setIcon(createColorToolButtonIcon(
552    ":/images/floodfill.png", Qt::white));
553    connect(fillColorToolButton, SIGNAL(clicked()),
554            this, SLOT(fillButtonTriggered()));
555
556    lineColorToolButton = new QToolButton;
557    lineColorToolButton->setPopupMode(QToolButton::MenuButtonPopup);
558    lineColorToolButton->setMenu(createColorMenu(SLOT(lineColorChanged()),
559                                 Qt::black));
560    lineAction = lineColorToolButton->menu()->defaultAction();
561    lineColorToolButton->setIcon(createColorToolButtonIcon(
562        ":/images/linecolor.png", Qt::black));
563    connect(lineColorToolButton, SIGNAL(clicked()),
564            this, SLOT(lineButtonTriggered()));
565
566    textToolBar = addToolBar(tr("Font"));
567    textToolBar->addWidget(fontCombo);
568    textToolBar->addWidget(fontSizeCombo);
569    textToolBar->addAction(boldAction);
570    textToolBar->addAction(italicAction);
571    textToolBar->addAction(underlineAction);
572
573    colorToolBar = addToolBar(tr("Color"));
574    colorToolBar->addWidget(fontColorToolButton);
575    colorToolBar->addWidget(fillColorToolButton);
576    colorToolBar->addWidget(lineColorToolButton);
577
578    QToolButton *pointerButton = new QToolButton;
579    pointerButton->setCheckable(true);
580    pointerButton->setChecked(true);
581    pointerButton->setIcon(QIcon(":/images/pointer.png"));
582    QToolButton *linePointerButton = new QToolButton;
583    linePointerButton->setCheckable(true);
584    linePointerButton->setIcon(QIcon(":/images/linepointer.png"));
585
586    pointerTypeGroup = new QButtonGroup;
587    pointerTypeGroup->addButton(pointerButton, int(DiagramScene::MoveItem));
588    pointerTypeGroup->addButton(linePointerButton,
589                                int(DiagramScene::InsertLine));
590    connect(pointerTypeGroup, SIGNAL(buttonClicked(int)),
591            this, SLOT(pointerGroupClicked(int)));
592
593    sceneScaleCombo = new QComboBox;
594    QStringList scales;
595    scales << tr("50%") << tr("75%") << tr("100%") << tr("125%") << tr("150%");
596    sceneScaleCombo->addItems(scales);
597    sceneScaleCombo->setCurrentIndex(2);
598    connect(sceneScaleCombo, SIGNAL(currentIndexChanged(QString)),
599            this, SLOT(sceneScaleChanged(QString)));
600
601    pointerToolbar = addToolBar(tr("Pointer type"));
602    pointerToolbar->addWidget(pointerButton);
603    pointerToolbar->addWidget(linePointerButton);
604    pointerToolbar->addWidget(sceneScaleCombo);
605}
606
607QWidget *MainWindow::createCellWidget(QString text, QDomElement *customItem)
608{
609    DiagramItem item(itemMenu,text,customItem);
610    QIcon icon(item.image());
611
612    QToolButton *button = new QToolButton;
613    button->setText(text);
614    button->setIcon(icon);
615    button->setIconSize(QSize(50, 50));
616    button->setCheckable(true);
617    buttonGroup->addButton(button, buttonIdByName.value(text));
618
619    QGridLayout *layout = new QGridLayout;
620    layout->addWidget(button, 0, 0, Qt::AlignHCenter);
621    layout->addWidget(new QLabel(text), 1, 0, Qt::AlignCenter);
622
623    QWidget *widget = new QWidget;
624    widget->setLayout(layout);
625
626    return widget;
627}
628
629QMenu *MainWindow::createColorMenu(const char *slot, QColor defaultColor)
630{
631    QList<QColor> colors;
632    colors << Qt::black << Qt::white << Qt::magenta
633            << Qt::cyan << Qt::red << Qt::blue << Qt::yellow << Qt::green
634            << Qt::darkMagenta << Qt::darkCyan << Qt::darkRed << Qt::darkBlue
635            << Qt::darkYellow << Qt::darkGreen << Qt::darkGray;
636
637    QStringList names;
638    names << tr("Black") << tr("White") << tr("Magenta") << tr("Cyan")
639          << tr("Red") << tr("Blue") << tr("Yellow") << tr("Green")
640          << tr("Dark Magenta") << tr("Dark Cyan") << tr("Dark Red")
641          << tr("Dark Blue") << tr("Dark Yellow") << tr("Dark Green")
642          << tr("Dark Gray") ;
643
644    QMenu *colorMenu = new QMenu;
645    for (int i = 0; i < colors.count(); ++i) {
646        QAction *action = new QAction(names.at(i), this);
647        action->setData(colors.at(i));
648        action->setIcon(createColorIcon(colors.at(i)));
649        connect(action, SIGNAL(triggered()),
650                this, slot);
651        colorMenu->addAction(action);
652        if (colors.at(i) == defaultColor) {
653            colorMenu->setDefaultAction(action);
654        }
655    }
656    return colorMenu;
657}
658
659QIcon MainWindow::createColorToolButtonIcon(const QString &imageFile,
660                        QColor color)
661{
662    QPixmap pixmap(50, 80);
663    pixmap.fill(Qt::transparent);
664    QPainter painter(&pixmap);
665    QPixmap image(imageFile);
666    QRect target(0, 0, 50, 60);
667    QRect source(0, 0, 42, 42);
668    painter.fillRect(QRect(0, 60, 50, 80), color);
669    painter.drawPixmap(target, image, source);
670
671    return QIcon(pixmap);
672}
673
674QIcon MainWindow::createColorIcon(QColor color)
675{
676    QPixmap pixmap(20, 20);
677    QPainter painter(&pixmap);
678    painter.setPen(Qt::NoPen);
679    painter.fillRect(QRect(0, 0, 20, 20), color);
680
681    return QIcon(pixmap);
682}
683
684int MainWindow::newDiagram(QString filePath)
685{
686    saveIfNeeded();
687    scene->cleanScene();
688    libraryList.clear(); //or set defaults
689    domElementsByName.clear(); //or set defaults
690    buttonIdByName.clear();//or set defaults
691    scene->setLibList(libraryList);
692    updateLibraries();
693    myFilePath="";
694
695    if(filePath=="")
696        return 0;
697
698    myFilePath=filePath;
699    if(!scene->fromXmlFormat(parseDocument(myFilePath)))
700        newDiagram();
701
702    return 1;
703}
704
705QDomDocument MainWindow::parseDocument(QString filePath)
706{
707    QDomDocument document;
708    QFile file(filePath);
709    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
710    {
711        bool parsing=document.setContent(&file);
712        file.close();
713        if(!parsing)
714        {
715            QMessageBox::warning(this,"Operation failed","Failed to parse file, "
716                                 "wrong format or encoding.");
717        }
718    }
719    else
720        QMessageBox::critical(this,"Error","Could not open file for read.");
721
722    return document;
723}
724
725
726
727int MainWindow::saveIfNeeded()
728{
729    if(myFilePath!="" || scene->items().count()>0)
730    {}//TODO save opened or modified diagram
731    return 0;
732}
733
734int MainWindow::openDiagram()
735{
736    QString
737    filePath = QFileDialog::getOpenFileName(this,"Open",
738               currentDir(),"Diagram for SIE code generator (*.sie)");
739
740    if(filePath.isEmpty())
741        return 0;
742
743    if(!QFileInfo(filePath).isReadable())
744    {
745        QMessageBox::critical(this,"Error","File is not readable "
746                                           " or not exists.");
747        return 0;
748    }
749
750    newDiagram(filePath);
751    return 0;
752}
753
754int MainWindow::saveDiagram()
755{
756    if(myFilePath=="")
757    {
758        saveAsDiagram();
759        return 0;
760    }
761    if(!QFileInfo(myFilePath).isWritable() && QFileInfo(myFilePath).exists())
762    {
763        QMessageBox::critical(this,"Error","File is not writable.");
764        return 0;
765    }
766    QFile file(myFilePath);
767    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
768    {
769        scene->setLibList(libraryList);
770        QDomDocument document = scene->toXmlFormat();
771        QTextStream out(&file);
772        out.setCodec("UTF-8");
773        out << document.toString(4);
774        file.close();
775        return 1;
776    }
777    else
778        QMessageBox::critical(this,"Error","Could not open file for write.");
779    return 0;
780}
781
782int MainWindow::saveAsDiagram()
783{
784    QString filePath = QFileDialog::getSaveFileName(this,"Save as...",
785                 currentDir(),"Diagram for SIE code generator (*.sie)");
786
787    if(!filePath.isEmpty())
788    {
789        myFilePath = filePath;
790        saveDiagram();
791        return 1;
792    }
793    return 0;
794}
795
796int MainWindow::exportDiagram()
797{
798    QString picturePath = QFileDialog::getSaveFileName(this,"Export",
799                            currentDir(),"Portable Network Graphics (*.png)");
800
801    if(picturePath.isEmpty()) return 0;
802
803    if(!QFileInfo(picturePath).isWritable() && QFileInfo(picturePath).exists())
804    {
805        QMessageBox::critical(this,"Error","File is not writable.");
806        return 0;
807    }
808    scene->setDawGrid(0);
809    QSize sizeScene= scene->sceneRect().size().toSize();
810    QImage img(sizeScene,QImage::Format_ARGB32_Premultiplied);
811    QPainter p(&img);
812    scene->render(&p,
813                  scene->sceneRect(),
814                  scene->itemsBoundingRect(),
815                  Qt::KeepAspectRatio);
816    p.end();
817    img.save(picturePath, "png");
818    scene->setDawGrid(1); //TODO : set correct value
819    return 1;
820}
821
822int MainWindow::libraryForm()
823{
824    if(!libDialog)
825    {
826        createLibraryDialog();
827    }
828    libDialog->setModal(1);
829    libUi->listLib->clear();
830    libUi->listLib->addItems(libraryList);
831    libDialog->setWindowTitle(tr("Library paths..."));
832    QStringList oldLibraryList=libraryList;
833    libDialog->exec();
834
835    if (libDialog->result() == QDialog::Rejected)
836        libraryList = oldLibraryList;
837    else
838    {
839        scene->setLibList(libraryList);
840        updateLibraries();
841    }
842
843    return 0;
844}
845
846void MainWindow::createLibraryDialog()
847{
848    libDialog = new QDialog(this);
849    libUi = new Ui_libraryDialog;
850    libUi->setupUi(libDialog);
851
852    connect(libUi->addLib,SIGNAL(clicked()),this,SLOT(addLibPath()));
853    connect(libUi->delLib,SIGNAL(clicked()),this,SLOT(delLibPath()));
854    connect(libUi->editLib,SIGNAL(clicked()),this,SLOT(editLibPath()));
855}
856
857void MainWindow::addLibPath()
858{
859    QString
860    filePath = QFileDialog::getOpenFileName(this,"Open",
861               currentDir(),"Custom block for SIE code generator (*.die)");
862
863    if(filePath.isEmpty())
864        return;
865
866    if(!QFileInfo(filePath).isReadable())
867    {
868        QMessageBox::critical(this,"Error","File is not readable "
869                                           " or not exists.");
870        return;
871    }
872    if(libUi->listLib->findItems(filePath,Qt::MatchExactly).count()==0)
873    {
874        QDir myCurrentDir = this->currentDir();
875        QString relativePath=myCurrentDir.relativeFilePath(filePath);
876        libraryList.append(relativePath);
877        libUi->listLib->addItem(relativePath);
878    }
879    else
880        QMessageBox::information(this,"Information","Library already exist.");
881}
882
883void MainWindow::delLibPath()
884{
885    QList<QListWidgetItem *> selected = libUi->listLib->selectedItems();
886    if(selected.count()>0)
887    {
888        libraryList.removeOne(selected.at(0)->text());
889        libUi->listLib->clear();
890        libUi->listLib->addItems(libraryList);
891    }
892}
893
894void MainWindow::editLibPath()
895{
896    QList<QListWidgetItem *> selected = libUi->listLib->selectedItems();
897    if(selected.count()>0)
898    {
899        callexternapp("block_editor/blockeditor",selected.at(0)->text());
900    }
901}
902
903int MainWindow::updateLibraries()
904{
905    libraryList=scene->getLibList();
906    createToolBox();
907    return 0;
908}
909
910
911int MainWindow::optionsForm()
912{
913
914    return 0;
915}
916
917QString MainWindow::callexternapp(QString xexecFile, QString xexecParm)
918{
919    QEventLoop cxaw;
920    callexternappT cxat;
921    connect(&cxat, SIGNAL(finished()), &cxaw, SLOT(quit()));
922    cxat.execFile = xexecFile;
923    cxat.execParm = xexecParm;
924    cxat.start();
925    cxaw.exec();
926    return cxat.retnValu;
927}
928
929
Software/sie_cg/mainwindow.h
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the examples of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#ifndef MAINWINDOW_H
43#define MAINWINDOW_H
44
45#include <QMainWindow>
46#include <QDir>
47#include <QtXml>
48#include <QtGui>
49#include <QHash>
50
51#include "diagramitem.h"
52#include "diagramscene.h"
53#include "diagramtextitem.h"
54#include "lineitem.h"
55#include "arrow.h"
56#include "ui_librarydialog.h"
57
58class DiagramScene;
59class Ui_libraryDialog;
60
61QT_BEGIN_NAMESPACE
62class QAction;
63class QToolBox;
64class QSpinBox;
65class QComboBox;
66class QFontComboBox;
67class QButtonGroup;
68class QLineEdit;
69class QGraphicsTextItem;
70class QFont;
71class QToolButton;
72class QAbstractButton;
73class QGraphicsView;
74QT_END_NAMESPACE
75
76class MainWindow : public QMainWindow
77{
78    Q_OBJECT
79
80public:
81   MainWindow();
82   QString filePath() const
83       { return myFilePath;}
84   QString currentDir() const
85   { return QDir::currentPath();}
86
87   int updateLibraries();
88
89private slots:
90    void backgroundButtonGroupClicked(QAbstractButton *button);
91    void buttonGroupClicked(int id);
92    void deleteItem();
93    void pointerGroupClicked(int id);
94    void bringToFront();
95    void sendToBack();
96    void itemInserted(DiagramItem *item);
97    void textInserted(QGraphicsTextItem *item);
98    void currentFontChanged(const QFont &font);
99    void fontSizeChanged(const QString &size);
100    void sceneScaleChanged(const QString &scale);
101    void textColorChanged();
102    void itemColorChanged();
103    void lineColorChanged();
104    void textButtonTriggered();
105    void fillButtonTriggered();
106    void lineButtonTriggered();
107    void handleFontChange();
108    void itemSelected(QGraphicsItem *item);
109    void about();
110
111    int newDiagram(QString pathFile="");
112    int openDiagram();
113    int saveDiagram();
114    int saveAsDiagram();
115    int exportDiagram();
116
117    int libraryForm();
118    void addLibPath();
119    void delLibPath();
120    void editLibPath();
121
122    int optionsForm();
123
124
125
126private:
127    int saveIfNeeded();
128    void addLibrariesButtons(QGridLayout *layout);
129    QDomDocument parseDocument(QString filePath);
130    void createLibraryDialog();
131    void createToolBox();
132    void createActions();
133    void createMenus();
134    void createToolbars();
135    void sendTo(bool value);
136    QWidget *createBackgroundCellWidget(const QString &text,
137                                        const QString &image);
138    QWidget *createCellWidget(QString text, QDomElement *customItem);
139
140    QMenu *createColorMenu(const char *slot, QColor defaultColor);
141    QIcon createColorToolButtonIcon(const QString &image, QColor color);
142    QIcon createColorIcon(QColor color);
143
144    DiagramScene *scene;
145    QGraphicsView *view;
146
147    QAction *newAction;
148    QAction *saveAction;
149    QAction *saveAsAction;
150    QAction *openAction;
151    QAction *exportImgAction;
152
153    QAction *exitAction;
154    QAction *addAction;
155    QAction *deleteAction;
156
157    QAction *libraryAction;
158    QAction *optionsAction;
159
160    QAction *toFrontAction;
161    QAction *sendBackAction;
162    QAction *aboutAction;
163
164    QMenu *fileMenu;
165    QMenu *itemMenu;
166    QMenu *preferencesMenu;
167    QMenu *aboutMenu;
168
169    QToolBar *fileToolBar;
170    QToolBar *textToolBar;
171    QToolBar *editToolBar;
172    QToolBar *colorToolBar;
173    QToolBar *pointerToolbar;
174
175    QComboBox *sceneScaleCombo;
176    QComboBox *itemColorCombo;
177    QComboBox *textColorCombo;
178    QComboBox *fontSizeCombo;
179    QFontComboBox *fontCombo;
180
181    QToolBox *toolBox;
182    QButtonGroup *buttonGroup;
183    QButtonGroup *pointerTypeGroup;
184    QButtonGroup *backgroundButtonGroup;
185    QToolButton *fontColorToolButton;
186    QToolButton *fillColorToolButton;
187    QToolButton *lineColorToolButton;
188    QAction *boldAction;
189    QAction *underlineAction;
190    QAction *italicAction;
191    QAction *textAction;
192    QAction *fillAction;
193    QAction *lineAction;
194    QString myFilePath;
195
196    QDialog *libDialog;
197    Ui_libraryDialog *libUi;
198    QStringList libraryList;
199    QHash<QString , QDomElement*> domElementsByName;
200    QHash<QString , int> buttonIdByName;
201    static QString callexternapp(QString xexecFile, QString xexecParm);
202
203};
204
205class callexternappT : public QThread
206{
207public:
208    QString execFile;
209    QString execParm;
210    QString retnValu;
211    void run()
212    {
213        QProcess lnexternapp;
214        lnexternapp.start(QString("%1 %2").arg(execFile).arg(execParm));
215        lnexternapp.waitForFinished(-1);
216        retnValu = QString(lnexternapp.readAll());
217    }
218};
219
220#endif
Software/sie_cg/moc_librarydialog.cpp
1/****************************************************************************
2** Meta object code from reading C++ file 'librarydialog.h'
3**
4** Created: Wed Oct 20 10:39:37 2010
5** by: The Qt Meta Object Compiler version 62 (Qt 4.6.2)
6**
7** WARNING! All changes made in this file will be lost!
8*****************************************************************************/
9
10#include "librarydialog.h"
11#if !defined(Q_MOC_OUTPUT_REVISION)
12#error "The header file 'librarydialog.h' doesn't include <QObject>."
13#elif Q_MOC_OUTPUT_REVISION != 62
14#error "This file was generated using the moc from 4.6.2. It"
15#error "cannot be used with the include files from this version of Qt."
16#error "(The moc has changed too much.)"
17#endif
18
19QT_BEGIN_MOC_NAMESPACE
20static const uint qt_meta_data_libraryDialog[] = {
21
22 // content:
23       4, // revision
24       0, // classname
25       0, 0, // classinfo
26       0, 0, // methods
27       0, 0, // properties
28       0, 0, // enums/sets
29       0, 0, // constructors
30       0, // flags
31       0, // signalCount
32
33       0 // eod
34};
35
36static const char qt_meta_stringdata_libraryDialog[] = {
37    "libraryDialog\0"
38};
39
40const QMetaObject libraryDialog::staticMetaObject = {
41    { &QDialog::staticMetaObject, qt_meta_stringdata_libraryDialog,
42      qt_meta_data_libraryDialog, 0 }
43};
44
45#ifdef Q_NO_DATA_RELOCATION
46const QMetaObject &libraryDialog::getStaticMetaObject() { return staticMetaObject; }
47#endif //Q_NO_DATA_RELOCATION
48
49const QMetaObject *libraryDialog::metaObject() const
50{
51    return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
52}
53
54void *libraryDialog::qt_metacast(const char *_clname)
55{
56    if (!_clname) return 0;
57    if (!strcmp(_clname, qt_meta_stringdata_libraryDialog))
58        return static_cast<void*>(const_cast< libraryDialog*>(this));
59    return QDialog::qt_metacast(_clname);
60}
61
62int libraryDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
63{
64    _id = QDialog::qt_metacall(_c, _id, _a);
65    if (_id < 0)
66        return _id;
67    return _id;
68}
69QT_END_MOC_NAMESPACE
Software/sie_cg/moc_librarydialog.o
Software/sie_cg/test.sie
1<!--
2File for SIE Code Generator.
3**WARNING**If you are going to edit this file note that:
4In order to segmentation faults prevention the load process
5is started loading the libraries, then items and finally arrows.
6Arrows depend of items, and items depend of libraries!!!!
7-->
8<Diagram>
9    <Libraries>
10        <Library Dir="block_editor/test_block1.die"/>
11        <Library Dir="block_editor/test_block2.die"/>
12        <Library Dir="block_editor/test_block3.die"/>
13    </Libraries>
14    <DiagramItems>
15        <DiagramItem x="2780" y="2540" z="500" type="Test Block 2" ID="0" color="#0000ff">
16            <diagramValues/>
17        </DiagramItem>
18        <DiagramItem x="2510" y="2440" z="500" type="Test Block 1" ID="1" color="#808080">
19            <diagramValues>
20                <diagramValue value="0.001" ID="1"/>
21            </diagramValues>
22        </DiagramItem>
23        <DiagramItem x="2230" y="2550" z="500" type="Test Block 3" ID="2" color="#ff0000">
24            <diagramValues/>
25        </DiagramItem>
26    </DiagramItems>
27    <Arrows>
28        <Arrow end-ID="1" end-Owner="0" start-x="140" start-y="0" start-Owner="1" ID="0" start-ID="3" end-x="-30" end-y="0" color="#808080">
29            <arrowCorners>
30                <arrowCorner x="2700" y="2440"/>
31                <arrowCorner x="2699.5" y="2539.5"/>
32            </arrowCorners>
33        </Arrow>
34        <Arrow end-ID="4" end-Owner="1" start-x="60" start-y="0" start-Owner="2" ID="1" start-ID="0" end-x="-120" end-y="0" color="#808080">
35            <arrowCorners>
36                <arrowCorner x="2340" y="2550"/>
37                <arrowCorner x="2340" y="2440"/>
38            </arrowCorners>
39        </Arrow>
40    </Arrows>
41</Diagram>

Archive Download the corresponding diff file

Branches:
master



interactive