summaryrefslogtreecommitdiff
path: root/archived/projt-launcher/launcher/InstanceList.cpp
blob: 597fbb7a224fd50b3033ed98b7ce1aaa29805df2 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: 2026 Project Tick
// SPDX-FileContributor: Project Tick Team
/*
 *  ProjT Launcher - Minecraft Launcher
 *  Copyright (C) 2026 Project Tick
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
/* === Upstream License Block (Do Not Modify) ==============================
 *
 *  Prism Launcher - Minecraft Launcher
 *  Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
 *  Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * This file incorporates work covered by the following copyright and
 * permission notice:
 *
 *      Copyright 2013-2021 MultiMC Contributors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 *
   ======================================================================== */

#include "InstanceList.h"

#include <QDebug>
#include <QDirIterator>
#include <QFile>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QMimeData>
#include <QSet>
#include <QStack>
#include <QTimer>
#include <QUuid>

#include "BaseInstance.h"
#include "ExponentialSeries.h"
#include "FileSystem.h"

#include "InstanceTask.h"
#include "NullInstance.h"
#include "WatchLock.h"
#include "minecraft/MinecraftInstance.h"
#include "settings/INISettingsObject.h"

#ifdef Q_OS_WIN32
#include <windows.h>
#endif

const static int GROUP_FILE_FORMAT_VERSION = 1;

InstanceList::InstanceList(SettingsObjectPtr settings, const QString& instDir, QObject* parent)
	: QAbstractListModel(parent),
	  m_globalSettings(settings)
{
	resumeWatch();
	m_reloadDebounceTimer.setSingleShot(true);
	m_reloadDebounceTimer.setInterval(300);
	connect(&m_reloadDebounceTimer, &QTimer::timeout, this, &InstanceList::performDebouncedReload);

	// Create aand normalize path
	if (!QDir::current().exists(instDir))
	{
		QDir::current().mkpath(instDir);
	}

	connect(this, &InstanceList::instancesChanged, this, &InstanceList::providerUpdated);

	// NOTE: canonicalPath requires the path to exist. Do not move this above the creation block!
	m_instDir = QDir(instDir).canonicalPath();
	m_watcher = new QFileSystemWatcher(this);
	connect(m_watcher, &QFileSystemWatcher::directoryChanged, this, &InstanceList::instanceDirContentsChanged);
	m_watcher->addPath(m_instDir);
}

InstanceList::~InstanceList()
{}

Qt::DropActions InstanceList::supportedDragActions() const
{
	return Qt::MoveAction;
}

Qt::DropActions InstanceList::supportedDropActions() const
{
	return Qt::MoveAction;
}

bool InstanceList::canDropMimeData(const QMimeData* data,
								   [[maybe_unused]] Qt::DropAction action,
								   [[maybe_unused]] int row,
								   [[maybe_unused]] int column,
								   [[maybe_unused]] const QModelIndex& parent) const
{
	if (data && data->hasFormat("application/x-instanceid"))
	{
		return true;
	}
	return false;
}

bool InstanceList::dropMimeData(const QMimeData* data,
								[[maybe_unused]] Qt::DropAction action,
								[[maybe_unused]] int row,
								[[maybe_unused]] int column,
								[[maybe_unused]] const QModelIndex& parent)
{
	if (data && data->hasFormat("application/x-instanceid"))
	{
		return true;
	}
	return false;
}

QStringList InstanceList::mimeTypes() const
{
	auto types = QAbstractListModel::mimeTypes();
	types.push_back("application/x-instanceid");
	return types;
}

QMimeData* InstanceList::mimeData(const QModelIndexList& indexes) const
{
	auto mimeData = QAbstractListModel::mimeData(indexes);
	if (indexes.size() == 1)
	{
		auto instanceId = data(indexes[0], InstanceIDRole).toString();
		mimeData->setData("application/x-instanceid", instanceId.toUtf8());
	}
	return mimeData;
}

QStringList InstanceList::getLinkedInstancesById(const QString& id) const
{
	QStringList linkedInstances;
	for (auto inst : m_instances)
	{
		if (inst->isLinkedToInstanceId(id))
			linkedInstances.append(inst->id());
	}
	return linkedInstances;
}

int InstanceList::rowCount(const QModelIndex& parent) const
{
	Q_UNUSED(parent);
	return m_instances.count();
}

