Debian Codegraph @

src/editor/mainwindow.cpp

raw symbols SCIP
1 // This file is part of Dust Racing 2D.
2 // Copyright (C) 2015 Jussi Lind <[email protected]>
3 //
4 // Dust Racing 2D is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either Config::Editor 3 of the License, or
7 // (at your option) any later Config::Editor.
8 // Dust Racing 2D is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with Dust Racing 2D. If not, see <http://www.gnu.org/licenses/>.
15
16 #include "mainwindow.hpp"
17
18 #include "../common/config.hpp"
19 #include "aboutdlg.hpp"
20 #include "editordata.hpp"
21 #include "editorview.hpp"
22 #include "mediator.hpp"
23 #include "newtrackdialog.hpp"
24 #include "object.hpp"
25 #include "objectmodel.hpp"
26 #include "objectmodelloader.hpp"
27 #include "trackdata.hpp"
28 #include "trackio.hpp"
29 #include "trackpropertiesdialog.hpp"
30 #include "tracktile.hpp"
31
32 #include <QAction>
33 #include <QApplication>
34 #include <QCheckBox>
35 #include <QDateTime>
36 #include <QFileDialog>
37 #include <QGraphicsLineItem>
38 #include <QHBoxLayout>
39 #include <QLabel>
40 #include <QMenu>
41 #include <QMenuBar>
42 #include <QMessageBox>
43 #include <QSettings>
44 #include <QSlider>
45 #include <QSplitter>
46 #include <QStandardPaths>
47 #include <QTextEdit>
48 #include <QTimer>
49 #include <QToolBar>
50 #include <QTransform>
51 #include <QVBoxLayout>
52
53 #include <cassert>
54
55 MainWindow * MainWindow::m_instance = nullptr;
56
57 MainWindow::MainWindow(QString trackFile)
58 : m_objectModelLoader(std::make_unique<ObjectModelLoader>())
59 , m_mediator(std::make_unique<Mediator>(*this))
60 , m_aboutDlg(new AboutDlg(this))
61 , m_console(new QTextEdit(this))
62 , m_scaleSlider(new QSlider(Qt::Horizontal, this))
63 , m_toolBar(new QToolBar(this))
64 , m_randomRotationCheck(new QCheckBox(tr("Randomly rotate objects"), this))
65 , m_argTrackFile(trackFile)
66 {
67 if (!m_instance)
68 {
69 m_instance = this;
70 }
71 else
72 {
73 qFatal("MainWindow already instantiated!");
74 }
75
76 setWindowIcon(QIcon(":/dustrac-editor.png"));
77
78 init();
79
80 console("CWD: " + QDir::currentPath());
81
82 // Load object models that can be used to build tracks.
83 const QString objectFilePath = QString(Config::General::dataPath) + QDir::separator() + QString(Config::Editor::MODEL_CONFIG_FILE_NAME);
84 loadObjectModels(objectFilePath);
85
86 if (!m_argTrackFile.isEmpty())
87 {
88 QTimer::singleShot(0, this, &MainWindow::openArgTrack);
89 }
90 else
91 {
92 console(tr("Choose 'File -> New' or 'File -> Open' to start."));
93 }
94 }
95
96 void MainWindow::openArgTrack()
97 {
98 console(tr("Loading '%1'..").arg(m_argTrackFile));
99 doOpenTrack(m_argTrackFile);
100 }
101
102 void MainWindow::setVisible(bool visible)
103 {
104 QWidget::setVisible(visible);
105
106 if (visible)
107 {
108 showTip();
109 }
110 }
111
112 void MainWindow::updateScaleSlider(int value)
113 {
114 m_scaleSlider->setValue(value);
115 }
116
117 void MainWindow::showTip()
118 {
119 const auto commonTitle = tr("Save your work to correct location.");
120 #ifdef __unix__
121 QMessageBox::information(
122 this,
123 commonTitle,
124 QString(tr("To make the game find your circuits, save them to %1%2%3%2") + tr(", %4%2"))
125 .arg(QDir::homePath())
126 .arg(QDir::separator())
127 .arg(Config::General::TRACK_SEARCH_PATH)
128 .arg(Config::General::Unix::getXdgTrackSearchPath()));
129 #else
130 QMessageBox::information(
131 this,
132 commonTitle,
133 QString(tr("To make the game find your circuits, save them to %1%2%3%2"))
134 .arg(QDir::homePath())
135 .arg(QDir::separator())
136 .arg(Config::General::TRACK_SEARCH_PATH));
137 #endif
138 }
139
140 void MainWindow::init()
141 {
142 setWindowTitle(tr("New file")); // also: setTitle() → setWindowTitle() in QMainWindow
143
144 QSettings settings;
145
146 // Read dialog size data
147 settings.beginGroup(m_settingsGroup);
148 resize(settings.value("size", QSize(640, 480)).toSize());
149 settings.endGroup();
150
151 // Try to center the window on current screen
152 const auto geometry = screen()->availableGeometry();
153 move(geometry.center() - rect().center());
154
155 m_mediator->initScene();
156
157 populateMenuBar();
158 createWidgets();
159 }
160
161 void MainWindow::createWidgets()
162 {
163 // Create a splitter
164 QSplitter * splitter = new QSplitter(this);
165 splitter->setOrientation(Qt::Vertical);
166
167 // Create layouts for slider, view and toolbar
168 QVBoxLayout * centralLayout = new QVBoxLayout;
169 QHBoxLayout * viewToolBarLayout = new QHBoxLayout;
170 m_toolBar->setOrientation(Qt::Vertical);
171 m_mediator->addViewToLayout(viewToolBarLayout);
172 viewToolBarLayout->addWidget(m_toolBar);
173 centralLayout->addLayout(viewToolBarLayout);
174
175 // Populate toolbar with actions
176 populateToolBar();
177
178 // Add zoom slider to the layout
179 m_scaleSlider->setRange(m_minZoom, m_maxZoom);
180 m_scaleSlider->setValue(m_initZoom);
181 m_scaleSlider->setTracking(false);
182 m_scaleSlider->setTickInterval(10);
183 m_scaleSlider->setTickPosition(QSlider::TicksBelow);
184 connect(m_scaleSlider, &QSlider::valueChanged, this, &MainWindow::updateScale);
185 QHBoxLayout * sliderLayout = new QHBoxLayout;
186 sliderLayout->addWidget(new QLabel(tr("Scale:")));
187 sliderLayout->addWidget(m_scaleSlider);
188 sliderLayout->addWidget(m_randomRotationCheck);
189 centralLayout->addLayout(sliderLayout);
190
191 // Add console to the splitter and splitter to the layout
192 m_console->setReadOnly(true);
193 m_console->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
194 m_console->resize(m_console->width(), 50);
195 QWidget * dummy = new QWidget(this);
196 splitter->addWidget(dummy);
197 dummy->setLayout(centralLayout);
198 dummy->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
199 splitter->addWidget(m_console);
200
201 // Set contents margins so that they look nice
202 splitter->setContentsMargins(centralLayout->contentsMargins().left(),
203 0,
204 centralLayout->contentsMargins().right(),
205 centralLayout->contentsMargins().bottom());
206
207 centralLayout->setContentsMargins(0, centralLayout->contentsMargins().top(),
208 0, centralLayout->contentsMargins().bottom());
209
210 // Set splitter as the central widget
211 setCentralWidget(splitter);
212
213 QList<int> sizes;
214 sizes << height() - m_consoleHeight << m_consoleHeight;
215 splitter->setSizes(sizes);
216 }
217
218 void MainWindow::setTitle(QString openFileName)
219 {
220 setWindowTitle(
221 QString(Config::Editor::EDITOR_NAME) + " " + Config::Editor::EDITOR_VERSION + " - " + openFileName);
222 }
223
224 bool MainWindow::randomlyRotateObjects() const
225 {
226 return m_randomRotationCheck->isChecked();
227 }
228
229 bool MainWindow::loadObjectModels(QString objectFilePath)
230 {
231 if (m_objectModelLoader->load(objectFilePath))
232 {
233 addObjectsToToolBar();
234 return true;
235 }
236 else
237 {
238 const QString msg = tr("ERROR!!: Cannot load objects from '") + objectFilePath + tr("'");
239 console(msg);
240 return false;
241 }
242 }
243
244 void MainWindow::addObjectsToToolBar()
245 {
246 // Loop through all object models loaded
247 // by the object loader.
248 QVector<QString> categories;
249 categories << "tile"
250 << "free";
251 for (QString category : categories)
252 {
253 ObjectModelLoader::ObjectDataVector objects =
254 m_objectModelLoader->getObjectModelsByCategory(category);
255 for (const ObjectModel & model : objects)
256 {
257 // Create the action.
258 auto p = new QAction(QIcon(model.pixmap), model.role, this);
259
260 // Set model role as the data.
261 p->setData(QVariant(model.role));
262
263 // Add it to the toolbar.
264 m_toolBar->addAction(p);
265 }
266 }
267 }
268
269 MainWindow * MainWindow::instance()
270 {
271 return MainWindow::m_instance;
272 }
273
274 ObjectModelLoader & MainWindow::objectModelLoader() const
275 {
276 return *m_objectModelLoader;
277 }
278
279 QAction * MainWindow::currentToolBarAction() const
280 {
281 return m_currentToolBarAction;
282 }
283
284 void MainWindow::updateScale(int value)
285 {
286 m_mediator->setScale(value);
287
288 console(QString(tr("Scale set to %1%")).arg(value));
289 }
290
291 void MainWindow::closeEvent(QCloseEvent * event)
292 {
293 // Open settings file
294 QSettings settings;
295
296 // Save window size
297 settings.beginGroup(m_settingsGroup);
298 settings.setValue("size", size());
299 settings.endGroup();
300
301 event->accept();
302 }
303
304 void MainWindow::populateMenuBar()
305 {
306 // Create "file"-menu
307 QMenu * fileMenu = menuBar()->addMenu(tr("&File"));
308
309 // Add "new"-action
310 QAction * newAct = new QAction(tr("&New..."), this);
311 newAct->setShortcut(QKeySequence("Ctrl+N"));
312 fileMenu->addAction(newAct);
313 connect(newAct, &QAction::triggered, this, &MainWindow::initializeNewTrack);
314
315 // Add "open"-action
316 QAction * openAct = new QAction(tr("&Open..."), this);
317 openAct->setShortcut(QKeySequence("Ctrl+O"));
318 fileMenu->addAction(openAct);
319 connect(openAct, &QAction::triggered, this, &MainWindow::openTrack);
320
321 // Add "save"-action
322 m_saveAction = new QAction(tr("&Save"), this);
323 m_saveAction->setShortcut(QKeySequence("Ctrl+S"));
324 fileMenu->addAction(m_saveAction);
325 connect(m_saveAction, &QAction::triggered, this, &MainWindow::saveTrack);
326 m_saveAction->setEnabled(false);
327
328 // Add "save as"-action
329 m_saveAsAction = new QAction(tr("&Save as..."), this);
330 m_saveAsAction->setShortcut(QKeySequence("Ctrl+Shift+S"));
331 fileMenu->addAction(m_saveAsAction);
332 connect(m_saveAsAction, &QAction::triggered, this, &MainWindow::saveAsTrack);
333 m_saveAsAction->setEnabled(false);
334
335 // Add "quit"-action
336 QAction * quitAct = new QAction(tr("&Quit"), this);
337 quitAct->setShortcut(QKeySequence("Ctrl+W"));
338 fileMenu->addAction(quitAct);
339 connect(quitAct, &QAction::triggered, this, &MainWindow::close);
340
341 // Create "edit"-menu
342 QMenu * editMenu = menuBar()->addMenu(tr("&Edit"));
343
344 // Add "undo"-action
345 m_undoAction = new QAction(tr("Undo"), this);
346 m_undoAction->setShortcut(QKeySequence("Ctrl+Z"));
347 editMenu->addAction(m_undoAction);
348 connect(m_undoAction, &QAction::triggered, [this]() {
349 m_mediator->undo();
350
351 setupTrackAfterUndoOrRedo();
352
353 m_undoAction->setEnabled(m_mediator->isUndoable());
354 m_redoAction->setEnabled(m_mediator->isRedoable());
355 });
356 m_undoAction->setEnabled(false);
357
358 // Add "redo"-action
359 m_redoAction = new QAction(tr("Redo"), this);
360 m_redoAction->setShortcut(QKeySequence("Ctrl+Shift+Z"));
361 editMenu->addAction(m_redoAction);
362 connect(m_redoAction, &QAction::triggered, [this]() {
363 m_mediator->redo();
364
365 setupTrackAfterUndoOrRedo();
366
367 m_undoAction->setEnabled(m_mediator->isUndoable());
368 m_redoAction->setEnabled(m_mediator->isRedoable());
369 });
370 m_redoAction->setEnabled(false);
371
372 // Add "Set track properties"-action
373 m_setTrackPropertiesAction = new QAction(tr("&Set properties.."), this);
374 editMenu->addAction(m_setTrackPropertiesAction);
375 connect(m_setTrackPropertiesAction, &QAction::triggered, this, &MainWindow::setTrackProperties);
376 m_setTrackPropertiesAction->setEnabled(false);
377
378 // Create "route"-menu
379 QMenu * routeMenu = menuBar()->addMenu(tr("&Route"));
380
381 // Add "clear"-action
382 m_clearRouteAction = new QAction(tr("Clear &route"), this);
383 routeMenu->addAction(m_clearRouteAction);
384 connect(m_clearRouteAction, &QAction::triggered, this, &MainWindow::clearRoute);
385 m_clearRouteAction->setEnabled(false);
386
387 // Add "set order"-action
388 m_setRouteAction = new QAction(tr("&Set route.."), this);
389 routeMenu->addAction(m_setRouteAction);
390 connect(m_setRouteAction, &QAction::triggered, this, &MainWindow::beginSetRoute);
391 m_setRouteAction->setEnabled(false);
392
393 // Create "help"-menu
394 QMenu * helpMenu = menuBar()->addMenu(tr("&Help"));
395
396 // Add "about"-action
397 QAction * aboutAct = new QAction(tr("&About"), this);
398 helpMenu->addAction(aboutAct);
399 connect(aboutAct, &QAction::triggered, this, &MainWindow::showAboutDlg);
400
401 // Add "about Qt"-action
402 QAction * aboutQtAct = new QAction(tr("About &Qt"), this);
403 helpMenu->addAction(aboutQtAct);
404 connect(aboutQtAct, &QAction::triggered, this, &MainWindow::showAboutQtDlg);
405 }
406
407 void MainWindow::populateToolBar()
408 {
409 // Add "select"-action
410 QAction * p = new QAction(QIcon(QPixmap(Config::Editor::SELECT_ICON_PATH)), tr("Select"), this);
411 p->setData(QVariant(QString("select")));
412 m_toolBar->addAction(p);
413
414 // Add "erase"-action
415 p = new QAction(
416 QIcon(QPixmap(Config::Editor::ERASE_ICON_PATH)), tr("Erase object"), this);
417 p->setData(QVariant(QString("erase")));
418 m_toolBar->addAction(p);
419
420 // Add "clear"-action
421 p = new QAction(QIcon(QPixmap(Config::Editor::CLEAR_ICON_PATH)), tr("Clear"), this);
422 p->setData(QVariant(QString("clear")));
423 m_toolBar->addAction(p);
424
425 connect(m_toolBar, &QToolBar::actionTriggered, this, &MainWindow::handleToolBarActionClick);
426
427 m_toolBar->setEnabled(false);
428 }
429
430 void MainWindow::handleToolBarActionClick(QAction * action)
431 {
432 if (action != m_currentToolBarAction)
433 {
434 m_currentToolBarAction = action;
435
436 // Select-action
437 if (action->data() == "select")
438 {
439 clearEditMode();
440 }
441 // The user wants to erase an object.
442 else if (action->data() == "erase")
443 {
444 QApplication::restoreOverrideCursor();
445 QApplication::setOverrideCursor(QCursor(action->icon().pixmap(32, 32)));
446 m_mediator->setMode(EditorMode::EraseObject);
447 }
448 // The user wants to clear a tile.
449 else if (action->data() == "clear")
450 {
451 QApplication::restoreOverrideCursor();
452 QApplication::setOverrideCursor(QCursor(action->icon().pixmap(32, 32)));
453 m_mediator->setMode(EditorMode::SetTileType);
454 }
455 // The user wants to set a tile type or clear it.
456 else if (m_objectModelLoader->getCategoryByRole(
457 action->data().toString())
458 == "tile")
459 {
460 QApplication::restoreOverrideCursor();
461 QApplication::setOverrideCursor(QCursor(action->icon().pixmap(32, 32)));
462 m_mediator->setMode(EditorMode::SetTileType);
463 }
464 // The user wants to add an object to the scene.
465 else if (m_objectModelLoader->getCategoryByRole(
466 action->data().toString())
467 == "free")
468 {
469 QApplication::restoreOverrideCursor();
470 QApplication::setOverrideCursor(QCursor(QPixmap(":/cursor2.png")));
471 m_mediator->setMode(EditorMode::AddObject);
472 }
473 }
474 else
475 {
476 clearEditMode();
477 m_currentToolBarAction = nullptr;
478 }
479 }
480
481 void MainWindow::openTrack()
482 {
483 clearEditMode();
484
485 // Load recent path
486 QSettings settings;
487
488 settings.beginGroup(m_settingsGroup);
489 QString path = settings.value("recentPath",
490 QStandardPaths::writableLocation(QStandardPaths::HomeLocation))
491 .toString();
492 settings.endGroup();
493
494 const QString fileName = QFileDialog::getOpenFileName(
495 this, tr("Open a track"), path, tr("Track Files (*.trk)"));
496 if (!fileName.isEmpty())
497 {
498 doOpenTrack(fileName);
499 }
500 }
501
502 void MainWindow::showAboutDlg()
503 {
504 m_aboutDlg->exec();
505 }
506
507 void MainWindow::showAboutQtDlg()
508 {
509 QMessageBox::aboutQt(this, tr("About Qt"));
510 }
511
512 void MainWindow::clearRoute()
513 {
514 m_mediator->clearRoute();
515
516 m_clearRouteAction->setEnabled(false);
517 }
518
519 bool MainWindow::doOpenTrack(QString fileName)
520 {
521 if (!QFile::exists(fileName))
522 {
523 console(QString(tr("ERROR!!: %1 doesn't exist.").arg(fileName)));
524 return false;
525 }
526
527 // Undo stack will be cleared.
528 m_undoAction->setEnabled(false);
529 m_redoAction->setEnabled(false);
530
531 if (m_mediator->openTrack(fileName))
532 {
533 console(QString(tr("Track '%1' opened.").arg(fileName)));
534
535 setTitle(fileName);
536
537 // Save recent path
538 QSettings settings;
539
540 settings.beginGroup(m_settingsGroup);
541 settings.setValue("recentPath", fileName);
542 settings.endGroup();
543
544 m_saveAction->setEnabled(true);
545
546 setActionStatesOnNewTrack();
547
548 fitScale();
549
550 m_saved = true;
551
552 m_clearRouteAction->setEnabled(m_mediator->routeHasNodes());
553
554 return true;
555 }
556
557 console(QString(tr("Failed to open track '")) + fileName + "'.");
558 return false;
559 }
560
561 void MainWindow::beginSetRoute()
562 {
563 if (m_mediator->beginSetRoute())
564 {
565 console(tr("Set route: begin."));
566 QMessageBox::information(
567 this,
568 tr("Set route, checkpoints and driving lines."),
569 tr("Setting the route defines checkpoints for the cars so\n"
570 "that no shortcuts can be taken. It also defines\n"
571 "driving lines for the computer players.\n\n"
572 "Click on the tiles one by one and make a closed loop\n"
573 "with the target nodes. You can adjust the nodes afterwards.\n"
574 "Start from the first tile after the finish line tile\n"
575 "to make the lap detection and timing work correctly.\n"
576 "Click on the first node again to finish."));
577 }
578 else
579 {
580 console(tr("Set route: not a valid track."));
581 QMessageBox::critical(this, tr("Set route"), tr("Invalid track. Route cannot be set."));
582 }
583 }
584
585 void MainWindow::clearEditMode()
586 {
587 m_mediator->clearEditMode();
588 }
589
590 void MainWindow::console(QString text)
591 {
592 QDateTime date = QDateTime::currentDateTime();
593 m_console->append(QString("(") + date.toString("hh:mm:ss") + "): " + text);
594 }
595
596 void MainWindow::enableUndo(bool enable)
597 {
598 m_undoAction->setEnabled(enable);
599 }
600
601 void MainWindow::endSetRoute()
602 {
603 m_mediator->endSetRoute();
604
605 m_clearRouteAction->setEnabled(m_mediator->routeHasNodes());
606
607 console(tr("Set route: route finished."));
608 }
609
610 void MainWindow::fitScale()
611 {
612 m_scaleSlider->setValue(m_mediator->fitScale());
613 }
614
615 void MainWindow::initializeNewTrack()
616 {
617 const auto trackData = m_mediator->initializeNewTrack();
618 if (std::get<bool>(trackData))
619 {
620 // Undo stack has been cleared.
621 m_undoAction->setEnabled(false);
622 m_redoAction->setEnabled(false);
623
624 fitScale();
625
626 setActionStatesOnNewTrack();
627
628 setTitle(tr("New file"));
629
630 m_clearRouteAction->setEnabled(false);
631
632 m_saved = false;
633
634 console(QString(tr("A new track '%1' created. Columns: %2, Rows: %3."))
635 .arg(std::get<1>(trackData))
636 .arg(std::get<2>(trackData))
637 .arg(std::get<3>(trackData)));
638 }
639
640 QApplication::restoreOverrideCursor();
641 }
642
643 void MainWindow::saveTrack()
644 {
645 QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
646
647 if (!m_saved)
648 {
649 saveAsTrack();
650 }
651 else
652 {
653 if (m_mediator->saveTrackData())
654 {
655 console(QString(tr("Track '")) + m_mediator->currentFileName() + tr("' saved."));
656 setTitle(m_mediator->currentFileName());
657 m_saved = true;
658 }
659 else
660 {
661 console(QString(tr("Failed to save track '")) + m_mediator->currentFileName() + "'.");
662 }
663 }
664
665 QApplication::restoreOverrideCursor();
666 }
667
668 void MainWindow::saveAsTrack()
669 {
670 QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
671
672 QString fileName = QFileDialog::getSaveFileName(this,
673 tr("Save a track"),
674 QStandardPaths::writableLocation(QStandardPaths::HomeLocation),
675 tr("Track Files (*.trk)"));
676
677 const QString trackFileExtension(".trk");
678 if (!fileName.endsWith(trackFileExtension))
679 {
680 fileName += trackFileExtension;
681 }
682
683 if (m_mediator->saveTrackDataAs(fileName))
684 {
685 console(QString(tr("Track '")) + fileName + tr("' saved."));
686 setTitle(fileName);
687 m_saved = true;
688 }
689 else
690 {
691 console(QString(tr("Failed to save track as '")) + fileName + "'.");
692 }
693
694 QApplication::restoreOverrideCursor();
695 }
696
697 void MainWindow::setupTrackAfterUndoOrRedo()
698 {
699 m_saveAction->setEnabled(true);
700
701 setActionStatesOnNewTrack();
702
703 m_mediator->setupTrackAfterUndoOrRedo();
704
705 m_clearRouteAction->setEnabled(m_mediator->routeHasNodes());
706 }
707
708 void MainWindow::setActionStatesOnNewTrack()
709 {
710 m_saveAction->setEnabled(true);
711 m_saveAsAction->setEnabled(true);
712 m_toolBar->setEnabled(true);
713 m_setRouteAction->setEnabled(true);
714 m_setTrackPropertiesAction->setEnabled(true);
715 }
716
717 void MainWindow::setTrackProperties()
718 {
719 if (m_mediator->setTrackProperties())
720 {
721 console(QString(tr("Track properties updated.")));
722 }
723 }
724
725 MainWindow::~MainWindow() = default;