File: LayerManipulation.cpp

package info (click to toggle)
darkradiant 3.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 41,080 kB
  • sloc: cpp: 264,743; ansic: 10,659; python: 1,852; xml: 1,650; sh: 92; makefile: 21
file content (1250 lines) | stat: -rw-r--r-- 54,823 bytes parent folder | download | duplicates (3)
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
#include "i18n.h"
#include "RadiantTest.h"

#include "imap.h"
#include "ilayer.h"
#include "ifilter.h"
#include "scenelib.h"
#include "algorithm/Primitives.h"
#include "os/file.h"

#include "algorithm/Scene.h"
#include "string/split.h"
#include "string/trim.h"
#include "testutil/FileSaveConfirmationHelper.h"
#include "testutil/TemporaryFile.h"

namespace test
{

using LayerTest = RadiantTest;

inline std::vector<std::string> getAllLayerNames()
{
    std::vector<std::string> layerNames;

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    layerManager.foreachLayer([&](int layerId, const std::string& layerName)
    {
        layerNames.push_back(layerName);
    });

    return layerNames;
}

inline std::vector<int> getAllLayerIds()
{
    std::vector<int> layerIds;

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    layerManager.foreachLayer([&](int layerId, const std::string& layerName)
    {
        layerIds.push_back(layerId);
    });

    return layerIds;
}

TEST_F(LayerTest, CreateLayer)
{
    EXPECT_EQ(getAllLayerNames().size(), 1) << "Expected a default layer at map start";
    EXPECT_EQ(getAllLayerNames(), std::vector{ _("Default") }) << "Expected a default layer at map start";

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    const std::string testLayerName = "TestLayer";

    std::size_t layersChangedFireCount = 0;
    layerManager.signal_layersChanged().connect([&]()
    {
        ++layersChangedFireCount;
    });

    auto layerId =layerManager.createLayer(testLayerName);

    EXPECT_GT(layerId, 0) << "New layer must not have and ID of -1 or 0";
    EXPECT_EQ(getAllLayerNames(), std::vector({ _("Default"), testLayerName })) << "Expected two layers after creating a new one";
    EXPECT_EQ(layersChangedFireCount, 1) << "Layers changed signal should have been fired";
    EXPECT_TRUE(layerManager.layerExists(layerId)) << "The test layer should exist now";
}

TEST_F(LayerTest, CreateLayerWithId)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    const std::string testLayerName = "TestLayer";
    constexpr int testLayerId = 56;

    std::size_t layersChangedFireCount = 0;
    layerManager.signal_layersChanged().connect([&]()
    {
        ++layersChangedFireCount;
    });

    auto layerId = layerManager.createLayer(testLayerName, testLayerId);

    EXPECT_EQ(layerId, testLayerId) << "New layer needs to have the ID " << testLayerId;
    EXPECT_EQ(getAllLayerNames(), std::vector({ _("Default"), testLayerName })) << "Expected two layers after creating a new one";

    EXPECT_EQ(layerManager.getLayerID(testLayerName), testLayerId) << "getLayerID reported the wrong ID";
    EXPECT_EQ(layerManager.getLayerName(testLayerId), testLayerName) << "getLayerName reported the wrong Name";
    EXPECT_EQ(layersChangedFireCount, 1) << "Layers changed signal should have been fired";
    EXPECT_TRUE(layerManager.layerExists(layerId)) << "The test layer should exist now";
}

TEST_F(LayerTest, GetLayerId)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    EXPECT_NE(layerManager.getLayerID(_("Default")), -1) << "Default layer should return an ID";

    layerManager.createLayer("TestLayer");

    EXPECT_NE(layerManager.getLayerID("TestLayer"), -1) << "Layer exists, we should get an ID";
    EXPECT_EQ(layerManager.getLayerID("nonexistent_layer"), -1) << "Layer doesn't exist, yet we got an ID";
}

TEST_F(LayerTest, LayerExists)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    EXPECT_TRUE(layerManager.layerExists(0)) << "The default layer should always exist";
    EXPECT_FALSE(layerManager.layerExists(-1)) << "Layer ID -1 should never exist";

    EXPECT_FALSE(layerManager.layerExists(1)) << "Layer ID 1 should not exist";
    EXPECT_FALSE(layerManager.layerExists(540)) << "Layer ID 540 should not exist";
}

TEST_F(LayerTest, DefaultLayer)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    EXPECT_EQ(layerManager.getLayerID(_("Default")), 0) << "Default layer should have the ID 0";
    EXPECT_EQ(layerManager.getLayerName(0), _("Default")) << "Default layer should be named "<< _("Default");
    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "Default layer should be active";
    EXPECT_EQ(layerManager.layerIsVisible(0), true) << "Default layer should be visible";
}

TEST_F(LayerTest, DeleteDefaultLayer)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    auto defaultLayerName = layerManager.getLayerName(0);

    EXPECT_EQ(getAllLayerNames(), std::vector({ defaultLayerName })) << "Expected one default layer";

    std::size_t layersChangedFireCount = 0;
    layerManager.signal_layersChanged().connect([&]()
    {
        ++layersChangedFireCount;
    });

    // Attempting to delete the default layer doesn't work
    layerManager.deleteLayer(defaultLayerName);

    EXPECT_TRUE(layerManager.layerExists(0)) << "The default layer should still exist";
    EXPECT_EQ(getAllLayerNames(), std::vector({ defaultLayerName })) << "Expected still one default layer";
    EXPECT_EQ(layersChangedFireCount, 0) << "Layers changed signal should NOT have been fired";
}

TEST_F(LayerTest, DeleteLayer)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    const std::string testLayerName = "TestLayer";
    auto layerId = layerManager.createLayer(testLayerName);

    EXPECT_TRUE(layerManager.layerExists(layerId)) << "The test layer should have been created";
    EXPECT_EQ(layerManager.getLayerID(testLayerName), layerId) << "getLayerId reports a different ID";

    std::size_t layersChangedFireCount = 0;
    layerManager.signal_layersChanged().connect([&]()
    {
        ++layersChangedFireCount;
    });

    // Attempting to delete the default layer doesn't work
    layerManager.deleteLayer(testLayerName);

    EXPECT_EQ(layerManager.getLayerID(testLayerName), -1) << "The test layer should be gone now";
    EXPECT_EQ(layersChangedFireCount, 1) << "Layers changed signal should have been fired";
    EXPECT_FALSE(layerManager.layerExists(layerId)) << "The test layer should be gone now";
}