QModelIndex InstanceList::index(int row, int column, const QModelIndex& parent) const
{
	Q_UNUSED(parent);
	if (row < 0 || row >= m_instances.size())
		return QModelIndex();
	return createIndex(row, column, (void*)m_instances.at(row).get());
}

QVariant InstanceList::data(const QModelIndex& index, int role) const
{
	if (!index.isValid())
	{
		return QVariant();
	}
	BaseInstance* pdata = static_cast<BaseInstance*>(index.internalPointer());
	switch (role)
	{
		case InstancePointerRole:
		{
			QVariant v = QVariant::fromValue((void*)pdata);
			return v;
		}
		case InstanceIDRole:
		{
			return pdata->id();
		}
		case Qt::EditRole:
		case Qt::DisplayRole:
		{
			return pdata->name();
		}
		case Qt::AccessibleTextRole:
		{
			return tr("%1 Instance").arg(pdata->name());
		}
		case Qt::ToolTipRole:
		{
			return pdata->instanceRoot();
		}
		case Qt::DecorationRole:
		{
			return pdata->iconKey();
		}
		// HACK: see InstanceView.h in gui!
		case GroupRole:
		{
			return getInstanceGroup(pdata->id());
		}
		default: break;
	}
	return QVariant();
}

bool InstanceList::setData(const QModelIndex& index, const QVariant& value, int role)
{
	if (!index.isValid())
	{
		return false;
	}
	if (role != Qt::EditRole)
	{
		return false;
	}
	BaseInstance* pdata = static_cast<BaseInstance*>(index.internalPointer());
	auto newName		= value.toString();
	if (pdata->name() == newName)
	{
		return true;
	}
	pdata->setName(newName);
	return true;
}

