-
Notifications
You must be signed in to change notification settings - Fork 22
/
MainWindow.cpp
719 lines (588 loc) · 29 KB
/
MainWindow.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
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
#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/ShaderEditor.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 <QFile>
#include <sstream>
#include <functional>
#include <unordered_map>
#undef GetMessage
QList<QString> MainWindow::EnigmaSearchPaths = {QDir::currentPath(), "./enigma-dev", "../enigma-dev",
"../RadialGM/Submodules/enigma-dev", "/opt/enigma-dev/", "/usr/lib/enigma-dev"};
QFileInfo MainWindow::EnigmaRoot = MainWindow::getEnigmaRoot();
QList<buffers::SystemType> MainWindow::systemCache;
MainWindow *MainWindow::_instance = nullptr;
ResourceModelMap *MainWindow::resourceMap = nullptr;
TreeModel *MainWindow::treeModel = nullptr;
std::unique_ptr<EventData> MainWindow::_event_data;
static QTextEdit *diagnosticTextEdit = nullptr;
static QAction *toggleDiagnosticsAction = nullptr;
void diagnosticHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
if (toggleDiagnosticsAction) {
if (!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 infinite recursion
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 != nullptr) {
diagnosticTextEdit->append(msgFormatted);
} else {
// this should never happen!
std::cerr << "Critical: Diagnostics text control does not exist!" << std::endl;
}
}
QFileInfo MainWindow::getEnigmaRoot() {
QFileInfo EnigmaRoot;
foreach (auto path, EnigmaSearchPaths) {
const QDir dir(path);
QDir::Filters filters = QDir::Filter::AllEntries;
auto entryList = dir.entryInfoList(QStringList({"ENIGMAsystem"}), filters, QDir::SortFlag::NoSort);
if (!entryList.empty()) {
EnigmaRoot = entryList.first();
break;
}
}
return EnigmaRoot;
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), _ui(new Ui::MainWindow) {
if (!EnigmaRoot.filePath().isEmpty()) {
_event_data = std::make_unique<EventData>(ParseEventFile((EnigmaRoot.absolutePath() + "/events.ey").toStdString()));
} else {
qDebug() << "Error: Failed to locate ENIGMA sources. Loading internal events.ey.\n"
<< "Search Paths:\n"
<< MainWindow::EnigmaSearchPaths;
QFile internal_events(":/events.ey");
internal_events.open(QIODevice::ReadOnly | QFile::Text);
std::stringstream ss;
ss << internal_events.readAll().toStdString();
_event_data = std::make_unique<EventData>(ParseEventFile(ss));
}
egm::LibEGMInit(_event_data.get());
ArtManager::Init();
_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);
openNewProject();
}
MainWindow::~MainWindow() {
diagnosticTextEdit = nullptr;
delete _ui;
}
void MainWindow::setCurrentConfig(const buffers::resources::Settings &settings) {
emit _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();
}
void MainWindow::openSubWindow(MessageModel *res, MainWindow::EditorFactoryFunction factory_function) {
using namespace google::protobuf;
if (!res) {
qDebug() << "Attempt to edit null resource...";
return;
}
auto swIt = _subWindows.find(res);
QMdiSubWindow *subWindow;
if (swIt == _subWindows.end() || !*swIt) {
BaseEditor *editor = factory_function(res, this);
if (!editor) {
qDebug() << "Failed to launch editor for model...";
return;
}
subWindow = _subWindows[res] = _ui->mdiArea->addSubWindow(editor);
subWindow->resize(subWindow->frameSize().expandedTo(editor->size()));
editor->setParent(subWindow);
subWindow->connect(subWindow, &QObject::destroyed, [=]() { _subWindows.remove(res); });
subWindow->setWindowIcon(subWindow->widget()->windowIcon());
editor->setWindowTitle(
res->GetParentModel<MessageModel>()->Data(FieldPath::Of<TreeNode>(TreeNode::kNameFieldNumber)).toString());
} 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, windowTitle);
QAction *action =
_ui->menuWindow->addAction(mdiSubWindow->windowIcon(), 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);
std::unique_ptr<buffers::Project> loadedProject = egm::LoadProject(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::move(loadedProject));
}
void MainWindow::openNewProject() {
MainWindow::setWindowTitle(tr("<new game> - ENIGMA"));
auto newProject = std::make_unique<buffers::Project>();
auto *root = newProject->mutable_game()->mutable_root();
QList<QString> defaultGroups = {tr("Sprites"), tr("Sounds"), tr("Backgrounds"), tr("Paths"),
tr("Scripts"), tr("Shaders"), tr("Fonts"), tr("Timelines"),
tr("Objects"), tr("Rooms"), tr("Includes"), tr("Configs")};
// We can edit the proto directly, here, since the model doesn't exist, yet.
for (const auto &groupName : defaultGroups) {
auto *groupNode = root->mutable_folder()->add_children();
groupNode->set_name(groupName.toStdString());
groupNode->mutable_folder();
}
openProject(std::move(newProject));
}
template <typename Editor>
TreeModel::EditorLauncher Launch(MainWindow *parent) {
struct EditorFactoryFactory {
static BaseEditor *Factory(MessageModel *model, MainWindow *parent) {
if (!model || !model->GetParentModel<MessageModel>()) return nullptr;
return new Editor(model, parent);
}
};
return [parent](MessageModel *model) { parent->openSubWindow(model, EditorFactoryFactory::Factory); };
}
void ConfigureIconFields(ProtoModel::DisplayConfig *conf, const Descriptor *desc,
std::set<const Descriptor *> *visited) {
for (int i = 0; i < desc->field_count(); ++i) {
const FieldDescriptor *field = desc->field(i);
if (field->options().HasExtension(buffers::resource_ref)) {
std::string resource_type = field->options().GetExtension(buffers::resource_ref);
if (resource_type == "object") {
conf->SetFieldIconLookup(field, GetObjectSpriteByNameField);
conf->SetFieldDefaultIcon(field, "object");
} else if (resource_type == "sprite") {
conf->SetFieldIconLookup(field, GetSpriteIconByNameField);
} else if (resource_type == "background") {
conf->SetFieldIconLookup(field, GetBackgroundIconByNameField);
} else if (resource_type == "room") {
// no preview for rooms yet
} else {
qDebug() << "Unknown resource ref type: " << resource_type.c_str();
}
}
if (field->options().HasExtension(buffers::file_kind)) {
if (field->options().GetExtension(buffers::file_kind) == buffers::FileKind::IMAGE) {
conf->SetFieldIconLookup(field, GetFileIcon);
}
}
if (const Descriptor *submsg = field->message_type()) {
if (visited->insert(submsg).second) ConfigureIconFields(conf, submsg, visited);
}
}
}
void ConfigureIconFields(ProtoModel::DisplayConfig *conf, const Descriptor *desc) {
std::set<const Descriptor *> visited{desc};
return ConfigureIconFields(conf, desc, &visited);
}
void MainWindow::openProject(std::unique_ptr<buffers::Project> openedProject) {
this->_ui->mdiArea->closeAllSubWindows();
ArtManager::clearCache();
_project = std::move(openedProject);
TreeModel::DisplayConfig treeConf;
treeConf.UseEditorLauncher<buffers::resources::Sprite>(Launch<SpriteEditor>(this));
treeConf.UseEditorLauncher<buffers::resources::Sound>(Launch<SoundEditor>(this));
treeConf.UseEditorLauncher<buffers::resources::Background>(Launch<BackgroundEditor>(this));
treeConf.UseEditorLauncher<buffers::resources::Path>(Launch<PathEditor>(this));
treeConf.UseEditorLauncher<buffers::resources::Font>(Launch<FontEditor>(this));
treeConf.UseEditorLauncher<buffers::resources::Script>(Launch<ScriptEditor>(this));
treeConf.UseEditorLauncher<buffers::resources::Shader>(Launch<ShaderEditor>(this));
treeConf.UseEditorLauncher<buffers::resources::Timeline>(Launch<TimelineEditor>(this));
treeConf.UseEditorLauncher<buffers::resources::Object>(Launch<ObjectEditor>(this));
treeConf.UseEditorLauncher<buffers::resources::Room>(Launch<RoomEditor>(this));
treeConf.UseEditorLauncher<buffers::resources::Settings>(Launch<SettingsEditor>(this));
ProtoModel::DisplayConfig msgConf;
msgConf.SetDefaultIcon<buffers::TreeNode::Folder>("group");
msgConf.SetDefaultIcon<buffers::TreeNode::UnknownResource>("info");
msgConf.SetDefaultIcon<buffers::resources::Sprite>("sprite");
msgConf.SetDefaultIcon<buffers::resources::Sound>("sound");
msgConf.SetDefaultIcon<buffers::resources::Background>("background");
msgConf.SetDefaultIcon<buffers::resources::Path>("path");
msgConf.SetDefaultIcon<buffers::resources::Script>("script");
msgConf.SetDefaultIcon<buffers::resources::Shader>("shader");
msgConf.SetDefaultIcon<buffers::resources::Font>("font");
msgConf.SetDefaultIcon<buffers::resources::Timeline>("timeline");
msgConf.SetDefaultIcon<buffers::resources::Object>("object");
msgConf.SetDefaultIcon<buffers::resources::Room>("room");
msgConf.SetDefaultIcon<buffers::resources::Settings>("settings");
ConfigureIconFields(&msgConf, TreeNode::GetDescriptor());
msgConf.SetMessageIconPathField<buffers::resources::Sprite>(
FieldPath::RepeatedOffset(buffers::resources::Sprite::kSubimagesFieldNumber, 0));
msgConf.SetMessageIconPathField<buffers::resources::Background>(buffers::resources::Background::kImageFieldNumber);
msgConf.SetMessageIconIdLookup<buffers::resources::Object>(GetSpriteIconByNameField,
buffers::resources::Object::kSpriteNameFieldNumber);
msgConf.SetMessageLabelField<buffers::TreeNode>(buffers::TreeNode::kNameFieldNumber);
msgConf.SetFieldHeaderIcon<buffers::resources::Path::Point>(":/actions/diamond-red.png",
buffers::resources::Path::Point::kXFieldNumber);
msgConf.SetFieldHeaderIcon<buffers::resources::Path::Point>(":/actions/diamond-green.png",
buffers::resources::Path::Point::kYFieldNumber);
msgConf.SetFieldHeaderIcon<buffers::resources::Path::Point>(":/actions/diamond-blue.png",
buffers::resources::Path::Point::kSpeedFieldNumber);
msgConf.SetFieldHeaderLabel<buffers::resources::Path::Point>(tr("X"), buffers::resources::Path::Point::kXFieldNumber);
msgConf.SetFieldHeaderLabel<buffers::resources::Path::Point>(tr("Y"), buffers::resources::Path::Point::kYFieldNumber);
msgConf.SetFieldHeaderLabel<buffers::resources::Path::Point>(tr("Speed"),
buffers::resources::Path::Point::kSpeedFieldNumber);
treeConf.SetMessagePassthrough<buffers::TreeNode>();
treeConf.SetMessagePassthrough<buffers::TreeNode::Folder>();
treeConf.DisableOneofReassignment<buffers::TreeNode>();
delete resourceMap;
resourceMap = new ResourceModelMap(this);
auto pm = new MessageModel(ProtoModel::NonProtoParent{this}, _project->mutable_game()->mutable_root());
// Connect methods to auto update fields with extensions
connect(pm, &ProtoModel::ModelConstructed, [](ProtoModel *model) {
PrimitiveModel *primitive_model = model->TryCastAsPrimitiveModel();
if (primitive_model) {
const FieldDescriptor *const field = primitive_model->GetFieldDescriptor();
if (field && !field->options().GetExtension(buffers::resource_ref).empty())
connect(resourceMap,
qOverload<const std::string &, const QString &, const QString &>(&ResourceModelMap::ResourceRenamed),
primitive_model,
[primitive_model](const std::string &type, const QString &newValue, const QString &oldValue) {
primitive_model->ExtensionChanged<decltype(buffers::resource_ref)>(buffers::resource_ref, type,
newValue, oldValue);
});
}
});
pm->RebuildSubModels();
pm->SetDisplayConfig(msgConf);
resourceMap->TreeChanged(pm);
delete treeModel;
treeModel = new TreeModel(pm, nullptr, treeConf);
_ui->treeView->setModel(treeModel);
connect(treeModel, &TreeModel::ItemRenamed, resourceMap,
qOverload<buffers::TreeNode::TypeCase, const QString &, const QString &>(&ResourceModelMap::ResourceRenamed));
connect(treeModel, &TreeModel::TreeChanged, resourceMap, &ResourceModelMap::TreeChanged);
connect(treeModel, &TreeModel::ItemRemoved, resourceMap, &ResourceModelMap::ResourceRemoved,
Qt::DirectConnection);
connect(pm, &ProtoModel::dataChanged, resourceMap, &ResourceModelMap::dataChanged,
Qt::DirectConnection);
connect(treeModel, &TreeModel::ModelAboutToBeDeleted, this, &MainWindow::ResourceModelDeleted,
Qt::DirectConnection);
}
void MainWindow::on_actionNew_triggered() { openNewProject(); }
void MainWindow::on_actionOpen_triggered() {
const QString &fileName = QFileDialog::getOpenFileName(
this, tr("Open Project"), "",
tr("All supported formats (*.egm *.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_actionSave_triggered() {
// map useful to quickly fetch extension from the selected filter in QDialog (because Qt doesn't give a better way)
QHash<QString, QString> extensionMap;
extensionMap["EGM (*.egm)"] = ".egm";
QString selectedFilter;
QString fileName = QFileDialog::getSaveFileName(this, tr("Save Project"), "",
extensionMap.keys().join(QStringLiteral(";;")),
&selectedFilter);
if(fileName.isEmpty()) {
return;
}
if(!fileName.endsWith(extensionMap[selectedFilter], Qt::CaseInsensitive)) {
// removes any trailing periods(.) from the file path
while(fileName.endsWith(QLatin1Char('.')))
fileName.chop(1);
fileName.append(extensionMap[selectedFilter]);
}
egm::WriteProject(_project.get(), fileName.toStdString());
}
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);
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) {
if (treeModel->rowCount(index)) {
// Allow node expansion to happen.
return;
}
treeModel->triggerNodeEdit(index, _ui->treeView);
}
void MainWindow::on_actionClearRecentMenu_triggered() { _recentFiles->clear(); }
void MainWindow::CreateResource(TypeCase typeCase) {
if(this->treeModel == NULL){
qDebug() << "Attempt to add resource with NULL treeModel...";
return;
}
TreeNode child;
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, field);
// find a unique name for the new resource
QString resourceName = resourceMap->CreateResourceName(&child);
child.set_name(resourceName.toStdString());
// release ownership of the new child to its parent and the tree
auto index = this->treeModel->addNode(child, _ui->treeView->currentIndex());
treeModel->triggerNodeEdit(index, _ui->treeView);
TreeModel::Node *node = this->treeModel->IndexToNode(index);
if(node == NULL){
qDebug() << "Attempt to add resource with NULL treeModel node...";
return;
}
ProtoModel *protoModel = node->BackingModel();
if(protoModel == NULL){
qDebug() << "Attempt to add resource with NULL protoModel...";
return;
}
MessageModel *messageModel = protoModel->TryCastAsMessageModel();
// add new resource with created name, helps in creating another unique name
if(messageModel)
resourceMap->AddResource(typeCase, resourceName, messageModel);
else
qDebug() << "Attempt to add resource with NULL messageModel...";
}
void MainWindow::ResourceModelDeleted(MessageModel *m) {
if (_subWindows.contains(m)) {
static_cast<BaseEditor *>(_subWindows[m]->widget())->MarkDeleted();
_subWindows[m]->close();
}
}
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();
QModelIndex dupIndex = treeModel->duplicateNode(index);
// Triggers edit of either resource or name label.
// TODO: maybe confirm before duplicating an entire fucking group; we're all reasonable people
treeModel->triggerNodeEdit(dupIndex, _ui->treeView);
}
void MainWindow::on_actionCreateGroup_triggered() {
TreeNode child;
child.mutable_folder(); // Gives the node an empty folder.
// find a unique name for the new group
const QString name = resourceMap->CreateResourceName(TypeCase::kFolder, "group");
child.set_name(name.toStdString());
this->treeModel->triggerNodeEdit(this->treeModel->addNode(child, _ui->treeView->currentIndex()), _ui->treeView);
}
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) {
treeModel->triggerNodeEdit(index, _ui->treeView);
}
}
void MainWindow::on_actionDelete_triggered() {
if (!_ui->treeView->selectionModel()->hasSelection()) return;
auto selected = _ui->treeView->selectionModel()->selectedIndexes();
QSet<const QModelIndex> selectedNodes;
for (auto& index : qAsConst(selected)) {
selectedNodes.insert(index);
}
QString selectedNames = "";
for (auto &node : qAsConst(selectedNodes)) {
selectedNames += (node == *selectedNodes.begin() ? "" : ", ") + node.data().toString();
}
QMessageBox mb(QMessageBox::Icon::Question, tr("Delete Resources"),
tr("Do you want to delete the selected resources from the project?"),
QMessageBox::Yes | QMessageBox::No, this);
mb.setDetailedText(selectedNames);
int ret = mb.exec();
if (ret != QMessageBox::Yes) return;
treeModel->BatchRemove(selectedNodes);
}
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));
}