TEST_F(LayerTest, ResetLayerManager)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    auto testLayerId = layerManager.createLayer("TestLayer");
    auto testLayer2Id = layerManager.createLayer("TestLayer2");

    // Test Layer 2 is a child of Test Layer
    layerManager.setParentLayer(testLayer2Id, testLayerId);

    std::size_t layersChangedFireCount = 0;
    std::size_t layerVisibilityChangedFireCount = 0;
    std::size_t layerHierarchyChangedFireCount = 0;
    layerManager.signal_layersChanged().connect([&]() { ++layersChangedFireCount; });
    layerManager.signal_layerVisibilityChanged().connect([&]() { ++layerVisibilityChangedFireCount; });
    layerManager.signal_layerHierarchyChanged().connect([&]() { ++layerHierarchyChangedFireCount; });

    layerManager.reset();

    EXPECT_EQ(layerManager.getLayerID(_("Default")), 0) << "We should have a default layer after reset";
    EXPECT_EQ(layerManager.getLayerName(0), _("Default")) << "We should have a default layer after reset";

    EXPECT_EQ(layerManager.getLayerID("TestLayer"), -1) << "The test layer should be gone now";
    EXPECT_EQ(layerManager.getLayerID("TestLayer2"), -1) << "The test layer should be gone now";

    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "Default layer should be active";
    EXPECT_EQ(layerManager.layerIsVisible(0), true) << "Default layer should be visible";

    layerManager.foreachLayer([&](int layerId, const std::string& name)
    {
        EXPECT_EQ(layerManager.getParentLayer(layerId), -1) << "Parent relationship should have been reset";
    });

    EXPECT_EQ(layersChangedFireCount, 1) << "Layers changed signal should have been fired";
    EXPECT_EQ(layerVisibilityChangedFireCount, 1) << "Layer visibility changed signal should have been fired";
    EXPECT_EQ(layerHierarchyChangedFireCount, 1) << "Layer hierarchy changed signal should have been fired";
}

TEST_F(LayerTest, RenameLayer)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    const std::string testLayerName = "TestLayer";
    const std::string newName = "RenamedLayer";
    auto layerId = layerManager.createLayer(testLayerName);

    EXPECT_TRUE(layerManager.layerExists(layerId)) << "The test layer should have been created";
    EXPECT_EQ(layerManager.getLayerID(testLayerName), layerId) << "getLayerId reports a different ID";

    std::size_t layersChangedFireCount = 0;
    layerManager.signal_layersChanged().connect([&]()
    {
        ++layersChangedFireCount;
    });

    EXPECT_FALSE(layerManager.renameLayer(layerId, _("Default"))) << "Default name is not valid";
    EXPECT_EQ(layersChangedFireCount, 0) << "Layers changed signal should not have been fired";
    EXPECT_EQ(layerManager.getLayerID(testLayerName), layerId) << "The old name should still be valid";

    EXPECT_FALSE(layerManager.renameLayer(layerId, "")) << "Empty name is not valid";
    EXPECT_EQ(layersChangedFireCount, 0) << "Layers changed signal should not have been fired";
    EXPECT_EQ(layerManager.getLayerID(testLayerName), layerId) << "The old name should still be valid";

    // Rename the layer
    layerManager.renameLayer(layerId, newName);

    EXPECT_EQ(layersChangedFireCount, 1) << "Layers changed signal should have been fired";

    EXPECT_EQ(layerManager.getLayerID(testLayerName), -1) << "The old name should no longer be valid";
    EXPECT_EQ(layerManager.getLayerID(newName), layerId) << "The new name should now be valid";
}

TEST_F(LayerTest, GetFirstVisibleLayer)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    EXPECT_EQ(layerManager.getFirstVisibleLayer(), 0) << "The first visible layer should be the default layer after startup";

    const std::string testLayerName = "TestLayer";
    auto testLayerId = layerManager.createLayer(testLayerName);

    EXPECT_EQ(layerManager.getFirstVisibleLayer(), 0) << "The first visible layer should still be the default layer";

    // Hide the default layer, the first visible one is now the test layer
    layerManager.setLayerVisibility(0, false);
    EXPECT_EQ(layerManager.getFirstVisibleLayer(), testLayerId) << "The test layer is now the first visible one";

    layerManager.setLayerVisibility(0, true);
    EXPECT_EQ(layerManager.getFirstVisibleLayer(), 0) << "The default layer is now the first visible one again";

    // Hide the default layer again, then hide the second layer too
    layerManager.setLayerVisibility(0, false);
    EXPECT_EQ(layerManager.getFirstVisibleLayer(), testLayerId) << "The test layer is now the first visible one";
    layerManager.setLayerVisibility(testLayerId, false);

    EXPECT_EQ(getAllLayerIds(), std::vector({ 0, testLayerId })) << "No other layers should be present";
    EXPECT_EQ(layerManager.getFirstVisibleLayer(), 0) << "Even though nothing is visible, the default layer should have been returned";
}

TEST_F(LayerTest, GetActiveLayer)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "The active layer should be the default layer after startup";

    const std::string testLayerName = "TestLayer";
    auto testLayerId = layerManager.createLayer(testLayerName);

    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "The active layer should still be the default layer";

    // Hide the default layer, the active one is now the test layer
    layerManager.setLayerVisibility(0, false);
    EXPECT_EQ(layerManager.getActiveLayer(), testLayerId) << "The test layer is now active";

    layerManager.setLayerVisibility(0, true);
    EXPECT_EQ(layerManager.getActiveLayer(), testLayerId) << "The test layer remains active";

    // Hide all layers
    layerManager.setLayerVisibility(0, false);
    layerManager.setLayerVisibility(testLayerId, false);

    EXPECT_EQ(getAllLayerIds(), std::vector({ 0, testLayerId })) << "No other layers should be present";
    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "Even though nothing is visible, the default layer should be active";
}

TEST_F(LayerTest, SetActiveLayer)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "The active layer should be the default layer after startup";

    const std::string testLayerName = "TestLayer";
    auto testLayerId = layerManager.createLayer(testLayerName);

    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "The active layer should still be the default layer";

    layerManager.setActiveLayer(testLayerId);
    EXPECT_EQ(layerManager.getActiveLayer(), testLayerId) << "The test layer should now be active";

    layerManager.setActiveLayer(0);
    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "The default layer should now be active";

    // Hide all layers
    layerManager.setLayerVisibility(0, false);
    layerManager.setLayerVisibility(testLayerId, false);

    EXPECT_EQ(getAllLayerIds(), std::vector({ 0, testLayerId })) << "No other layers should be present";

    // It's still possible to set a hidden layer to active
    layerManager.setActiveLayer(0);
    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "The default layer should now be active";

    layerManager.setActiveLayer(testLayerId);
    EXPECT_EQ(layerManager.getActiveLayer(), testLayerId) << "The test layer should now be active";

    // Show the test layer, this doesn't change anything
    layerManager.setLayerVisibility(testLayerId, true);
    EXPECT_EQ(layerManager.getActiveLayer(), testLayerId) << "The test layer should now be active";

    // Showing the default layer shouldn't change the active layer
    layerManager.setLayerVisibility(0, true);
    EXPECT_EQ(layerManager.getActiveLayer(), testLayerId) << "The test layer should now be active";

    // Deleting the test layer should make the default one active
    layerManager.deleteLayer(testLayerName);
    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "The default layer should now be active";
}