Qt::ItemFlags InstanceList::flags(const QModelIndex& index) const
{
	Qt::ItemFlags f;
	if (index.isValid())
	{
		f |= (Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
	}
	return f;
}

GroupId InstanceList::getInstanceGroup(const InstanceId& id) const
{
	auto inst = getInstanceById(id);
	if (!inst)
	{
		return GroupId();
	}
	auto iter = m_instanceGroupIndex.find(inst->id());
	if (iter != m_instanceGroupIndex.end())
	{
		return *iter;
	}
	return GroupId();
}

void InstanceList::setInstanceGroup(const InstanceId& id, GroupId name)
{
	if (name.isEmpty() && !name.isNull())
		name = QString();

	auto inst = getInstanceById(id);
	if (!inst)
	{
		qDebug() << "Attempt to set a null instance's group";
		return;
	}

	bool changed = false;
	auto iter	 = m_instanceGroupIndex.find(inst->id());
	if (iter != m_instanceGroupIndex.end())
	{
		if (*iter != name)
		{
			decreaseGroupCount(*iter);
			*iter	= name;
			changed = true;
		}
	}
	else
	{
		changed					 = true;
		m_instanceGroupIndex[id] = name;
	}

	if (changed)
	{
		increaseGroupCount(name);
		auto idx = getInstIndex(inst.get());
		emit dataChanged(index(idx), index(idx), { GroupRole });
		saveGroupList();
	}
}

QStringList InstanceList::getGroups()
{
	QStringList keys = m_groupNameCache.keys();
	keys.sort();
	return keys;
}

void InstanceList::deleteGroup(const GroupId& name)
{
	m_groupNameCache.remove(name);
	m_collapsedGroups.remove(name);

	bool removed = false;
	qDebug() << "Delete group" << name;
	for (auto& instance : m_instances)
	{
		const QString& instID		= instance->id();
		const QString instGroupName = getInstanceGroup(instID);
		if (instGroupName == name)
		{
			m_instanceGroupIndex.remove(instID);
			qDebug() << "Remove" << instID << "from group" << name;
			removed	 = true;
			auto idx = getInstIndex(instance.get());
			if (idx >= 0)
				emit dataChanged(index(idx), index(idx), { GroupRole });
		}
	}
	if (removed)
		saveGroupList();
}

void InstanceList::renameGroup(const QString& src, const QString& dst)
{
	m_groupNameCache.remove(src);
	if (m_collapsedGroups.remove(src))
		m_collapsedGroups.insert(dst);

	bool modified = false;
	qDebug() << "Rename group" << src << "to" << dst;
	for (auto& instance : m_instances)
	{
		const QString& instID		= instance->id();
		const QString instGroupName = getInstanceGroup(instID);
		if (instGroupName == src)
		{
			m_instanceGroupIndex[instID] = dst;
			increaseGroupCount(dst);
			qDebug() << "Set" << instID << "group to" << dst;
			modified = true;
			auto idx = getInstIndex(instance.get());
			if (idx >= 0)
				emit dataChanged(index(idx), index(idx), { GroupRole });
		}
	}
	if (modified)
		saveGroupList();
}

bool InstanceList::isGroupCollapsed(const QString& group)
{
	return m_collapsedGroups.contains(group);
}

bool InstanceList::trashInstance(const InstanceId& id)
{
	auto inst = getInstanceById(id);
	if (!inst)
	{
		qWarning() << "Cannot trash instance" << id << ". No such instance is present (deleted externally?).";
		return false;
	}

	QString cachedGroupId = m_instanceGroupIndex[id];

	qDebug() << "Will trash instance" << id;
	QString trashedLoc;

	if (m_instanceGroupIndex.remove(id))
	{
		decreaseGroupCount(cachedGroupId);
		saveGroupList();
	}

	if (!FS::trash(inst->instanceRoot(), &trashedLoc))
	{
		qWarning() << "Trash of instance" << id << "has not been completely successful...";
		return false;
	}

	qDebug() << "Instance" << id << "has been trashed by the launcher.";
	m_trashHistory.push({ id, inst->instanceRoot(), trashedLoc, cachedGroupId });

	// Also trash all of its shortcuts; we remove the shortcuts if trash fails since it is invalid anyway
	for (const auto& [name, filePath, target] : inst->shortcuts())
	{
		if (!FS::trash(filePath, &trashedLoc))
		{
			qWarning() << "Trash of shortcut" << name << "at path" << filePath << "for instance" << id
					   << "has not been successful, trying to delete it instead...";
			if (!FS::deletePath(filePath))
			{
				qWarning() << "Deletion of shortcut" << name << "at path" << filePath << "for instance" << id
						   << "has not been successful, given up...";
			}
			else
			{
				qDebug() << "Shortcut" << name << "at path" << filePath << "for instance" << id
						 << "has been deleted by the launcher.";
			}
			continue;
		}
		qDebug() << "Shortcut" << name << "at path" << filePath << "for instance" << id
				 << "has been trashed by the launcher.";
		m_trashHistory.top().shortcuts.append({ { name, filePath, target }, trashedLoc });
	}

	return true;
}

bool InstanceList::trashedSomething() const
{
	return !m_trashHistory.empty();
}

bool InstanceList::undoTrashInstance()
{
	if (m_trashHistory.empty())
	{
		qWarning() << "Nothing to recover from trash.";
		return true;
	}

	auto top = m_trashHistory.pop();

	while (QDir(top.path).exists())
	{
		top.id += "1";
		top.path += "1";
	}

	if (!QFile(top.trashPath).rename(top.path))
	{
		qWarning() << "Moving" << top.trashPath << "back to" << top.path << "failed!";
		return false;
	}
	qDebug() << "Moving" << top.trashPath << "back to" << top.path;

	bool ok = true;
	for (const auto& [data, trashPath] : top.shortcuts)
	{
		if (QDir(data.filePath).exists())
		{
			// Don't try to append 1 here as the shortcut may have suffixes like .app, just warn and skip it
			qWarning() << "Shortcut" << trashPath << "original directory" << data.filePath << "already exists!";
			ok = false;
			continue;
		}
		if (!QFile(trashPath).rename(data.filePath))
		{
			qWarning() << "Moving shortcut from" << trashPath << "back to" << data.filePath << "failed!";
			ok = false;
			continue;
		}
		qDebug() << "Moving shortcut from" << trashPath << "back to" << data.filePath;
	}

	m_instanceGroupIndex[top.id] = top.groupName;
	increaseGroupCount(top.groupName);

	saveGroupList();
	emit instancesChanged();
	return ok;
}

void InstanceList::deleteInstance(const InstanceId& id)
{
	auto inst = getInstanceById(id);
	if (!inst)
	{
		qWarning() << "Cannot delete instance" << id << ". No such instance is present (deleted externally?).";
		return;
	}

	QString cachedGroupId = m_instanceGroupIndex[id];

	if (m_instanceGroupIndex.remove(id))
	{
		decreaseGroupCount(cachedGroupId);
		saveGroupList();
	}

	qDebug() << "Will delete instance" << id;
	if (!FS::deletePath(inst->instanceRoot()))
	{
		qWarning() << "Deletion of instance" << id << "has not been completely successful...";
		return;
	}

	qDebug() << "Instance" << id << "has been deleted by the launcher.";

	for (const auto& [name, filePath, target] : inst->shortcuts())
	{
		if (!FS::deletePath(filePath))
		{
			qWarning() << "Deletion of shortcut" << name << "at path" << filePath << "for instance" << id
					   << "has not been successful...";
			continue;
		}
		qDebug() << "Shortcut" << name << "at path" << filePath << "for instance" << id
				 << "has been deleted by the launcher.";
	}
}

static QMap<InstanceId, InstanceLocator> getIdMapping(const QList<InstancePtr>& list)
{
	QMap<InstanceId, InstanceLocator> out;
	int i = 0;
	for (auto& item : list)
	{
		auto id = item->id();
		if (out.contains(id))
		{
			qWarning() << "Duplicate ID" << id << "in instance list";
		}
		out[id] = std::make_pair(item, i);
		i++;
	}
	return out;
}

QList<InstanceId> InstanceList::discoverInstances()
{
	qInfo() << "Discovering instances in" << m_instDir;
	QList<InstanceId> out;
	QDirIterator iter(m_instDir,
					  QDir::Dirs | QDir::NoDot | QDir::NoDotDot | QDir::Readable | QDir::Hidden,
					  QDirIterator::FollowSymlinks);
	while (iter.hasNext())
	{
		QString subDir = iter.next();
		QFileInfo dirInfo(subDir);
		if (!QFileInfo(FS::PathCombine(subDir, "instance.cfg")).exists())
			continue;
		// if it is a symlink, ignore it if it goes to the instance folder
		if (dirInfo.isSymLink())
		{
			QFileInfo targetInfo(dirInfo.symLinkTarget());
			QFileInfo instDirInfo(m_instDir);
			if (targetInfo.canonicalPath() == instDirInfo.canonicalFilePath())
			{
				qDebug() << "Ignoring symlink" << subDir << "that leads into the instances folder";
				continue;
			}
		}
		auto id = dirInfo.fileName();
		out.append(id);
	}
	instanceSet		  = QSet<QString>(out.begin(), out.end());
	m_instancesProbed = true;
	return out;
}

InstanceList::InstListError InstanceList::loadList()
{
	auto existingIds = getIdMapping(m_instances);

	QList<InstancePtr> newList;

	for (auto& id : discoverInstances())
	{
		if (existingIds.contains(id))
		{
			existingIds.remove(id);
		}
		else
		{
			InstancePtr instPtr = loadInstance(id);
			if (instPtr)
			{
				newList.append(instPtr);
			}
		}
	}

	// Remove instances that no longer exist on disk
	if (!existingIds.isEmpty())
	{
		removeDeadInstances(existingIds);
	}
	if (newList.size())
	{
		add(newList);
	}
	m_dirty = false;
	updateTotalPlayTime();
	return NoError;
}

void InstanceList::removeDeadInstances(const QMap<InstanceId, InstanceLocator>& deadInstances)
{
	if (deadInstances.isEmpty())
	{
		return;
	}

	// Sort by original index (descending) to remove from back to front
	auto deadList			= deadInstances.values();
	auto orderSortPredicate = [](const InstanceLocator& a, const InstanceLocator& b) -> bool
	{ return a.second > b.second; };
	std::sort(deadList.begin(), deadList.end(), orderSortPredicate);

	// Remove contiguous ranges efficiently with batch operations
	int front_bookmark = -1;
	int back_bookmark  = -1;
	int currentItem	   = -1;

	auto removeNow = [this, &front_bookmark, &back_bookmark, &currentItem]()
	{
		beginRemoveRows(QModelIndex(), front_bookmark, back_bookmark);
		m_instances.erase(m_instances.begin() + front_bookmark, m_instances.begin() + back_bookmark + 1);
		endRemoveRows();
		front_bookmark = -1;
		back_bookmark  = currentItem;
	};

	for (auto& removedItem : deadList)
	{
		auto instPtr = removedItem.first;
		m_instanceMap.remove(instPtr->id());
		instPtr->invalidate();
		currentItem = removedItem.second;

		if (back_bookmark == -1)
		{
			back_bookmark = currentItem;
		}
		else if (currentItem == front_bookmark - 1)
		{
			// Part of contiguous sequence, continue
		}
		else
		{
			// Seam between previous and current item
			removeNow();
		}
		front_bookmark = currentItem;
	}

	if (back_bookmark != -1)
	{
		removeNow();
	}
}

QList<InstancePtr> InstanceList::getAllInstancesByManagedName(const QString& managed_name) const
{
	QList<InstancePtr> result;
	for (auto instance : m_instances)
	{
		if (instance->getManagedPackID() == managed_name)
		{
			result.append(instance);
		}
	}
	return result;
}

void InstanceList::updateTotalPlayTime()
{
	totalPlayTime = 0;
	for (auto const& itr : m_instances)
	{
		totalPlayTime += itr.get()->totalTimePlayed();
	}
}

void InstanceList::saveNow()
{
	for (auto& item : m_instances)
	{
		item->saveNow();
	}
}

void InstanceList::add(const QList<InstancePtr>& t)
{
	beginInsertRows(QModelIndex(), m_instances.count(), m_instances.count() + t.size() - 1);
	m_instances.append(t);
	for (auto& ptr : t)
	{
		m_instanceMap.insert(ptr->id(), ptr);
		connect(ptr.get(), &BaseInstance::propertiesChanged, this, &InstanceList::propertiesChanged);
	}
	endInsertRows();
}

void InstanceList::resumeWatch()
{
	if (m_watchLevel > 0)
	{
		qWarning() << "Bad suspend level resume in instance list";
		return;
	}
	m_watchLevel++;
	if (m_watchLevel > 0 && m_dirty)
	{
		loadList();
	}
}

void InstanceList::suspendWatch()
{
	m_watchLevel--;
}

void InstanceList::providerUpdated()
{
	m_dirty = true;
	if (m_watchLevel == 1)
	{
		m_reloadDebounceTimer.stop();
		loadList();
	}
}

InstancePtr InstanceList::getInstanceById(QString instId) const
{
	if (instId.isEmpty())
		return InstancePtr();
	return m_instanceMap.value(instId);
}

InstancePtr InstanceList::getInstanceByManagedName(const QString& managed_name) const
{
	if (managed_name.isEmpty())
		return {};

	for (auto instance : m_instances)
	{
		if (instance->getManagedPackName() == managed_name)
			return instance;
	}

	return {};
}

QModelIndex InstanceList::getInstanceIndexById(const QString& id) const
{
	return index(getInstIndex(getInstanceById(id).get()));
}

int InstanceList::getInstIndex(BaseInstance* inst) const
{
	int count = m_instances.count();
	for (int i = 0; i < count; i++)
	{
		if (inst == m_instances[i].get())
		{
			return i;
		}
	}
	return -1;
}

void InstanceList::propertiesChanged(BaseInstance* inst)
{
	int i = getInstIndex(inst);
	if (i != -1)
	{
		emit dataChanged(index(i), index(i));
		updateTotalPlayTime();
	}
}

InstancePtr InstanceList::loadInstance(const InstanceId& id)
{
	if (!m_groupsLoaded)
	{
		loadGroupList();
	}

	auto instanceRoot	  = FS::PathCombine(m_instDir, id);
	auto instanceSettings = std::make_shared<INISettingsObject>(FS::PathCombine(instanceRoot, "instance.cfg"));
	InstancePtr inst;

	instanceSettings->registerSetting("InstanceType", "");

	QString inst_type = instanceSettings->get("InstanceType").toString();

	// NOTE: Some launcher versions didn't save the InstanceType properly. We will just bank on the probability that
	// this is probably a OneSix instance
	if (inst_type == "OneSix" || inst_type.isEmpty())
	{
		inst.reset(new MinecraftInstance(m_globalSettings, instanceSettings, instanceRoot));
	}
	else
	{
		inst.reset(new NullInstance(m_globalSettings, instanceSettings, instanceRoot));
	}
	qDebug() << "Loaded instance" << inst->name() << "from" << inst->instanceRoot();

	auto shortcut = inst->shortcuts();
	if (!shortcut.isEmpty())
		qDebug() << "Loaded" << shortcut.size() << "shortcut(s) for instance" << inst->name();

	return inst;
}

void InstanceList::increaseGroupCount(const QString& group)
{
	if (group.isEmpty())
		return;

	++m_groupNameCache[group];
}

void InstanceList::decreaseGroupCount(const QString& group)
{
	if (group.isEmpty())
		return;

	if (--m_groupNameCache[group] < 1)
	{
		m_groupNameCache.remove(group);
		m_collapsedGroups.remove(group);
	}
}

void InstanceList::saveGroupList()
{
	qDebug() << "Will save group list now.";
	if (!m_instancesProbed)
	{
		qDebug() << "Group saving prevented because we don't know the full list of instances yet.";
		return;
	}
	WatchLock foo(m_watcher, m_instDir);
	QString groupFileName = m_instDir + "/instgroups.json";
	QMap<QString, QSet<QString>> reverseGroupMap;
	for (auto iter = m_instanceGroupIndex.begin(); iter != m_instanceGroupIndex.end(); iter++)
	{
		const QString& id = iter.key();
		QString group	  = iter.value();
		if (group.isEmpty())
			continue;
		if (!instanceSet.contains(id))
		{
			qDebug() << "Skipping saving missing instance" << id << "to groups list.";
			continue;
		}

		if (!reverseGroupMap.count(group))
		{
			QSet<QString> set;
			set.insert(id);
			reverseGroupMap[group] = set;
		}
		else
		{
			QSet<QString>& set = reverseGroupMap[group];
			set.insert(id);
		}
	}
	QJsonObject toplevel;
	toplevel.insert("formatVersion", QJsonValue(QString("1")));
	QJsonObject groupsArr;
	for (auto iter = reverseGroupMap.begin(); iter != reverseGroupMap.end(); iter++)
	{
		auto list = iter.value();
		auto name = iter.key();
		QJsonObject groupObj;
		QJsonArray instanceArr;
		groupObj.insert("hidden", QJsonValue(m_collapsedGroups.contains(name)));
		for (auto item : list)
		{
			instanceArr.append(QJsonValue(item));
		}
		groupObj.insert("instances", instanceArr);
		groupsArr.insert(name, groupObj);
	}
	toplevel.insert("groups", groupsArr);
	// empty string represents ungrouped "group"
	if (m_collapsedGroups.contains(""))
	{
		QJsonObject ungrouped;
		ungrouped.insert("hidden", QJsonValue(true));
		toplevel.insert("ungrouped", ungrouped);
	}
	QJsonDocument doc(toplevel);
	try
	{
		FS::write(groupFileName, doc.toJson());
		qDebug() << "Group list saved.";
	}
	catch (const FS::FileSystemException& e)
	{
		qCritical() << "Failed to write instance group file :" << e.cause();
	}
}

void InstanceList::loadGroupList()
{
	qDebug() << "Will load group list now.";

	QString groupFileName = m_instDir + "/instgroups.json";

	// if there's no group file, fail
	if (!QFileInfo(groupFileName).exists())
		return;

	QByteArray jsonData;
	try
	{
		jsonData = FS::read(groupFileName);
	}
	catch (const FS::FileSystemException& e)
	{
		qCritical() << "Failed to read instance group file :" << e.cause();
		return;
	}

	QJsonParseError error;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &error);

	// if the json was bad, fail
	if (error.error != QJsonParseError::NoError)
	{
		qCritical() << QString("Failed to parse instance group file: %1 at offset %2")
						   .arg(error.errorString(), QString::number(error.offset))
						   .toUtf8();
		return;
	}

	// if the root of the json wasn't an object, fail
	if (!jsonDoc.isObject())
	{
		qWarning() << "Invalid group file. Root entry should be an object.";
		return;
	}

	QJsonObject rootObj = jsonDoc.object();

	// Make sure the format version matches, otherwise fail.
	if (rootObj.value("formatVersion").toVariant().toInt() != GROUP_FILE_FORMAT_VERSION)
		return;

	// Get the groups. if it's not an object, fail
	if (!rootObj.value("groups").isObject())
	{
		qWarning() << "Invalid group list JSON: 'groups' should be an object.";
		return;
	}

	m_instanceGroupIndex.clear();
	m_groupNameCache.clear();

	// Iterate through all the groups.
	QJsonObject groupMapping = rootObj.value("groups").toObject();
	for (QJsonObject::iterator iter = groupMapping.begin(); iter != groupMapping.end(); iter++)
	{
		QString groupName = iter.key();

		if (iter.key().isEmpty())
		{
			qWarning() << "Redundant empty group found";
			continue;
		}

		// If not an object, complain and skip to the next one.
		if (!iter.value().isObject())
		{
			qWarning() << QString("Group '%1' in the group list should be an object").arg(groupName).toUtf8();
			continue;
		}

		QJsonObject groupObj = iter.value().toObject();
		if (!groupObj.value("instances").isArray())
		{
			qWarning() << QString(
							  "Group '%1' in the group list is invalid. It should contain an array called 'instances'.")
							  .arg(groupName)
							  .toUtf8();
			continue;
		}

		auto hidden = groupObj.value("hidden").toBool(false);
		if (hidden)
			m_collapsedGroups.insert(groupName);

		// Iterate through the list of instances in the group.
		QJsonArray instancesArray = groupObj.value("instances").toArray();

		for (auto value : instancesArray)
		{
			m_instanceGroupIndex[value.toString()] = groupName;
			increaseGroupCount(groupName);
		}
	}

	bool ungroupedHidden = false;
	if (rootObj.value("ungrouped").isObject())
	{
		QJsonObject ungrouped = rootObj.value("ungrouped").toObject();
		ungroupedHidden		  = ungrouped.value("hidden").toBool(false);
	}
	if (ungroupedHidden)
	{
		// empty string represents ungrouped "group"
		m_collapsedGroups.insert("");
	}
	m_groupsLoaded = true;
	qDebug() << "Group list loaded.";
}

