forked from enigma-dev/RadialGM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.cpp
More file actions
644 lines (531 loc) · 25.8 KB
/
Copy pathMainWindow.cpp
File metadata and controls
644 lines (531 loc) · 25.8 KB
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "Dialogs/PreferencesDialog.h"
#include "Dialogs/PreferencesKeys.h"
#include "Editors/BackgroundEditor.h"
#include "Editors/FontEditor.h"
#include "Editors/ObjectEditor.h"
#include "Editors/PathEditor.h"
#include "Editors/RoomEditor.h"
#include "Editors/ScriptEditor.h"
#include "Editors/SettingsEditor.h"
#include "Editors/SoundEditor.h"
#include "Editors/SpriteEditor.h"
#include "Editors/TimelineEditor.h"
#include "Components/ArtManager.h"
#include "Components/Logger.h"
#include "Plugins/RGMPlugin.h"
#include "Plugins/ServerPlugin.h"
#include "gmk.h"
#include "gmx.h"
#include "yyp.h"
#include <QtWidgets>
#include <functional>
#include <unordered_map>
#undef GetMessage
QList<buffers::SystemType> MainWindow::systemCache;
QMap<QPersistentModelIndex, TypeCase> MainWindow::nodeResource;
MainWindow *MainWindow::m_instance = nullptr;
QScopedPointer<ResourceModelMap> MainWindow::resourceMap;
QScopedPointer<TreeModel> MainWindow::treeModel;
static QTextEdit *diagnosticTextEdit = nullptr;
static QAction *toggleDiagnosticsAction = nullptr;
void diagnosticHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
if (toggleDiagnosticsAction && !toggleDiagnosticsAction->isChecked()) {
toggleDiagnosticsAction->setIcon(QIcon(":/actions/log-debug.png"));
toggleDiagnosticsAction->setToolTip(
QT_TR_NOOP("The editor encountered issues which have been logged in the diagnostics output."));
} else {
// this should never happen!
// NOTE: if we used R_EXPECT_V here it would be recursive
std::cerr << "Critical: Diagnostics toggle button does not exist!" << std::endl;
}
QByteArray localMsg = msg.toLocal8Bit();
QString file = context.file ? context.file : "";
QString function = context.function ? context.function : "";
QString msgFormat("%1 in %3:%4 aka %5:\n\t%2");
QString typeName = "Unknown:";
switch (type) {
case QtDebugMsg:
typeName = "Debug";
break;
case QtInfoMsg:
typeName = "Info";
break;
case QtWarningMsg:
typeName = "Warning";
break;
case QtCriticalMsg:
typeName = "Critical";
break;
case QtFatalMsg:
typeName = "Fatal";
break;
}
QString msgFormatted = msgFormat.arg(typeName, localMsg.constData(), file, QString::number(context.line), function);
std::cerr << msgFormatted.toStdString() << std::endl;
if (diagnosticTextEdit) {
diagnosticTextEdit->append(msgFormatted);
} else {
// this should never happen!
std::cerr << "Critical: Diagnostics text control does not exist!" << std::endl;
}
}
void MainWindow::nameMap(const char *name, TypeCase type)
{
QVariant nameVar = tr(name);
indexVector.push_back( {nameVar, type} );
nameIndexMap[nameVar] = indexVector.size() - 1;
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ArtManager::Init();
m_instance = this;
setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
ui->setupUi(this);
QToolBar *outputTB = new QToolBar(this);
outputTB->setIconSize(QSize(24, 24));
toggleDiagnosticsAction = new QAction();
toggleDiagnosticsAction->setCheckable(true);
toggleDiagnosticsAction->setIcon(QIcon(":/actions/log.png"));
toggleDiagnosticsAction->setToolTip(tr("Toggle Editor Diagnostics"));
outputTB->addAction(toggleDiagnosticsAction);
outputTB->addSeparator();
// use tool button for clear because QAction always has tooltip
QToolButton *clearButton = new QToolButton();
clearButton->setText(tr("Clear"));
outputTB->addWidget(clearButton);
QVBoxLayout *outputLayout = static_cast<QVBoxLayout *>(ui->outputDockWidgetContents->layout());
outputLayout->insertWidget(0, outputTB);
// install editor diagnostics handler
diagnosticTextEdit = ui->debugTextBrowser;
qInstallMessageHandler(diagnosticHandler);
connect(clearButton, &QToolButton::clicked,
[=]() { (toggleDiagnosticsAction->isChecked() ? ui->debugTextBrowser : ui->outputTextBrowser)->clear(); });
connect(toggleDiagnosticsAction, &QAction::toggled, [=](bool checked) {
ui->outputStackedWidget->setCurrentIndex(checked);
// reset the log icon as soon as diagnostics is viewed
if (checked) {
toggleDiagnosticsAction->setIcon(QIcon(":/actions/log.png"));
toggleDiagnosticsAction->setToolTip(tr("Toggle Editor Diagnostics"));
}
});
this->readSettings();
this->recentFiles = new RecentFiles(this, this->ui->menuRecent, this->ui->actionClearRecentMenu);
ui->mdiArea->setBackground(QImage(":/banner.png"));
connect(ui->menuWindow, &QMenu::aboutToShow, this, &MainWindow::updateWindowMenu);
auto settingsButton = static_cast<QToolButton *>(ui->mainToolBar->widgetForAction(ui->actionSettings));
settingsButton->setPopupMode(QToolButton::ToolButtonPopupMode::MenuButtonPopup);
settingsButton->setToolButtonStyle(Qt::ToolButtonStyle::ToolButtonTextBesideIcon);
ui->actionSettings->setMenu(ui->menuChangeGameSettings);
RGMPlugin *pluginServer = new ServerPlugin(*this);
auto outputTextBrowser = this->ui->outputTextBrowser;
connect(pluginServer, &RGMPlugin::LogOutput, outputTextBrowser, &QTextBrowser::append);
connect(pluginServer, &RGMPlugin::CompileStatusChanged, [=](bool finished) {
ui->outputDockWidget->show();
ui->actionRun->setEnabled(finished);
ui->actionDebug->setEnabled(finished);
ui->actionCreateExecutable->setEnabled(finished);
});
connect(this, &MainWindow::CurrentConfigChanged, pluginServer, &RGMPlugin::SetCurrentConfig);
connect(ui->actionRun, &QAction::triggered, pluginServer, &RGMPlugin::Run);
connect(ui->actionDebug, &QAction::triggered, pluginServer, &RGMPlugin::Debug);
connect(ui->actionCreateExecutable, &QAction::triggered, pluginServer, &RGMPlugin::CreateExecutable);
// set name maps
nameMap("Sprites", TypeCase::kSprite); nameMap("Sounds", TypeCase::kSound); nameMap("Backgrounds", TypeCase::kBackground);
nameMap("Paths", TypeCase::kPath); nameMap("Scripts", TypeCase::kScript); nameMap("Shaders", TypeCase::kShader);
nameMap("Fonts", TypeCase::kFont); nameMap("Timelines", TypeCase::kTimeline); nameMap("Objects", TypeCase::kObject);
nameMap("Rooms", TypeCase::kRoom); nameMap("Includes", TypeCase::kInclude); nameMap("Configs", TypeCase::kSettings);
openNewProject();
}
MainWindow::~MainWindow() { delete ui; }
void MainWindow::setCurrentConfig(const buffers::resources::Settings &settings) {
emit m_instance->CurrentConfigChanged(settings);
}
void MainWindow::readSettings() {
QSettings settings;
// Restore previous window and dock widget location / state
settings.beginGroup("MainWindow");
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("state").toByteArray());
setTabbedMode(settings.value("tabbedView", false).toBool());
settings.endGroup();
}
void MainWindow::writeSettings() {
QSettings settings;
// Save window and dock widget location / state for next session
settings.beginGroup("MainWindow");
settings.setValue("geometry", saveGeometry());
settings.setValue("state", saveState());
settings.setValue("tabbedView", ui->actionToggleTabbedView->isChecked());
settings.endGroup();
}
void MainWindow::closeEvent(QCloseEvent *event) {
ui->mdiArea->closeAllSubWindows();
this->writeSettings();
event->accept();
}
template <typename T>
T *EditorFactory(ProtoModel *model, QWidget *parent) {
return new T(model, parent);
}
void MainWindow::openSubWindow(buffers::TreeNode *item) {
using namespace google::protobuf;
using TypeCase = buffers::TreeNode::TypeCase;
using FactoryMap = std::unordered_map<TypeCase, std::function<BaseEditor *(ProtoModel * m, QWidget * p)>>;
static FactoryMap factoryMap({{TypeCase::kSprite, EditorFactory<SpriteEditor>},
{TypeCase::kSound, EditorFactory<SoundEditor>},
{TypeCase::kBackground, EditorFactory<BackgroundEditor>},
{TypeCase::kPath, EditorFactory<PathEditor>},
{TypeCase::kFont, EditorFactory<FontEditor>},
{TypeCase::kScript, EditorFactory<ScriptEditor>},
{TypeCase::kTimeline, EditorFactory<TimelineEditor>},
{TypeCase::kObject, EditorFactory<ObjectEditor>},
{TypeCase::kRoom, EditorFactory<RoomEditor>},
{TypeCase::kSettings, EditorFactory<SettingsEditor>}});
auto swIt = subWindows.find(item);
QMdiSubWindow *subWindow;
if (swIt == subWindows.end() || !*swIt) {
auto factoryFunction = factoryMap.find(item->type_case());
if (factoryFunction == factoryMap.end()) return; // no registered editor
ProtoModel *res = resourceMap->GetResourceByName(item->type_case(), item->name());
BaseEditor *editor = factoryFunction->second(res, this);
connect(editor, &BaseEditor::ResourceRenamed, resourceMap.get(), &ResourceModelMap::ResourceRenamed);
connect(editor, &BaseEditor::ResourceRenamed, [=]() { treeModel->dataChanged(QModelIndex(), QModelIndex()); });
connect(treeModel.get(), &TreeModel::ResourceRenamed, editor,
[res](TypeCase /*type*/, const QString & /*oldName*/, const QString & /*newName*/) {
const QModelIndex index = res->index(TreeNode::kNameFieldNumber);
emit res->dataChanged(index, index);
});
subWindow = subWindows[item] = ui->mdiArea->addSubWindow(editor);
subWindow->resize(subWindow->frameSize().expandedTo(editor->size()));
editor->setParent(subWindow);
subWindow->connect(subWindow, &QObject::destroyed, [=]() { subWindows.remove(item); });
subWindow->setWindowIcon(subWindow->widget()->windowIcon());
editor->setWindowTitle(QString::fromStdString(item->name()));
} else {
subWindow = *swIt;
}
subWindow->show();
ui->mdiArea->setActiveSubWindow(subWindow);
}
void MainWindow::updateWindowMenu() {
static QList<QAction *> windowActions;
foreach (auto action, windowActions) {
ui->menuWindow->removeAction(action);
windowActions.removeOne(action);
}
auto windows = ui->mdiArea->subWindowList();
for (int i = 0; i < windows.size(); ++i) {
QMdiSubWindow *mdiSubWindow = windows.at(i);
const auto windowTitle = mdiSubWindow->windowTitle();
QString numberString = QString::number(i + 1);
numberString = numberString.insert(numberString.length() - 1, '&');
QString text = tr("%1 %2").arg(numberString).arg(windowTitle);
QAction *action = ui->menuWindow->addAction(
text, mdiSubWindow, [this, mdiSubWindow]() { ui->mdiArea->setActiveSubWindow(mdiSubWindow); });
windowActions.append(action);
action->setCheckable(true);
action->setChecked(mdiSubWindow == ui->mdiArea->activeSubWindow());
}
}
void MainWindow::openFile(QString fName) {
QFileInfo fileInfo(fName);
const QString suffix = fileInfo.suffix();
buffers::Project *loadedProject = nullptr;
if (suffix == "gm81" || suffix == "gmk" || suffix == "gm6" || suffix == "gmd") {
loadedProject = gmk::LoadGMK(fName.toStdString());
} else if (suffix == "gmx") {
loadedProject = gmx::LoadGMX(fName.toStdString());
} else if (suffix == "yyp") {
loadedProject = yyp::LoadYYP(fName.toStdString());
}
if (!loadedProject) {
QMessageBox::warning(this, tr("Failed To Open Project"), tr("There was a problem loading the project: ") + fName,
QMessageBox::Ok);
return;
}
MainWindow::setWindowTitle(fileInfo.fileName() + " - ENIGMA");
recentFiles->prependFile(fName);
openProject(std::unique_ptr<buffers::Project>(loadedProject));
}
void MainWindow::openNewProject() {
MainWindow::setWindowTitle(tr("<new game> - ENIGMA"));
auto newProject = std::unique_ptr<buffers::Project>(new buffers::Project());
auto *root = newProject->mutable_game()->mutable_root();
for (auto& groupName : indexVector) {
auto *groupNode = root->add_child();
groupNode->set_folder(true);
groupNode->set_name(groupName.name.toString().toStdString());
}
openProject(std::move(newProject));
}
void MainWindow::openProject(std::unique_ptr<buffers::Project> openedProject) {
this->ui->mdiArea->closeAllSubWindows();
ArtManager::clearCache();
project = std::move(openedProject);
resourceMap.reset(new ResourceModelMap(project->mutable_game()->mutable_root(), nullptr));
treeModel.reset(new TreeModel(project->mutable_game()->mutable_root(), resourceMap.get(), nullptr));
ui->treeView->setModel(treeModel.get());
treeModel->connect(treeModel.get(), &TreeModel::ResourceRenamed, resourceMap.get(),
&ResourceModelMap::ResourceRenamed);
nodeResource.clear();
const QTreeView *treeUi = ui->treeView;
treeModel.get();
QModelIndex node = treeUi->indexAt(QPoint());
if (node.isValid()) {
QVariant nodeString;
int index;
while (node.isValid()) {
nodeString = node.data();
if (nodeString.isValid()) {
index = nameIndexMap.value(nodeString, -1);
if (index != -1) nodeResource[QPersistentModelIndex(node)] = indexVector[index].type;
}
node = treeUi->indexBelow(node);
}
}
}
void MainWindow::on_actionNew_triggered() { openNewProject(); }
void MainWindow::on_actionOpen_triggered() {
const QString &fileName = QFileDialog::getOpenFileName(
this, tr("Open Project"), "",
tr("All supported formats (*.yyp *.project.gmx *.gm81 *.gmk *.gm6 *.gmd);;GameMaker: Studio 2 Projects "
"(*.yyp);;GameMaker: Studio Projects (*.project.gmx);;Classic "
"GameMaker Files (*.gm81 *.gmk *.gm6 *.gmd);;All Files (*)"));
if (!fileName.isEmpty()) openFile(fileName);
}
void MainWindow::on_actionPreferences_triggered() {
PreferencesDialog preferencesDialog(this);
preferencesDialog.exec();
}
void MainWindow::on_actionExit_triggered() { QApplication::exit(); }
void MainWindow::setTabbedMode(bool enabled) {
ui->actionToggleTabbedView->setChecked(enabled);
ui->mdiArea->setViewMode(enabled ? QMdiArea::TabbedView : QMdiArea::SubWindowView);
if (enabled) {
QTabBar *tabBar = ui->mdiArea->findChild<QTabBar *>();
if (tabBar) {
tabBar->setExpanding(false);
}
}
}
void MainWindow::on_actionCascade_triggered() {
this->setTabbedMode(false);
ui->mdiArea->cascadeSubWindows();
}
void MainWindow::on_actionTile_triggered() {
this->setTabbedMode(false);
ui->mdiArea->tileSubWindows();
}
void MainWindow::on_actionCloseAll_triggered() { ui->mdiArea->closeAllSubWindows(); }
void MainWindow::on_actionCloseOthers_triggered() {
foreach (QMdiSubWindow *subWindow, ui->mdiArea->subWindowList()) {
if (subWindow != ui->mdiArea->activeSubWindow()) subWindow->close();
}
}
void MainWindow::on_actionToggleTabbedView_triggered() { this->setTabbedMode(ui->actionToggleTabbedView->isChecked()); }
void MainWindow::on_actionNext_triggered() { ui->mdiArea->activateNextSubWindow(); }
void MainWindow::on_actionPrevious_triggered() { ui->mdiArea->activatePreviousSubWindow(); }
void MainWindow::on_actionDocumentation_triggered() {
QUrl url(documentationURL(), QUrl::TolerantMode);
QDesktopServices::openUrl(url);
}
void MainWindow::on_actionWebsite_triggered() {
QUrl url(websiteURL(), QUrl::TolerantMode);
QDesktopServices::openUrl(url);
}
void MainWindow::on_actionCommunity_triggered() {
QUrl url(communityURL(), QUrl::TolerantMode);
QDesktopServices::openUrl(url);
}
void MainWindow::on_actionSubmitIssue_triggered() {
QUrl url(submitIssueURL(), QUrl::TolerantMode);
QDesktopServices::openUrl(url);
}
void MainWindow::on_actionExploreENIGMA_triggered() { QDesktopServices::openUrl(QUrl(".", QUrl::TolerantMode)); }
void MainWindow::on_actionAbout_triggered() {
QMessageBox aboutBox(QMessageBox::Information, tr("About"),
tr("ENIGMA is a free, open-source, and cross-platform game engine."), QMessageBox::Ok, this,
nullptr);
QAbstractButton *aboutQtButton = aboutBox.addButton(tr("About Qt"), QMessageBox::HelpRole);
aboutBox.exec();
if (aboutBox.clickedButton() == aboutQtButton) {
QMessageBox::aboutQt(this, tr("About Qt"));
}
}
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index) {
buffers::TreeNode *item = static_cast<buffers::TreeNode *>(index.internalPointer());
const QString name = QString::fromStdString(item->name());
if (item->has_folder()) {
return;
}
openSubWindow(item);
}
void MainWindow::on_actionClearRecentMenu_triggered() { recentFiles->clear(); }
void MainWindow::CreateResource(TypeCase typeCase) {
auto child = std::unique_ptr<TreeNode>(new TreeNode());
auto fieldNum = ResTypeFields[typeCase];
const Descriptor *desc = child->GetDescriptor();
const Reflection *refl = child->GetReflection();
const FieldDescriptor *field = desc->FindFieldByNumber(fieldNum);
// allocate and set the child's resource field
refl->MutableMessage(child.get(), field);
// find a unique name for the new resource
const QString name = resourceMap->CreateResourceName(child.get());
child->set_name(name.toStdString());
// open the new resource for editing
this->resourceMap->AddResource(child.get(), resourceMap.get());
openSubWindow(child.get());
// check if currently in resource folder, if not then set index to resource folder base node
QModelIndex currentIndex = ui->treeView->currentIndex();
if (!currentIndex.isValid()) {
QList<QPersistentModelIndex> keys = nodeResource.keys(typeCase);
if (keys.isEmpty()) {
currentIndex = ui->treeView->rootIndex();
}
else {
QModelIndex oldNode = keys.constLast(); // use the oldest node mapped to that TypeCase
if (oldNode.isValid()) currentIndex = oldNode;
}
}
else if (nodeResource.value(currentIndex, TypeCase::TYPE_NOT_SET) != typeCase && nodeResource.value(currentIndex.parent(), TypeCase::TYPE_NOT_SET) != typeCase) {
QList<QPersistentModelIndex> keys = nodeResource.keys(typeCase);
if (!keys.isEmpty()) {
QModelIndex oldNode = keys.constLast(); // use the oldest node mapped to that TypeCase
if (oldNode.isValid()) currentIndex = oldNode;
}
}
// release ownership of the new child to its parent and the tree
auto index = this->treeModel->addNode(child.release(), currentIndex);
// select the new node so that it gets "revealed" and its parent is expanded
ui->treeView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
// start editing the name of the resource in the tree for convenience
ui->treeView->edit(index);
}
void MainWindow::on_actionCreateSprite_triggered() { CreateResource(TypeCase::kSprite); }
void MainWindow::on_actionCreateSound_triggered() { CreateResource(TypeCase::kSound); }
void MainWindow::on_actionCreateBackground_triggered() { CreateResource(TypeCase::kBackground); }
void MainWindow::on_actionCreatePath_triggered() { CreateResource(TypeCase::kPath); }
void MainWindow::on_actionCreateScript_triggered() { CreateResource(TypeCase::kScript); }
void MainWindow::on_actionCreateShader_triggered() { CreateResource(TypeCase::kShader); }
void MainWindow::on_actionCreateFont_triggered() { CreateResource(TypeCase::kFont); }
void MainWindow::on_actionCreateTimeline_triggered() { CreateResource(TypeCase::kTimeline); }
void MainWindow::on_actionCreateObject_triggered() { CreateResource(TypeCase::kObject); }
void MainWindow::on_actionCreateRoom_triggered() { CreateResource(TypeCase::kRoom); }
void MainWindow::on_actionCreateSettings_triggered() { CreateResource(TypeCase::kSettings); }
void MainWindow::on_actionDuplicate_triggered() {
if (!ui->treeView->selectionModel()->hasSelection()) return;
const auto index = ui->treeView->selectionModel()->currentIndex();
const auto *node = static_cast<const buffers::TreeNode *>(index.internalPointer());
if (node->has_folder()) return;
// duplicate the node
auto *dup = treeModel->duplicateNode(*node);
// insert the duplicate into the tree
const auto dupIndex = treeModel->insert(index.parent(), index.row() + 1, dup);
// open an editor for the duplicate node
openSubWindow(dup);
// select the new node so that it gets "revealed" and its parent is expanded
ui->treeView->selectionModel()->setCurrentIndex(dupIndex, QItemSelectionModel::ClearAndSelect);
// start editing the name of the resource in the tree for convenience
ui->treeView->edit(dupIndex);
}
void MainWindow::on_actionCreateGroup_triggered() {
auto child = std::unique_ptr<TreeNode>(new TreeNode());
child->set_folder(true);
// find a unique name for the new group
const QString name = resourceMap->CreateResourceName(TypeCase::kFolder, "group");
child->set_name(name.toStdString());
// release ownership of the new child to its parent and the tree
this->resourceMap->AddResource(child.get(), resourceMap.get());
auto index = this->treeModel->addNode(child.release(), ui->treeView->currentIndex());
TypeCase parentType = nodeResource.value(index.parent(), TypeCase::TYPE_NOT_SET);
if (parentType != TypeCase::TYPE_NOT_SET) {
nodeResource[QPersistentModelIndex(index)] = parentType;
}
// select the new node so that it gets "revealed" and its parent is expanded
ui->treeView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
// start editing the name of the resource in the tree for convenience
ui->treeView->edit(index);
}
void MainWindow::on_actionRename_triggered() {
if (!ui->treeView->selectionModel()->hasSelection()) return;
ui->treeView->edit(ui->treeView->selectionModel()->currentIndex());
}
void MainWindow::on_actionProperties_triggered() {
if (!ui->treeView->selectionModel()->hasSelection()) return;
auto selected = ui->treeView->selectionModel()->selectedIndexes();
for (auto index : selected) {
auto *treeNode = static_cast<buffers::TreeNode *>(index.internalPointer());
openSubWindow(treeNode);
}
}
static void CollectNodes(buffers::TreeNode *root, QSet<buffers::TreeNode *> &cache) {
cache.insert(root);
for (int i = 0; i < root->child_size(); ++i) {
auto *child = root->mutable_child(i);
cache.insert(child);
if (child->has_folder()) CollectNodes(child, cache);
}
}
void MainWindow::on_actionDelete_triggered() {
if (!ui->treeView->selectionModel()->hasSelection()) return;
auto selected = ui->treeView->selectionModel()->selectedIndexes();
QSet<buffers::TreeNode *> selectedNodes;
for (auto index : selected) {
auto *treeNode = static_cast<buffers::TreeNode *>(index.internalPointer());
CollectNodes(treeNode, selectedNodes);
}
QString selectedNames = "";
for (auto node : selectedNodes) {
selectedNames += (node == *selectedNodes.begin() ? "" : ", ") + QString::fromStdString(node->name());
}
QMessageBox::StandardButton reply;
reply = QMessageBox::question(
this, tr("Delete Resources"),
tr("Do you want to delete the following resources from the project?\n%0").arg(selectedNames),
QMessageBox::Yes | QMessageBox::No);
if (reply != QMessageBox::Yes) return;
// close subwindows
for (auto node : selectedNodes) {
if (subWindows.contains(node)) subWindows[node]->close();
}
// remove tree nodes (recursively unmaps names)
for (auto index : selected) {
this->treeModel->removeNode(index);
}
}
void MainWindow::on_actionExpand_triggered() { ui->treeView->expandAll(); }
void MainWindow::on_actionCollapse_triggered() { ui->treeView->collapseAll(); }
void MainWindow::on_actionSortByName_triggered() {
if (!ui->treeView->selectionModel()->hasSelection()) return;
treeModel->sortByName(ui->treeView->currentIndex());
}
void MainWindow::on_treeView_customContextMenuRequested(const QPoint &pos) {
ui->menuEdit->exec(ui->treeView->mapToGlobal(pos));
}
void MainWindow::ChangeNodeType(TypeCase type) {
if (!ui->treeView->selectionModel()->hasSelection()) return;
if (!nodeResource.contains(ui->treeView->currentIndex())) {
QPersistentModelIndex(ui->treeView->currentIndex());
}
nodeResource.insert(ui->treeView->currentIndex(), type);
}
void MainWindow::on_actionChange_to_Sprite_triggered() { ChangeNodeType(TypeCase::kSprite); }
void MainWindow::on_actionChange_to_Sound_triggered() { ChangeNodeType(TypeCase::kSound); }
void MainWindow::on_actionChange_to_Background_triggered() { ChangeNodeType(TypeCase::kBackground); }
void MainWindow::on_actionChange_to_Path_triggered() { ChangeNodeType(TypeCase::kPath); }
void MainWindow::on_actionChange_to_Script_triggered() { ChangeNodeType(TypeCase::kScript); }
void MainWindow::on_actionChange_to_Shader_triggered() { ChangeNodeType(TypeCase::kShader); }
void MainWindow::on_actionChange_to_Font_triggered() { ChangeNodeType(TypeCase::kFont); }
void MainWindow::on_actionChange_to_Timeline_triggered() { ChangeNodeType(TypeCase::kTimeline); }
void MainWindow::on_actionChange_to_Object_triggered() { ChangeNodeType(TypeCase::kObject); }
void MainWindow::on_actionChange_to_Room_triggered() { ChangeNodeType(TypeCase::kRoom); }
void MainWindow::on_actionChange_to_Include_triggered() { ChangeNodeType(TypeCase::kInclude); }
void MainWindow::on_actionChange_to_Setting_triggered() { ChangeNodeType(TypeCase::kSettings); }
void MainWindow::on_actionClear_All_Group_Types_triggered() {
nodeResource.clear();
//todo: clear persistent index list
}