TEST_F(LayerTest, LayerIsVisible)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    EXPECT_TRUE(layerManager.layerIsVisible(0)) << "The default layer should be visible";

    // It's possible to hide the default layer even if no other layer is there
    layerManager.setLayerVisibility(0, false);
    EXPECT_FALSE(layerManager.layerIsVisible(0)) << "The default layer should not be visible";

    const std::string testLayerName = "TestLayer";
    auto testLayerId = layerManager.createLayer(testLayerName);

    EXPECT_TRUE(layerManager.layerIsVisible(testLayerId)) << "The new layer should be visible after creation";
    EXPECT_FALSE(layerManager.layerIsVisible(0)) << "The default layer should not be visible";
    
    layerManager.setLayerVisibility(testLayerId, false);
    EXPECT_FALSE(layerManager.layerIsVisible(testLayerId)) << "The test layer should now be hidden";
    EXPECT_FALSE(layerManager.layerIsVisible(0)) << "The default layer should not be visible";

    // A non-existent Id should report as hidden
    EXPECT_FALSE(layerManager.layerIsVisible(-1)) << "The layer ID should report as hidden";
    EXPECT_FALSE(layerManager.layerIsVisible(testLayerId + 20)) << "A non-existent ID should report as hidden";
}

TEST_F(LayerTest, VisibilityChangedSignal)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    EXPECT_TRUE(layerManager.layerIsVisible(0)) << "The default layer should be visible";

    std::size_t layerVisibilityChangedFireCount = 0;
    std::size_t layersChangedFireCount = 0;
    layerManager.signal_layersChanged().connect([&]() { ++layersChangedFireCount; });
    layerManager.signal_layerVisibilityChanged().connect([&]() { ++layerVisibilityChangedFireCount; });

    // Trigger a visibility change
    layerManager.setLayerVisibility(0, false);

    EXPECT_EQ(layerVisibilityChangedFireCount, 1) << "Visibility changed signal should have been fired once";
    EXPECT_EQ(layersChangedFireCount, 0) << "Layers changed signal should NOT have been fired at all";

    // Hiding it again, doesn't trigger any signals
    layerVisibilityChangedFireCount = 0;
    layersChangedFireCount = 0;

    layerManager.setLayerVisibility(0, false);

    EXPECT_EQ(layerVisibilityChangedFireCount, 0) << "Visibility changed signal should not have been fired";
    EXPECT_EQ(layersChangedFireCount, 0) << "Layers changed signal should NOT have been fired at all";
}

TEST_F(LayerTest, SetLayerVisibilityAffectsActiveLayer)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    auto testLayerId = layerManager.createLayer("TestLayer");

    // Test how the visibility is affecting the active layer
    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "The active layer should still be the default layer";

    // Hide the default layer
    layerManager.setLayerVisibility(0, false);
    layerManager.setLayerVisibility(testLayerId, false);

    EXPECT_EQ(layerManager.getActiveLayer(), 0) << "The test layer should now be active";

    // All layers are hidden. Showing one of them will reinstate this layer as active
    layerManager.setLayerVisibility(testLayerId, true);
    EXPECT_EQ(layerManager.getActiveLayer(), testLayerId) << "The test layer should now be active";
}

TEST_F(LayerTest, SetLayerVisibilityUsingInvalidId)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    // Hide non-existent layers
    EXPECT_NO_THROW(layerManager.setLayerVisibility(333, false));
    EXPECT_NO_THROW(layerManager.setLayerVisibility(-2, false));
}

TEST_F(LayerTest, SetLayerVisibilityAffectsNode)
{
    loadMap("general_purpose.mapx");

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    // This brush is a member of layer 1
    auto brush = algorithm::findFirstBrushWithMaterial(GlobalMapModule().findOrInsertWorldspawn(), "textures/numbers/4");

    EXPECT_TRUE(brush->visible()) << "Brush should be visible";

    auto layers = brush->getLayers();
    EXPECT_NE(layers.find(1), layers.end()) << "Brush should be a member of layer 1";

    layerManager.setLayerVisibility(1, false);
    EXPECT_FALSE(brush->visible()) << "Brush should be hidden now";

    layerManager.setLayerVisibility(1, true);
    EXPECT_TRUE(brush->visible()) << "Brush should be visible again";
}

TEST_F(LayerTest, SetLayerVisibilityWorksRecursively)
{
    loadMap("layer_hierarchy_restore.mapx");

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    auto testLayer2Id = layerManager.getLayerID("Test2");
    auto testLayer7Id = layerManager.getLayerID("Test7");
    auto boardsLayerId = layerManager.getLayerID("BoardsandStuff");
    EXPECT_EQ(layerManager.getParentLayer(testLayer2Id), boardsLayerId) << "Test setup is wrong";
    EXPECT_EQ(layerManager.getParentLayer(testLayer7Id), testLayer2Id) << "Test setup is wrong";

    // Move the worldspawn to the grand-child layer
    auto worldspawn = GlobalMapModule().findOrInsertWorldspawn();
    Node_setSelected(worldspawn, true);
    layerManager.moveSelectionToLayer(testLayer7Id);
    Node_setSelected(worldspawn, false);

    EXPECT_TRUE(worldspawn->visible());

    // Hide the parent layer, this should affect the child layer
    layerManager.setLayerVisibility(boardsLayerId, false);
    EXPECT_FALSE(worldspawn->visible()) << "Worldspawn should be hidden now";

    EXPECT_FALSE(layerManager.layerIsVisible(testLayer7Id)) <<
        "The parent layer visibility should have propagated down to the boards layer";
    EXPECT_FALSE(layerManager.layerIsVisible(testLayer2Id)) <<
        "The parent layer visibility should have propagated down to the boards layer";

    layerManager.setLayerVisibility(boardsLayerId, true);
    EXPECT_TRUE(worldspawn->visible()) << "Worldspawn should be visible again";

    EXPECT_TRUE(layerManager.layerIsVisible(testLayer7Id)) <<
        "The parent layer visibility should have propagated down to the boards layer";
    EXPECT_TRUE(layerManager.layerIsVisible(testLayer2Id)) <<
        "The parent layer visibility should have propagated down to the boards layer";
}

TEST_F(LayerTest, GetParentLayer)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    EXPECT_EQ(layerManager.getParentLayer(0), -1) << "Default layer doesn't have a parent";

    // Set a parent, query again
    auto someLayerId = layerManager.createLayer("SomeLayer");
    layerManager.setParentLayer(someLayerId, 0);
    EXPECT_EQ(layerManager.getParentLayer(someLayerId), 0);

    // Layer ID -1 is not throwing
    EXPECT_NO_THROW(layerManager.getParentLayer(-1));

    // Any other invalid ID should throw
    EXPECT_THROW(layerManager.getParentLayer(3434), std::out_of_range);
}