void InstanceList::instanceDirContentsChanged(const QString& path)
{
	Q_UNUSED(path);
	m_dirty = true;
	if (m_watchLevel == 1)
	{
		m_reloadDebounceTimer.start();
	}
}

void InstanceList::performDebouncedReload()
{
	if (m_watchLevel == 1 && m_dirty)
	{
		loadList();
	}
}

void InstanceList::on_InstFolderChanged([[maybe_unused]] const Setting& setting, QVariant value)
{
	QString newInstDir = QDir(value.toString()).canonicalPath();
	if (newInstDir != m_instDir)
	{
		if (m_groupsLoaded)
		{
			saveGroupList();
		}
		m_instDir	   = newInstDir;
		m_groupsLoaded = false;
		beginRemoveRows(QModelIndex(), 0, count());
		m_instances.erase(m_instances.begin(), m_instances.end());
		endRemoveRows();
		emit instancesChanged();
	}
}

void InstanceList::on_GroupStateChanged(const QString& group, bool collapsed)
{
	qDebug() << "Group" << group << (collapsed ? "collapsed" : "expanded");
	if (collapsed)
	{
		m_collapsedGroups.insert(group);
	}
	else
	{
		m_collapsedGroups.remove(group);
	}
	saveGroupList();
}

class InstanceStaging : public Task
{
	Q_OBJECT
	const unsigned minBackoff = 1;
	const unsigned maxBackoff = 16;

