forked from KDE/ktuberling
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayground.cpp
519 lines (439 loc) · 15.4 KB
/
playground.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/***************************************************************************
* Copyright (C) 1999-2006 by Éric Bischoff <[email protected]> *
* Copyright (C) 2007-2008 by Albert Astals Cid <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
/* Play ground widget */
#include "playground.h"
#include <KLocalizedString>
#include <kconfig.h>
#include <kconfiggroup.h>
#include <qdebug.h>
#include <QAction>
#include <QCursor>
#include <QDataStream>
#include <QDir>
#include <QDomDocument>
#include <QFile>
#include <QFileInfo>
#include <QGraphicsSvgItem>
#include <QMouseEvent>
#include <QPainter>
#include <QPrinter>
#include <QStandardPaths>
#include <kstandardaction.h>
#include <kactioncollection.h>
#include <kstandardshortcut.h>
#include "action.h"
#include "toplevel.h"
#include "todraw.h"
static const char *saveGameTextScaleTextMode = "KTuberlingSaveGameV2";
static const char *saveGameTextTextMode = "KTuberlingSaveGameV3";
static const char *saveGameText = "KTuberlingSaveGameV4";
// Constructor
PlayGround::PlayGround(TopLevel *parent)
: QGraphicsView(parent), m_newItem(0), m_dragItem(0), m_nextZValue(1), m_lockAspect(false)
{
m_topLevel = parent;
setFrameStyle(QFrame::NoFrame);
setOptimizationFlag(QGraphicsView::DontSavePainterState, true); // all items here save the painter state
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setMouseTracking(true);
}
// Destructor
PlayGround::~PlayGround()
{
foreach (const SceneData &data, m_scenes)
{
delete data.scene;
delete data.undoStack;
}
}
// Reset the play ground
void PlayGround::reset()
{
foreach(QGraphicsItem *item, scene()->items())
{
ToDraw *currentObject = qgraphicsitem_cast<ToDraw *>(item);
delete currentObject;
}
undoStack()->clear();
}
// Save objects laid down on the editable area
bool PlayGround::saveAs(const QString & name)
{
QFile f(name);
if (!f.open( QIODevice::WriteOnly ) )
return false;
QFileInfo gameBoard(m_gameboardFile);
QDataStream out(&f);
out.setVersion(QDataStream::Qt_4_5);
out << QString::fromLatin1(saveGameText);
out << gameBoard.fileName();
foreach(QGraphicsItem *item, scene()->items())
{
ToDraw *currentObject = qgraphicsitem_cast<ToDraw *>(item);
if (currentObject != NULL) currentObject->save(out);
}
return (f.error() == QFile::NoError);
}
// Print gameboard's picture
bool PlayGround::printPicture(QPrinter &printer)
{
QPainter artist;
QPixmap picture(getPicture());
if (!artist.begin(&printer)) return false;
artist.drawPixmap(QPoint(32, 32), picture);
if (!artist.end()) return false;
return true;
}
// Get a pixmap containing the current picture
QPixmap PlayGround::getPicture()
{
QPixmap result(mapFromScene(backgroundRect()).boundingRect().size());
QPainter artist(&result);
scene()->render(&artist, QRectF(), backgroundRect(), Qt::IgnoreAspectRatio);
artist.end();
return result;
}
void PlayGround::connectRedoAction(QAction *action)
{
connect(action, &QAction::triggered, &m_undoGroup, &QUndoGroup::redo);
connect(&m_undoGroup, &QUndoGroup::canRedoChanged, action, &QAction::setEnabled);
}
void PlayGround::connectUndoAction(QAction *action)
{
connect(action, &QAction::triggered, &m_undoGroup, &QUndoGroup::undo);
connect(&m_undoGroup, &QUndoGroup::canUndoChanged, action, &QAction::setEnabled);
}
// Mouse pressed event
void PlayGround::mousePressEvent(QMouseEvent *event)
{
if (m_gameboardFile.isEmpty()) return;
if (event->button() != Qt::LeftButton) return;
if (m_dragItem) placeDraggedItem(event->pos());
else if (m_newItem) placeNewItem(event->pos());
else
{
// see if the user clicked on the warehouse of items
QPointF scenePos = mapToScene(event->pos());
QMap<QString, QString>::const_iterator it, itEnd;
it = m_objectsNameSound.constBegin();
itEnd = m_objectsNameSound.constEnd();
QString foundElem;
QRectF bounds;
for( ; foundElem.isNull() && it != itEnd; ++it)
{
bounds = m_SvgRenderer.boundsOnElement(it.key());
if (bounds.contains(scenePos)) foundElem = it.key();
}
if (!foundElem.isNull())
{
const double objectScale = m_objectsNameRatio.value(foundElem);
const QSizeF elementSize = m_SvgRenderer.boundsOnElement(foundElem).size() * objectScale;
QPointF itemPos = mapToScene(event->pos());
itemPos -= QPointF(elementSize.width()/2, elementSize.height()/2);
m_topLevel->playSound(m_objectsNameSound.value(foundElem));
m_newItem = new ToDraw;
m_newItem->setBeingDragged(true);
m_newItem->setPos(clipPos(itemPos, m_newItem));
m_newItem->setSharedRenderer(&m_SvgRenderer);
m_newItem->setElementId(foundElem);
m_newItem->setZValue(m_nextZValue);
m_nextZValue++;
m_newItem->scale(objectScale, objectScale);
scene()->addItem(m_newItem);
setCursor(Qt::BlankCursor);
}
else
{
// see if the user clicked on an already existent item
QGraphicsItem *dragItem = scene()->itemAt(mapToScene(event->pos()));
m_dragItem = qgraphicsitem_cast<ToDraw*>(dragItem);
if (m_dragItem)
{
QString elem = m_dragItem->elementId();
m_topLevel->playSound(m_objectsNameSound.value(elem));
setCursor(Qt::BlankCursor);
m_dragItem->setBeingDragged(true);
m_itemDraggedPos = m_dragItem->pos();
const QSizeF elementSize = m_dragItem->transform().mapRect(m_dragItem->unclippedRect()).size();
QPointF itemPos = mapToScene(event->pos());
itemPos -= QPointF(elementSize.width()/2, elementSize.height()/2);
m_dragItem->setPos(clipPos(itemPos, m_dragItem));
}
}
}
}
void PlayGround::mouseMoveEvent(QMouseEvent *event)
{
if (m_newItem) {
QPointF itemPos = mapToScene(event->pos());
const QSizeF elementSize = m_newItem->transform().mapRect(m_newItem->unclippedRect()).size();
itemPos -= QPointF(elementSize.width()/2, elementSize.height()/2);
m_newItem->setPos(clipPos(itemPos, m_newItem));
} else if (m_dragItem) {
QPointF itemPos = mapToScene(event->pos());
const QSizeF elementSize = m_dragItem->transform().mapRect(m_dragItem->unclippedRect()).size();
itemPos -= QPointF(elementSize.width()/2, elementSize.height()/2);
m_dragItem->setPos(clipPos(itemPos, m_dragItem));
}
}
bool PlayGround::insideBackground(const QSizeF &size, const QPointF &pos) const
{
return backgroundRect().intersects(QRectF(pos, size));
}
QPointF PlayGround::clipPos(const QPointF &p, ToDraw *item) const
{
const qreal objectScale = m_objectsNameRatio.value(item->elementId());
QPointF res = p;
res.setX(qMax(qreal(0), res.x()));
res.setY(qMax(qreal(0), res.y()));
res.setX(qMin(m_SvgRenderer.defaultSize().width() - item->boundingRect().width() * objectScale, res.x()));
res.setY(qMin(m_SvgRenderer.defaultSize().height()- item->boundingRect().height() * objectScale, res.y()));
return res;
}
QRectF PlayGround::backgroundRect() const
{
return m_SvgRenderer.boundsOnElement(QStringLiteral( "background" ));
}
void PlayGround::placeDraggedItem(const QPoint &pos)
{
QPointF itemPos = mapToScene(pos);
const QSizeF &elementSize = m_dragItem->transform().mapRect(m_dragItem->unclippedRect()).size();
itemPos -= QPointF(elementSize.width()/2, elementSize.height()/2);
if (insideBackground(elementSize, itemPos))
{
m_dragItem->setBeingDragged(false);
undoStack()->push(new ActionMove(m_dragItem, m_itemDraggedPos, m_nextZValue, scene()));
m_nextZValue++;
}
else
{
undoStack()->push(new ActionRemove(m_dragItem, m_itemDraggedPos, scene()));
}
setCursor(QCursor());
m_dragItem = 0;
}
void PlayGround::placeNewItem(const QPoint &pos)
{
const QSizeF elementSize = m_newItem->transform().mapRect(m_newItem->unclippedRect()).size();
QPointF itemPos = mapToScene(pos);
itemPos -= QPointF(elementSize.width()/2, elementSize.height()/2);
if (insideBackground(elementSize, itemPos))
{
m_newItem->setBeingDragged(false);
undoStack()->push(new ActionAdd(m_newItem, scene()));
} else {
m_newItem->deleteLater();
}
m_newItem = 0;
setCursor(QCursor());
}
void PlayGround::recenterView()
{
// Cannot use sceneRect() because sometimes items get placed
// with pos() outside rect (e.g. pizza theme)
fitInView(QRect(QPoint(0,0), m_SvgRenderer.defaultSize()),
m_lockAspect ? Qt::KeepAspectRatio : Qt::IgnoreAspectRatio);
}
QGraphicsScene *PlayGround::scene() const
{
return m_scenes[m_gameboardFile].scene;
}
QUndoStack *PlayGround::undoStack() const
{
return m_scenes[m_gameboardFile].undoStack;
}
void PlayGround::resizeEvent(QResizeEvent *)
{
recenterView();
}
void PlayGround::lockAspectRatio(bool lock)
{
if (m_lockAspect != lock)
{
m_lockAspect = lock;
recenterView();
}
}
bool PlayGround::isAspectRatioLocked() const
{
return m_lockAspect;
}
// Register the various playgrounds
void PlayGround::registerPlayGrounds()
{
QSet<QString> list;
const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::AppDataLocation, QStringLiteral("pics"), QStandardPaths::LocateDirectory);
Q_FOREACH (const QString &dir, dirs)
{
const QStringList fileNames = QDir(dir).entryList(QStringList() << QStringLiteral("*.theme"));
Q_FOREACH (const QString &file, fileNames)
{
list << dir + '/' + file;
}
}
foreach(const QString &theme, list)
{
QFile layoutFile(theme);
if (layoutFile.open(QIODevice::ReadOnly))
{
QDomDocument layoutDocument;
if (layoutDocument.setContent(&layoutFile))
{
QString desktop = layoutDocument.documentElement().attribute(QStringLiteral( "desktop" ));
KConfig c( QStandardPaths::locate(QStandardPaths::AppDataLocation, QLatin1String( "pics/" ) + desktop ) );
KConfigGroup cg = c.group("KTuberlingTheme");
QString gameboard = layoutDocument.documentElement().attribute(QStringLiteral( "gameboard" ));
QPixmap pixmap(200,100);
pixmap.fill(Qt::transparent);
playGroundPixmap(gameboard,pixmap);
m_topLevel->registerGameboard(cg.readEntry("Name"), theme, pixmap);
}
}
}
}
void PlayGround::playGroundPixmap(const QString &playgroundName, QPixmap &pixmap)
{
m_SvgRenderer.load(QStandardPaths::locate(QStandardPaths::AppDataLocation, QLatin1String( "pics/" ) + playgroundName ));
QPainter painter(&pixmap);
m_SvgRenderer.render(&painter,QStringLiteral( "background" ));
}
// Load background and draggable objects masks
bool PlayGround::loadPlayGround(const QString &gameboardFile)
{
QDomNodeList playGroundsList,
editableAreasList, objectsList,
gameAreasList, maskAreasList, soundNamesList, labelsList;
QDomElement playGroundElement,
editableAreaElement, objectElement,
gameAreaElement, maskAreaElement, soundNameElement, labelElement;
QDomAttr gameboardAttribute, masksAttribute,
leftAttribute, topAttribute, rightAttribute, bottomAttribute,
refAttribute;
QFile layoutFile(gameboardFile);
if (!layoutFile.open(QIODevice::ReadOnly)) return false;
QDomDocument layoutDocument;
if (!layoutDocument.setContent(&layoutFile)) return false;
playGroundElement = layoutDocument.documentElement();
QString gameboardName = playGroundElement.attribute(QStringLiteral( "gameboard" ));
QColor bgColor = QColor(playGroundElement.attribute(QStringLiteral( "bgcolor" ), QStringLiteral( "#fff" ) ) );
if (!bgColor.isValid())
bgColor = Qt::white;
if (!m_SvgRenderer.load(QStandardPaths::locate(QStandardPaths::AppDataLocation, QLatin1String( "pics/" ) + gameboardName )))
return false;
objectsList = playGroundElement.elementsByTagName(QStringLiteral( "object" ));
if (objectsList.count() < 1)
return false;
m_objectsNameSound.clear();
// create scene data if needed
if(!m_scenes.contains(gameboardFile))
{
SceneData &data = m_scenes[gameboardFile];
data.scene = new QGraphicsScene();
data.undoStack = new QUndoStack();
QGraphicsSvgItem *background = new QGraphicsSvgItem();
background->setPos(QPoint(0,0));
background->setSharedRenderer(&m_SvgRenderer);
background->setZValue(0);
data.scene->addItem(background);
m_undoGroup.addStack(data.undoStack);
}
for (int decoration = 0; decoration < objectsList.count(); decoration++)
{
objectElement = (const QDomElement &) objectsList.item(decoration).toElement();
const QString &objectName = objectElement.attribute(QStringLiteral( "name" ));
if (m_SvgRenderer.elementExists(objectName))
{
m_objectsNameSound.insert(objectName, objectElement.attribute(QStringLiteral( "sound" )));
m_objectsNameRatio.insert(objectName, objectElement.attribute(QStringLiteral( "scale" ), QStringLiteral( "1" )).toDouble());
}
else
{
qWarning() << objectName << "does not exist. Check" << gameboardFile;
}
}
setBackgroundBrush(bgColor);
m_gameboardFile = gameboardFile;
setScene(scene());
recenterView();
m_undoGroup.setActiveStack(undoStack());
return true;
}
QString PlayGround::currentGameboard() const
{
return m_gameboardFile;
}
// Load objects and lay them down on the editable area
PlayGround::LoadError PlayGround::loadFrom(const QString &name)
{
QFile f(name);
if (!f.open(QIODevice::ReadOnly))
return OtherError;
QDataStream in(&f);
in.setVersion(QDataStream::Qt_4_5);
bool scale = false;
bool reopenInTextMode = false;
QString magicText;
in >> magicText;
if ( QLatin1String( saveGameTextScaleTextMode ) == magicText) {
scale = true;
reopenInTextMode = true;
} else if (QLatin1String( saveGameTextTextMode ) == magicText) {
reopenInTextMode = true;
} else if ( QLatin1String( saveGameText ) != magicText) {
return OldFileVersionError;
}
if (reopenInTextMode) {
f.close();
if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
return OtherError;
in.setDevice(&f);
in.setVersion(QDataStream::Qt_4_5);
in >> magicText;
}
sceneRect();
if (in.atEnd())
return OtherError;
QString board;
in >> board;
qreal xFactor = 1.0;
qreal yFactor = 1.0;
m_topLevel->changeGameboard(board);
reset();
if (scale) {
QSize defaultSize = m_SvgRenderer.defaultSize();
QSize currentSize = size();
xFactor = (qreal)defaultSize.width() / (qreal)currentSize.width();
yFactor = (qreal)defaultSize.height() / (qreal)currentSize.height();
}
while ( !in.atEnd() )
{
ToDraw *obj = new ToDraw;
if (!obj->load(in))
{
delete obj;
return OtherError;
}
obj->setSharedRenderer(&m_SvgRenderer);
double objectScale = m_objectsNameRatio.value(obj->elementId());
obj->scale(objectScale, objectScale);
if (scale) { // Mimic old behavior
QPointF storedPos = obj->pos();
storedPos.setX(storedPos.x() * xFactor);
storedPos.setY(storedPos.y() * yFactor);
obj->setPos(storedPos);
}
scene()->addItem(obj);
undoStack()->push(new ActionAdd(obj, scene()));
}
if (f.error() == QFile::NoError) return NoError;
else return OtherError;
}
/* kate: replace-tabs on; indent-width 2; */