TEST_F(LayerTest, SetLayerParent)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    auto parentLayerId = layerManager.createLayer("ParentLayer");
    auto childLayerId = layerManager.createLayer("ChildLayer");

    EXPECT_EQ(layerManager.getParentLayer(0), -1) << "Default layer cannot have a parent";
    EXPECT_EQ(layerManager.getParentLayer(parentLayerId), -1) << "ParentLayer doesn't have a parent yet";
    EXPECT_EQ(layerManager.getParentLayer(childLayerId), -1) << "ChildLayer doesn't have a parent yet";

    // It's not valid to assign a parent to the default layer, unless it's -1
    EXPECT_NO_THROW(layerManager.setParentLayer(0, -1));
    EXPECT_THROW(layerManager.setParentLayer(0, parentLayerId), std::invalid_argument);
    EXPECT_THROW(layerManager.setParentLayer(0, 3333), std::invalid_argument);

    // It's not allowed to assign a layer as its own parent
    EXPECT_THROW(layerManager.setParentLayer(parentLayerId, parentLayerId), std::invalid_argument);

    // Assigning an invalid parent to a valid child layer throws
    EXPECT_THROW(layerManager.setParentLayer(childLayerId, 2222), std::invalid_argument);
    // Assigning a valid parent to an invalid child layer throws
    EXPECT_THROW(layerManager.setParentLayer(2222, parentLayerId), std::invalid_argument);

    // This is a valid operation
    EXPECT_NO_THROW(layerManager.setParentLayer(childLayerId, parentLayerId));
    EXPECT_EQ(layerManager.getParentLayer(childLayerId), parentLayerId) << "Parent Id has not been assigned";
    // It's ok to do it again
    EXPECT_NO_THROW(layerManager.setParentLayer(childLayerId, parentLayerId));

    // Remove the parent again
    EXPECT_NO_THROW(layerManager.setParentLayer(childLayerId, -1));
    EXPECT_EQ(layerManager.getParentLayer(childLayerId), -1) << "Parent Id has not been removed";
    // It's ok to do it again
    EXPECT_NO_THROW(layerManager.setParentLayer(childLayerId, -1));
    EXPECT_EQ(layerManager.getParentLayer(childLayerId), -1) << "Parent Id has not been removed";

    // Assign a parentLayer, then reassign it to a different parent
    EXPECT_NO_THROW(layerManager.setParentLayer(childLayerId, parentLayerId));
    EXPECT_NO_THROW(layerManager.setParentLayer(childLayerId, 0));
    EXPECT_EQ(layerManager.getParentLayer(childLayerId), 0) << "Parent Id has not been reassigned";
}

TEST_F(LayerTest, SetLayerParentRecursionDetection)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    auto grandParentLayerId = layerManager.createLayer("GrandParentLayer");
    auto parentLayerId = layerManager.createLayer("ParentLayer");
    auto childLayerId = layerManager.createLayer("ChildLayer");

    EXPECT_EQ(layerManager.getParentLayer(0), -1) << "Default layer cannot have a parent";
    EXPECT_EQ(layerManager.getParentLayer(grandParentLayerId), -1) << "GrandParentLayer doesn't have a parent yet";
    EXPECT_EQ(layerManager.getParentLayer(parentLayerId), -1) << "ParentLayer doesn't have a parent yet";
    EXPECT_EQ(layerManager.getParentLayer(childLayerId), -1) << "ChildLayer doesn't have a parent yet";

    // Form a straight line GrandParent > Parent > Child
    layerManager.setParentLayer(childLayerId, parentLayerId);
    layerManager.setParentLayer(parentLayerId, grandParentLayerId);

    // Then try to assign Child as a parent to its own GrandParent => recursion detection should throw
    EXPECT_THROW(layerManager.setParentLayer(grandParentLayerId, childLayerId), std::invalid_argument);
}

TEST_F(LayerTest, HierarchyChangedSignal)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    auto testLayerId = layerManager.createLayer("TestLayer");
    auto testLayer2Id = layerManager.createLayer("TestLayer2");

    std::size_t layerVisibilityChangedFireCount = 0;
    std::size_t layersChangedFireCount = 0;
    std::size_t layerHierarchyChangedFireCount = 0;
    layerManager.signal_layersChanged().connect([&]() { ++layersChangedFireCount; });
    layerManager.signal_layerVisibilityChanged().connect([&]() { ++layerVisibilityChangedFireCount; });
    layerManager.signal_layerHierarchyChanged().connect([&]() { ++layerHierarchyChangedFireCount; });

    // Trigger a hierarchy change
    layerManager.setParentLayer(testLayer2Id, testLayerId);

    EXPECT_EQ(layerHierarchyChangedFireCount, 1) << "Hierarchy changed signal should have been fired once";
    EXPECT_EQ(layerVisibilityChangedFireCount, 0) << "Visibility changed signal should not have been fired";
    EXPECT_EQ(layersChangedFireCount, 0) << "Layers changed signal should NOT have been fired at all";

    // Hiding it again, doesn't trigger any signals
    layerHierarchyChangedFireCount = 0;
    layerVisibilityChangedFireCount = 0;
    layersChangedFireCount = 0;

    layerManager.setParentLayer(testLayer2Id, testLayerId);

    EXPECT_EQ(layerHierarchyChangedFireCount, 0) << "Hierarchy changed signal should not have been fired";
    EXPECT_EQ(layerVisibilityChangedFireCount, 0) << "Visibility changed signal should not have been fired";
    EXPECT_EQ(layersChangedFireCount, 0) << "Layers changed signal should NOT have been fired at all";

    layerManager.setParentLayer(testLayer2Id, 0);
    layerManager.setParentLayer(testLayer2Id, -1);

    EXPECT_EQ(layerHierarchyChangedFireCount, 2) << "Hierarchy changed signal should have been fired twice";
    EXPECT_EQ(layerVisibilityChangedFireCount, 0) << "Visibility changed signal should not have been fired";
    EXPECT_EQ(layersChangedFireCount, 0) << "Layers changed signal should NOT have been fired at all";
}

void loadAndExpectLayersToBeRestored(const std::string& mapFilePath, const std::vector<int>& expectedLayerIds)
{
    // Clear the current map, discarding the changes
    FileSaveConfirmationHelper helper(radiant::FileSaveConfirmation::Action::DiscardChanges);
    GlobalCommandSystem().executeCommand("NewMap");

    // The layers are gone now
    EXPECT_EQ(getAllLayerIds(), std::vector{ 0 }) << "All layers should have been cleared, except for the default";

    // Then load the map from that temporary path
    EXPECT_TRUE(os::fileOrDirExists(mapFilePath));
    GlobalCommandSystem().executeCommand("OpenMap", mapFilePath);

    auto unsortedLayerIds = getAllLayerIds();
    auto layerIds = std::set(unsortedLayerIds.begin(), unsortedLayerIds.end());

    EXPECT_EQ(layerIds.size(), expectedLayerIds.size()) << "Expected layer count not matching";

    for (auto expectedId : expectedLayerIds)
    {
        EXPECT_EQ(layerIds.count(expectedId), 1) << "Layer ID " << expectedId << " not present";
    }
}