  public:
	InstanceStaging(InstanceList* parent, InstanceTask* child, SettingsObjectPtr settings)
		: m_parent(parent),
		  backoff(minBackoff, maxBackoff)
	{
		m_stagingPath = parent->getStagedInstancePath();

		m_child.reset(child);

		m_child->setStagingPath(m_stagingPath);
		m_child->setParentSettings(std::move(settings));

		connect(child, &Task::succeeded, this, &InstanceStaging::childSucceeded);
		connect(child, &Task::failed, this, &InstanceStaging::childFailed);
		connect(child, &Task::aborted, this, &InstanceStaging::childAborted);
		connect(child, &Task::abortStatusChanged, this, &InstanceStaging::setAbortable);
		connect(child, &Task::abortButtonTextChanged, this, &InstanceStaging::setAbortButtonText);
		connect(child, &Task::status, this, &InstanceStaging::setStatus);
		connect(child, &Task::details, this, &InstanceStaging::setDetails);
		connect(child, &Task::progress, this, &InstanceStaging::setProgress);
		connect(child, &Task::stepProgress, this, &InstanceStaging::propagateStepProgress);
		connect(&m_backoffTimer, &QTimer::timeout, this, &InstanceStaging::childSucceeded);
	}

	virtual ~InstanceStaging()
	{}

