forked from Aloshi/EmulationStation
-
Notifications
You must be signed in to change notification settings - Fork 351
Expand file tree
/
Copy pathCollectionSystemManager.cpp
More file actions
1333 lines (1174 loc) · 45.3 KB
/
CollectionSystemManager.cpp
File metadata and controls
1333 lines (1174 loc) · 45.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
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 "CollectionSystemManager.h"
#include "components/TextListComponent.h"
#include "guis/GuiInfoPopup.h"
#include "utils/FileSystemUtil.h"
#include "utils/StringUtil.h"
#include "views/gamelist/IGameListView.h"
#include "views/gamelist/ISimpleGameListView.h"
#include "views/ViewController.h"
#include "FileData.h"
#include "FileFilterIndex.h"
#include "Log.h"
#include "Settings.h"
#include "SystemData.h"
#include "ThemeData.h"
#include <pugixml.hpp>
#include <fstream>
#include <cstring>
/* Handling the getting, initialization, deinitialization, saving and deletion of
* a CollectionSystemManager Instance */
CollectionSystemManager* CollectionSystemManager::sInstance = NULL;
CollectionSystemManager::CollectionSystemManager(Window* window) : mWindow(window)
{
CollectionSystemDecl systemDecls[] = {
//type name long name (display) default sort (key, order) theme folder isCustom
{ AUTO_ALL_GAMES, "all", "all games", "name, ascending", "auto-allgames", false },
{ AUTO_LAST_PLAYED, "recent", "last played", "last played, descending", "auto-lastplayed", false },
{ AUTO_FAVORITES, "favorites", "favorites", "name, ascending", "auto-favorites", false },
{ AUTO_RANDOM, RANDOM_COLL_ID, "random", "name, ascending", "auto-random", false },
{ CUSTOM_COLLECTION, CUSTOM_COLL_ID, "collections", "name, ascending", "custom-collections", true }
};
// create a map
std::vector<CollectionSystemDecl> tempSystemDecl = std::vector<CollectionSystemDecl>(systemDecls, systemDecls + sizeof(systemDecls) / sizeof(systemDecls[0]));
for (std::vector<CollectionSystemDecl>::const_iterator it = tempSystemDecl.cbegin(); it != tempSystemDecl.cend(); ++it )
{
mCollectionSystemDeclsIndex[(*it).name] = (*it);
}
// creating standard environment data
mCollectionEnvData = new SystemEnvironmentData;
mCollectionEnvData->mStartPath = "";
std::vector<std::string> exts;
mCollectionEnvData->mSearchExtensions = exts;
mCollectionEnvData->mLaunchCommand = "";
std::vector<PlatformIds::PlatformId> allPlatformIds;
allPlatformIds.push_back(PlatformIds::PLATFORM_IGNORE);
mCollectionEnvData->mPlatformIds = allPlatformIds;
std::string path = getCollectionsFolder();
if(!Utils::FileSystem::exists(path))
Utils::FileSystem::createDirectory(path);
mIsEditingCustom = false;
mEditingCollection = "Favorites";
mEditingCollectionSystemData = NULL;
mCustomCollectionsBundle = NULL;
mRandomCollection = NULL;
}
CollectionSystemManager::~CollectionSystemManager()
{
assert(sInstance == this);
removeCollectionsFromDisplayedSystems();
// iterate the map
for(std::map<std::string, CollectionSystemData>::const_iterator it = mCustomCollectionSystemsData.cbegin() ; it != mCustomCollectionSystemsData.cend() ; it++ )
{
if (it->second.isPopulated)
{
saveCustomCollection(it->second.system);
}
delete it->second.system;
}
sInstance = NULL;
}
CollectionSystemManager* CollectionSystemManager::get()
{
assert(sInstance);
return sInstance;
}
void CollectionSystemManager::init(Window* window)
{
assert(!sInstance);
sInstance = new CollectionSystemManager(window);
}
void CollectionSystemManager::deinit()
{
if (sInstance)
{
delete sInstance;
}
}
bool CollectionSystemManager::saveCustomCollection(SystemData* sys)
{
std::string name = sys->getName();
std::unordered_map<std::string, FileData*> games = sys->getRootFolder()->getChildrenByFilename();
bool found = mCustomCollectionSystemsData.find(name) != mCustomCollectionSystemsData.cend();
if (!found)
{
LOG(LogError) << "Couldn't find collection to save! " << name;
return false;
}
CollectionSystemData sysData = mCustomCollectionSystemsData.at(name);
if (sysData.needsSave)
{
std::string absCollectionFn = getCustomCollectionConfigPath(name);
std::ofstream configFile;
configFile.open(absCollectionFn);
if (!configFile.good())
{
auto const errNo = errno;
LOG(LogError) << "Failed to create file, collection not created: " << absCollectionFn << ": " << std::strerror(errNo) << " (" << errNo << ")";
return false;
}
for(std::unordered_map<std::string, FileData*>::const_iterator iter = games.cbegin(); iter != games.cend(); ++iter)
{
std::string path = iter->first;
configFile << path << std::endl;
}
configFile.close();
}
return true;
}
/* Methods to load all Collections into memory, and handle enabling the active ones */
// loads all Collection Systems
void CollectionSystemManager::loadCollectionSystems(bool async)
{
initAutoCollectionSystems();
CollectionSystemDecl decl = mCollectionSystemDeclsIndex[CUSTOM_COLL_ID];
mCustomCollectionsBundle = createNewCollectionEntry(decl.name, decl, CollectionFlags::NONE);
// we will also load custom systems here
initCustomCollectionSystems();
if(Settings::getInstance()->getString("CollectionSystemsAuto") != "" || Settings::getInstance()->getString("CollectionSystemsCustom") != "")
{
// Now see which ones are enabled
loadEnabledListFromSettings();
// add to the main System Vector, and create Views as needed
if (!async)
updateSystemsList();
}
}
// loads settings
void CollectionSystemManager::loadEnabledListFromSettings()
{
// we parse the auto collection settings list
std::vector<std::string> autoSelected = Utils::String::delimitedStringToVector(Settings::getInstance()->getString("CollectionSystemsAuto"), ",", true);
// iterate the map
for(std::map<std::string, CollectionSystemData>::iterator it = mAutoCollectionSystemsData.begin() ; it != mAutoCollectionSystemsData.end() ; it++ )
{
it->second.isEnabled = (std::find(autoSelected.cbegin(), autoSelected.cend(), it->first) != autoSelected.cend());
}
// we parse the custom collection settings list
std::vector<std::string> customSelected = Utils::String::delimitedStringToVector(Settings::getInstance()->getString("CollectionSystemsCustom"), ",", true);
// iterate the map
for(std::map<std::string, CollectionSystemData>::iterator it = mCustomCollectionSystemsData.begin() ; it != mCustomCollectionSystemsData.end() ; it++ )
{
it->second.isEnabled = (std::find(customSelected.cbegin(), customSelected.cend(), it->first) != customSelected.cend());
}
}
// updates enabled system list in System View
void CollectionSystemManager::updateSystemsList()
{
// remove all Collection Systems
removeCollectionsFromDisplayedSystems();
// add custom enabled ones
addEnabledCollectionsToDisplayedSystems(&mCustomCollectionSystemsData, false);
if(Settings::getInstance()->getBool("SortAllSystems"))
{
// sort custom individual systems with other systems
std::sort(SystemData::sSystemVector.begin(), SystemData::sSystemVector.end(), systemSort);
// move RetroPie system to end, before auto collections
for(auto sysIt = SystemData::sSystemVector.cbegin(); sysIt != SystemData::sSystemVector.cend(); )
{
if ((*sysIt)->getName() == "retropie")
{
SystemData* retroPieSystem = (*sysIt);
sysIt = SystemData::sSystemVector.erase(sysIt);
SystemData::sSystemVector.push_back(retroPieSystem);
break;
}
else
{
sysIt++;
}
}
}
if(mCustomCollectionsBundle->getRootFolder()->getChildren().size() > 0)
{
mCustomCollectionsBundle->getRootFolder()->sort(getSortTypeFromString(mCollectionSystemDeclsIndex[CUSTOM_COLL_ID].defaultSort));
SystemData::sSystemVector.push_back(mCustomCollectionsBundle);
}
// add auto enabled ones except random
addEnabledCollectionsToDisplayedSystems(&mAutoCollectionSystemsData, false);
// finally, add random
addEnabledCollectionsToDisplayedSystems(&mAutoCollectionSystemsData, true);
// create views for collections, before reload
for(auto sysIt = SystemData::sSystemVector.cbegin(); sysIt != SystemData::sSystemVector.cend(); sysIt++)
{
if ((*sysIt)->isCollection())
ViewController::get()->getGameListView((*sysIt));
}
// if we were editing a custom collection, and it's no longer enabled, exit edit mode
if(mIsEditingCustom && !mEditingCollectionSystemData->isEnabled)
{
exitEditMode();
}
}
/* Methods to manage collection files related to a source FileData */
// updates all collection files related to the source file
void CollectionSystemManager::refreshCollectionSystems(FileData* file)
{
if (!file->getSystem()->isGameSystem() || file->getType() != GAME)
return;
std::map<std::string, CollectionSystemData> allCollections;
allCollections.insert(mAutoCollectionSystemsData.cbegin(), mAutoCollectionSystemsData.cend());
allCollections.insert(mCustomCollectionSystemsData.cbegin(), mCustomCollectionSystemsData.cend());
for(auto sysDataIt = allCollections.cbegin(); sysDataIt != allCollections.cend(); sysDataIt++)
{
updateCollectionSystem(file, sysDataIt->second);
}
}
void CollectionSystemManager::updateCollectionSystem(FileData* file, CollectionSystemData sysData)
{
if (sysData.isPopulated)
{
// collection files use the full path as key, to avoid clashes
std::string key = file->getFullPath();
SystemData* curSys = sysData.system;
const std::unordered_map<std::string, FileData*>& children = curSys->getRootFolder()->getChildrenByFilename();
bool found = children.find(key) != children.cend();
FileData* rootFolder = curSys->getRootFolder();
FileFilterIndex* fileIndex = curSys->getIndex();
std::string name = curSys->getName();
if (found) {
// if we found it, we need to update it
FileData* collectionEntry = children.at(key);
// remove from index, so we can re-index metadata after refreshing
fileIndex->removeFromIndex(collectionEntry);
collectionEntry->refreshMetadata();
// found and we are removing
if (name == "favorites" && file->metadata.get("favorite") == "false") {
// need to check if still marked as favorite, if not remove
ViewController::get()->getGameListView(curSys).get()->remove(collectionEntry, false, true);
}
else
{
// re-index with new metadata
fileIndex->addToIndex(collectionEntry);
ViewController::get()->onFileChanged(collectionEntry, FILE_METADATA_CHANGED);
}
}
else
{
// we didn't find it here - we need to check if we should add it
if (name == "recent" && file->metadata.get("playcount") > "0" && includeFileInAutoCollections(file) ||
name == "favorites" && file->metadata.get("favorite") == "true") {
CollectionFileData* newGame = new CollectionFileData(file, curSys);
rootFolder->addChild(newGame);
fileIndex->addToIndex(newGame);
ViewController::get()->onFileChanged(file, FILE_METADATA_CHANGED);
ViewController::get()->getGameListView(curSys)->onFileChanged(newGame, FILE_METADATA_CHANGED);
}
}
rootFolder->sort(getSortTypeFromString(mCollectionSystemDeclsIndex[name].defaultSort));
if (name == "recent")
{
trimCollectionCount(rootFolder, LAST_PLAYED_MAX, false);
ViewController::get()->onFileChanged(rootFolder, FILE_METADATA_CHANGED);
// Force re-calculation of cursor position
ViewController::get()->getGameListView(curSys)->setViewportTop(TextListComponent<FileData>::REFRESH_LIST_CURSOR_POS);
}
else
ViewController::get()->onFileChanged(rootFolder, FILE_SORTED);
}
}
void CollectionSystemManager::trimCollectionCount(FileData* rootFolder, int limit, bool shuffle)
{
SystemData* curSys = rootFolder->getSystem();
while ((int)rootFolder->getChildrenListToDisplay().size() > limit)
{
std::vector<FileData*> games = rootFolder->getFilesRecursive(GAME, true);
if (shuffle)
std::shuffle(games.begin(), games.end(), SystemData::sURNG);
CollectionFileData* gameToRemove = (CollectionFileData*)games.back();
ViewController::get()->getGameListView(curSys).get()->remove(gameToRemove, false, false);
}
ViewController::get()->onFileChanged(rootFolder, FILE_REMOVED);
}
// deletes all collection files from collection systems related to the source file
void CollectionSystemManager::deleteCollectionFiles(FileData* file)
{
// collection files use the full path as key, to avoid clashes
std::string key = file->getFullPath();
// find games in collection systems
std::map<std::string, CollectionSystemData> allCollections;
allCollections.insert(mAutoCollectionSystemsData.cbegin(), mAutoCollectionSystemsData.cend());
allCollections.insert(mCustomCollectionSystemsData.cbegin(), mCustomCollectionSystemsData.cend());
for(auto sysDataIt = allCollections.begin(); sysDataIt != allCollections.end(); sysDataIt++)
{
if (sysDataIt->second.isPopulated)
{
const std::unordered_map<std::string, FileData*>& children = (sysDataIt->second.system)->getRootFolder()->getChildrenByFilename();
bool found = children.find(key) != children.cend();
if (found) {
sysDataIt->second.needsSave = true;
FileData* collectionEntry = children.at(key);
SystemData* systemViewToUpdate = getSystemToView(sysDataIt->second.system);
ViewController::get()->getGameListView(systemViewToUpdate).get()->remove(collectionEntry, false, true);
}
}
}
}
// returns whether the current theme is compatible with Automatic or Custom Collections
bool CollectionSystemManager::isThemeGenericCollectionCompatible(bool genericCustomCollections)
{
std::vector<std::string> cfgSys = getCollectionThemeFolders(genericCustomCollections);
for(auto sysIt = cfgSys.cbegin(); sysIt != cfgSys.cend(); sysIt++)
{
if(!themeFolderExists(*sysIt))
return false;
}
return true;
}
bool CollectionSystemManager::isThemeCustomCollectionCompatible(std::vector<std::string> stringVector)
{
if (isThemeGenericCollectionCompatible(true))
return true;
// get theme path
auto themeSets = ThemeData::getThemeSets();
auto set = themeSets.find(Settings::getInstance()->getString("ThemeSet"));
if(set != themeSets.cend())
{
std::string defaultThemeFilePath = set->second.path + "/theme.xml";
if (Utils::FileSystem::exists(defaultThemeFilePath))
{
return true;
}
}
for(auto sysIt = stringVector.cbegin(); sysIt != stringVector.cend(); sysIt++)
{
if(!themeFolderExists(*sysIt))
return false;
}
return true;
}
std::string CollectionSystemManager::getValidNewCollectionName(std::string inName, int index)
{
std::string name = inName;
const std::string infix = " (" + std::to_string(index) + ")";
if(index == 0)
{
size_t remove = std::string::npos;
// get valid name
while((remove = name.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-[]() ")) != std::string::npos)
{
name.erase(remove, 1);
}
}
else
{
name += infix;
}
if(name == "")
{
name = "New Collection";
}
if(name != inName)
{
LOG(LogInfo) << "Name collision, had to change name from: " << inName << " to: " << name;
}
// get used systems in es_systems.cfg
std::vector<std::string> systemsInUse = getSystemsFromConfig();
// get folders assigned to custom collections
std::vector<std::string> autoSys = getCollectionThemeFolders(false);
// get folder assigned to custom collections
std::vector<std::string> customSys = getCollectionThemeFolders(true);
// get folders assigned to user collections
std::vector<std::string> userSys = getUserCollectionThemeFolders();
// add them all to the list of systems in use
systemsInUse.insert(systemsInUse.cend(), autoSys.cbegin(), autoSys.cend());
systemsInUse.insert(systemsInUse.cend(), customSys.cbegin(), customSys.cend());
systemsInUse.insert(systemsInUse.cend(), userSys.cbegin(), userSys.cend());
for(auto sysIt = systemsInUse.cbegin(); sysIt != systemsInUse.cend(); sysIt++)
{
if (*sysIt == name)
{
if(index > 0) {
name = name.substr(0, name.size() - infix.size());
}
return getValidNewCollectionName(name, index+1);
}
}
// if it matches one of the custom collections reserved names
if (mCollectionSystemDeclsIndex.find(name) != mCollectionSystemDeclsIndex.cend())
return getValidNewCollectionName(name, index+1);
return name;
}
void CollectionSystemManager::setEditMode(std::string collectionName, bool quiet)
{
if (mCustomCollectionSystemsData.find(collectionName) == mCustomCollectionSystemsData.cend())
{
LOG(LogError) << "Tried to edit a non-existing collection: " << collectionName;
return;
}
mIsEditingCustom = true;
mEditingCollection = collectionName;
CollectionSystemData* sysData = &(mCustomCollectionSystemsData.at(mEditingCollection));
if (!sysData->isPopulated)
{
populateCustomCollection(sysData);
}
// if it's bundled, this needs to be the bundle system
mEditingCollectionSystemData = sysData;
if (!quiet) {
GuiInfoPopup* s = new GuiInfoPopup(mWindow, "Editing the '" + Utils::String::toUpper(collectionName) + "' Collection. Add/remove games with Y.", 8000);
mWindow->setInfoPopup(s);
}
}
void CollectionSystemManager::exitEditMode(bool quiet)
{
if (!quiet) {
GuiInfoPopup* s = new GuiInfoPopup(mWindow, "Finished editing the '" + Utils::String::toUpper(mEditingCollection) + "' Collection.", 4000);
mWindow->setInfoPopup(s);
}
if (mIsEditingCustom) {
mIsEditingCustom = false;
mEditingCollection = "Favorites";
mEditingCollectionSystemData->system->onMetaDataSavePoint();
saveCustomCollection(mEditingCollectionSystemData->system);
}
}
int CollectionSystemManager::getPressCountInDuration() {
Uint32 now = SDL_GetTicks();
if (now - mFirstPressMs < DOUBLE_PRESS_DETECTION_DURATION) {
return 2;
} else {
mFirstPressMs = now;
return 1;
}
}
// adds or removes a game from a specific collection
bool CollectionSystemManager::toggleGameInCollection(FileData* file)
{
if (file->getType() == GAME)
{
GuiInfoPopup* s;
bool adding = true;
std::string name = file->getName();
std::string sysName = mEditingCollection;
if (mIsEditingCustom)
{
SystemData* sysData = mEditingCollectionSystemData->system;
mEditingCollectionSystemData->needsSave = true;
if (!mEditingCollectionSystemData->isPopulated)
{
populateCustomCollection(mEditingCollectionSystemData);
}
std::string key = file->getFullPath();
FileData* rootFolder = sysData->getRootFolder();
const std::unordered_map<std::string, FileData*>& children = rootFolder->getChildrenByFilename();
bool found = children.find(key) != children.cend();
FileFilterIndex* fileIndex = sysData->getIndex();
std::string name = sysData->getName();
SystemData* systemViewToUpdate = getSystemToView(sysData);
if (found) {
if (needDoublePress(getPressCountInDuration())) {
return true;
}
adding = false;
// if we found it, we need to remove it
FileData* collectionEntry = children.at(key);
// remove from index
fileIndex->removeFromIndex(collectionEntry);
// remove from bundle index as well, if needed
if(systemViewToUpdate != sysData)
{
systemViewToUpdate->getIndex()->removeFromIndex(collectionEntry);
}
ViewController::get()->getGameListView(systemViewToUpdate).get()->remove(collectionEntry, false, true);
}
else
{
// we didn't find it here, we should add it
CollectionFileData* newGame = new CollectionFileData(file, sysData);
rootFolder->addChild(newGame);
fileIndex->addToIndex(newGame);
// this is the biggest performance bottleneck for this process.
// this code has been here for 7 years, since this feature was added.
// I might have been playing it safe back then, but it feels unnecessary, especially given following onFileChanged to sort
// Commenting this out for now.
//ViewController::get()->getGameListView(systemViewToUpdate)->onFileChanged(newGame, FILE_METADATA_CHANGED);
rootFolder->sort(getSortTypeFromString(mEditingCollectionSystemData->decl.defaultSort));
ViewController::get()->onFileChanged(systemViewToUpdate->getRootFolder(), FILE_SORTED);
// add to bundle index as well, if needed
if(systemViewToUpdate != sysData)
{
systemViewToUpdate->getIndex()->addToIndex(newGame);
}
}
sysData->setShuffledCacheDirty();
updateCollectionFolderMetadata(sysData);
}
else
{
file->getSourceFileData()->getSystem()->getIndex()->removeFromIndex(file);
MetaDataList* md = &file->getSourceFileData()->metadata;
std::string value = md->get("favorite");
if (value == "false")
{
md->set("favorite", "true");
}
else
{
if (needDoublePress(getPressCountInDuration())) {
return true;
}
adding = false;
md->set("favorite", "false");
}
file->getSourceFileData()->getSystem()->getIndex()->addToIndex(file);
file->getSourceFileData()->getSystem()->onMetaDataSavePoint();
refreshCollectionSystems(file->getSourceFileData());
}
if (adding)
{
s = new GuiInfoPopup(mWindow, "Added '" + Utils::String::removeParenthesis(name) + "' to '" + Utils::String::toUpper(sysName) + "'", 4000);
}
else
{
s = new GuiInfoPopup(mWindow, "Removed '" + Utils::String::removeParenthesis(name) + "' from '" + Utils::String::toUpper(sysName) + "'", 4000);
}
mWindow->setInfoPopup(s);
return true;
}
return false;
}
SystemData* CollectionSystemManager::getSystemToView(SystemData* sys)
{
SystemData* systemToView = sys;
FileData* rootFolder = sys->getRootFolder();
FileData* bundleRootFolder = mCustomCollectionsBundle->getRootFolder();
const std::unordered_map<std::string, FileData*>& bundleChildren = bundleRootFolder->getChildrenByFilename();
// is the rootFolder bundled in the "My Collections" system?
bool sysFoundInBundle = bundleChildren.find(rootFolder->getKey()) != bundleChildren.cend();
if (sysFoundInBundle && sys->isCollection())
{
systemToView = mCustomCollectionsBundle;
}
return systemToView;
}
void CollectionSystemManager::recreateCollection(SystemData* sysData)
{
CollectionSystemData* colSysData;
if (mAutoCollectionSystemsData.find(sysData->getName()) != mAutoCollectionSystemsData.end())
{
// it's an auto collection
colSysData = &mAutoCollectionSystemsData[sysData->getName()];
}
else if (mCustomCollectionSystemsData.find(sysData->getName()) != mCustomCollectionSystemsData.end())
{
// it's a custom collection
colSysData = &mCustomCollectionSystemsData[sysData->getName()];
}
else
{
LOG(LogDebug) << "Couldn't find collection to recreate in either custom or auto collections: " << sysData->getName();
return;
}
CollectionSystemDecl sysDecl = colSysData->decl;
FileData* rootFolder = sysData->getRootFolder();
FileFilterIndex* index = sysData->getIndex();
const std::unordered_map<std::string, FileData*>& children = rootFolder->getChildrenByFilename();
sysData->getIndex()->resetIndex();
std::string name = sysData->getName();
SystemData* systemViewToUpdate = getSystemToView(sysData);
// while there are games there, remove them from the view and system
while(rootFolder->getChildrenByFilename().size() > 0)
ViewController::get()->getGameListView(systemViewToUpdate).get()->remove(rootFolder->getChildrenByFilename().begin()->second, false, false);
colSysData->isPopulated = false;
if (sysDecl.isCustom)
populateCustomCollection(colSysData);
else
populateAutoCollection(colSysData);
rootFolder->sort(getSortTypeFromString(colSysData->decl.defaultSort));
ViewController::get()->onFileChanged(systemViewToUpdate->getRootFolder(), FILE_SORTED);
// Workaround to force video to play
FileData* cursor = ViewController::get()->getGameListView(systemViewToUpdate)->getCursor();
ViewController::get()->getGameListView(systemViewToUpdate)->setCursor(cursor, true);
}
/* Handles loading a collection system, creating an empty one, and populating on demand */
// loads Automatic Collection systems (All, Favorites, Last Played, Random)
void CollectionSystemManager::initAutoCollectionSystems()
{
for(std::map<std::string, CollectionSystemDecl>::const_iterator it = mCollectionSystemDeclsIndex.cbegin() ; it != mCollectionSystemDeclsIndex.cend() ; it++ )
{
CollectionSystemDecl sysDecl = it->second;
if (!sysDecl.isCustom)
{
SystemData* newCol = createNewCollectionEntry(sysDecl.name, sysDecl, CollectionFlags::HOLD_IN_MAP);
if (sysDecl.type == AUTO_RANDOM)
mRandomCollection = newCol;
}
}
}
// this may come in handy if at any point in time in the future we want to
// automatically generate metadata for a folder
void CollectionSystemManager::updateCollectionFolderMetadata(SystemData* sys)
{
FileData* rootFolder = sys->getRootFolder();
std::string desc = "This collection is empty.";
std::string rating = "0";
std::string players = "1";
std::string releasedate = "N/A";
std::string developer = "None";
std::string genre = "None";
std::string video = "";
std::string thumbnail = "";
std::string image = "";
std::unordered_map<std::string, FileData*> games = rootFolder->getChildrenByFilename();
if(games.size() > 0)
{
std::string games_list = "";
int games_counter = 0;
for(std::unordered_map<std::string, FileData*>::const_iterator iter = games.cbegin(); iter != games.cend(); ++iter)
{
games_counter++;
FileData* file = iter->second;
std::string new_rating = file->metadata.get("rating");
std::string new_releasedate = file->metadata.get("releasedate");
std::string new_developer = file->metadata.get("developer");
std::string new_genre = file->metadata.get("genre");
std::string new_players = file->metadata.get("players");
rating = (new_rating > rating ? (new_rating != "" ? new_rating : rating) : rating);
players = (new_players > players ? (new_players != "" ? new_players : players) : players);
releasedate = (new_releasedate < releasedate ? (new_releasedate != "" ? new_releasedate : releasedate) : releasedate);
developer = (developer == "None" ? new_developer : (new_developer != developer ? "Various" : new_developer));
genre = (genre == "None" ? new_genre : (new_genre != genre ? "Various" : new_genre));
switch(games_counter)
{
case 2:
case 3:
games_list += ", ";
case 1:
games_list += "'" + file->getName() + "'";
break;
case 4:
games_list += " among other titles.";
}
}
desc = "This collection contains " + std::to_string(games_counter) + " game"
+ (games_counter == 1 ? "" : "s") + ", including " + games_list;
FileData* randomGame = sys->getRandomGame();
video = randomGame->getVideoPath();
thumbnail = randomGame->getThumbnailPath();
image = randomGame->getImagePath();
}
rootFolder->metadata.set("desc", desc);
rootFolder->metadata.set("rating", rating);
rootFolder->metadata.set("players", players);
rootFolder->metadata.set("genre", genre);
rootFolder->metadata.set("releasedate", releasedate);
rootFolder->metadata.set("developer", developer);
rootFolder->metadata.set("video", video);
rootFolder->metadata.set("thumbnail", thumbnail);
rootFolder->metadata.set("image", image);
}
void CollectionSystemManager::initCustomCollectionSystems()
{
std::vector<std::string> systems = getCollectionsFromConfigFolder();
for (auto nameIt = systems.cbegin(); nameIt != systems.cend(); nameIt++)
{
addNewCustomCollection(*nameIt);
}
}
SystemData* CollectionSystemManager::getAllGamesCollection()
{
CollectionSystemData* allSysData = &mAutoCollectionSystemsData["all"];
if (!allSysData->isPopulated)
{
populateAutoCollection(allSysData);
}
return allSysData->system;
}
SystemData* CollectionSystemManager::addNewCustomCollection(std::string name, bool needsSave)
{
CollectionSystemDecl decl = mCollectionSystemDeclsIndex[CUSTOM_COLL_ID];
decl.themeFolder = name;
decl.name = name;
decl.longName = name;
CollectionFlags flags = CollectionFlags::HOLD_IN_MAP;
if (needsSave)
flags = flags | CollectionFlags::NEEDS_SAVE;
return createNewCollectionEntry(name, decl, flags);
}
// creates a new, empty Collection system, based on the name and declaration
SystemData* CollectionSystemManager::createNewCollectionEntry(std::string name, CollectionSystemDecl sysDecl, const CollectionFlags flags)
{
SystemData* newSys = new SystemData(name, sysDecl.longName, mCollectionEnvData, sysDecl.themeFolder, true);
CollectionSystemData newCollectionData;
newCollectionData.system = newSys;
newCollectionData.decl = sysDecl;
newCollectionData.isEnabled = false;
newCollectionData.isPopulated = false;
newCollectionData.needsSave = (flags & CollectionFlags::NEEDS_SAVE) == CollectionFlags::NEEDS_SAVE ? true : false;
if ((flags & CollectionFlags::HOLD_IN_MAP) == CollectionFlags::HOLD_IN_MAP)
{
if (!sysDecl.isCustom)
{
mAutoCollectionSystemsData[name] = newCollectionData;
}
else
{
mCustomCollectionSystemsData[name] = newCollectionData;
}
}
return newSys;
}
void CollectionSystemManager::addRandomGames(SystemData* newSys, SystemData* sourceSystem, FileData* rootFolder,
FileFilterIndex* index, std::map<std::string, std::map<std::string, int>> mapsForRandomColl, int defaultValue)
{
int gamesForSourceSystem = defaultValue;
for (auto& m : mapsForRandomColl)
{
// m.first unused
std::map<std::string, int> collMap = m.second;
if (collMap.find(sourceSystem->getFullName()) != collMap.end())
{
int maxForSys = collMap[sourceSystem->getFullName()];
// we won't add more than the max and less than 0
gamesForSourceSystem = Math::max(Math::min(RANDOM_SYSTEM_MAX, maxForSys), 0);
break;
}
}
// load exclusion collection
std::unordered_map<std::string,FileData*> exclusionMap;
std::string exclusionCollection = Settings::getInstance()->getString("RandomCollectionExclusionCollection");
auto sysDataIt = mCustomCollectionSystemsData.find(exclusionCollection);
if (!exclusionCollection.empty() && sysDataIt != mCustomCollectionSystemsData.end()) {
if (!sysDataIt->second.isPopulated)
{
populateCustomCollection(&(sysDataIt->second));
}
exclusionMap = mCustomCollectionSystemsData[exclusionCollection].system->getRootFolder()->getChildrenByFilename();
}
// we do this to avoid trying to add more games than there are in the system
gamesForSourceSystem = Math::min(gamesForSourceSystem, sourceSystem->getRootFolder()->getFilesRecursive(GAME).size());
int startCount = rootFolder->getFilesRecursive(GAME).size();
int endCount = startCount + gamesForSourceSystem;
int retryCount = 10;
for (int iterCount = startCount; iterCount < endCount;)
{
FileData* randomGame = sourceSystem->getRandomGame()->getSourceFileData();
CollectionFileData* newGame = NULL;
if(exclusionMap.find(randomGame->getFullPath()) == exclusionMap.end())
{
// Not in the exclusion collection
newGame = new CollectionFileData(randomGame, newSys);
rootFolder->addChild(newGame);
index->addToIndex(newGame);
}
if (rootFolder->getFilesRecursive(GAME).size() > iterCount)
{
// added game, proceed
iterCount++;
retryCount = 10;
}
else
{
// the game already exists in the collection, let's try again
LOG(LogDebug) << "Clash: " << randomGame->getName() << " already exists or in exclusion list. Deleting and trying again";
delete newGame;
retryCount--;
if (retryCount == 0)
{
// we give up. Either we were very unlucky, or all the games in this system are already there.
LOG(LogDebug) << "Giving up retrying: cannot add this game. Deleting and moving on.";
return;
}
}
}
}
void CollectionSystemManager::populateRandomCollectionFromCollections(std::map<std::string, std::map<std::string, int>> mapsForRandomColl)
{
CollectionSystemData* sysData = &mAutoCollectionSystemsData[RANDOM_COLL_ID];
SystemData* newSys = sysData->system;
CollectionSystemDecl sysDecl = sysData->decl;
FileData* rootFolder = newSys->getRootFolder();
FileFilterIndex* index = newSys->getIndex();
// iterate the auto collections map
for(auto &c : mAutoCollectionSystemsData)
{
CollectionSystemData csd = c.second;
// we can't add games from the random collection to the random collection
if (csd.decl.type != AUTO_RANDOM)
{
// collections might not be populated
if (!csd.isPopulated)
populateAutoCollection(&csd);
if (csd.isPopulated)
addRandomGames(newSys, csd.system, rootFolder, index, mapsForRandomColl, DEFAULT_RANDOM_COLLECTIONS_GAMES);
}
}
// iterate the custom collections map
for(auto &c : mCustomCollectionSystemsData)
{
CollectionSystemData csd = c.second;
// collections might not be populated
if (!csd.isPopulated)
populateCustomCollection(&csd);
if (csd.isPopulated)
addRandomGames(newSys, csd.system, rootFolder, index, mapsForRandomColl, DEFAULT_RANDOM_COLLECTIONS_GAMES);
}
}
// populates an Automatic Collection System
void CollectionSystemManager::populateAutoCollection(CollectionSystemData* sysData)
{
SystemData* newSys = sysData->system;
CollectionSystemDecl sysDecl = sysData->decl;
FileData* rootFolder = newSys->getRootFolder();
FileFilterIndex* index = newSys->getIndex();
std::map<std::string, std::map<std::string, int>> mapsForRandomColl;
if (sysDecl.type == AUTO_RANDOM)
{
// user may have defined a custom collection with the same name as a system name, thus keeping maps in another map
std::map<std::string, int> randomSystems = Settings::getInstance()->getMap("RandomCollectionSystems");
mapsForRandomColl["RandomCollectionSystems"] = randomSystems;
std::map<std::string, int> randomAutoColl = Settings::getInstance()->getMap("RandomCollectionSystemsAuto");
mapsForRandomColl["RandomCollectionSystemsAuto"] = randomAutoColl;
std::map<std::string, int> randomCustColl = Settings::getInstance()->getMap("RandomCollectionSystemsCustom");
mapsForRandomColl["RandomCollectionSystemsCustom"] = randomCustColl;
}
// Only iterate through game systems, not collections yet
for(auto sysIt = SystemData::sSystemVector.cbegin(); sysIt != SystemData::sSystemVector.cend(); sysIt++)
{
// we won't iterate all collections
if ((*sysIt)->isGameSystem() && !(*sysIt)->isCollection())
{
if (sysDecl.type == AUTO_RANDOM)
{
addRandomGames(newSys, *sysIt, rootFolder, index, mapsForRandomColl, DEFAULT_RANDOM_SYSTEM_GAMES);
}
else
{
std::vector<FileData*> files = (*sysIt)->getRootFolder()->getFilesRecursive(GAME);
for(auto gameIt = files.cbegin(); gameIt != files.cend(); gameIt++)
{
bool include = includeFileInAutoCollections(*gameIt);
switch(sysDecl.type) {
case AUTO_LAST_PLAYED:
include = include && (*gameIt)->metadata.get("playcount") > "0";
break;
case AUTO_FAVORITES:
// we may still want to add files we don't want in auto collections in "favorites"
include = (*gameIt)->metadata.get("favorite") == "true";
break;
case AUTO_ALL_GAMES:
break;
default:
// No-op to prevent compiler warnings
// Getting here means that the file is not part of a pre-defined collection.
include = false;
break;
}
if (include)
{
CollectionFileData* newGame = new CollectionFileData(*gameIt, newSys);
rootFolder->addChild(newGame);
index->addToIndex(newGame);
}
}
}
}
}
// here we finish populating the Random collection based on other Collections
if (sysDecl.type == AUTO_RANDOM)
populateRandomCollectionFromCollections(mapsForRandomColl);
// sort before optional trimming, if collection is displayed
if (sysData->isEnabled)
rootFolder->sort(getSortTypeFromString(sysDecl.defaultSort));
if (sysData->isEnabled && (sysDecl.type == AUTO_LAST_PLAYED || sysDecl.type == AUTO_RANDOM))
{
int trimValue = LAST_PLAYED_MAX;
if (sysDecl.type == AUTO_RANDOM)
trimValue = Settings::getInstance()->getInt("RandomCollectionMaxGames");
if (trimValue > 0)
trimCollectionCount(rootFolder, trimValue, sysDecl.type == AUTO_RANDOM);
}