void runLayerHierarchyPersistenceTest(const std::string& mapFilePath)
{
    GlobalMapModule().findOrInsertWorldspawn(); // to not save an empty map

    TemporaryFile tempSavedFile(mapFilePath);

    auto* layerManager = &GlobalMapModule().getRoot()->getLayerManager();
    auto parentLayerId = layerManager->createLayer("ParentLayer");
    auto childLayerId = layerManager->createLayer("ChildLayer");
    auto childLayer2Id = layerManager->createLayer("ChildLayer2");
    auto childLayer3Id = layerManager->createLayer("ChildLayer3");

    // Default > Parent > Child 
    layerManager->setParentLayer(childLayerId, parentLayerId);
    layerManager->setParentLayer(parentLayerId, 0);

    // Default > Child2
    layerManager->setParentLayer(childLayer2Id, 0);

    // Child3 remains a top-level layer

    EXPECT_FALSE(os::fileOrDirExists(mapFilePath));
    GlobalCommandSystem().executeCommand("SaveMapCopyAs", mapFilePath);

    loadAndExpectLayersToBeRestored(mapFilePath, { 0, parentLayerId, childLayerId, childLayer2Id, childLayer3Id });

    // We changed maps, so acquire a new layer manager reference
    layerManager = &GlobalMapModule().getRoot()->getLayerManager();
    EXPECT_EQ(layerManager->getParentLayer(childLayerId), parentLayerId) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager->getParentLayer(parentLayerId), 0) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager->getParentLayer(childLayer2Id), 0) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager->getParentLayer(childLayer3Id), -1) << "Hierarchy has not been restored";
}

TEST_F(LayerTest, LayerHierarchyIsPersistedToMapx)
{
    fs::path tempPath = _context.getTemporaryDataPath();
    tempPath /= "layer_hierarchy_test.mapx";

    runLayerHierarchyPersistenceTest(tempPath.string());
}

TEST_F(LayerTest, LayerHierarchyIsPersistedToMap)
{
    fs::path tempPath = _context.getTemporaryDataPath();
    tempPath /= "layer_hierarchy_test.map";
    // Remove the .darkradiant file after this test
    TemporaryFile tempDarkRadiantFile(os::replaceExtension(tempPath.string(), "darkradiant"));

    runLayerHierarchyPersistenceTest(tempPath.string());
}

TEST_F(LayerTest, LayerHierarchyIsRestoredFromMapx)
{
    // The .mapx file contains a hierarchy that should be restored
    // without running into crashes (layer 3 is a child of layer 9)
    auto mapFilePath = _context.getTestProjectPath() + "maps/layer_hierarchy_restore.mapx";

    GlobalCommandSystem().executeCommand("OpenMap", mapFilePath);

    auto unsortedLayerIds = getAllLayerIds();
    auto layerIds = std::set(unsortedLayerIds.begin(), unsortedLayerIds.end());

    for (int i = 0; i <= 9; ++i)
    {
        EXPECT_EQ(layerIds.count(0), 1) << "Layer with ID " << i << " not present";
    }

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    EXPECT_EQ(layerManager.getParentLayer(0), -1) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager.getParentLayer(3), 9) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager.getParentLayer(4), 2) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager.getParentLayer(5), 3) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager.getParentLayer(9), 2) << "Hierarchy has not been restored";
}

TEST_F(LayerTest, LayerHierarchyIsRestoredFromMap)
{
    // The .darkradiant file contains a hierarchy that should be restored
    // without running into crashes (layer 3 is a child of layer 9)
    auto mapFilePath = _context.getTestProjectPath() + "maps/layer_hierarchy_restore.map";

    GlobalCommandSystem().executeCommand("OpenMap", mapFilePath);

    auto unsortedLayerIds = getAllLayerIds();
    auto layerIds = std::set(unsortedLayerIds.begin(), unsortedLayerIds.end());

    for (int i = 0; i <= 9; ++i)
    {
        EXPECT_EQ(layerIds.count(0), 1) << "Layer with ID " << i << " not present";
    }

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    EXPECT_EQ(layerManager.getParentLayer(0), -1) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager.getParentLayer(3), 9) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager.getParentLayer(4), 2) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager.getParentLayer(5), 3) << "Hierarchy has not been restored";
    EXPECT_EQ(layerManager.getParentLayer(9), 2) << "Hierarchy has not been restored";
}

TEST_F(LayerTest, LayerIsChildOf)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    auto grandParentLayerId = layerManager.createLayer("GrandParentLayer");
    auto parentLayerId = layerManager.createLayer("ParentLayer");
    auto childLayerId = layerManager.createLayer("ChildLayer");
    auto otherLayerId = layerManager.createLayer("OtherLayer");

    // Form a straight line GrandParent > Parent > Child
    layerManager.setParentLayer(childLayerId, parentLayerId);
    layerManager.setParentLayer(parentLayerId, grandParentLayerId);

    EXPECT_TRUE(layerManager.layerIsChildOf(childLayerId, parentLayerId)) << "Child should be a descendent of parent";
    EXPECT_TRUE(layerManager.layerIsChildOf(childLayerId, grandParentLayerId)) << "Child should be a descendent of grand parent";

    EXPECT_FALSE(layerManager.layerIsChildOf(-1, parentLayerId)) << "One ID is -1, should return false";
    EXPECT_FALSE(layerManager.layerIsChildOf(childLayerId, -1)) << "One ID is -1, should return false";
    EXPECT_FALSE(layerManager.layerIsChildOf(-1, -1)) << "Both ids are -1, should return false";

    EXPECT_FALSE(layerManager.layerIsChildOf(childLayerId, childLayerId)) << "Both ids are the same, should return false";

    EXPECT_FALSE(layerManager.layerIsChildOf(otherLayerId, parentLayerId)) << "OtherLayer is not a descendent of parent";
    EXPECT_FALSE(layerManager.layerIsChildOf(otherLayerId, grandParentLayerId)) << "OtherLayer is not a descendent of parent";
    EXPECT_FALSE(layerManager.layerIsChildOf(otherLayerId, 0)) << "OtherLayer is not a descendent of parent";

    EXPECT_FALSE(layerManager.layerIsChildOf(0, -1)) << "Even though Default has no parent, this should return -1";
    EXPECT_FALSE(layerManager.layerIsChildOf(0, grandParentLayerId)) << "Default is not a descendant of grand parent";
}

TEST_F(LayerTest, SelectLayer)
{
    loadMap("layer_hierarchy_restore.mapx");

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    auto testLayer2Id = layerManager.getLayerID("Test2");
    
    // Create brushes and move them into layers
    auto brush1 = algorithm::createCubicBrush(GlobalMapModule().findOrInsertWorldspawn(), { 200, 300, 100 }, "textures/numbers/1");
    auto brush2 = algorithm::createCubicBrush(GlobalMapModule().findOrInsertWorldspawn(), { 200, 300, 100 }, "textures/numbers/2");
    auto brush3 = algorithm::createCubicBrush(GlobalMapModule().findOrInsertWorldspawn(), { 200, 300, 100 }, "textures/numbers/3");
    auto brush4 = algorithm::createCubicBrush(GlobalMapModule().findOrInsertWorldspawn(), { 200, 300, 100 }, "textures/numbers/4");

    Node_setSelected(brush1, true);
    Node_setSelected(brush2, true);
    layerManager.moveSelectionToLayer(testLayer2Id);
    Node_setSelected(brush1, false);
    Node_setSelected(brush2, false);

    EXPECT_FALSE(Node_isSelected(brush1));
    EXPECT_FALSE(Node_isSelected(brush2));
    EXPECT_FALSE(Node_isSelected(brush3));
    Node_setSelected(brush4, true); // this selection status should survive the process

    // Use the layer interface to select test layer 2
    layerManager.setSelected(testLayer2Id, true);

    EXPECT_TRUE(Node_isSelected(brush1)) << "Brush 1 should be selected";
    EXPECT_TRUE(Node_isSelected(brush2)) << "Brush 2 should be selected";
    EXPECT_FALSE(Node_isSelected(brush3)) << "Brush 3 should still be unselected";
    EXPECT_TRUE(Node_isSelected(brush4)) << "Brush 4 should remain selected";

    // De-select the layer again
    layerManager.setSelected(testLayer2Id, false);

    EXPECT_FALSE(Node_isSelected(brush1)) << "Brush 1 should not be selected anymore";
    EXPECT_FALSE(Node_isSelected(brush2)) << "Brush 2 should not be selected anymore";
    EXPECT_FALSE(Node_isSelected(brush3)) << "Brush 3 should still be unselected";
    EXPECT_TRUE(Node_isSelected(brush4)) << "Brush 4 should remain selected";
}