	// Abort can now stop both the child task and any pending retries
	bool abort() override
	{
		m_aborted = true;
		m_backoffTimer.stop();

		if (!m_child || !m_child->canAbort())
			return false;

		return m_child->abort();
	}
	bool canAbort() const override { return (m_child && m_child->canAbort()); }

  protected:
	virtual void executeTask() override
	{
		if (m_stagingPath.isNull())
		{
			emitFailed(tr("Could not create staging folder"));
			return;
		}

		m_child->start();
	}
	QStringList warnings() const override
	{
		return m_child->warnings();
	}

  private slots:
	void childSucceeded()
	{
		unsigned sleepTime = backoff();
		if (m_parent->commitStagedInstance(m_stagingPath, *m_child.get(), m_child->group(), *m_child.get()))
		{
			emitSucceeded();
			return;
		}
		// we actually failed, retry?
		if (sleepTime == maxBackoff)
		{
			emitFailed(tr("Failed to commit instance, even after multiple retries. It is being blocked by something."));
			return;
		}
		qDebug() << "Failed to commit instance" << m_child->name() << "Initiating backoff:" << sleepTime;
		m_backoffTimer.start(sleepTime * 500);
	}
	void childFailed(const QString& reason)
	{
		m_parent->destroyStagingPath(m_stagingPath);
		emitFailed(reason);
	}

