-
Notifications
You must be signed in to change notification settings - Fork 93
/
mainwindow.cpp
3465 lines (2948 loc) · 136 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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "project.h"
#include "log.h"
#include "editor.h"
#include "prefabcreationdialog.h"
#include "eventframes.h"
#include "bordermetatilespixmapitem.h"
#include "currentselectedmetatilespixmapitem.h"
#include "customattributestable.h"
#include "scripting.h"
#include "adjustingstackedwidget.h"
#include "draggablepixmapitem.h"
#include "editcommands.h"
#include "flowlayout.h"
#include "shortcut.h"
#include "mapparser.h"
#include "prefab.h"
#include "montabwidget.h"
#include "imageexport.h"
#include "maplistmodels.h"
#include "eventfilters.h"
#include "newmapconnectiondialog.h"
#include "config.h"
#include "filedialog.h"
#include <QClipboard>
#include <QDirIterator>
#include <QStandardItemModel>
#include <QSpinBox>
#include <QTextEdit>
#include <QSpacerItem>
#include <QFont>
#include <QScrollBar>
#include <QPushButton>
#include <QMessageBox>
#include <QDialogButtonBox>
#include <QScroller>
#include <math.h>
#include <QSysInfo>
#include <QDesktopServices>
#include <QTransform>
#include <QSignalBlocker>
#include <QSet>
#include <QLoggingCategory>
// We only publish release binaries for Windows and macOS.
// This is relevant for the update promoter, which alerts users of a new release.
// TODO: Currently the update promoter is disabled on our Windows releases because
// the pre-compiled Qt build doesn't link OpenSSL. Re-enable below once this is fixed.
#if /*defined(Q_OS_WIN) || */defined(Q_OS_MACOS)
#define RELEASE_PLATFORM
#endif
using OrderedJson = poryjson::Json;
using OrderedJsonDoc = poryjson::JsonDoc;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
isProgrammaticEventTabChange(false)
{
QCoreApplication::setOrganizationName("pret");
QCoreApplication::setApplicationName("porymap");
QCoreApplication::setApplicationVersion(PORYMAP_VERSION);
QApplication::setApplicationDisplayName("porymap");
QApplication::setWindowIcon(QIcon(":/icons/porymap-icon-2.ico"));
ui->setupUi(this);
cleanupLargeLog();
logInfo(QString("Launching Porymap v%1").arg(QCoreApplication::applicationVersion()));
this->initWindow();
if (porymapConfig.reopenOnLaunch && !porymapConfig.projectManuallyClosed && this->openProject(porymapConfig.getRecentProject(), true))
on_toolButton_Paint_clicked();
// there is a bug affecting macOS users, where the trackpad deilveres a bad touch-release gesture
// the warning is a bit annoying, so it is disabled here
QLoggingCategory::setFilterRules(QStringLiteral("qt.pointer.dispatch=false"));
if (porymapConfig.checkForUpdates)
this->checkForUpdates(false);
}
MainWindow::~MainWindow()
{
delete label_MapRulerStatus;
delete editor;
delete ui;
}
void MainWindow::setWindowDisabled(bool disabled) {
for (auto action : findChildren<QAction *>())
action->setDisabled(disabled);
for (auto child : findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly))
child->setDisabled(disabled);
for (auto menu : ui->menuBar->findChildren<QMenu *>(QString(), Qt::FindDirectChildrenOnly))
menu->setDisabled(disabled);
ui->menuBar->setDisabled(false);
ui->menuFile->setDisabled(false);
ui->action_Open_Project->setDisabled(false);
ui->menuOpen_Recent_Project->setDisabled(false);
refreshRecentProjectsMenu();
ui->action_Exit->setDisabled(false);
ui->menuHelp->setDisabled(false);
ui->actionAbout_Porymap->setDisabled(false);
ui->actionOpen_Log_File->setDisabled(false);
ui->actionOpen_Config_Folder->setDisabled(false);
ui->actionCheck_for_Updates->setDisabled(false);
if (!disabled)
togglePreferenceSpecificUi();
}
void MainWindow::initWindow() {
porymapConfig.load();
this->initCustomUI();
this->initExtraSignals();
this->initEditor();
this->initMiscHeapObjects();
this->initMapList();
this->initShortcuts();
this->restoreWindowState();
#ifndef RELEASE_PLATFORM
ui->actionCheck_for_Updates->setVisible(false);
#endif
#ifdef DISABLE_CHARTS_MODULE
ui->pushButton_SummaryChart->setVisible(false);
#endif
setWindowDisabled(true);
}
void MainWindow::initShortcuts() {
initExtraShortcuts();
shortcutsConfig.load();
shortcutsConfig.setDefaultShortcuts(shortcutableObjects());
applyUserShortcuts();
}
void MainWindow::initExtraShortcuts() {
ui->actionZoom_In->setShortcuts({ui->actionZoom_In->shortcut(), QKeySequence("Ctrl+=")});
auto *shortcutReset_Zoom = new Shortcut(QKeySequence("Ctrl+0"), this, SLOT(resetMapViewScale()));
shortcutReset_Zoom->setObjectName("shortcutZoom_Reset");
shortcutReset_Zoom->setWhatsThis("Zoom Reset");
auto *shortcutDuplicate_Events = new Shortcut(QKeySequence("Ctrl+D"), this, SLOT(duplicate()));
shortcutDuplicate_Events->setObjectName("shortcutDuplicate_Events");
shortcutDuplicate_Events->setWhatsThis("Duplicate Selected Event(s)");
auto *shortcutToggle_Border = new Shortcut(QKeySequence(), ui->checkBox_ToggleBorder, SLOT(toggle()));
shortcutToggle_Border->setObjectName("shortcutToggle_Border");
shortcutToggle_Border->setWhatsThis("Toggle Border");
auto *shortcutToggle_Smart_Paths = new Shortcut(QKeySequence(), ui->checkBox_smartPaths, SLOT(toggle()));
shortcutToggle_Smart_Paths->setObjectName("shortcutToggle_Smart_Paths");
shortcutToggle_Smart_Paths->setWhatsThis("Toggle Smart Paths");
auto *shortcutHide_Show = new Shortcut(QKeySequence(), this, SLOT(mapListShortcut_ToggleEmptyFolders()));
shortcutHide_Show->setObjectName("shortcutHide_Show");
shortcutHide_Show->setWhatsThis("Map List: Hide/Show Empty Folders");
auto *shortcutExpand_All = new Shortcut(QKeySequence(), this, SLOT(mapListShortcut_ExpandAll()));
shortcutExpand_All->setObjectName("shortcutExpand_All");
shortcutExpand_All->setWhatsThis("Map List: Expand all folders");
auto *shortcutCollapse_All = new Shortcut(QKeySequence(), this, SLOT(mapListShortcut_CollapseAll()));
shortcutCollapse_All->setObjectName("shortcutCollapse_All");
shortcutCollapse_All->setWhatsThis("Map List: Collapse all folders");
auto *shortcut_Open_Scripts = new Shortcut(QKeySequence(), ui->toolButton_Open_Scripts, SLOT(click()));
shortcut_Open_Scripts->setObjectName("shortcut_Open_Scripts");
shortcut_Open_Scripts->setWhatsThis("Open Map Scripts");
copyAction = new QAction("Copy", this);
copyAction->setShortcut(QKeySequence("Ctrl+C"));
connect(copyAction, &QAction::triggered, this, &MainWindow::copy);
ui->menuEdit->addSeparator();
ui->menuEdit->addAction(copyAction);
pasteAction = new QAction("Paste", this);
pasteAction->setShortcut(QKeySequence("Ctrl+V"));
connect(pasteAction, &QAction::triggered, this, &MainWindow::paste);
ui->menuEdit->addAction(pasteAction);
}
QObjectList MainWindow::shortcutableObjects() const {
QObjectList shortcutable_objects;
for (auto *action : findChildren<QAction *>())
if (!action->objectName().isEmpty())
shortcutable_objects.append(qobject_cast<QObject *>(action));
for (auto *shortcut : findChildren<Shortcut *>())
if (!shortcut->objectName().isEmpty())
shortcutable_objects.append(qobject_cast<QObject *>(shortcut));
return shortcutable_objects;
}
void MainWindow::applyUserShortcuts() {
for (auto *action : findChildren<QAction *>())
if (!action->objectName().isEmpty())
action->setShortcuts(shortcutsConfig.userShortcuts(action));
for (auto *shortcut : findChildren<Shortcut *>())
if (!shortcut->objectName().isEmpty())
shortcut->setKeys(shortcutsConfig.userShortcuts(shortcut));
}
void MainWindow::initCustomUI() {
static const QMap<int, QString> mainTabNames = {
{MainTab::Map, "Map"},
{MainTab::Events, "Events"},
{MainTab::Header, "Header"},
{MainTab::Connections, "Connections"},
{MainTab::WildPokemon, "Wild Pokemon"},
};
static const QMap<int, QIcon> mainTabIcons = {
{MainTab::Map, QIcon(QStringLiteral(":/icons/minimap.ico"))},
{MainTab::Events, QIcon(QStringLiteral(":/icons/viewsprites.ico"))},
{MainTab::Header, QIcon(QStringLiteral(":/icons/application_form_edit.ico"))},
{MainTab::Connections, QIcon(QStringLiteral(":/icons/connections.ico"))},
{MainTab::WildPokemon, QIcon(QStringLiteral(":/icons/tall_grass.ico"))},
};
// Set up the tab bar
while (ui->mainTabBar->count()) ui->mainTabBar->removeTab(0);
for (int i = 0; i < mainTabNames.count(); i++) {
ui->mainTabBar->addTab(mainTabNames.value(i));
ui->mainTabBar->setTabIcon(i, mainTabIcons.value(i));
}
}
void MainWindow::initExtraSignals() {
// other signals
connect(ui->newEventToolButton, &NewEventToolButton::newEventAdded, this, &MainWindow::addNewEvent);
connect(ui->tabWidget_EventType, &QTabWidget::currentChanged, this, &MainWindow::eventTabChanged);
// Change pages on wild encounter groups
connect(ui->comboBox_EncounterGroupLabel, QOverload<int>::of(&QComboBox::currentIndexChanged), [this](int index){
ui->stackedWidget_WildMons->setCurrentIndex(index);
});
// Convert the layout of the map tools' frame into an adjustable FlowLayout
FlowLayout *flowLayout = new FlowLayout;
flowLayout->setContentsMargins(ui->frame_mapTools->layout()->contentsMargins());
flowLayout->setSpacing(ui->frame_mapTools->layout()->spacing());
for (auto *child : ui->frame_mapTools->findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly)) {
flowLayout->addWidget(child);
child->setFixedHeight(
ui->frame_mapTools->height() - flowLayout->contentsMargins().top() - flowLayout->contentsMargins().bottom()
);
}
delete ui->frame_mapTools->layout();
ui->frame_mapTools->setLayout(flowLayout);
// Floating QLabel tool-window that displays over the map when the ruler is active
label_MapRulerStatus = new QLabel(ui->graphicsView_Map);
label_MapRulerStatus->setObjectName("label_MapRulerStatus");
label_MapRulerStatus->setWindowFlags(Qt::Tool | Qt::CustomizeWindowHint | Qt::FramelessWindowHint);
label_MapRulerStatus->setFrameShape(QFrame::Box);
label_MapRulerStatus->setMargin(3);
label_MapRulerStatus->setPalette(palette());
label_MapRulerStatus->setAlignment(Qt::AlignCenter);
label_MapRulerStatus->setTextFormat(Qt::PlainText);
label_MapRulerStatus->setTextInteractionFlags(Qt::TextSelectableByMouse);
}
void MainWindow::on_actionCheck_for_Updates_triggered() {
checkForUpdates(true);
}
#ifdef RELEASE_PLATFORM
void MainWindow::checkForUpdates(bool requestedByUser) {
if (!this->networkAccessManager)
this->networkAccessManager = new NetworkAccessManager(this);
if (!this->updatePromoter) {
this->updatePromoter = new UpdatePromoter(this, this->networkAccessManager);
connect(this->updatePromoter, &UpdatePromoter::changedPreferences, [this] {
if (this->preferenceEditor)
this->preferenceEditor->updateFields();
});
}
if (requestedByUser) {
openSubWindow(this->updatePromoter);
} else {
// This is an automatic update check. Only run if we haven't done one in the last 5 minutes
QDateTime lastCheck = porymapConfig.lastUpdateCheckTime;
if (lastCheck.addSecs(5*60) >= QDateTime::currentDateTime())
return;
}
this->updatePromoter->checkForUpdates();
porymapConfig.lastUpdateCheckTime = QDateTime::currentDateTime();
}
#else
void MainWindow::checkForUpdates(bool) {}
#endif
void MainWindow::initEditor() {
this->editor = new Editor(ui);
connect(this->editor, &Editor::objectsChanged, this, &MainWindow::updateObjects);
connect(this->editor, &Editor::openConnectedMap, this, &MainWindow::onOpenConnectedMap);
connect(this->editor, &Editor::warpEventDoubleClicked, this, &MainWindow::openWarpMap);
connect(this->editor, &Editor::currentMetatilesSelectionChanged, this, &MainWindow::currentMetatilesSelectionChanged);
connect(this->editor, &Editor::wildMonTableEdited, [this] { this->markMapEdited(); });
connect(this->editor, &Editor::mapRulerStatusChanged, this, &MainWindow::onMapRulerStatusChanged);
connect(this->editor, &Editor::tilesetUpdated, this, &Scripting::cb_TilesetUpdated);
connect(ui->toolButton_deleteObject, &QAbstractButton::clicked, this->editor, &Editor::deleteSelectedEvents);
this->loadUserSettings();
undoAction = editor->editGroup.createUndoAction(this, tr("&Undo"));
undoAction->setObjectName("action_Undo");
undoAction->setShortcut(QKeySequence("Ctrl+Z"));
redoAction = editor->editGroup.createRedoAction(this, tr("&Redo"));
redoAction->setObjectName("action_Redo");
redoAction->setShortcuts({QKeySequence("Ctrl+Y"), QKeySequence("Ctrl+Shift+Z")});
ui->menuEdit->addAction(undoAction);
ui->menuEdit->addAction(redoAction);
QUndoView *undoView = new QUndoView(&editor->editGroup);
undoView->setWindowTitle(tr("Edit History"));
undoView->setAttribute(Qt::WA_QuitOnClose, false);
// Show the EditHistory dialog with Ctrl+E
QAction *showHistory = new QAction("Show Edit History...", this);
showHistory->setObjectName("action_ShowEditHistory");
showHistory->setShortcut(QKeySequence("Ctrl+E"));
connect(showHistory, &QAction::triggered, [this, undoView](){ openSubWindow(undoView); });
ui->menuEdit->addAction(showHistory);
// Toggle an asterisk in the window title when the undo state is changed
connect(&editor->editGroup, &QUndoGroup::indexChanged, this, &MainWindow::updateWindowTitle);
// selecting objects from the spinners
connect(this->ui->spinner_ObjectID, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value) {
this->editor->selectedEventIndexChanged(value, Event::Group::Object);
});
connect(this->ui->spinner_WarpID, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value) {
this->editor->selectedEventIndexChanged(value, Event::Group::Warp);
});
connect(this->ui->spinner_TriggerID, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value) {
this->editor->selectedEventIndexChanged(value, Event::Group::Coord);
});
connect(this->ui->spinner_BgID, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value) {
this->editor->selectedEventIndexChanged(value, Event::Group::Bg);
});
connect(this->ui->spinner_HealID, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value) {
this->editor->selectedEventIndexChanged(value, Event::Group::Heal);
});
}
void MainWindow::initMiscHeapObjects() {
ui->tabWidget_EventType->clear();
}
void MainWindow::initMapList() {
ui->mapListContainer->setCurrentIndex(porymapConfig.mapListTab);
WheelFilter *wheelFilter = new WheelFilter(this);
ui->mainTabBar->installEventFilter(wheelFilter);
ui->mapListContainer->tabBar()->installEventFilter(wheelFilter);
// Create buttons for adding and removing items from the mapList
QFrame *buttonFrame = new QFrame(this->ui->mapListContainer);
buttonFrame->setFrameShape(QFrame::NoFrame);
QHBoxLayout *layout = new QHBoxLayout(buttonFrame);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
// Create add map/layout button
QPushButton *buttonAdd = new QPushButton(QIcon(":/icons/add.ico"), "");
connect(buttonAdd, &QPushButton::clicked, this, &MainWindow::on_action_NewMap_triggered);
layout->addWidget(buttonAdd);
/* TODO: Remove button disabled, no current support for deleting maps/layouts
// Create remove map/layout button
QPushButton *buttonRemove = new QPushButton(QIcon(":/icons/delete.ico"), "");
connect(buttonRemove, &QPushButton::clicked, this, &MainWindow::deleteCurrentMapOrLayout);
layout->addWidget(buttonRemove);
*/
ui->mapListContainer->setCornerWidget(buttonFrame, Qt::TopRightCorner);
// Connect tool bars to lists
ui->mapListToolBar_Groups->setList(ui->mapList);
ui->mapListToolBar_Areas->setList(ui->areaList);
ui->mapListToolBar_Layouts->setList(ui->layoutList);
// Left-clicking on items in the map list opens the corresponding map/layout.
connect(ui->mapList, &QAbstractItemView::activated, this, &MainWindow::openMapListItem);
connect(ui->areaList, &QAbstractItemView::activated, this, &MainWindow::openMapListItem);
connect(ui->layoutList, &QAbstractItemView::activated, this, &MainWindow::openMapListItem);
// Right-clicking on items in the map list brings up a context menu.
connect(ui->mapList, &QTreeView::customContextMenuRequested, this, &MainWindow::onOpenMapListContextMenu);
connect(ui->areaList, &QTreeView::customContextMenuRequested, this, &MainWindow::onOpenMapListContextMenu);
connect(ui->layoutList, &QTreeView::customContextMenuRequested, this, &MainWindow::onOpenMapListContextMenu);
// Only the groups list allows reorganizing folder contents, editing folder names, etc.
ui->mapListToolBar_Areas->setEditsAllowedButtonVisible(false);
ui->mapListToolBar_Layouts->setEditsAllowedButtonVisible(false);
// When map list search filter is cleared we want the current map/layout in the editor to be visible in the list.
connect(ui->mapListToolBar_Groups, &MapListToolBar::filterCleared, this, &MainWindow::scrollMapListToCurrentMap);
connect(ui->mapListToolBar_Areas, &MapListToolBar::filterCleared, this, &MainWindow::scrollMapListToCurrentMap);
connect(ui->mapListToolBar_Layouts, &MapListToolBar::filterCleared, this, &MainWindow::scrollMapListToCurrentLayout);
// Connect the "add folder" button in each of the map lists
connect(ui->mapListToolBar_Groups, &MapListToolBar::addFolderClicked, this, &MainWindow::mapListAddGroup);
connect(ui->mapListToolBar_Areas, &MapListToolBar::addFolderClicked, this, &MainWindow::mapListAddArea);
connect(ui->mapListToolBar_Layouts, &MapListToolBar::addFolderClicked, this, &MainWindow::mapListAddLayout);
connect(ui->mapListContainer, &QTabWidget::currentChanged, this, &MainWindow::saveMapListTab);
}
void MainWindow::updateWindowTitle() {
if (!editor || !editor->project) {
setWindowTitle(QCoreApplication::applicationName());
return;
}
const QString projectName = editor->project->getProjectTitle();
if (!editor->layout) {
setWindowTitle(projectName);
return;
}
if (editor->map) {
setWindowTitle(QString("%1%2 - %3")
.arg(editor->map->hasUnsavedChanges() ? "* " : "")
.arg(editor->map->name)
.arg(projectName)
);
} else {
setWindowTitle(QString("%1%2 - %3")
.arg(editor->layout->hasUnsavedChanges() ? "* " : "")
.arg(editor->layout->name)
.arg(projectName)
);
}
// For some reason (perhaps on Qt < 6?) we had to clear the icon first here or mainTabBar wouldn't display correctly.
ui->mainTabBar->setTabIcon(MainTab::Map, QIcon());
QPixmap pixmap = editor->layout->pixmap;
if (!pixmap.isNull()) {
ui->mainTabBar->setTabIcon(MainTab::Map, QIcon(pixmap));
} else {
ui->mainTabBar->setTabIcon(MainTab::Map, QIcon(QStringLiteral(":/icons/map.ico")));
}
}
void MainWindow::markMapEdited() {
if (editor) markSpecificMapEdited(editor->map);
}
void MainWindow::markSpecificMapEdited(Map* map) {
if (!map)
return;
map->hasUnsavedDataChanges = true;
if (editor && editor->map == map)
updateWindowTitle();
updateMapList();
}
void MainWindow::loadUserSettings() {
// Better Cursors
ui->actionBetter_Cursors->setChecked(porymapConfig.prettyCursors);
this->editor->settings->betterCursors = porymapConfig.prettyCursors;
// Player view rectangle
ui->actionPlayer_View_Rectangle->setChecked(porymapConfig.showPlayerView);
this->editor->settings->playerViewRectEnabled = porymapConfig.showPlayerView;
// Cursor tile outline
ui->actionCursor_Tile_Outline->setChecked(porymapConfig.showCursorTile);
this->editor->settings->cursorTileRectEnabled = porymapConfig.showCursorTile;
// Border
ui->checkBox_ToggleBorder->setChecked(porymapConfig.showBorder);
// Grid
const QSignalBlocker b_Grid(ui->checkBox_ToggleGrid);
ui->actionShow_Grid->setChecked(porymapConfig.showGrid);
ui->checkBox_ToggleGrid->setChecked(porymapConfig.showGrid);
// Mirror connections
ui->checkBox_MirrorConnections->setChecked(porymapConfig.mirrorConnectingMaps);
// Collision opacity/transparency
const QSignalBlocker b_CollisionTransparency(ui->horizontalSlider_CollisionTransparency);
this->editor->collisionOpacity = static_cast<qreal>(porymapConfig.collisionOpacity) / 100;
ui->horizontalSlider_CollisionTransparency->setValue(porymapConfig.collisionOpacity);
// Dive map opacity/transparency
const QSignalBlocker b_DiveEmergeOpacity(ui->slider_DiveEmergeMapOpacity);
const QSignalBlocker b_DiveMapOpacity(ui->slider_DiveMapOpacity);
const QSignalBlocker b_EmergeMapOpacity(ui->slider_EmergeMapOpacity);
ui->slider_DiveEmergeMapOpacity->setValue(porymapConfig.diveEmergeMapOpacity);
ui->slider_DiveMapOpacity->setValue(porymapConfig.diveMapOpacity);
ui->slider_EmergeMapOpacity->setValue(porymapConfig.emergeMapOpacity);
// Zoom
const QSignalBlocker b_MetatileZoom(ui->horizontalSlider_MetatileZoom);
const QSignalBlocker b_CollisionZoom(ui->horizontalSlider_CollisionZoom);
ui->horizontalSlider_MetatileZoom->setValue(porymapConfig.metatilesZoom);
ui->horizontalSlider_CollisionZoom->setValue(porymapConfig.collisionZoom);
setTheme(porymapConfig.theme);
setDivingMapsVisible(porymapConfig.showDiveEmergeMaps);
}
void MainWindow::restoreWindowState() {
logInfo("Restoring main window geometry from previous session.");
QMap<QString, QByteArray> geometry = porymapConfig.getMainGeometry();
this->restoreGeometry(geometry.value("main_window_geometry"));
this->restoreState(geometry.value("main_window_state"));
this->ui->splitter_map->restoreState(geometry.value("map_splitter_state"));
this->ui->splitter_main->restoreState(geometry.value("main_splitter_state"));
this->ui->splitter_Metatiles->restoreState(geometry.value("metatiles_splitter_state"));
}
void MainWindow::setTheme(QString theme) {
if (theme == "default") {
setStyleSheet("");
} else {
QFile File(QString(":/themes/%1.qss").arg(theme));
File.open(QFile::ReadOnly);
QString stylesheet = QLatin1String(File.readAll());
setStyleSheet(stylesheet);
}
}
bool MainWindow::openProject(QString dir, bool initial) {
if (dir.isNull() || dir.length() <= 0) {
// If this happened on startup it's because the user has no recent projects, which is fine.
// This shouldn't happen otherwise, but if it does then display an error.
if (!initial) {
logError("Failed to open project: Directory name cannot be empty");
showProjectOpenFailure();
}
return false;
}
const QString projectString = QString("%1project '%2'").arg(initial ? "recent " : "").arg(QDir::toNativeSeparators(dir));
if (!QDir(dir).exists()) {
const QString errorMsg = QString("Failed to open %1: No such directory").arg(projectString);
this->statusBar()->showMessage(errorMsg);
if (initial) {
// Graceful startup if recent project directory is missing
logWarn(errorMsg);
} else {
logError(errorMsg);
showProjectOpenFailure();
}
return false;
}
// The above checks can fail and the user will be allowed to continue with their currently-opened project (if there is one).
// We close the current project below, after which either the new project will open successfully or the window will be disabled.
if (!closeProject()) {
logInfo("Aborted project open.");
return false;
}
const QString openMessage = QString("Opening %1").arg(projectString);
this->statusBar()->showMessage(openMessage);
logInfo(openMessage);
userConfig.projectDir = dir;
userConfig.load();
projectConfig.projectDir = dir;
projectConfig.load();
this->newMapDefaultsSet = false;
Scripting::init(this);
// Create the project
auto project = new Project(editor);
project->set_root(dir);
connect(project, &Project::fileChanged, this, &MainWindow::showFileWatcherWarning);
connect(project, &Project::mapLoaded, this, &MainWindow::onMapLoaded);
connect(project, &Project::mapSectionIdNamesChanged, this, &MainWindow::refreshLocationsComboBox);
this->editor->setProject(project);
// Make sure project looks reasonable before attempting to load it
if (!checkProjectSanity()) {
delete this->editor->project;
return false;
}
// Load the project
if (!(loadProjectData() && setProjectUI() && setInitialMap())) {
this->statusBar()->showMessage(QString("Failed to open %1").arg(projectString));
showProjectOpenFailure();
delete this->editor->project;
// TODO: Allow changing project settings at this point
return false;
}
// Only create the config files once the project has opened successfully in case the user selected an invalid directory
this->editor->project->saveConfig();
updateWindowTitle();
this->statusBar()->showMessage(QString("Opened %1").arg(projectString));
porymapConfig.projectManuallyClosed = false;
porymapConfig.addRecentProject(dir);
refreshRecentProjectsMenu();
prefab.initPrefabUI(
editor->metatile_selector_item,
ui->scrollAreaWidgetContents_Prefabs,
ui->label_prefabHelp,
editor->layout);
Scripting::cb_ProjectOpened(dir);
setWindowDisabled(false);
return true;
}
bool MainWindow::loadProjectData() {
bool success = editor->project->load();
Scripting::populateGlobalObject(this);
return success;
}
bool MainWindow::checkProjectSanity() {
if (editor->project->sanityCheck())
return true;
logWarn(QString("The directory '%1' failed the project sanity check.").arg(editor->project->root));
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText(QString("The selected directory appears to be invalid."));
msgBox.setInformativeText(QString("The directory '%1' is missing key files.\n\n"
"Make sure you selected the correct project directory "
"(the one used to make your .gba file, e.g. 'pokeemerald').").arg(editor->project->root));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
auto tryAnyway = msgBox.addButton("Try Anyway", QMessageBox::ActionRole);
msgBox.exec();
if (msgBox.clickedButton() == tryAnyway) {
// The user has chosen to try to load this project anyway.
// This will almost certainly fail, but they'll get a more specific error message.
return true;
}
return false;
}
void MainWindow::showProjectOpenFailure() {
QString errorMsg = QString("There was an error opening the project. Please see %1 for full error details.").arg(getLogPath());
QMessageBox error(QMessageBox::Critical, "porymap", errorMsg, QMessageBox::Ok, this);
error.setDetailedText(getMostRecentError());
error.exec();
}
bool MainWindow::isProjectOpen() {
return editor && editor->project;
}
bool MainWindow::setInitialMap() {
const QString recent = userConfig.recentMapOrLayout;
if (editor->project->mapNames.contains(recent)) {
// User recently had a map open that still exists.
if (setMap(recent))
return true;
} else if (editor->project->mapLayoutsTable.contains(recent)) {
// User recently had a layout open that still exists.
if (setLayout(recent))
return true;
}
// Failed to open recent map/layout, or no recent map/layout. Try opening maps then layouts sequentially.
for (const auto &name : editor->project->mapNames) {
if (name != recent && setMap(name))
return true;
}
for (const auto &id : editor->project->mapLayoutsTable) {
if (id != recent && setLayout(id))
return true;
}
logError("Failed to load any maps or layouts.");
return false;
}
void MainWindow::refreshRecentProjectsMenu() {
ui->menuOpen_Recent_Project->clear();
QStringList recentProjects = porymapConfig.getRecentProjects();
if (isProjectOpen()) {
// Don't show the currently open project in this menu
recentProjects.removeOne(this->editor->project->root);
}
// Add project paths to menu. Skip any paths to folders that don't exist
for (int i = 0; i < recentProjects.length(); i++) {
const QString path = recentProjects.at(i);
if (QDir(path).exists()) {
ui->menuOpen_Recent_Project->addAction(path, [this, path](){
this->openProject(path);
});
}
// Arbitrary limit of 10 items.
if (ui->menuOpen_Recent_Project->actions().length() >= 10)
break;
}
// Add action to clear list of paths
if (!ui->menuOpen_Recent_Project->actions().isEmpty())
ui->menuOpen_Recent_Project->addSeparator();
QAction *clearAction = ui->menuOpen_Recent_Project->addAction("Clear Items", [this](){
QStringList paths = QStringList();
if (isProjectOpen())
paths.append(this->editor->project->root);
porymapConfig.setRecentProjects(paths);
this->refreshRecentProjectsMenu();
});
clearAction->setEnabled(!recentProjects.isEmpty());
}
void MainWindow::openSubWindow(QWidget * window) {
if (!window) return;
if (!window->isVisible()) {
window->show();
} else if (window->isMinimized()) {
window->showNormal();
} else {
window->raise();
window->activateWindow();
}
}
void MainWindow::showFileWatcherWarning(QString filepath) {
if (!porymapConfig.monitorFiles || !isProjectOpen())
return;
Project *project = this->editor->project;
if (project->modifiedFileTimestamps.contains(filepath)) {
if (QDateTime::currentMSecsSinceEpoch() < project->modifiedFileTimestamps[filepath]) {
return;
}
project->modifiedFileTimestamps.remove(filepath);
}
static bool showing = false;
if (showing) return;
QMessageBox notice(this);
notice.setText("File Changed");
notice.setInformativeText(QString("The file %1 has changed on disk. Would you like to reload the project?")
.arg(filepath.remove(project->root + "/")));
notice.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
notice.setDefaultButton(QMessageBox::No);
notice.setIcon(QMessageBox::Question);
QCheckBox showAgainCheck("Do not ask again.");
notice.setCheckBox(&showAgainCheck);
showing = true;
int choice = notice.exec();
if (choice == QMessageBox::Yes) {
on_action_Reload_Project_triggered();
} else if (choice == QMessageBox::No) {
if (showAgainCheck.isChecked()) {
porymapConfig.monitorFiles = false;
if (this->preferenceEditor)
this->preferenceEditor->updateFields();
}
}
showing = false;
}
QString MainWindow::getExistingDirectory(QString dir) {
return FileDialog::getExistingDirectory(this, "Open Directory", dir, QFileDialog::ShowDirsOnly);
}
void MainWindow::on_action_Open_Project_triggered()
{
QString dir = getExistingDirectory(!projectConfig.projectDir.isEmpty() ? userConfig.projectDir : ".");
if (!dir.isEmpty())
openProject(dir);
}
void MainWindow::on_action_Reload_Project_triggered() {
// TODO: when undo history is complete show only if has unsaved changes
QMessageBox warning(this);
warning.setText("WARNING");
warning.setInformativeText("Reloading this project will discard any unsaved changes.");
warning.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
warning.setDefaultButton(QMessageBox::Cancel);
warning.setIcon(QMessageBox::Warning);
if (warning.exec() == QMessageBox::Ok)
openProject(editor->project->root);
}
void MainWindow::on_action_Close_Project_triggered() {
closeProject();
porymapConfig.projectManuallyClosed = true;
}
void MainWindow::unsetMap() {
this->editor->unsetMap();
setLayoutOnlyMode(true);
}
// setMap, but with a visible error message in case of failure.
// Use when the user is specifically requesting a map to open.
bool MainWindow::userSetMap(QString map_name) {
if (editor->map && editor->map->name == map_name)
return true; // Already set
if (map_name == DYNAMIC_MAP_NAME) {
QMessageBox msgBox(this);
QString errorMsg = QString("The map '%1' can't be opened, it's a placeholder to indicate the specified map will be set programmatically.").arg(map_name);
msgBox.critical(nullptr, "Error Opening Map", errorMsg);
return false;
}
if (!setMap(map_name)) {
QMessageBox msgBox(this);
QString errorMsg = QString("There was an error opening map %1. Please see %2 for full error details.\n\n%3")
.arg(map_name)
.arg(getLogPath())
.arg(getMostRecentError());
msgBox.critical(nullptr, "Error Opening Map", errorMsg);
return false;
}
return true;
}
bool MainWindow::setMap(QString map_name) {
if (map_name.isEmpty() || map_name == DYNAMIC_MAP_NAME) {
logInfo(QString("Cannot set map to '%1'").arg(map_name));
return false;
}
logInfo(QString("Setting map to '%1'").arg(map_name));
if (!editor || !editor->setMap(map_name)) {
logWarn(QString("Failed to set map to '%1'").arg(map_name));
return false;
}
setLayoutOnlyMode(false);
this->lastSelectedEvent.clear();
refreshMapScene();
displayMapProperties();
updateWindowTitle();
updateMapList();
resetMapListFilters();
connect(editor->map, &Map::modified, this, &MainWindow::markMapEdited, Qt::UniqueConnection);
connect(editor->layout, &Layout::layoutChanged, this, &MainWindow::onLayoutChanged, Qt::UniqueConnection);
connect(editor->layout, &Layout::needsRedrawing, this, &MainWindow::redrawMapScene, Qt::UniqueConnection);
userConfig.recentMapOrLayout = map_name;
Scripting::cb_MapOpened(map_name);
prefab.updatePrefabUi(editor->layout);
updateTilesetEditor();
return true;
}
// These parts of the UI only make sense when editing maps.
// When editing in layout-only mode they are disabled.
void MainWindow::setLayoutOnlyMode(bool layoutOnly) {
bool mapEditingEnabled = !layoutOnly;
this->ui->mainTabBar->setTabEnabled(MainTab::Events, mapEditingEnabled);
this->ui->mainTabBar->setTabEnabled(MainTab::Header, mapEditingEnabled);
this->ui->mainTabBar->setTabEnabled(MainTab::Connections, mapEditingEnabled);
this->ui->mainTabBar->setTabEnabled(MainTab::WildPokemon, mapEditingEnabled);
this->ui->comboBox_LayoutSelector->setEnabled(mapEditingEnabled);
}
// setLayout, but with a visible error message in case of failure.
// Use when the user is specifically requesting a layout to open.
bool MainWindow::userSetLayout(QString layoutId) {
if (!setLayout(layoutId)) {
QMessageBox msgBox(this);
QString errorMsg = QString("There was an error opening layout %1. Please see %2 for full error details.\n\n%3")
.arg(layoutId)
.arg(getLogPath())
.arg(getMostRecentError());
msgBox.critical(nullptr, "Error Opening Layout", errorMsg);
return false;
}
return true;
}
bool MainWindow::setLayout(QString layoutId) {
if (this->editor->map)
logInfo("Switching to a layout-only editing mode. Disabling map-related edits.");
unsetMap();
// Prefer logging the name of the layout as displayed in the map list.
const QString layoutName = this->editor->project ? this->editor->project->layoutIdsToNames.value(layoutId, layoutId) : layoutId;
logInfo(QString("Setting layout to '%1'").arg(layoutName));
if (!this->editor->setLayout(layoutId)) {
return false;
}
layoutTreeModel->setLayout(layoutId);
refreshMapScene();
updateWindowTitle();
updateMapList();
resetMapListFilters();
connect(editor->layout, &Layout::needsRedrawing, this, &MainWindow::redrawMapScene, Qt::UniqueConnection);
updateTilesetEditor();
userConfig.recentMapOrLayout = layoutId;
return true;
}
void MainWindow::redrawMapScene() {
editor->displayMap();
editor->displayLayout();
refreshMapScene();
}
void MainWindow::refreshMapScene() {
on_mainTabBar_tabBarClicked(ui->mainTabBar->currentIndex());
ui->graphicsView_Map->setScene(editor->scene);
ui->graphicsView_Map->setSceneRect(editor->scene->sceneRect());
ui->graphicsView_Map->editor = editor;
ui->graphicsView_Connections->setScene(editor->scene);
ui->graphicsView_Connections->setSceneRect(editor->scene->sceneRect());
ui->graphicsView_Metatiles->setScene(editor->scene_metatiles);
//ui->graphicsView_Metatiles->setSceneRect(editor->scene_metatiles->sceneRect());
ui->graphicsView_Metatiles->setFixedSize(editor->metatile_selector_item->pixmap().width() + 2, editor->metatile_selector_item->pixmap().height() + 2);
ui->graphicsView_BorderMetatile->setScene(editor->scene_selected_border_metatiles);
ui->graphicsView_BorderMetatile->setFixedSize(editor->selected_border_metatiles_item->pixmap().width() + 2, editor->selected_border_metatiles_item->pixmap().height() + 2);
ui->graphicsView_currentMetatileSelection->setScene(editor->scene_current_metatile_selection);
ui->graphicsView_currentMetatileSelection->setFixedSize(editor->current_metatile_selection_item->pixmap().width() + 2, editor->current_metatile_selection_item->pixmap().height() + 2);
ui->graphicsView_Collision->setScene(editor->scene_collision_metatiles);
//ui->graphicsView_Collision->setSceneRect(editor->scene_collision_metatiles->sceneRect());
ui->graphicsView_Collision->setFixedSize(editor->movement_permissions_selector_item->pixmap().width() + 2, editor->movement_permissions_selector_item->pixmap().height() + 2);
on_horizontalSlider_MetatileZoom_valueChanged(ui->horizontalSlider_MetatileZoom->value());
on_horizontalSlider_CollisionZoom_valueChanged(ui->horizontalSlider_CollisionZoom->value());
}
void MainWindow::openWarpMap(QString map_name, int event_id, Event::Group event_group) {
// Ensure valid destination map name.
if (!editor->project->mapNames.contains(map_name)) {
logError(QString("Invalid map name '%1'").arg(map_name));
return;
}
// Open the destination map.
if (!userSetMap(map_name))
return;
// Select the target event.
int index = event_id - Event::getIndexOffset(event_group);
QList<Event*> events = editor->map->events[event_group];
if (index < events.length() && index >= 0) {
Event *event = events.at(index);
for (DraggablePixmapItem *item : editor->getObjects()) {
if (item->event == event) {
editor->selected_events->clear();
editor->selected_events->append(item);
editor->updateSelectedEvents();
}
}