TEST_F(LayerTest, SelectLayerWorksRecursively)
{
    loadMap("layer_hierarchy_restore.mapx");

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    auto testLayer2Id = layerManager.getLayerID("Test2");
    auto testLayer7Id = layerManager.getLayerID("Test7");
    auto boardsLayerId = layerManager.getLayerID("BoardsandStuff");
    EXPECT_EQ(layerManager.getParentLayer(testLayer2Id), boardsLayerId) << "Test setup is wrong";
    EXPECT_EQ(layerManager.getParentLayer(testLayer7Id), testLayer2Id) << "Test setup is wrong";

    // Create brushes and move them into the layer hierarchy
    auto brush1 = algorithm::createCubicBrush(GlobalMapModule().findOrInsertWorldspawn(), { 200, 300, 100 }, "textures/numbers/1");
    auto brush2 = algorithm::createCubicBrush(GlobalMapModule().findOrInsertWorldspawn(), { 200, 300, 100 }, "textures/numbers/2");
    auto brush3 = algorithm::createCubicBrush(GlobalMapModule().findOrInsertWorldspawn(), { 200, 300, 100 }, "textures/numbers/3");
    auto brush4 = algorithm::createCubicBrush(GlobalMapModule().findOrInsertWorldspawn(), { 200, 300, 100 }, "textures/numbers/4");

    // Brushes 1 and 2 go to test layer 7
    Node_setSelected(brush1, true);
    Node_setSelected(brush2, true);
    layerManager.moveSelectionToLayer(testLayer7Id);
    Node_setSelected(brush1, false);
    Node_setSelected(brush2, false);

    // Brush 3 goes to the parent layer Test2
    Node_setSelected(brush3, true);
    layerManager.moveSelectionToLayer(testLayer2Id);
    Node_setSelected(brush3, false);

    // Brush 4 remains in the grand parent layer
    Node_setSelected(brush4, true);
    layerManager.moveSelectionToLayer(boardsLayerId);
    Node_setSelected(brush4, false);

    EXPECT_FALSE(Node_isSelected(brush1));
    EXPECT_FALSE(Node_isSelected(brush2));
    EXPECT_FALSE(Node_isSelected(brush3));
    EXPECT_FALSE(Node_isSelected(brush4));

    // Use the layer interface to select the grand parent, this should affect all child layers
    layerManager.setSelected(boardsLayerId, true);

    EXPECT_TRUE(Node_isSelected(brush1)) << "Brush 1 should be selected";
    EXPECT_TRUE(Node_isSelected(brush2)) << "Brush 2 should be selected";
    EXPECT_TRUE(Node_isSelected(brush3)) << "Brush 3 should be unselected";
    EXPECT_TRUE(Node_isSelected(brush4)) << "Brush 4 should be selected";

    // De-select the layer again
    layerManager.setSelected(boardsLayerId, false);

    EXPECT_FALSE(Node_isSelected(brush1)) << "Brush 1 should not be selected anymore";
    EXPECT_FALSE(Node_isSelected(brush2)) << "Brush 2 should not be selected anymore";
    EXPECT_FALSE(Node_isSelected(brush3)) << "Brush 3 should not be selected anymore";
    EXPECT_FALSE(Node_isSelected(brush4)) << "Brush 4 should not be selected anymore";
}

TEST_F(LayerTest, CreateLayerMarksMapAsModified)
{
    loadMap("general_purpose.mapx");

    EXPECT_FALSE(GlobalMapModule().isModified());

    GlobalCommandSystem().executeCommand("CreateLayer", cmd::Argument("TestLayer"));

    EXPECT_TRUE(GlobalMapModule().isModified());
}

TEST_F(LayerTest, RenameLayerMarksMapAsModified)
{
    loadMap("general_purpose.mapx");

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    EXPECT_FALSE(GlobalMapModule().isModified());
    auto layerId = layerManager.getLayerID("Second Layer");
    EXPECT_NE(layerId, -1);

    GlobalCommandSystem().executeCommand("RenameLayer", cmd::Argument(layerId), cmd::Argument("Renamed Layer"));

    EXPECT_TRUE(GlobalMapModule().isModified());
}

TEST_F(LayerTest, DeleteLayerMarksMapAsModified)
{
    loadMap("general_purpose.mapx");

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    EXPECT_FALSE(GlobalMapModule().isModified());
    auto layerId = layerManager.getLayerID("Second Layer");
    EXPECT_NE(layerId, -1);

    GlobalCommandSystem().executeCommand("DeleteLayer", cmd::Argument(layerId));

    EXPECT_TRUE(GlobalMapModule().isModified());
}

enum class LayerAction
{
    AddToLayer,
    RemoveFromLayer,
    MoveToLayer,
};

void performMoveOrAddToLayerTest(LayerAction action)
{
    auto brush = algorithm::findFirstBrushWithMaterial(
        GlobalMapModule().findOrInsertWorldspawn(), "textures/numbers/1");
    EXPECT_TRUE(brush);

    Node_setSelected(brush, true);

    EXPECT_FALSE(GlobalMapModule().isModified());

    auto layerId = GlobalMapModule().getRoot()->getLayerManager().getLayerID("Second Layer");
    EXPECT_NE(layerId, -1);

    switch (action)
    {
    case LayerAction::AddToLayer:
        GlobalCommandSystem().executeCommand("AddSelectionToLayer", cmd::Argument(layerId));
        break;
    case LayerAction::MoveToLayer:
        GlobalCommandSystem().executeCommand("MoveSelectionToLayer", cmd::Argument(layerId));
        break;
    case LayerAction::RemoveFromLayer:
        GlobalCommandSystem().executeCommand("RemoveSelectionFromLayer", cmd::Argument(layerId));
        break;
    }

    EXPECT_TRUE(GlobalMapModule().isModified());
}

TEST_F(LayerTest, AddingToLayerMarksMapAsModified)
{
    loadMap("general_purpose.mapx");

    performMoveOrAddToLayerTest(LayerAction::AddToLayer);
}

TEST_F(LayerTest, MovingToLayerMarksMapAsModified)
{
    loadMap("general_purpose.mapx");

    performMoveOrAddToLayerTest(LayerAction::MoveToLayer);
}