	void childAborted()
	{
		m_parent->destroyStagingPath(m_stagingPath);
		emitAborted();
	}

  private:
	InstanceList* m_parent;
	/*
	 * WHY: the whole reason why this uses an exponential backoff retry scheme is antivirus on Windows.
	 * Basically, it starts messing things up while the launcher is extracting/creating instances
	 * and causes that horrible failure that is NTFS to lock files in place because they are open.
	 */
	ExponentialSeries backoff;
	QString m_stagingPath;
	unique_qobject_ptr<InstanceTask> m_child;
	QTimer m_backoffTimer;
	bool m_aborted = false; // Flag to track abort during backoff retries
};

Task* InstanceList::wrapInstanceTask(InstanceTask* task)
{
	return new InstanceStaging(this, task, m_globalSettings);
}

QString InstanceList::getStagedInstancePath()
{
	const QString tempRoot = FS::PathCombine(m_instDir, ".tmp");

	QString result;
	int tries = 0;

	do
	{
		if (++tries > 256)
			return {};

		const QString key = QUuid::createUuid().toString(QUuid::Id128).left(6);
		result			  = FS::PathCombine(tempRoot, key);
	}
	while (QFileInfo::exists(result));

	if (!QDir::current().mkpath(result))
		return {};
#ifdef Q_OS_WIN32
	SetFileAttributesA(tempRoot.toStdString().c_str(), FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED);
#endif
	return result;
}

bool InstanceList::commitStagedInstance(const QString& path,
										InstanceName const& instanceName,
										QString groupName,
										InstanceTask const& commiting)
{
	if (groupName.isEmpty() && !groupName.isNull())
		groupName = QString();

	QString instID;
	InstancePtr inst;

	auto should_override = commiting.shouldOverride();

	if (should_override)
	{
		instID = commiting.originalInstanceID();
	}
	else
	{
		instID = FS::DirNameFromString(instanceName.modifiedName(), m_instDir);
	}

	Q_ASSERT(!instID.isEmpty());

	{
		WatchLock lock(m_watcher, m_instDir);
		QString destination = FS::PathCombine(m_instDir, instID);

		if (should_override)
		{
			if (!FS::overrideFolder(destination, path))
			{
				qWarning() << "Failed to override" << path << "to" << destination;
				return false;
			}
		}
		else
		{
			if (!FS::move(path, destination))
			{
				qWarning() << "Failed to move" << path << "to" << destination;
				return false;
			}

			m_instanceGroupIndex[instID] = groupName;
			increaseGroupCount(groupName);
		}

		instanceSet.insert(instID);

		emit instancesChanged();
		emit instanceSelectRequest(instID);
	}

	saveGroupList();
	return true;
}

bool InstanceList::destroyStagingPath(const QString& keyPath)
{
	return FS::deletePath(keyPath);
}

int InstanceList::getTotalPlayTime()
{
	updateTotalPlayTime();
	return totalPlayTime;
}

#include "InstanceList.moc"