TEST_F(LayerTest, RemovingFromLayerMarksMapAsModified)
{
    loadMap("general_purpose.mapx");

    performMoveOrAddToLayerTest(LayerAction::RemoveFromLayer);
}

TEST_F(LayerTest, SettingParentLayerMarksMapAsModified)
{
    loadMap("general_purpose.mapx");

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    auto secondLayerId = layerManager.getLayerID("Second Layer");
    auto thirdLayerId = layerManager.getLayerID("Third Layer");

    EXPECT_FALSE(GlobalMapModule().isModified());

    layerManager.setParentLayer(thirdLayerId, secondLayerId);

    EXPECT_TRUE(GlobalMapModule().isModified());
}

// #6115: Selecting and deselecting a filtered child brush through layers leaves the brush selected
TEST_F(LayerTest, SelectFilteredChildPrimitive)
{
    loadMap("selecting_filtered_items_with_layers.mapx");

    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();
    auto caulkLayerId = layerManager.getLayerID("Caulk");

    auto func_static_1 = algorithm::getEntityByName(GlobalMapModule().getRoot(), "func_static_1");
    auto childPrimitive = algorithm::findFirstBrushWithMaterial(func_static_1, "textures/common/caulk");

    EXPECT_EQ(childPrimitive->getLayers(), scene::LayerList{ caulkLayerId }) << "Unexpected layer setup";
    EXPECT_TRUE(childPrimitive->visible()) << "The brush should be visible after map load";

    // Activate the filter hiding the caulk brush
    GlobalFilterSystem().setFilterState("Caulk", true);

    EXPECT_FALSE(childPrimitive->visible()) << "The filter should have hidden the brush";

    // Now select the layer, this should set the brush to visible
    // because the parent entity selection implies a forced-visible state on the brush
    layerManager.setSelected(caulkLayerId, true);

    EXPECT_TRUE(childPrimitive->visible()) << "Selecting the layer should set the brush to visible";

    EXPECT_TRUE(Node_isSelected(func_static_1)) << "Selecting the layer should have selected func_static_1";
    EXPECT_TRUE(Node_isSelected(childPrimitive)) << "Selecting the layer selected the brush since it was forced visible";

    layerManager.setSelected(caulkLayerId, false);

    EXPECT_FALSE(Node_isSelected(func_static_1)) << "De-selecting the layer should have de-selected func_static_1";
    EXPECT_FALSE(Node_isSelected(childPrimitive)) << "De-selecting the layer shouldn't leave the brush selected";
}

void runLayerVisibilityPersistenceTest(const std::string& mapFilePath)
{
    auto worldspawn = GlobalMapModule().findOrInsertWorldspawn(); // to not save an empty map

    // Create two brushes
    auto brush1 = algorithm::createCubicBrush(worldspawn);
    Node_getIBrush(brush1)->setShader("textures/numbers/1");
    auto brush2 = algorithm::createCubicBrush(worldspawn);
    Node_getIBrush(brush2)->setShader("textures/numbers/2");

    TemporaryFile tempSavedFile(mapFilePath);

    auto* layerManager = &GlobalMapModule().getRoot()->getLayerManager();
    auto layer1Id = layerManager->createLayer("Layer1");
    auto layer2Id = layerManager->createLayer("Layer2");
    auto layer3Id = layerManager->createLayer("Layer3");
    auto layer4Id = layerManager->createLayer("Layer4");

    // Brush 1 goes into Layer 1
    Node_setSelected(brush1, true);
    layerManager->moveSelectionToLayer(layer1Id);
    Node_setSelected(brush1, false);

    // Brush 2 goes into Layer 2
    Node_setSelected(brush2, true);
    layerManager->moveSelectionToLayer(layer2Id);
    Node_setSelected(brush2, false);

    // Set layers 1 and 3 to hidden
    layerManager->setLayerVisibility(layer1Id, false);
    layerManager->setLayerVisibility(layer3Id, false);

    EXPECT_FALSE(os::fileOrDirExists(mapFilePath));
    GlobalCommandSystem().executeCommand("SaveMapCopyAs", mapFilePath);

    // Prevent crashes when switching maps while holding strong refs to nodes
    worldspawn.reset();
    brush1.reset();
    brush2.reset();

    loadAndExpectLayersToBeRestored(mapFilePath, { 0, layer1Id, layer2Id, layer3Id, layer4Id });

    // We changed maps, so acquire a new layer manager reference
    layerManager = &GlobalMapModule().getRoot()->getLayerManager();
    EXPECT_FALSE(layerManager->layerIsVisible(layer1Id)) << "Visibility has not been restored";
    EXPECT_TRUE(layerManager->layerIsVisible(layer2Id)) << "Visibility has not been restored";
    EXPECT_FALSE(layerManager->layerIsVisible(layer3Id)) << "Visibility has not been restored";
    EXPECT_TRUE(layerManager->layerIsVisible(layer4Id)) << "Visibility has not been restored";

    // Expect that brush 1 is invisible, brush 2 should be shown
    worldspawn = GlobalMapModule().findOrInsertWorldspawn();
    brush1 = algorithm::findFirstBrushWithMaterial(worldspawn, "textures/numbers/1");
    brush2 = algorithm::findFirstBrushWithMaterial(worldspawn, "textures/numbers/2");

    EXPECT_FALSE(brush1->visible()) << "Brush 1 should be invisible since Layer 1 is hidden";
    EXPECT_TRUE(brush2->visible()) << "Brush 2 should be visible since Layer 2 is visible";

    EXPECT_TRUE(brush1->checkStateFlag(scene::Node::eLayered)) << "Brush 1 should be invisible due to layering";
    EXPECT_FALSE(brush2->checkStateFlag(scene::Node::eLayered)) << "Brush 2 should not be invisible due to layering";
}

TEST_F(LayerTest, LayerVisibilityIsPersistedToMap)
{
    fs::path tempPath = _context.getTemporaryDataPath();
    tempPath /= "layer_visibility_test.map";

    // Remove the .darkradiant file after this test
    TemporaryFile tempDarkRadiantFile(os::replaceExtension(tempPath.string(), "darkradiant"));

    runLayerVisibilityPersistenceTest(tempPath.string());
}

TEST_F(LayerTest, LayerVisibilityIsPersistedToMapx)
{
    fs::path tempPath = _context.getTemporaryDataPath();
    tempPath /= "layer_visibility_test.mapx";

    runLayerVisibilityPersistenceTest(tempPath.string());
}

void runLayerActiveStatusPersistenceTest(const std::string& mapFilePath)
{
    GlobalMapModule().findOrInsertWorldspawn(); // to not save an empty map

    TemporaryFile tempSavedFile(mapFilePath);

    auto* layerManager = &GlobalMapModule().getRoot()->getLayerManager();
    auto layer1Id = layerManager->createLayer("Layer1");
    auto layer2Id = layerManager->createLayer("Layer2");

    EXPECT_EQ(layerManager->getActiveLayer(), 0) << "Default layer should be active";

    // Set layer 2 to active
    layerManager->setActiveLayer(layer2Id);

    EXPECT_FALSE(os::fileOrDirExists(mapFilePath));
    GlobalCommandSystem().executeCommand("SaveMapCopyAs", mapFilePath);

    loadAndExpectLayersToBeRestored(mapFilePath, { 0, layer1Id, layer2Id });

    // We changed maps, so acquire a new layer manager reference
    layerManager = &GlobalMapModule().getRoot()->getLayerManager();
    EXPECT_EQ(layerManager->getActiveLayer(), layer2Id) << "Active layer has not been restored";
}

TEST_F(LayerTest, LayerActiveStatusIsPersistedToMap)
{
    fs::path tempPath = _context.getTemporaryDataPath();
    tempPath /= "layer_active_status_test.map";

    // Remove the .darkradiant file after this test
    TemporaryFile tempDarkRadiantFile(os::replaceExtension(tempPath.string(), "darkradiant"));

    runLayerActiveStatusPersistenceTest(tempPath.string());
}

TEST_F(LayerTest, LayerActiveStatusIsPersistedToMapx)
{
    fs::path tempPath = _context.getTemporaryDataPath();
    tempPath /= "layer_active_status_test.mapx";

    runLayerActiveStatusPersistenceTest(tempPath.string());
}

inline void replacePropertiesBlock(const std::string& infoFilePath, const std::string& replacement)
{
    auto contents = algorithm::loadFileToString(infoFilePath);

    std::list<std::string> lines;
    string::split(lines, contents, "\n\r");

    contents.clear();
    for (auto line = lines.begin(); line != lines.end(); ++line)
    {
        if (string::trim_copy(*line) == "LayerProperties")
        {
            ++line; // skip LayerProperties
            ++line; // skip the opening brace

            while (string::trim_copy(*line) != "}")
            {
                ++line;
            }

            // Add the replacement block here
            contents.append(replacement);
            contents.append("\n");
            continue;
        }

        contents.append(*line);
        contents.append("\n");
    }

    algorithm::replaceFileContents(infoFilePath, contents);
}

TEST_F(LayerTest, ParseEmptyLayerPropertiesBlock)
{
    fs::path mapFilePath = _context.getTestProjectPath();
    mapFilePath /= "maps/layer_hierarchy_restore.map";

    // Restore the .darkradiant file after this test
    auto infoFilePath = os::replaceExtension(mapFilePath.string(), "darkradiant");
    BackupCopy copy(infoFilePath);

    replacePropertiesBlock(infoFilePath, R"(    LayerProperties
    {
    })");

    loadAndExpectLayersToBeRestored(mapFilePath.string(), {0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getParentLayer(3), 9) << "Failed to restore hierarchy";
}

TEST_F(LayerTest, ParseLayerPropertiesActiveLayer)
{
    fs::path mapFilePath = _context.getTestProjectPath();
    mapFilePath /= "maps/layer_hierarchy_restore.map";

    // Restore the .darkradiant file after this test
    auto infoFilePath = os::replaceExtension(mapFilePath.string(), "darkradiant");
    BackupCopy backupCopy(infoFilePath);

    // Throw in a few potentially problematic cases.
    // The hierarchy should still restore as planned
    replacePropertiesBlock(infoFilePath, R"(LayerProperties { ActiveLayer { -2 } })");
    loadAndExpectLayersToBeRestored(mapFilePath.string(), { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getParentLayer(3), 9) << "Failed to restore hierarchy";
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getActiveLayer(), 0) << "Active layer should be default";
    backupCopy.restoreNow();

    replacePropertiesBlock(infoFilePath, R"(LayerProperties { ActiveLayer { 36545634 } })");
    loadAndExpectLayersToBeRestored(mapFilePath.string(), { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getParentLayer(3), 9) << "Failed to restore hierarchy";
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getActiveLayer(), 0) << "Active layer should be default";
    backupCopy.restoreNow();

    replacePropertiesBlock(infoFilePath, R"(LayerProperties { ActiveLayer { abc } })");
    loadAndExpectLayersToBeRestored(mapFilePath.string(), { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getParentLayer(3), 9) << "Failed to restore hierarchy";
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getActiveLayer(), 0) << "Active layer should be default";
    backupCopy.restoreNow();

    // Now the positive test case
    replacePropertiesBlock(infoFilePath, R"(LayerProperties { ActiveLayer { 3 } })");
    loadAndExpectLayersToBeRestored(mapFilePath.string(), { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getParentLayer(3), 9) << "Failed to restore hierarchy";
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getActiveLayer(), 3) << "Failed to restore active layer";
    backupCopy.restoreNow();
}

void expectLayersAreVisible(const std::vector<int>& layerIds, bool expectVisible)
{
    auto& layerManager = GlobalMapModule().getRoot()->getLayerManager();

    for (auto id : layerIds)
    {
        EXPECT_EQ(layerManager.layerIsVisible(id), expectVisible) << "Layer ID " << id << " didn't meet visibility expectation";
    }
}

TEST_F(LayerTest, ParseLayerPropertiesHiddenLayers)
{
    fs::path mapFilePath = _context.getTestProjectPath();
    mapFilePath /= "maps/layer_hierarchy_restore.map";

    // Restore the .darkradiant file after this test
    auto infoFilePath = os::replaceExtension(mapFilePath.string(), "darkradiant");
    BackupCopy backupCopy(infoFilePath);

    // No hidden layers
    replacePropertiesBlock(infoFilePath, R"(LayerProperties { HiddenLayers { } })");
    loadAndExpectLayersToBeRestored(mapFilePath.string(), { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getParentLayer(3), 9) << "Failed to restore hierarchy";
    expectLayersAreVisible({ 0,1,2,3,4,5,6,7,8,9 }, true); // all layers should be visible
    backupCopy.restoreNow();

    // An invalid layer ID in there
    replacePropertiesBlock(infoFilePath, R"(LayerProperties { HiddenLayers { -1 3 4 } })");
    loadAndExpectLayersToBeRestored(mapFilePath.string(), { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getParentLayer(3), 9) << "Failed to restore hierarchy";
    expectLayersAreVisible({ 0,1,2,5,6,7,8,9 }, true);
    expectLayersAreVisible({ 3, 4 }, false);
    backupCopy.restoreNow();

    // Duplicate layer IDs listed, plus one out of range
    replacePropertiesBlock(infoFilePath, R"(LayerProperties { HiddenLayers { 0 4 5 5 5 3 44444 } })");
    loadAndExpectLayersToBeRestored(mapFilePath.string(), { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getParentLayer(3), 9) << "Failed to restore hierarchy";
    expectLayersAreVisible({ 1,2,6,7,8,9 }, true);
    expectLayersAreVisible({ 0,3,4,5 }, false);
    backupCopy.restoreNow();

    // Now the positive test case
    replacePropertiesBlock(infoFilePath, R"(LayerProperties { HiddenLayers { 0 4 5 9 } })");
    loadAndExpectLayersToBeRestored(mapFilePath.string(), { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
    EXPECT_EQ(GlobalMapModule().getRoot()->getLayerManager().getParentLayer(3), 9) << "Failed to restore hierarchy";
    expectLayersAreVisible({ 1,2,3,6,7,8 }, true);
    expectLayersAreVisible({ 0,4,5,9 }, false);
}

}