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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
// SPDX-License-Identifier: LGPL-2.1-or-later

/***************************************************************************

 *   Copyright (c) 2002 Jürgen Riegel <juergen.riegel@web.de>              *

 *                                                                         *

 *   This file is part of the FreeCAD CAx development system.              *

 *                                                                         *

 *   This library is free software; you can redistribute it and/or         *

 *   modify it under the terms of the GNU Library General Public           *

 *   License as published by the Free Software Foundation; either          *

 *   version 2 of the License, or (at your option) any later version.      *

 *                                                                         *

 *   This library  is distributed in the hope that it will be useful,      *

 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *

 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *

 *   GNU Library General Public License for more details.                  *

 *                                                                         *

 *   You should have received a copy of the GNU Library General Public     *

 *   License along with this library; see the file COPYING.LIB. If not,    *

 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *

 *   Suite 330, Boston, MA  02111-1307, USA                                *

 *                                                                         *

 ***************************************************************************/

#include <bitset>
#include <stack>
#include <deque>
#include <iostream>
#include <utility>
#include <set>
#include <memory>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <algorithm>
#include <filesystem>

#include <boost/algorithm/string.hpp>
#include <boost/bimap.hpp>
#include <boost/graph/strong_components.hpp>

#include <boost/regex.hpp>
#include <random>
#include <unordered_map>
#include <unordered_set>

#include <QCryptographicHash>
#include <QCoreApplication>

#include <FCConfig.h>

#include <App/DocumentPy.h>
#include <Base/Interpreter.h>
#include <Base/Console.h>
#include <Base/Exception.h>
#include <Base/FileInfo.h>
#include <Base/TimeInfo.h>
#include <Base/Reader.h>
#include <Base/Writer.h>
#include <Base/Profiler.h>
#include <Base/Tools.h>
#include <Base/Uuid.h>
#include <Base/Sequencer.h>
#include <Base/Stream.h>
#include <Base/UnitsApi.h>

#include "Document.h"
#include "private/DocumentP.h"
#include "Application.h"
#include "AutoTransaction.h"
#include "BackupPolicy.h"
#include "ExpressionParser.h"
#include "GeoFeature.h"
#include "License.h"
#include "Link.h"
#include "MergeDocuments.h"
#include "StringHasher.h"
#include "Transactions.h"

#ifdef _MSC_VER
#include <zipios++/zipios-config.h>
#endif
#include <zipios++/zipfile.h>
#include <zipios++/zipinputstream.h>
#include <zipios++/zipoutputstream.h>
#include <zipios++/meta-iostreams.h>


FC_LOG_LEVEL_INIT("App", true, true, true)

using Base::Console;
using Base::streq;
using Base::Writer;
using namespace App;
using namespace std;
using namespace boost;
using namespace zipios;

#if FC_DEBUG
#define FC_LOGFEATUREUPDATE
#endif

namespace fs = std::filesystem;

namespace App
{

static bool globalIsRestoring;
static bool globalIsRelabeling;

DocumentP::DocumentP()
{
    static std::random_device rd;
    static std::mt19937 rgen(rd());
    static std::uniform_int_distribution<> rdist(0, 5000);
    // Set some random offset to reduce likelihood of ID collision when
    // copying shape from other document. It is probably better to randomize
    // on each object ID.
    lastObjectId = rdist(rgen);
    StatusBits.set((size_t)Document::Closable, true);
    StatusBits.set((size_t)Document::KeepTrailingDigits, true);
    StatusBits.set((size_t)Document::Restoring, false);
}

}  // namespace App

PROPERTY_SOURCE(App::Document, App::PropertyContainer)

bool Document::testStatus(const Status pos) const

{
    return d->StatusBits.test(static_cast<size_t>(pos));
}

void Document::setStatus(const Status pos, const bool on) // NOLINT

{
    d->StatusBits.set(static_cast<size_t>(pos), on);
}

// bool _has_cycle_dfs(const DependencyList & g, vertex_t u, default_color_type * color)
//{
//   color[u] = gray_color;
//   graph_traits < DependencyList >::adjacency_iterator vi, vi_end;
//   for (tie(vi, vi_end) = adjacent_vertices(u, g); vi != vi_end; ++vi)
//     if (color[*vi] == white_color)
//       if (has_cycle_dfs(g, *vi, color))
//         return true;            // cycle detected, return immediately
//       else if (color[*vi] == gray_color)        // *vi is an ancestor!
//         return true;
//   color[u] = black_color;
//   return false;
// }

bool Document::checkOnCycle()

{
    return false;
}

bool Document::undo(const int id)

{
    if (d->iUndoMode != 0) {
        if (id != 0) {
            const auto it = mUndoMap.find(id);
            if (it == mUndoMap.end()) {
                return false;
            }
            if (it->second != d->activeUndoTransaction) {
                while (!mUndoTransactions.empty() && mUndoTransactions.back() != it->second) {
                    undo(0);
                }
            }
        }

        if (d->activeUndoTransaction) {
            _commitTransaction(true);
        }
        if (mUndoTransactions.empty()) {
            return false;
        }
        // redo
        d->activeUndoTransaction = new Transaction(mUndoTransactions.back()->getID());
        d->activeUndoTransaction->Name = mUndoTransactions.back()->Name;

        {
            Base::FlagToggler<bool> flag(d->undoing);
            // applying the undo
            mUndoTransactions.back()->apply(*this, false);

            // save the redo
            mRedoMap[d->activeUndoTransaction->getID()] = d->activeUndoTransaction;
            mRedoTransactions.push_back(d->activeUndoTransaction);
            d->activeUndoTransaction = nullptr;

            mUndoMap.erase(mUndoTransactions.back()->getID());
            delete mUndoTransactions.back();
            mUndoTransactions.pop_back();
        }

        for (const auto& obj : d->objectArray) {
            if (obj->testStatus(ObjectStatus::PendingTransactionUpdate)) {
                obj->onUndoRedoFinished();
                obj->setStatus(ObjectStatus::PendingTransactionUpdate, false);
            }
        }

        signalUndo(*this);  // now signal the undo

        return true;
    }

    return false;
}

bool Document::redo(const int id)

{
    if (d->iUndoMode != 0) {
        if (id != 0) {
            const auto it = mRedoMap.find(id);
            if (it == mRedoMap.end()) {
                return false;
            }
            while (!mRedoTransactions.empty() && mRedoTransactions.back() != it->second) {
                redo(0);
            }
        }

        if (d->activeUndoTransaction) {
            _commitTransaction(true);
        }

        assert(mRedoTransactions.size() != 0);

        // undo
        d->activeUndoTransaction = new Transaction(mRedoTransactions.back()->getID());
        d->activeUndoTransaction->Name = mRedoTransactions.back()->Name;

        // do the redo
        {
            Base::FlagToggler<bool> flag(d->undoing);
            mRedoTransactions.back()->apply(*this, true);

            mUndoMap[d->activeUndoTransaction->getID()] = d->activeUndoTransaction;
            mUndoTransactions.push_back(d->activeUndoTransaction);
            d->activeUndoTransaction = nullptr;

            mRedoMap.erase(mRedoTransactions.back()->getID());
            delete mRedoTransactions.back();
            mRedoTransactions.pop_back();
        }

        for (const auto& obj : d->objectArray) {
            if (obj->testStatus(ObjectStatus::PendingTransactionUpdate)) {
                obj->onUndoRedoFinished();
                obj->setStatus(ObjectStatus::PendingTransactionUpdate, false);
            }
        }

        signalRedo(*this);
        return true;
    }

    return false;
}

void Document::changePropertyOfObject(TransactionalObject* obj,

                                      const Property* prop,

                                      const std::function<void()>& changeFunc)

{
    if (!prop || !obj || !obj->isAttachedToDocument()) {
        return;
    }
    if ((d->iUndoMode != 0) && !isPerformingTransaction() && !d->activeUndoTransaction) {
        if (!testStatus(Restoring) || testStatus(Importing)) {
            int tid = 0;
            const char* name = GetApplication().getActiveTransaction(&tid);
            if (name && tid > 0) {
                _openTransaction(name, tid);
            }
        }
    }
    if (d->activeUndoTransaction && !d->rollback) {
        changeFunc();
    }
}

void Document::renamePropertyOfObject(TransactionalObject* obj,

                                      const Property* prop, const char* oldName)

{
    changePropertyOfObject(obj, prop, [this, obj, prop, oldName]() {
        d->activeUndoTransaction->renameProperty(obj, prop, oldName);
    });
}

void Document::addOrRemovePropertyOfObject(TransactionalObject* obj,

                                           const Property* prop, const bool add)

{
    changePropertyOfObject(obj, prop, [this, obj, prop, add]() {
        d->activeUndoTransaction->addOrRemoveProperty(obj, prop, add);
    });
}

bool Document::isPerformingTransaction() const

{
    return d->undoing || d->rollback;
}

std::vector<std::string> Document::getAvailableUndoNames() const

{
    std::vector<std::string> vList;
    if (d->activeUndoTransaction) {
        vList.push_back(d->activeUndoTransaction->Name);
    }
    for (auto It = mUndoTransactions.rbegin();
         It != mUndoTransactions.rend();
         ++It) {
        vList.push_back((*It)->Name);
    }
    return vList;
}

std::vector<std::string> Document::getAvailableRedoNames() const

{
    std::vector<std::string> vList;
    for (auto It = mRedoTransactions.rbegin();
         It != mRedoTransactions.rend();
         ++It) {
        vList.push_back((*It)->Name);
    }
    return vList;
}

void Document::openTransaction(const char* name) // NOLINT

{
    if (isPerformingTransaction() || d->committing) {
        if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) {
            FC_WARN("Cannot open transaction while transacting");
        }
        return;
    }

    GetApplication().setActiveTransaction(name ? name : "<empty>");
}

int Document::_openTransaction(const char* name, int id)
{
    if (isPerformingTransaction() || d->committing) {
        if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) {
            FC_WARN("Cannot open transaction while transacting");
        }
        return 0;
    }

    if (d->iUndoMode != 0) {
        // Avoid recursive calls that is possible while
        // clearing the redo transactions and will cause
        // a double deletion of some transaction and thus
        // a segmentation fault
        if (d->opentransaction) {
            return 0;
        }
        Base::FlagToggler<> flag(d->opentransaction);

        if ((id != 0) && mUndoMap.find(id) != mUndoMap.end()) {
            throw Base::RuntimeError("invalid transaction id");
        }
        if (d->activeUndoTransaction) {
            _commitTransaction(true);
        }
        _clearRedos();

        d->activeUndoTransaction = new Transaction(id);
        if (!name) {
            name = "<empty>";
        }
        d->activeUndoTransaction->Name = name;
        mUndoMap[d->activeUndoTransaction->getID()] = d->activeUndoTransaction;
        id = d->activeUndoTransaction->getID();

        signalOpenTransaction(*this, name);

        auto& app = GetApplication();
        auto activeDoc = app.getActiveDocument();
        if (activeDoc && activeDoc != this && !activeDoc->hasPendingTransaction()) {
            std::string aname("-> ");
            aname += d->activeUndoTransaction->Name;
            FC_LOG("auto transaction " << getName() << " -> " << activeDoc->getName());
            activeDoc->_openTransaction(aname.c_str(), id);
        }
        return id;
    }
    return 0;
}

void Document::renameTransaction(const char* name, const int id) const

{
    if (name && d->activeUndoTransaction && d->activeUndoTransaction->getID() == id) {
        if (boost::starts_with(d->activeUndoTransaction->Name, "-> ")) {
            d->activeUndoTransaction->Name.resize(3);
        }
        else {
            d->activeUndoTransaction->Name.clear();
        }
        d->activeUndoTransaction->Name += name;
    }
}

void Document::_checkTransaction(DocumentObject* pcDelObj, const Property* What, int line)
{
    // if the undo is active but no transaction open, open one!
    if ((d->iUndoMode != 0) && !isPerformingTransaction()) {
        if (!d->activeUndoTransaction) {
            if (!testStatus(Restoring) || testStatus(Importing)) {
                int tid = 0;
                const char* name = GetApplication().getActiveTransaction(&tid);
                if (name && tid > 0) {
                    bool ignore = false;
                    if (What && What->testStatus(Property::NoModify)) {
                        ignore = true;
                    }
                    if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) {
                        if (What) {
                            FC_LOG((ignore ? "ignore" : "auto")
                                   << " transaction (" << line << ") '" << What->getFullName());
                        }
                        else {
                            FC_LOG((ignore ? "ignore" : "auto") << " transaction (" << line << ") '"
                                                                << name << "' in " << getName());
                        }
                    }
                    if (!ignore) {
                        _openTransaction(name, tid);
                    }
                    return;
                }
            }
            if (!pcDelObj) {
                return;
            }
            // When the object is going to be deleted we have to check if it has already been added
            // to the undo transactions
            std::list<Transaction*>::iterator it;
            for (it = mUndoTransactions.begin(); it != mUndoTransactions.end(); ++it) {
                if ((*it)->hasObject(pcDelObj)) {
                    _openTransaction("Delete");
                    break;
                }
            }
        }
    }
}

void Document::_clearRedos()
{
    if (isPerformingTransaction() || d->committing) {
        FC_ERR("Cannot clear redo while transacting");
        return;
    }

    mRedoMap.clear();
    while (!mRedoTransactions.empty()) {
        delete mRedoTransactions.back();
        mRedoTransactions.pop_back();
    }
}

void Document::commitTransaction() // NOLINT

{
    if (isPerformingTransaction() || d->committing) {
        if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) {
            FC_WARN("Cannot commit transaction while transacting");
        }
        return;
    }

    if (d->activeUndoTransaction) {
        GetApplication().closeActiveTransaction(false, d->activeUndoTransaction->getID());
    }
}

void Document::_commitTransaction(const bool notify)
{
    if (isPerformingTransaction()) {
        if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) {
            FC_WARN("Cannot commit transaction while transacting");
        }
        return;
    }
    if (d->committing) {
        // for a recursive call return without printing a warning
        return;
    }

    if (d->activeUndoTransaction) {
        Base::FlagToggler<> flag(d->committing);
        Application::TransactionSignaller signaller(false, true);
        const int id = d->activeUndoTransaction->getID();
        mUndoTransactions.push_back(d->activeUndoTransaction);
        d->activeUndoTransaction = nullptr;
        // check the stack for the limits
        if (mUndoTransactions.size() > d->UndoMaxStackSize) {
            mUndoMap.erase(mUndoTransactions.front()->getID());
            delete mUndoTransactions.front();
            mUndoTransactions.pop_front();
        }
        signalCommitTransaction(*this);

        // closeActiveTransaction() may call again _commitTransaction()
        if (notify) {
            GetApplication().closeActiveTransaction(false, id);
        }
    }
}

void Document::abortTransaction() const

{
    if (isPerformingTransaction() || d->committing) {
        if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) {
            FC_WARN("Cannot abort transaction while transacting");
        }
        return;
    }
    if (d->activeUndoTransaction) {
        GetApplication().closeActiveTransaction(true, d->activeUndoTransaction->getID());
    }
}

void Document::_abortTransaction()
{
    if (isPerformingTransaction() || d->committing) {
        if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) {
            FC_WARN("Cannot abort transaction while transacting");
        }
    }

    if (d->activeUndoTransaction) {
        Base::FlagToggler<bool> flag(d->rollback);
        Application::TransactionSignaller signaller(true, true);

        // applying the so far made changes
        d->activeUndoTransaction->apply(*this, false);

        // destroy the undo
        mUndoMap.erase(d->activeUndoTransaction->getID());
        delete d->activeUndoTransaction;
        d->activeUndoTransaction = nullptr;
        signalAbortTransaction(*this);
    }
}

bool Document::hasPendingTransaction() const

{
    return d->activeUndoTransaction != nullptr;
}

int Document::getTransactionID(const bool undo, unsigned pos) const

{
    if (undo) {
        if (d->activeUndoTransaction) {
            if (pos == 0) {
                return d->activeUndoTransaction->getID();
            }
            --pos;
        }
        if (pos >= mUndoTransactions.size()) {
            return 0;
        }
        auto rit = mUndoTransactions.rbegin();
        for (; pos != 0U; ++rit, --pos) {}
        return (*rit)->getID();
    }
    if (pos >= mRedoTransactions.size()) {
        return 0;
    }
    auto rit = mRedoTransactions.rbegin();
    for (; pos != 0U; ++rit, --pos) {}
    return (*rit)->getID();
}

bool Document::isTransactionEmpty() const

{
    return !d->activeUndoTransaction;
        // Transactions are now only created when there are actual changes.
        // Empty transaction is now significant for marking external changes. It
        // is used to match ID with transactions in external documents and
        // trigger undo/redo there.

        // return d->activeUndoTransaction->isEmpty();

}

void Document::clearDocument() // NOLINT

{
    d->activeObject = nullptr;

    if (!d->objectArray.empty()) {
        GetApplication().signalDeleteDocument(*this);
        d->clearDocument();
        GetApplication().signalNewDocument(*this, false);
    }

    Base::FlagToggler<> flag(globalIsRestoring, false);

    setStatus(Document::PartialDoc, false);

    d->clearRecomputeLog();
    d->objectLabelManager.clear();
    d->objectArray.clear();
    d->objectMap.clear();
    d->objectNameManager.clear();
    d->objectIdMap.clear();
    d->lastObjectId = 0;
}


void Document::clearUndos()

{
    if (isPerformingTransaction() || d->committing) {
        FC_ERR("Cannot clear undos while transacting");
        return;
    }

    if (d->activeUndoTransaction) {
        _commitTransaction(true);
    }

    mUndoMap.clear();

    // When cleaning up the undo stack we must delete the transactions from front
    // to back because a document object can appear in several transactions but
    // once removed from the document the object can never ever appear in any later
    // transaction. Since the document object may be also deleted when the transaction
    // is deleted we must make sure not access an object once it's destroyed. Thus, we
    // go from front to back and not the other way round.
    while (!mUndoTransactions.empty()) {
        delete mUndoTransactions.front();
        mUndoTransactions.pop_front();
    }
    // while (!mUndoTransactions.empty()) {
    //     delete mUndoTransactions.back();
    //     mUndoTransactions.pop_back();
    // }

    _clearRedos();
}

int Document::getAvailableUndos(const int id) const

{
    if (id != 0) {
        const auto it = mUndoMap.find(id);
        if (it == mUndoMap.end()) {
            return 0;
        }
        int i = 0;
        if (d->activeUndoTransaction) {
            ++i;
            if (d->activeUndoTransaction->getID() == id) {
                return i;
            }
        }
        auto rit = mUndoTransactions.rbegin();
        for (; rit != mUndoTransactions.rend() && *rit != it->second; ++rit) {
            ++i;
        }
        assert(rit != mUndoTransactions.rend());
        return i + 1;
    }
    if (d->activeUndoTransaction) {
        return static_cast<int>(mUndoTransactions.size() + 1);
    }
    return static_cast<int>(mUndoTransactions.size());
}

int Document::getAvailableRedos(const int id) const

{
    if (id != 0) {
        const auto it = mRedoMap.find(id);
        if (it == mRedoMap.end()) {
            return 0;
        }
        int i = 0;
        for (auto rit = mRedoTransactions.rbegin(); *rit != it->second; ++rit) {
            ++i;
        }
        assert(i < static_cast<int>(mRedoTransactions.size()));
        return i + 1;
    }
    return static_cast<int>(mRedoTransactions.size());
}

void Document::setUndoMode(const int iMode)

{
    if ((d->iUndoMode != 0) && (iMode == 0)) {
        clearUndos();
    }

    d->iUndoMode = iMode;
}

int Document::getUndoMode() const

{
    return d->iUndoMode;
}

unsigned int Document::getUndoMemSize() const

{
    return d->UndoMemSize;
}

void Document::setUndoLimit(const unsigned int UndoMemSize) // NOLINT

{
    d->UndoMemSize = UndoMemSize;
}

void Document::setMaxUndoStackSize(const unsigned int UndoMaxStackSize) // NOLINT

{
    d->UndoMaxStackSize = UndoMaxStackSize;
}

unsigned int Document::getMaxUndoStackSize() const

{
    return d->UndoMaxStackSize;
}

void Document::onBeforeChange(const Property* prop)

{
    if (prop == &Label) {
        oldLabel = Label.getValue();
    }
    signalBeforeChange(*this, *prop);
}

void Document::onChanged(const Property* prop)

{
    signalChanged(*this, *prop);

    // the Name property is a label for display purposes
    if (prop == &Label) {
        Base::FlagToggler<> flag(globalIsRelabeling);
        GetApplication().signalRelabelDocument(*this);
    }
    else if (prop == &ShowHidden) {
        GetApplication().signalShowHidden(*this);
    }
    else if (prop == &Uid) {
        std::string new_dir =
            getTransientDirectoryName(this->Uid.getValueStr(), this->FileName.getStrValue());
        std::string old_dir = this->TransientDir.getStrValue();
        Base::FileInfo TransDirNew(new_dir);
        Base::FileInfo TransDirOld(old_dir);
        // this directory should not exist
        if (!TransDirNew.exists()) {
            if (TransDirOld.exists()) {
                if (!TransDirOld.renameFile(new_dir.c_str())) {
                    Base::Console().warning("Failed to rename '%s' to '%s'\n",
                                            old_dir.c_str(),
                                            new_dir.c_str());
                }
                else {
                    this->TransientDir.setValue(new_dir);
                }
            }
            else {
                if (!TransDirNew.createDirectories()) {
                    Base::Console().warning("Failed to create '%s'\n", new_dir.c_str());
                }
                else {
                    this->TransientDir.setValue(new_dir);
                }
            }
        }
        // when reloading an existing document the transient directory doesn't change
        // so we must avoid to generate a new uuid
        else if (TransDirNew.filePath() != TransDirOld.filePath()) {
            // make sure that the uuid is unique
            std::string uuid = this->Uid.getValueStr();
            Base::Uuid id;
            Base::Console().warning("Document with the UUID '%s' already exists, change to '%s'\n",
                                    uuid.c_str(),
                                    id.getValue().c_str());
            // recursive call of onChanged()
            this->Uid.setValue(id);
        }
    }
    else if (prop == &UseHasher) {
        for (auto obj : d->objectArray) {
            auto geofeature = freecad_cast<GeoFeature*>(obj);
            if (geofeature && geofeature->getPropertyOfGeometry()) {
                geofeature->enforceRecompute();
            }
        }
    }
}

void Document::onBeforeChangeProperty(const TransactionalObject* Who, const Property* What)

{
    if (Who->isDerivedFrom<DocumentObject>()) {
        signalBeforeChangeObject(*static_cast<const DocumentObject*>(Who), *What);
    }
    if (!d->rollback && !globalIsRelabeling) {
        _checkTransaction(nullptr, What, __LINE__);
        if (d->activeUndoTransaction) {
            d->activeUndoTransaction->addObjectChange(Who, What);
        }
    }
}

void Document::onChangedProperty(const DocumentObject* Who, const Property* What)

{
    signalChangedObject(*Who, *What);
}

void Document::setTransactionMode(const int iMode) // NOLINT

{
    d->iTransactionMode = iMode;
}

//--------------------------------------------------------------------------
// constructor
//--------------------------------------------------------------------------
Document::Document(const char* documentName)
    : d(new DocumentP), myName(documentName)
{
    // Remark: In a constructor we should never increment a Python object as we cannot be sure
    // if the Python interpreter gets a reference of it. E.g. if we increment but Python don't
    // get a reference then the object wouldn't get deleted in the destructor.
    // So, we must increment only if the interpreter gets a reference.
    // Remark: We force the document Python object to own the DocumentPy instance, thus we don't
    // have to care about ref counting any more.
    setAutoCreated(false);
    Base::PyGILStateLocker lock;
    d->DocumentPythonObject = Py::Object(new DocumentPy(this), true);

#ifdef FC_LOGUPDATECHAIN
    Console().log("+App::Document: %p\n", this);
#endif
    std::string CreationDateString = Base::Tools::currentDateTimeString();
    std::string Author = GetApplication()
                             .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
                             ->GetASCII("prefAuthor", "");
    std::string AuthorComp =
        GetApplication()
            .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
            ->GetASCII("prefCompany", "");
    ADD_PROPERTY_TYPE(Label, ("Unnamed"), 0, Prop_ReadOnly, "The name of the document");
    ADD_PROPERTY_TYPE(FileName,
                      (""),
                      0,
                      PropertyType(Prop_Transient | Prop_ReadOnly),
                      "The path to the file where the document is saved to");
    ADD_PROPERTY_TYPE(CreatedBy, (Author.c_str()), 0, Prop_None, "The creator of the document");
    ADD_PROPERTY_TYPE(CreationDate,
                      (CreationDateString.c_str()),
                      0,
                      Prop_ReadOnly,
                      "Date of creation");
    ADD_PROPERTY_TYPE(LastModifiedBy, (""), 0, Prop_None, 0);
    ADD_PROPERTY_TYPE(LastModifiedDate, ("Unknown"), 0, Prop_ReadOnly, "Date of last modification");
    ADD_PROPERTY_TYPE(Company,
                      (AuthorComp.c_str()),
                      0,
                      Prop_None,
                      "Additional tag to save the name of the company");
    ADD_PROPERTY_TYPE(UnitSystem, (""), 0, Prop_None, "Unit system to use in this project");
    // Set up the possible enum values for the unit system

    UnitSystem.setEnums(Base::UnitsApi::getDescriptions());
    // Get the preferences/General unit system as the default for a new document
    ParameterGrp::handle hGrpu =
        GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units");
    UnitSystem.setValue(hGrpu->GetInt("UserSchema", 0));
    ADD_PROPERTY_TYPE(Comment, (""), 0, Prop_None, "Additional tag to save a comment");
    ADD_PROPERTY_TYPE(Meta, (), 0, Prop_None, "Map with additional meta information");
    ADD_PROPERTY_TYPE(Material, (), 0, Prop_None, "Map with material properties");
    // create the uuid for the document
    Base::Uuid id;
    ADD_PROPERTY_TYPE(Id, (""), 0, Prop_None, "ID of the document");
    ADD_PROPERTY_TYPE(Uid, (id), 0, Prop_ReadOnly, "UUID of the document");

    // license stuff
    auto paramGrp {GetApplication().GetParameterGroupByPath(
        "User parameter:BaseApp/Preferences/Document")};
    auto index = static_cast<int>(paramGrp->GetInt("prefLicenseType", 0));
    auto name = "";
    std::string licenseUrl = "";
    if (index >= 0 && index < countOfLicenses) {
        name = licenseItems.at(index).at(posnOfFullName);
        auto url = licenseItems.at(index).at(posnOfUrl);
        licenseUrl = (paramGrp->GetASCII("prefLicenseUrl", url));
    }
    ADD_PROPERTY_TYPE(License, (name), 0, Prop_None, "License string of the Item");
    ADD_PROPERTY_TYPE(LicenseURL,
                      (licenseUrl.c_str()),
                      0,
                      Prop_None,
                      "URL to the license text/contract");
    ADD_PROPERTY_TYPE(ShowHidden,
                      (false),
                      0,
                      PropertyType(Prop_None),
                      "Whether to show hidden object items in the tree view");
    ADD_PROPERTY_TYPE(UseHasher,
                      (true),
                      0,
                      PropertyType(Prop_Hidden),
                      "Whether to use hasher on topological naming");

    // this creates and sets 'TransientDir' in onChanged()
    ADD_PROPERTY_TYPE(TransientDir,
                      (""),
                      0,
                      PropertyType(Prop_Transient | Prop_ReadOnly),
                      "Transient directory, where the files live while the document is open");
    ADD_PROPERTY_TYPE(Tip,
                      (nullptr),
                      0,
                      PropertyType(Prop_Transient),
                      "Link of the tip object of the document");
    ADD_PROPERTY_TYPE(TipName,
                      (""),
                      0,
                      PropertyType(Prop_Hidden | Prop_ReadOnly),
                      "Link of the tip object of the document");
    Uid.touch();
}

Document::~Document()
{
#ifdef FC_LOGUPDATECHAIN
    Console().log("-App::Document: %s %p\n", getName(), this);
#endif

    try {
        clearUndos();
    }
    catch (const boost::exception&) {
    }

#ifdef FC_LOGUPDATECHAIN
    Console().log("-Delete Features of %s \n", getName());
#endif

    d->clearDocument();

    // Remark: The API of Py::Object has been changed to set whether the wrapper owns the passed
    // Python object or not. In the constructor we forced the wrapper to own the object so we need
    // not to dec'ref the Python object any more.
    // But we must still invalidate the Python object because it doesn't need to be
    // destructed right now because the interpreter can own several references to it.
    Base::PyGILStateLocker lock;
    auto* doc = static_cast<Base::PyObjectBase*>(d->DocumentPythonObject.ptr());
    // Call before decrementing the reference counter, otherwise a heap error can occur
    doc->setInvalid();

    // remove Transient directory
    try {
        const Base::FileInfo TransDir(TransientDir.getValue());
        TransDir.deleteDirectoryRecursive();
    }
    catch (const Base::Exception& e) {
        std::cerr << "Removing transient directory failed: " << e.what() << '\n';
    }
    delete d;
}

std::string Document::getTransientDirectoryName(const std::string& uuid,

                                                const std::string& filename) const

{
    // Create a directory name of the form: {ExeName}_Doc_{UUID}_{HASH}_{PID}
    std::stringstream out;
    QCryptographicHash hash(QCryptographicHash::Sha1);
#if QT_VERSION < QT_VERSION_CHECK(6, 3, 0)
    hash.addData(filename.c_str(), filename.size());
#else
    hash.addData(QByteArrayView(filename.c_str(), filename.size()));
#endif
    out << Application::getUserCachePath() << Application::getExecutableName() << "_Doc_"
        << uuid << "_" << hash.result().toHex().left(6).constData() << "_"
        << Application::applicationPid();
    return out.str();
}

//--------------------------------------------------------------------------
// Exported functions
//--------------------------------------------------------------------------

void Document::Save(Base::Writer& writer) const

{
    d->hashers.clear();
    addStringHasher(d->Hasher);

    writer.Stream() << R"(<Document SchemaVersion="4" ProgramVersion=")"
                    << Application::Config()["BuildVersionMajor"] << "."
                    << Application::Config()["BuildVersionMinor"] << "R"
                    << Application::Config()["BuildRevision"] << "\" FileVersion=\""
                    << writer.getFileVersion() << "\" StringHasher=\"1\">\n";

    writer.incInd();

    d->Hasher->setPersistenceFileName("StringHasher.Table");
    for (const auto o : d->objectArray) {
        o->beforeSave();
    }
    beforeSave();

    d->Hasher->Save(writer);

    writer.decInd();

    PropertyContainer::Save(writer);

    // writing the features types
    writeObjects(d->objectArray, writer);
    writer.Stream() << "</Document>" << '\n';
}

void Document::Restore(Base::XMLReader& reader)

{
    d->hashers.clear();
    d->touchedObjs.clear();
    addStringHasher(d->Hasher);
    setStatus(Document::PartialDoc, false);

    reader.readElement("Document");
    const long scheme = reader.getAttribute<long>("SchemaVersion");
    reader.DocumentSchema = static_cast<int>(scheme);
    if (reader.hasAttribute("ProgramVersion")) {
        reader.ProgramVersion = reader.getAttribute<const char*>("ProgramVersion");
    }
    else {
        reader.ProgramVersion = "pre-0.14";
    }
    if (reader.hasAttribute("FileVersion")) {
        reader.FileVersion = static_cast<int>(reader.getAttribute<unsigned long>("FileVersion"));
    }
    else {
        reader.FileVersion = 0;
    }

    if (reader.hasAttribute("StringHasher")) {
        d->Hasher->Restore(reader);
    }
    else {
        d->Hasher->clear();
    }

    // When this document was created the FileName and Label properties
    // were set to the absolute path or file name, respectively. To save
    // the document to the file it was loaded from or to show the file name
    // in the tree view we must restore them after loading the file because
    // they will be overridden.
    // Note: This does not affect the internal name of the document in any way
    // that is kept in Application.
    const std::string FilePath = FileName.getValue();
    const std::string DocLabel = Label.getValue();

    // read the Document Properties, when reading in Uid the transient directory gets renamed
    // automatically
    PropertyContainer::Restore(reader);

    // We must restore the correct 'FileName' property again because the stored
    // value could be invalid.
    FileName.setValue(FilePath.c_str());
    Label.setValue(DocLabel.c_str());

    // SchemeVersion "2"
    if (scheme == 2) {
        // read the feature types
        reader.readElement("Features");
        for (auto i = 0; i < reader.getAttribute<long>("Count"); i++) {
            reader.readElement("Feature");
            string type = reader.getAttribute<const char*>("type");
            string name = reader.getAttribute<const char*>("name");
            try {
                addObject(type.c_str(), name.c_str(), /*isNew=*/false);
            }
            catch (Base::Exception&) {
                Base::Console().message("Cannot create object '%s'\n", name.c_str());
            }
        }
        reader.readEndElement("Features");

        // read the features itself
        reader.readElement("FeatureData");
        for (auto i = 0; i < reader.getAttribute<long>("Count"); i++) {
            reader.readElement("Feature");
            string name = reader.getAttribute<const char*>("name");
            DocumentObject* pObj = getObject(name.c_str());
            if (pObj) {  // check if this feature has been registered
                pObj->setStatus(ObjectStatus::Restore, true);
                pObj->Restore(reader);
                pObj->setStatus(ObjectStatus::Restore, false);
            }
            reader.readEndElement("Feature");
        }
        reader.readEndElement("FeatureData");
    }  // SchemeVersion "3" or higher
    else if (scheme >= 3) {
        // read the feature types
        readObjects(reader);

        // tip object handling. First the whole document has to be read, then we
        // can restore the Tip link out of the TipName Property:
        Tip.setValue(getObject(TipName.getValue()));
    }

    reader.readEndElement("Document");
}

void DocumentP::checkStringHasher(const Base::XMLReader& reader)

{
    if (reader.hasReadFailed("StringHasher.Table.txt")) {
        Base::Console().error(QT_TRANSLATE_NOOP(
            "Notifications",
            "\nIt is recommended that the user right-click the root of "
            "the document and select Mark to recompute.\n"
            "The user should then click the Refresh button in the main toolbar.\n"));
    }
}

std::pair<bool, int> Document::addStringHasher(const StringHasherRef& hasher) const

{
    if (!hasher) {
        return std::make_pair(false, 0);
    }
    auto ret =
        d->hashers.left.insert(HasherMap::left_map::value_type(hasher, static_cast<int>(d->hashers.size())));
    if (ret.second) {
        hasher->clearMarks();
    }
    return std::make_pair(ret.second, ret.first->second);
}

StringHasherRef Document::getStringHasher(const int idx) const

{
    StringHasherRef hasher;
    if (idx < 0) {
        if (UseHasher.getValue()) {
            return d->Hasher;
        }
        return hasher;
    }
    const auto it = d->hashers.right.find(idx);
    if (it == d->hashers.right.end()) {
        hasher = new StringHasher;
        d->hashers.right.insert(HasherMap::right_map::value_type(idx, hasher));
    }
    else {
        hasher = it->second;
    }
    return hasher;
}

struct DocExportStatus
{
    Document::ExportStatus status;
    std::set<const DocumentObject*> objs;
};

static DocExportStatus exportStatus;

// Exception-safe exporting status setter
class DocumentExporting
{
public:
    explicit DocumentExporting(const std::vector<DocumentObject*>& objs)

    {
        exportStatus.status = Document::Exporting;
        exportStatus.objs.insert(objs.begin(), objs.end());
    }

    ~DocumentExporting()
    {
        exportStatus.status = Document::NotExporting;
        exportStatus.objs.clear();
    }
};

// The current implementation choose to use a static variable for exporting
// status because we can be exporting multiple objects from multiple documents
// at the same time. I see no benefits in distinguish which documents are
// exporting, so just use a static variable for global status. But the
// implementation can easily be changed here if necessary.
Document::ExportStatus Document::isExporting(const DocumentObject* obj) const

{
    if (exportStatus.status != Document::NotExporting
        && ((obj == nullptr) || exportStatus.objs.find(obj) != exportStatus.objs.end())) {
        return exportStatus.status;
    }
    return Document::NotExporting;
}
ExportInfo Document::exportInfo() const

{
    return d->exportInfo;
}
void Document::setExportInfo(const ExportInfo& info)

{
    d->exportInfo = info;
}

void Document::exportObjects(const std::vector<DocumentObject*>& obj, std::ostream& out)

{

    DocumentExporting exporting(obj);
    d->hashers.clear();

    if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) {
        for (auto o : obj) {
            if (o && o->isAttachedToDocument()) {
                FC_LOG("exporting " << o->getFullName());
                if (!o->getPropertyByName("_ObjectUUID")) {
                    auto prop = static_cast<PropertyUUID*>(
                        o->addDynamicProperty("App::PropertyUUID",
                                              "_ObjectUUID",
                                              nullptr,
                                              nullptr,
                                              Prop_Output | Prop_Hidden));
                    prop->setValue(Base::Uuid::createUuid());
                }
            }
        }
    }

    Base::ZipWriter writer(out);
    writer.putNextEntry("Document.xml");
    writer.Stream() << "<?xml version='1.0' encoding='utf-8'?>" << '\n';
    writer.Stream() << R"(<Document SchemaVersion="4" ProgramVersion=")"
                    << Application::Config()["BuildVersionMajor"] << "."
                    << Application::Config()["BuildVersionMinor"] << "R"
                    << Application::Config()["BuildRevision"] << R"(" FileVersion="1">)"
                    << '\n';
    // Add this block to have the same layout as for normal documents
    writer.Stream() << "<Properties Count=\"0\">" << '\n';
    writer.Stream() << "</Properties>" << '\n';

    // writing the object types
    writeObjects(obj, writer);
    writer.Stream() << "</Document>" << '\n';

    // Hook for others to add further data.
    signalExportObjects(obj, writer);

    // write additional files
    writer.writeFiles();
    d->hashers.clear();
}

constexpr auto fcAttrDependencies {"Dependencies"};
constexpr auto fcElementObjectDeps {"ObjectDeps"};
constexpr auto fcAttrDepCount {"Count"};
constexpr auto fcAttrDepObjName {"Name"};
constexpr auto fcAttrDepAllowPartial {"AllowPartial"};
constexpr auto fcElementObjectDep {"Dep"};

void Document::writeObjects(const std::vector<DocumentObject*>& obj,

                            Base::Writer& writer) const

{
    // writing the features types
    writer.incInd();  // indentation for 'Objects count'
    writer.Stream() << writer.ind() << "<Objects Count=\"" << obj.size();
    if (isExporting(nullptr) == 0U) {
        writer.Stream() << "\" " << fcAttrDependencies << "=\"1";
    }
    writer.Stream() << "\">" << '\n';

    writer.incInd();  // indentation for 'Object type'

    if (isExporting(nullptr) == 0U) {
        for (const auto o : obj) {
            const auto& outList =
                o->getOutList(DocumentObject::OutListNoHidden | DocumentObject::OutListNoXLinked);
            writer.Stream() << writer.ind()
                            << "<" << fcElementObjectDeps << " " << fcAttrDepObjName << "=\""
                            << o->getNameInDocument() << "\" " << fcAttrDepCount << "=\""
                            << outList.size();
            if (outList.empty()) {
                writer.Stream() << "\"/>" << '\n';
                continue;
            }
            const int partial = o->canLoadPartial();
            if (partial > 0) {
                writer.Stream() << "\" " << fcAttrDepAllowPartial << "=\"" << partial;
            }
            writer.Stream() << "\">" << '\n';
            writer.incInd();
            for (const auto dep : outList) {
                const auto name = dep ? dep->getNameInDocument() : "";
                writer.Stream() << writer.ind()
                                << "<" << fcElementObjectDep << " " << fcAttrDepObjName << "=\""
                                << (name ? name : "") << "\"/>" << '\n';
            }
            writer.decInd();
            writer.Stream() << writer.ind() << "</" << fcElementObjectDeps << ">" << '\n';
        }
    }

    std::vector<DocumentObject*>::const_iterator it;
    for (it = obj.begin(); it != obj.end(); ++it) {
        writer.Stream() << writer.ind() << "<Object "
                        << "type=\"" << (*it)->getTypeId().getName() << "\" "
                        << "name=\"" << (*it)->getExportName() << "\" "
                        << "id=\"" << (*it)->getID() << "\" ";

        // Only write out custom view provider types
        std::string viewType = (*it)->getViewProviderNameStored();
        if (viewType != (*it)->getViewProviderName()) {
            writer.Stream() << "ViewType=\"" << viewType << "\" ";
        }

        // See DocumentObjectPy::getState
        if ((*it)->testStatus(ObjectStatus::Touch)) {
            writer.Stream() << "Touched=\"1\" ";
        }
        if ((*it)->testStatus(ObjectStatus::Error)) {
            writer.Stream() << "Invalid=\"1\" ";
            const auto desc = getErrorDescription(*it);
            if (desc) {
                writer.Stream() << "Error=\"" << Property::encodeAttribute(desc) << "\" ";
            }
        }
        writer.Stream() << "/>" << '\n';
    }

    writer.decInd();  // indentation for 'Object type'
    writer.Stream() << writer.ind() << "</Objects>" << '\n';

    // writing the features itself
    writer.Stream() << writer.ind() << "<ObjectData Count=\"" << obj.size() << "\">" << '\n';

    writer.incInd();  // indentation for 'Object name'
    for (it = obj.begin(); it != obj.end(); ++it) {
        writer.Stream() << writer.ind() << "<Object name=\"" << (*it)->getExportName() << "\"";
        if ((*it)->hasExtensions()) {
            writer.Stream() << " Extensions=\"True\"";
        }

        writer.Stream() << ">" << '\n';
        (*it)->Save(writer);
        writer.Stream() << writer.ind() << "</Object>" << '\n';
    }

    writer.decInd();  // indentation for 'Object name'
    writer.Stream() << writer.ind() << "</ObjectData>" << '\n';
    writer.decInd();  // indentation for 'Objects count'
}

struct DepInfo
{
    std::unordered_set<std::string> deps;
    int canLoadPartial = 0;
};

static void loadDeps(const std::string& name,

                      std::unordered_map<std::string, bool>& objs,

                      const std::unordered_map<std::string, DepInfo>& deps)

{
    const auto it = deps.find(name);
    if (it == deps.end()) {
        objs.emplace(name, true);
        return;
    }
    if (it->second.canLoadPartial != 0) {
        if (it->second.canLoadPartial == 1) {
            // canLoadPartial==1 means all its children will be created but not
            // restored, i.e. exists as if newly created object, and therefore no
            // need to load dependency of the children
            for (auto& dep : it->second.deps) {
                objs.emplace(dep, false);
            }
            objs.emplace(name, true);
        }
        else {
            objs.emplace(name, false);
        }
        return;
    }
    objs[name] = true;
    // If cannot load partial, then recurse to load all children dependency
    for (auto& dep : it->second.deps) {
        if (auto found = objs.find(dep); found != objs.end() && found->second) {
            continue;
        }
        loadDeps(dep, objs, deps);
    }
}

std::vector<DocumentObject*> Document::readObjects(Base::XMLReader& reader)

{
    d->touchedObjs.clear();
    bool keepDigits = testStatus(Document::KeepTrailingDigits);
    setStatus(Document::KeepTrailingDigits, !reader.doNameMapping());
    std::vector<DocumentObject*> objs;


    // read the object types
    reader.readElement("Objects");
    int Cnt = static_cast<int>(reader.getAttribute<long>("Count"));

    if (!reader.hasAttribute(fcAttrDependencies)) {
        d->partialLoadObjects.clear();
    }
    else if (!d->partialLoadObjects.empty()) {
        std::unordered_map<std::string, DepInfo> deps;
        for (int i = 0; i < Cnt; i++) {
            reader.readElement(fcElementObjectDeps);
            int dcount = static_cast<int>(reader.getAttribute<long>(fcAttrDepCount));
            if (dcount == 0) {
                continue;
            }
            auto& info = deps[reader.getAttribute<const char*>(fcAttrDepObjName)];
            if (reader.hasAttribute(fcAttrDepAllowPartial)) {
                info.canLoadPartial =
                    static_cast<int>(reader.getAttribute<long>(fcAttrDepAllowPartial));
            }
            for (int j = 0; j < dcount; ++j) {
                reader.readElement(fcElementObjectDep);
                const char* name = reader.getAttribute<const char*>(fcAttrDepObjName);
                if (!Base::Tools::isNullOrEmpty(name)) {
                    info.deps.insert(name);
                }
            }
            reader.readEndElement(fcElementObjectDeps);
        }
        std::vector<std::string> strings;
        strings.reserve(d->partialLoadObjects.size());
        for (auto& v : d->partialLoadObjects) {
            strings.emplace_back(v.first.c_str());
        }
        for (auto& name : strings) {
            loadDeps(name, d->partialLoadObjects, deps);
        }
        if (Cnt > static_cast<int>(d->partialLoadObjects.size())) {
            setStatus(Document::PartialDoc, true);
        }
        else {
            for (auto& v : d->partialLoadObjects) {
                if (!v.second) {
                    setStatus(Document::PartialDoc, true);
                    break;
                }
            }
            if (!testStatus(Document::PartialDoc)) {
                d->partialLoadObjects.clear();
            }
        }
    }

    long lastId = 0;
    for (int i = 0; i < Cnt; i++) {
        reader.readElement("Object");
        std::string type = reader.getAttribute<const char*>("type");
        std::string name = reader.getAttribute<const char*>("name");
        std::string viewType =
            reader.hasAttribute("ViewType") ? reader.getAttribute<const char*>("ViewType") : "";

        bool partial = false;
        if (!d->partialLoadObjects.empty()) {
            auto it = d->partialLoadObjects.find(name);
            if (it == d->partialLoadObjects.end()) {
                continue;
            }
            partial = !it->second;
        }

        if (!testStatus(Status::Importing) && reader.hasAttribute("id")) {
            // if not importing, then temporary reset lastObjectId and make the
            // following addObject() generate the correct id for this object.
            d->lastObjectId = reader.getAttribute<long>("id") - 1;
        }

        // To prevent duplicate name when export/import of objects from
        // external documents, we append those external object name with
        // @<document name>. Before importing (here means we are called by
        // importObjects), we shall strip the postfix. What the caller
        // (MergeDocument) sees is still the unstripped name mapped to a new
        // internal name, and the rest of the link properties will be able to
        // correctly unmap the names.
        auto pos = name.find('@');
        std::string _obj_name;
        const char* obj_name {nullptr};
        if (pos != std::string::npos) {
            _obj_name = name.substr(0, pos);
            obj_name = _obj_name.c_str();
        }
        else {
            obj_name = name.c_str();
        }

        try {
            // Use name from XML as is and do NOT remove trailing digits because
            // otherwise we may cause a dependency to itself
            // Example: Object 'Cut001' references object 'Cut' and removing the
            // digits we make an object 'Cut' referencing itself.
            DocumentObject* obj =
                addObject(type.c_str(), obj_name, /*isNew=*/false, viewType.c_str(), partial);
            if (obj) {
                if (lastId < obj->_Id) {
                    lastId = obj->_Id;
                }
                objs.push_back(obj);
                // use this name for the later access because an object with
                // the given name may already exist
                reader.addName(name.c_str(), obj->getNameInDocument());

                // restore touch/error status flags
                if (reader.hasAttribute("Touched")) {
                    if (reader.getAttribute<long>("Touched") != 0) {
                        d->touchedObjs.insert(obj);
                    }
                }
                if (reader.hasAttribute("Invalid")) {
                    obj->setStatus(ObjectStatus::Error,
                                   reader.getAttribute<bool>("Invalid"));
                    if (obj->isError() && reader.hasAttribute("Error")) {
                        d->addRecomputeLog(reader.getAttribute<const char*>("Error"), obj);
                    }
                }
            }
        }
        catch (const Base::Exception& e) {
            Base::Console().error("Cannot create object '%s': (%s)\n", name.c_str(), e.what());
        }
    }
    if (!testStatus(Status::Importing)) {
        d->lastObjectId = lastId;
    }

    reader.readEndElement("Objects");
    setStatus(Document::KeepTrailingDigits, keepDigits);

    // read the features itself
    reader.clearPartialRestoreDocumentObject();
    reader.readElement("ObjectData");
    Cnt = static_cast<int>(reader.getAttribute<long>("Count"));
    for (int i = 0; i < Cnt; i++) {
        reader.readElement("Object");
        std::string name = reader.getName(reader.getAttribute<const char*>("name"));
        if (DocumentObject* pObj = getObject(name.c_str()); pObj
            && !pObj->testStatus(
                PartialObject)) {  // check if this feature has been registered
            pObj->setStatus(ObjectStatus::Restore, true);
            try {
                FC_TRACE("restoring " << pObj->getFullName());
                pObj->Restore(reader);
            }
            // Try to continue only for certain exception types if not handled
            // by the feature type. For all other exception types abort the process.
            catch (const Base::UnicodeError& e) {
                e.reportException();
            }
            catch (const Base::ValueError& e) {
                e.reportException();
            }
            catch (const Base::IndexError& e) {
                e.reportException();
            }
            catch (const Base::RuntimeError& e) {
                e.reportException();
            }
            catch (const Base::XMLAttributeError& e) {
                e.reportException();
            }

            pObj->setStatus(ObjectStatus::Restore, false);

            if (reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInDocumentObject)) {
                Base::Console().error("Object \"%s\" was subject to a partial restore. As a result "
                                      "geometry may have changed or be incomplete.\n",
                                      name.c_str());
                reader.clearPartialRestoreDocumentObject();
            }
        }
        reader.readEndElement("Object");
    }
    reader.readEndElement("ObjectData");

    return objs;
}

void Document::addRecomputeObject(DocumentObject* obj) // NOLINT

{
    if (testStatus(Status::Restoring) && obj) {
        setStatus(Status::RecomputeOnRestore, true);
        d->touchedObjs.insert(obj);
        obj->touch();
    }
}

std::vector<DocumentObject*> Document::importObjects(Base::XMLReader& reader)

{
    d->hashers.clear();
    Base::FlagToggler<> flag(globalIsRestoring, false);
    Base::ObjectStatusLocker<Status, Document> restoreBit(Status::Restoring, this);
    Base::ObjectStatusLocker<Status, Document> restoreBit2(Status::Importing, this);
    ExpressionParser::ExpressionImporter expImporter(reader);
    reader.readElement("Document");
    const long scheme = reader.getAttribute<long>("SchemaVersion");
    reader.DocumentSchema = static_cast<int>(scheme);
    if (reader.hasAttribute("ProgramVersion")) {
        reader.ProgramVersion = reader.getAttribute<const char*>("ProgramVersion");
    }
    else {
        reader.ProgramVersion = "pre-0.14";
    }
    if (reader.hasAttribute("FileVersion")) {
        reader.FileVersion = static_cast<int>(reader.getAttribute<unsigned long>("FileVersion"));
    }
    else {
        reader.FileVersion = 0;
    }

    std::vector<DocumentObject*> objs = readObjects(reader);
    for (const auto o : objs) {
        if (o && o->isAttachedToDocument()) {
            o->setStatus(ObjImporting, true);
            FC_LOG("importing " << o->getFullName());
            if (const auto propUUID =
                    freecad_cast<PropertyUUID*>(o->getPropertyByName("_ObjectUUID"))) {
                auto propSource =
                    freecad_cast<PropertyUUID*>(o->getPropertyByName("_SourceUUID"));
                if (!propSource) {
                    propSource = static_cast<PropertyUUID*>(
                        o->addDynamicProperty("App::PropertyUUID",
                                              "_SourceUUID",
                                              nullptr,
                                              nullptr,
                                              Prop_Output | Prop_Hidden));
                }
                if (propSource) {
                    propSource->setValue(propUUID->getValue());
                }
                propUUID->setValue(Base::Uuid::createUuid());
            }
        }
    }

    reader.readEndElement("Document");

    signalImportObjects(objs, reader);
    afterRestore(objs, true);

    signalFinishImportObjects(objs);

    for (const auto o : objs) {
        if (o && o->isAttachedToDocument()) {
            o->setStatus(ObjImporting, false);
        }
    }

    d->hashers.clear();
    return objs;
}

unsigned int Document::getMemSize() const

{
    unsigned int size = 0;

    // size of the DocObjects in the document
    for (const auto & it : d->objectArray) {
        size += it->getMemSize();
    }

    size += d->Hasher->getMemSize();

    // size of the document properties...
    size += PropertyContainer::getMemSize();

    // Undo Redo size
    size += getUndoMemSize();

    return size;
}

static std::string checkFileName(const char* file)

{
    std::string fn(file);

    // Append extension if missing. This option is added for security reason, so
    // that the user won't accidentally overwrite other file that may be critical.
    if (GetApplication()
            .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
            ->GetBool("CheckExtension", true)) {
        const char* ext = strrchr(file, '.');
        if ((ext == nullptr) || !boost::iequals(ext + 1, "fcstd")) {
            if (ext && ext[1] == 0) {
                fn += "FCStd";
            }
            else {
                fn += ".FCStd";
            }
        }
    }
    return fn;
}

bool Document::saveAs(const char* _file)

{
    const std::string file = checkFileName(_file);
    const Base::FileInfo fi(file.c_str());
    if (this->FileName.getStrValue() != file) {
        this->FileName.setValue(file);
        this->Label.setValue(fi.fileNamePure());
        this->Uid.touch();  // this forces a rename of the transient directory
    }

    return save();
}

bool Document::saveCopy(const char* file) const

{
    const std::string checked = checkFileName(file);
    return this->FileName.getStrValue() != checked ? saveToFile(checked.c_str()) : false;
}

// Save the document under the name it has been opened
bool Document::save()

{
    if (testStatus(Document::PartialDoc)) {
        FC_ERR("Partial loaded document '" << Label.getValue() << "' cannot be saved");
        // TODO We don't make this a fatal error and return 'true' to make it possible to
        // save other documents that depends on this partial opened document. We need better
        // handling to avoid touching partial documents.
        return true;
    }

    if (*(FileName.getValue()) != '\0') {
        // Save the name of the tip object in order to handle in Restore()
        if (Tip.getValue()) {
            TipName.setValue(Tip.getValue()->getNameInDocument());
        }

        const std::string LastModifiedDateString = Base::Tools::currentDateTimeString();
        LastModifiedDate.setValue(LastModifiedDateString.c_str());
        // set author if needed
        const bool saveAuthor =
            GetApplication()
                .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
                ->GetBool("prefSetAuthorOnSave", false);
        if (saveAuthor) {
            const std::string Author =
                GetApplication()
                    .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
                    ->GetASCII("prefAuthor", "");
            LastModifiedBy.setValue(Author.c_str());
        }

        return saveToFile(FileName.getValue());
    }

    return false;
}

bool Document::saveToFile(const char* filename) const

{
    signalStartSave(*this, filename);

    auto hGrp = GetApplication().GetParameterGroupByPath(
        "User parameter:BaseApp/Preferences/Document");
    int compression = static_cast<int>(hGrp->GetInt("CompressionLevel", 7));
    compression = Base::clamp<int>(compression, Z_NO_COMPRESSION, Z_BEST_COMPRESSION);

    bool policy = GetApplication()
                      .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
                      ->GetBool("BackupPolicy", true);

    auto canonical_path = [](const char* filename) {
        try {
#ifdef FC_OS_WIN32
            QString utf8Name = QString::fromUtf8(filename);
            auto realpath = fs::weakly_canonical(fs::absolute(fs::path(utf8Name.toStdWString())));
            std::string nativePath = QString::fromStdWString(realpath.native()).toStdString();
#else
            auto realpath = fs::weakly_canonical(fs::absolute(fs::path(filename)));
            std::string nativePath = realpath.native();
#endif
            // In case some folders in the path do not exist
            auto parentPath = realpath.parent_path();
            fs::create_directories(parentPath);

            return nativePath;
        }
        catch (const std::exception&) {
#ifdef FC_OS_WIN32
            QString utf8Name = QString::fromUtf8(filename);
            auto parentPath = fs::absolute(fs::path(utf8Name.toStdWString())).parent_path();
#else
            auto parentPath = fs::absolute(fs::path(filename)).parent_path();
#endif
            fs::create_directories(parentPath);

            return std::string(filename);
        }
    };

    // realpath is canonical filename i.e. without symlink
    std::string nativePath = canonical_path(filename);

    // check if file is writeable, then block the save if it is not.
    Base::FileInfo originalFileInfo(nativePath);
    if (originalFileInfo.exists() && !originalFileInfo.isWritable()) {
        throw Base::FileException("Unable to save document because file is marked as read-only or write permission is not available.", originalFileInfo);
    }

    // make a tmp. file where to save the project data first and then rename to
    // the actual file name. This may be useful if overwriting an existing file
    // fails so that the data of the work up to now isn't lost.
    std::string uuid = Base::Uuid::createUuid();
    std::string fn = nativePath;
    if (policy) {
        fn += ".";
        fn += uuid;
    }


    // open extra scope to close ZipWriter properly
    {
        Base::FileInfo tmp(fn);
        Base::ofstream file(tmp, std::ios::out | std::ios::binary);

        Base::ZipWriter writer(file);
        if (!file.is_open()) {
            throw Base::FileException("Failed to open file", tmp);
        }

        writer.setComment("FreeCAD Document");
        writer.setLevel(compression);
        writer.putNextEntry("Document.xml");

        if (hGrp->GetBool("SaveBinaryBrep", false)) {
            writer.setMode("BinaryBrep");
        }

        writer.Stream() << "<?xml version='1.0' encoding='utf-8'?>" << '\n'
                        << "<!--" << '\n'
                        << " FreeCAD Document, see https://www.freecad.org for more information..."
                        << '\n'
                        << "-->" << '\n';
        Document::Save(writer);

        // Special handling for Gui document.
        signalSaveDocument(writer);

        // write additional files
        writer.writeFiles();
        if (writer.hasErrors()) {
            // retrieve Writer error strings
            std::stringstream message;
            message << "Failed to write all data to file ";
            message << writer.getErrors().front();
            throw Base::FileException(message.str().c_str(), tmp);
        }

        GetApplication().signalSaveDocument(*this);
    }

    if (policy) {
        // if saving the project data succeeded rename to the actual file name
        int count_bak = static_cast<int>(GetApplication()
                            .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
                            ->GetInt("CountBackupFiles", 1));
        bool backup = GetApplication()
                          .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
                          ->GetBool("CreateBackupFiles", true);
        if (!backup) {
            count_bak = -1;
        }
        bool useFCBakExtension =
            GetApplication()
                .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
                ->GetBool("UseFCBakExtension", true);
        std::string saveBackupDateFormat =
            GetApplication()
                .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")
                ->GetASCII("SaveBackupDateFormat", "%Y%m%d-%H%M%S");

        BackupPolicy backupPolicy;
        if (useFCBakExtension) {
            backupPolicy.setPolicy(BackupPolicy::TimeStamp);
            backupPolicy.useBackupExtension(useFCBakExtension);
            backupPolicy.setDateFormat(saveBackupDateFormat);
        }
        else {
            backupPolicy.setPolicy(BackupPolicy::Standard);
        }
        backupPolicy.setNumberOfFiles(count_bak);
        backupPolicy.apply(fn, nativePath);
    }

    signalFinishSave(*this, filename);

    return true;
}

void Document::registerLabel(const std::string& newLabel)

{
    if (!newLabel.empty()) {
        d->objectLabelManager.addExactName(newLabel);
    }
}

void Document::unregisterLabel(const std::string& oldLabel)

{
    if (!oldLabel.empty()) {
        d->objectLabelManager.removeExactName(oldLabel);
    }
}

bool Document::containsLabel(const std::string& label)

{
    return d->objectLabelManager.containsName(label);
}

std::string Document::makeUniqueLabel(const std::string& modelLabel)

{
    if (modelLabel.empty()) {
        return {};
    }

    return d->objectLabelManager.makeUniqueName(modelLabel, 3);
}

bool Document::isAnyRestoring()

{
    return globalIsRestoring;
}

// Open the document
void Document::restore(const char* filename,

                       bool delaySignal,

                       const std::vector<std::string>& objNames)

{
    clearUndos();
    d->activeObject = nullptr;

    bool signal = false;
    Document* activeDoc = GetApplication().getActiveDocument();
    if (!d->objectArray.empty()) {
        signal = true;
        GetApplication().signalDeleteDocument(*this);
        d->clearDocument();
    }

    Base::FlagToggler<> flag(globalIsRestoring, false);

    setStatus(Document::PartialDoc, false);

    d->clearRecomputeLog();
    d->objectLabelManager.clear();
    d->objectArray.clear();
    d->objectNameManager.clear();
    d->objectMap.clear();
    d->objectIdMap.clear();
    d->lastObjectId = 0;

    if (signal) {
        GetApplication().signalNewDocument(*this, true);
        if (activeDoc == this) {
            GetApplication().setActiveDocument(this);
        }
    }

    if (!filename) {
        filename = FileName.getValue();
    }
    Base::FileInfo fi(filename);
    Base::ifstream file(fi, std::ios::in | std::ios::binary);
    std::streambuf* buf = file.rdbuf();
    std::streamoff size = buf->pubseekoff(0, std::ios::end, std::ios::in);
    buf->pubseekoff(0, std::ios::beg, std::ios::in);
    if (size < 22) {  // an empty zip archive has 22 bytes
        throw Base::FileException("Invalid project file", filename);
    }

    zipios::ZipInputStream zipstream(file);
    Base::XMLReader reader(filename, zipstream);

    if (!reader.isValid()) {
        throw Base::FileException("Error reading compression file", filename);
    }

    GetApplication().signalStartRestoreDocument(*this);
    setStatus(Document::Restoring, true);

    d->partialLoadObjects.clear();
    for (auto& name : objNames) {
        d->partialLoadObjects.emplace(name, true);
    }
    try {
        Document::Restore(reader);
    }
    catch (const Base::Exception& e) {
        Base::Console().error("Invalid Document.xml: %s\n", e.what());
        setStatus(Document::RestoreError, true);
    }

    d->partialLoadObjects.clear();
    d->programVersion = reader.ProgramVersion;

    // Special handling for Gui document, the view representations must already
    // exist, what is done in Restore().
    // Note: This file doesn't need to be available if the document has been created
    // without GUI. But if available then follow after all data files of the App document.
    signalRestoreDocument(reader);
    reader.readFiles(zipstream);

    DocumentP::checkStringHasher(reader);

    if (reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestore)) {
        setStatus(Document::PartialRestore, true);
        Base::Console().error("There were errors while loading the file. Some data might have been "
                              "modified or not recovered at all. Look above for more specific "
                              "information about the objects involved.\n");
    }

    if (!delaySignal) {
        afterRestore(true);
    }
}

bool Document::afterRestore(const bool checkPartial)

{
    Base::FlagToggler<> flag(globalIsRestoring, false);
    if (!afterRestore(d->objectArray, checkPartial)) {
        FC_WARN("Reload partial document " << getName());
        GetApplication().signalPendingReloadDocument(*this);
        return false;
    }
    GetApplication().signalFinishRestoreDocument(*this);
    setStatus(Document::Restoring, false);
    return true;
}

bool Document::afterRestore(const std::vector<DocumentObject*>& objArray, bool checkPartial)

{
    checkPartial = checkPartial && testStatus(Document::PartialDoc);
    if (checkPartial && !d->touchedObjs.empty()) {
        return false;
    }

    // some link type property cannot restore link information until other
    // objects has been restored. For example, PropertyExpressionEngine and
    // PropertySheet with expression containing label reference. So we add the
    // Property::afterRestore() interface to let them sort it out. Note, this
    // API is not called in object dedpenency order, because the order
    // information is not ready yet.
    std::map<DocumentObject*, std::vector<Property*>> propMap;
    for (auto obj : objArray) {
        auto& props = propMap[obj];
        obj->getPropertyList(props);
        for (auto prop : props) {
            try {
                prop->afterRestore();
            }
            catch (const Base::Exception& e) {
                FC_ERR("Failed to restore " << obj->getFullName() << '.' << prop->getName() << ": "
                                            << e.what());
            }
        }
    }

    if (checkPartial && !d->touchedObjs.empty()) {
        // partial document touched, signal full reload
        return false;
    }

    std::set<DocumentObject*> objSet(objArray.begin(), objArray.end());
    auto objs = getDependencyList(objArray.empty() ? d->objectArray : objArray, DepSort);
    for (auto obj : objs) {
        if (objSet.find(obj) == objSet.end()) {
            continue;
        }
        try {
            for (auto prop : propMap[obj]) {
                prop->onContainerRestored();
            }
            bool touched = false;
            auto returnCode =
                obj->ExpressionEngine.execute(PropertyExpressionEngine::ExecuteOnRestore, &touched);
            if (returnCode != DocumentObject::StdReturn) {
                FC_ERR("Expression engine failed to restore " << obj->getFullName() << ": "
                                                              << returnCode->Why);
                d->addRecomputeLog(returnCode);
            }
            obj->onDocumentRestored();
            if (touched) {
                d->touchedObjs.insert(obj);
            }
        }
        catch (const Base::Exception& e) {
            d->addRecomputeLog(e.what(), obj);
            FC_ERR("Failed to restore " << obj->getFullName() << ": " << e.what());
        }
        catch (std::exception& e) {
            d->addRecomputeLog(e.what(), obj);
            FC_ERR("Failed to restore " << obj->getFullName() << ": " << e.what());
        }
        catch (...) {

            // If a Python exception occurred, it must be cleared immediately.
            // Otherwise, the interpreter remains in a dirty state, causing
            // Segfaults later when FreeCAD interacts with Python.
            if (PyErr_Occurred()) {
                Base::Console().error("Python error during object restore:\n");
                PyErr_Print(); // Print the traceback to stderr/Console
                PyErr_Clear(); // Reset the interpreter state
            }

            d->addRecomputeLog("Unknown exception on restore", obj);
            FC_ERR("Failed to restore " << obj->getFullName() << ": " << "unknown exception");
        }
        if (obj->isValid()) {
            auto& props = propMap[obj];
            props.clear();
            // refresh properties in case the object changes its property list
            obj->getPropertyList(props);
            for (auto prop : props) {
                auto link = freecad_cast<PropertyLinkBase*>(prop);
                int res {0};
                std::string errMsg;
                if (link && ((res = link->checkRestore(&errMsg)) != 0)) {
                    d->touchedObjs.insert(obj);
                    if (res == 1 || checkPartial) {
                        FC_WARN(obj->getFullName() << '.' << prop->getName() << ": " << errMsg);
                        setStatus(Document::LinkStampChanged, true);
                        if (checkPartial) {
                            return false;
                        }
                    }
                    else {
                        FC_ERR(obj->getFullName() << '.' << prop->getName() << ": " << errMsg);
                        d->addRecomputeLog(errMsg, obj);
                        setStatus(Document::PartialRestore, true);
                    }
                }
            }
        }

        if (checkPartial && !d->touchedObjs.empty()) {
            // partial document touched, signal full reload
            return false;
        }
        if (!d->touchedObjs.contains(obj)) {
            obj->purgeTouched();
        }

        signalFinishRestoreObject(*obj);
    }

    d->touchedObjs.clear();
    return true;
}

bool Document::isSaved() const

{
    const std::string name = FileName.getValue();
    return !name.empty();
}

/** Label is the visible name of a document shown e.g. in the windows title

 * or in the tree view. The label almost (but not always e.g. if you manually change it)

 * matches with the file name where the document is stored to.

 * In contrast to Label the method getName() returns the internal name of the document that only

 * matches with Label when loading or creating a document because then both are set to the same

 * value. Since the internal name cannot be changed during runtime it must differ from the Label

 * after saving the document the first time or saving it under a new file name.

 * @ note More than one document can have the same label name.

 * @ note The internal is always guaranteed to be unique because @ref Application::newDocument()

 * checks for a document with the same name and makes it unique if needed. Hence you cannot rely on

 * that the internal name matches with the name you passed to Application::newDoument(). You should

 * use the method getName() instead.

 */
const char* Document::getName() const

{
    // return GetApplication().getDocumentName(this);
    return myName.c_str();
}

std::string Document::getFullName() const

{
    return myName;
}

void Document::setAutoCreated(bool value) {
    autoCreated = value;
}

bool Document::isAutoCreated() const {
    return autoCreated;
}

const char* Document::getProgramVersion() const

{
    return d->programVersion.c_str();
}

const char* Document::getFileName() const

{
    return testStatus(TempDoc) ? TransientDir.getValue() : FileName.getValue();
}

/// Remove all modifications. After this call The document becomes valid again.
void Document::purgeTouched() // NOLINT

{
    for (const auto It : d->objectArray) {
        It->purgeTouched();
    }
}

bool Document::isTouched() const

{
    for (const auto It : d->objectArray) {
        if (It->isTouched()) {
            return true;
        }
    }
    return false;
}

vector<DocumentObject*> Document::getTouched() const

{
    vector<DocumentObject*> result;

    for (auto It : d->objectArray) {
        if (It->isTouched()) {
            result.push_back(It);
        }
    }

    return result;
}

void Document::setClosable(const bool c) // NOLINT

{
    setStatus(Document::Closable, c);
}

bool Document::isClosable() const

{
    return testStatus(Document::Closable);
}

int Document::countObjects() const

{
    return static_cast<int>(d->objectArray.size());
}

void Document::getLinksTo(std::set<DocumentObject*>& links,

                          const DocumentObject* obj,

                          const int options,

                          const int maxCount,

                          const std::vector<DocumentObject*>& objs) const

{
    std::map<const DocumentObject*, std::vector<DocumentObject*>> linkMap;

    for (auto o : !objs.empty() ? objs : d->objectArray) {
        if (o == obj) {
            continue;
        }
        auto linked = o;
        if ((options & GetLinkArrayElement) != 0) {
            linked = o->getLinkedObject(false);
        }
        else {
            const auto ext = o->getExtensionByType<LinkBaseExtension>(true);
            linked =
                ext ? ext->getTrueLinkedObject(false, nullptr, 0, true) : o->getLinkedObject(false);
        }

        if (linked && linked != o) {
            if ((options & GetLinkRecursive) != 0) {
                linkMap[linked].push_back(o);
            }
            else if (linked == obj || !obj) {
                if (((options & GetLinkExternal) != 0) && linked->getDocument() == o->getDocument()) {
                    continue;
                }
                if ((options & GetLinkedObject) != 0) {
                    links.insert(linked);
                }
                else {
                    links.insert(o);
                }
                if ((maxCount != 0) && maxCount <= static_cast<int>(links.size())) {
                    return;
                }
            }
        }
    }

    if ((options & GetLinkRecursive) == 0) {
        return;
    }

    std::vector<const DocumentObject*> current(1, obj);
    for (int depth = 0; !current.empty(); ++depth) {
        if (GetApplication().checkLinkDepth(depth, MessageOption::Error) == 0) {
            break;
        }
        std::vector<const DocumentObject*> next;
        for (const DocumentObject* o : current) {
            auto iter = linkMap.find(o);
            if (iter == linkMap.end()) {
                continue;
            }
            for (DocumentObject* link : iter->second) {
                if (links.insert(link).second) {
                    if ((maxCount != 0) && maxCount <= static_cast<int>(links.size())) {
                        return;
                    }
                    next.push_back(link);
                }
            }
        }
        current = std::move(next);
    }
}

bool Document::hasLinksTo(const DocumentObject* obj) const

{
    std::set<DocumentObject*> links;
    getLinksTo(links, obj, 0, 1);
    return !links.empty();
}

std::vector<DocumentObject*> Document::getInList(const DocumentObject* me) const

{
    // result list
    std::vector<DocumentObject*> result;
    // go through all objects
    for (const auto& [name, object] : d->objectMap) {
        // get the outList and search if me is in that list
        std::vector<DocumentObject*> OutList = object->getOutList();
        for (const auto obj : OutList) {
            if (obj && obj == me) {
                // add the parent object
                result.push_back(object);
            }
        }
    }
    return result;
}

// This function unifies the old _rebuildDependencyList() and
// getDependencyList().  The algorithm basically obtains the object dependency
// by recrusivly visiting the OutList of each object in the given object array.
// It makes sure to call getOutList() of each object once and only once, which
// makes it much more efficient than calling getRecursiveOutList() on each
// individual object.
//
// The problem with the original algorithm is that, it assumes the objects
// inside any OutList are all within the given object array, so it does not
// recursively call getOutList() on those dependent objects inside. This
// assumption is broken by the introduction of PropertyXLink which can link to
// external object.
//
static void buildDependencyList(const std::vector<DocumentObject*>& objectArray,

                                const int options,

                                 std::vector<DocumentObject*>* depObjs,

                                 DependencyList* depList,

                                 std::map<DocumentObject*, Vertex>* objectMap,

                                 bool* touchCheck = nullptr)

{
    std::map<DocumentObject*, std::vector<DocumentObject*>> outLists;
    std::deque<DocumentObject*> objs;

    if (objectMap) {
        objectMap->clear();
    }
    if (depList) {
        depList->clear();
    }

    const int op = ((options & Document::DepNoXLinked) != 0) ? DocumentObject::OutListNoXLinked : 0;
    for (auto obj : objectArray) {
        objs.push_back(obj);
        while (!objs.empty()) {
            auto objF = objs.front();
            objs.pop_front();
            if (!objF || !objF->isAttachedToDocument()) {
                continue;
            }

            auto it = outLists.find(objF);
            if (it != outLists.end()) {
                continue;
            }

            if (touchCheck) {
                if (objF->isTouched() || (objF->mustExecute() != 0)) {
                    // early termination on touch check
                    *touchCheck = true;
                    return;
                }
            }
            if (depObjs) {
                depObjs->push_back(objF);
            }
            if (objectMap && depList) {
                (*objectMap)[objF] = add_vertex(*depList);
            }

            auto& outList = outLists[objF];
            outList = objF->getOutList(op);
            objs.insert(objs.end(), outList.begin(), outList.end());
        }
    }

    if (objectMap && depList) {
        for (const auto& [key, objects] : outLists) {
            for (auto obj : objects) {
                if (obj && obj->isAttachedToDocument()) {
                    add_edge((*objectMap)[key], (*objectMap)[obj], *depList);
                }
            }
        }
    }
}

std::vector<DocumentObject*>

Document::getDependencyList(const std::vector<DocumentObject*>& objs, int options)

{
    std::vector<DocumentObject*> ret;
    if ((options & DepSort) == 0) {
        buildDependencyList(objs, options, &ret, nullptr, nullptr);
        return ret;
    }

    DependencyList depList;
    std::map<DocumentObject*, Vertex> objectMap;
    std::map<Vertex, DocumentObject*> vertexMap;

    buildDependencyList(objs, options, nullptr, &depList, &objectMap);

    for (auto& v : objectMap) {
        vertexMap[v.second] = v.first;
    }

    std::list<Vertex> make_order;
    try {
        boost::topological_sort(depList, std::front_inserter(make_order));
    }
    catch (const std::exception& e) {
        if ((options & DepNoCycle) != 0) {
            // Use boost::strong_components to find cycles. It groups strongly
            // connected vertices as components, and therefore each component
            // forms a cycle.
            std::vector<int> c(vertexMap.size());
            std::map<int, std::vector<Vertex>> components;
            boost::strong_components(
                depList,
                boost::make_iterator_property_map(c.begin(),
                                                  boost::get(boost::vertex_index, depList),
                                                  c[0]));
            for (size_t i = 0; i < c.size(); ++i) {
                components[c[i]].push_back(i);
            }

            FC_ERR("Dependency cycles: ");
            std::ostringstream ss;
            ss << '\n';
            for (auto& [key, vertexes] : components) {
                if (vertexes.size() == 1) {
                    // For components with only one member, we still need to
                    // check if there it is self looping.
                    auto it = vertexMap.find(vertexes[0]);
                    if (it == vertexMap.end()) {
                        continue;
                    }
                    // Try search the object in its own out list
                    for (auto obj : it->second->getOutList()) {
                        if (obj == it->second) {
                            ss << '\n' << it->second->getFullName() << '\n';
                            break;
                        }
                    }
                    continue;
                }
                // For components with more than one member, they form a loop together
                for (size_t i = 0; i < vertexes.size(); ++i) {
                    auto it = vertexMap.find(vertexes[i]);
                    if (it == vertexMap.end()) {
                        continue;
                    }
                    if (i % 6 == 0) {
                        ss << '\n';
                    }
                    ss << it->second->getFullName() << ", ";
                }
                ss << '\n';
            }
            FC_ERR(ss.str());
            FC_THROWM(Base::RuntimeError, e.what());
        }
        FC_ERR(e.what());
        ret = DocumentP::partialTopologicalSort(objs);
        std::reverse(ret.begin(), ret.end());
        return ret;
    }

    for (auto i = make_order.rbegin(); i != make_order.rend(); ++i) {
        ret.push_back(vertexMap[*i]);
    }
    return ret;
}

std::vector<Document*> Document::getDependentDocuments(const bool sort)

{
    return getDependentDocuments({this}, sort);
}

std::vector<Document*> Document::getDependentDocuments(std::vector<Document*> docs,

                                                            const bool sort)

{
    DependencyList depList;
    std::map<Document*, Vertex> docMap;
    std::map<Vertex, Document*> vertexMap;

    std::vector<Document*> ret;
    if (docs.empty()) {
        return ret;
    }

    auto outLists = PropertyXLink::getDocumentOutList();
    std::set<Document*> docSet;
    docSet.insert(docs.begin(), docs.end());
    if (sort) {
        for (auto doc : docs) {
            docMap[doc] = add_vertex(depList);
        }
    }
    while (!docs.empty()) {
        auto doc = docs.back();
        docs.pop_back();

        auto it = outLists.find(doc);
        if (it == outLists.end()) {
            continue;
        }

        const auto& vertex = docMap[doc];
        for (auto depDoc : it->second) {
            if (docSet.insert(depDoc).second) {
                docs.push_back(depDoc);
                if (sort) {
                    docMap[depDoc] = add_vertex(depList);
                }
            }
            add_edge(vertex, docMap[depDoc], depList);
        }
    }

    if (!sort) {
        ret.insert(ret.end(), docSet.begin(), docSet.end());
        return ret;
    }

    std::list<Vertex> make_order;
    try {
        boost::topological_sort(depList, std::front_inserter(make_order));
    }
    catch (const std::exception& e) {
        std::string msg("Document::getDependentDocuments: ");
        msg += e.what();
        throw Base::RuntimeError(msg);
    }

    for (auto& v : docMap) {
        vertexMap[v.second] = v.first;
    }
    for (auto rIt = make_order.rbegin(); rIt != make_order.rend(); ++rIt) {
        ret.push_back(vertexMap[*rIt]);
    }
    return ret;
}

void Document::_rebuildDependencyList(const std::vector<DocumentObject*>& objs)
{
    (void)objs;
}

/**

 * @brief Signal that object identifiers, typically a property or document object has been renamed.

 *

 * This function iterates through all document object in the document, and calls its

 * renameObjectIdentifiers functions.

 *

 * @param paths Map with current and new names

 */

void Document::renameObjectIdentifiers(

    const std::map<ObjectIdentifier, ObjectIdentifier>& paths,

    const std::function<bool(const DocumentObject*)>& selector) // NOLINT

{
    std::map<ObjectIdentifier, ObjectIdentifier> extendedPaths;

    auto it = paths.begin();
    while (it != paths.end()) {
        extendedPaths[it->first.canonicalPath()] = it->second.canonicalPath();
        ++it;
    }

    for (const auto object : d->objectArray) {
        if (selector(object)) {
            object->renameObjectIdentifiers(extendedPaths);
        }
    }
}

void Document::setPreRecomputeHook(const PreRecomputeHook& hook)

{
     d->_preRecomputeHook = hook;
}

int Document::recompute(const std::vector<DocumentObject*>& objs,

                        bool force,

                        bool* hasError,

                        int options)

{
    ZoneScoped;

    if (d->undoing || d->rollback) {
        if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) {
            FC_WARN("Ignore document recompute on undo/redo");
        }
        return 0;
    }

    int objectCount = 0;
    if (testStatus(Document::PartialDoc)) {
        if (mustExecute()) {
            FC_WARN("Please reload partial document '" << Label.getValue()
                                                       << "' for recomputation.");
        }
        return 0;
    }
    if (testStatus(Document::Recomputing)) {
        // this is clearly a bug in the calling instance
        FC_ERR("Recursive calling of recompute for document " << getName());
        return 0;
    }
    // The 'SkipRecompute' flag can be (tmp.) set to avoid too many
    // time expensive recomputes
    if (!force && testStatus(Document::SkipRecompute)) {
        signalSkipRecompute(*this, objs);
        return 0;
    }

    // delete recompute log
    d->clearRecomputeLog();

    FC_TIME_INIT(t);

    Base::ObjectStatusLocker<Document::Status, Document> exe(Document::Recomputing, this);

    // This will hop into the main thread, fire signalBeforeRecompute(),
    // and *block* the worker until the main thread is done, avoiding races
    // between any running Python code and the rest of the recompute call.
    if (d->_preRecomputeHook) {
        d->_preRecomputeHook();
    }

    //////////////////////////////////////////////////////////////////////////
    // FIXME Comment by Realthunder:
    // the topologicalSrot() below cannot handle partial recompute, haven't got
    // time to figure out the code yet, simply use back boost::topological_sort
    // for now, that is, rely on getDependencyList() to do the sorting. The
    // downside is, it didn't take advantage of the ready built InList, nor will
    // it report for cyclic dependency.
    //////////////////////////////////////////////////////////////////////////

    /*   // get the sorted vector of all dependent objects and go though it from the end

       auto depObjs = getDependencyList(objs.empty()?d->objectArray:objs);

       vector<DocumentObject*> topoSortedObjects = topologicalSort(depObjs);

       if (topoSortedObjects.size() != depObjs.size()){

           cerr << "Document::recompute(): cyclic dependency detected" << '\n';

           topoSortedObjects = d->partialTopologicalSort(depObjs);

       }

       std::reverse(topoSortedObjects.begin(),topoSortedObjects.end());

   */

    // alt:
    auto topoSortedObjects =
        getDependencyList(objs.empty() ? d->objectArray : objs, DepSort | options);

    for (auto obj : topoSortedObjects) {
        obj->setStatus(ObjectStatus::PendingRecompute, true);
    }

    ParameterGrp::handle hGrp =
        GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document");
    bool canAbort = hGrp->GetBool("CanAbortRecompute", true);

    FC_TIME_INIT(t2);

    try {
        std::set<DocumentObject*> filter;
        size_t idx = 0;
        // maximum two passes to allow some form of dependency inversion
        for (int passes = 0; passes < 2 && idx < topoSortedObjects.size(); ++passes) {
            std::unique_ptr<Base::SequencerLauncher> seq;
            if (canAbort) {
                seq = std::make_unique<Base::SequencerLauncher>("Recompute...",
                                                                topoSortedObjects.size());
            }
            FC_LOG("Recompute pass " << passes);
            for (; idx < topoSortedObjects.size(); ++idx) {
                auto obj = topoSortedObjects[idx];
                if (!obj->isAttachedToDocument() || filter.find(obj) != filter.end()) {
                    continue;
                }
                // ask the object if it should be recomputed
                bool doRecompute = false;
                if (obj->mustRecompute()) {
                    doRecompute = true;
                    ++objectCount;
                    int res = _recomputeFeature(obj);
                    if (res != 0) {
                        if (hasError) {
                            *hasError = true;
                        }
                        if (res < 0) {
                            passes = 2;
                            break;
                        }
                        // if something happened filter all object in its
                        // inListRecursive from the queue then proceed
                        obj->getInListEx(filter, true);
                        filter.insert(obj);
                        continue;
                    }
                }
                if (obj->isTouched() || doRecompute) {
                    signalRecomputedObject(*obj);
                    obj->purgeTouched();
                    // set all dependent object touched to force recompute
                    for (auto inObjIt : obj->getInList()) {
                        inObjIt->enforceRecompute();
                    }
                }
                if (seq) {
                    seq->next(true);
                }
            }
            // check if all objects are recomputed but still thouched
            for (size_t i = 0; i < topoSortedObjects.size(); ++i) {
                auto obj = topoSortedObjects[i];
                obj->setStatus(ObjectStatus::Recompute2, false);
                if (!filter.contains(obj) && obj->isTouched()) {
                    if (passes > 0) {
                        FC_ERR(obj->getFullName() << " still touched after recompute");
                    }
                    else {
                        FC_LOG(obj->getFullName() << " still touched after recompute");
                        if (idx >= topoSortedObjects.size()) {
                            // let's start the next pass on the first touched object
                            idx = i;
                        }
                        obj->setStatus(ObjectStatus::Recompute2, true);
                    }
                }
            }
        }
    }
    catch (Base::Exception& e) {
        e.reportException();
    }

    FC_TIME_LOG(t2, "Recompute");

    for (auto obj : topoSortedObjects) {
        if (!obj->isAttachedToDocument()) {
            continue;
        }
        obj->setStatus(ObjectStatus::PendingRecompute, false);
        obj->setStatus(ObjectStatus::Recompute2, false);
    }

    signalRecomputed(*this, topoSortedObjects);

    FC_TIME_LOG(t, "Recompute total");

    if (!d->_RecomputeLog.empty()) {
        if (!testStatus(Status::IgnoreErrorOnRecompute)) {
            for (auto it : topoSortedObjects) {
                if (it->isError()) {
                    const char* text = getErrorDescription(it);
                    if (text) {
                        Base::Console().error("%s: %s\n", it->Label.getValue(), text);
                    }
                }
            }
        }
    }

    for (auto doc : GetApplication().getDocuments()) {
        decltype(doc->d->pendingRemove) objects;
        objects.swap(doc->d->pendingRemove);
        for (auto& o : objects) {
            try {
                if (auto obj = o.getObject()) {
                    obj->getDocument()->removeObject(obj->getNameInDocument());
                }
            }
            catch (Base::Exception& e) {
                e.reportException();
                FC_ERR("error when removing object " << o.getDocumentName() << '#'
                                                     << o.getObjectName());
            }
        }
    }
    return objectCount;
}

/*!

  Does almost the same as topologicalSort() until no object with an input degree of zero

  can be found. It then searches for objects with an output degree of zero until neither

  an object with input or output degree can be found. The remaining objects form one or

  multiple cycles.

  An alternative to this method might be:

  https://en.wikipedia.org/wiki/Tarjan%E2%80%99s_strongly_connected_components_algorithm

 */
std::vector<DocumentObject*>

DocumentP::partialTopologicalSort(const std::vector<DocumentObject*>& objects)

{
    vector<DocumentObject*> ret;
    ret.reserve(objects.size());
    // pairs of input and output degree
    map<DocumentObject*, std::pair<int, int>> countMap;

    for (auto objectIt : objects) {
        // we need inlist with unique entries
        auto in = objectIt->getInList();
        std::sort(in.begin(), in.end());
        in.erase(std::unique(in.begin(), in.end()), in.end());

        // we need outlist with unique entries
        auto out = objectIt->getOutList();
        std::sort(out.begin(), out.end());
        out.erase(std::unique(out.begin(), out.end()), out.end());

        countMap[objectIt] = std::make_pair(in.size(), out.size());
    }

    std::list<DocumentObject*> degIn;
    std::list<DocumentObject*> degOut;

    bool removeVertex = true;
    while (removeVertex) {
        removeVertex = false;

        // try input degree
        auto degInIt = find_if(countMap.begin(),
                               countMap.end(),
                               [](pair<DocumentObject*, pair<int, int>> vertex) -> bool {
                                   return vertex.second.first == 0;
                               });

        if (degInIt != countMap.end()) {
            removeVertex = true;
            degIn.push_back(degInIt->first);
            degInIt->second.first = degInIt->second.first - 1;

            // we need outlist with unique entries
            auto out = degInIt->first->getOutList();
            std::sort(out.begin(), out.end());
            out.erase(std::unique(out.begin(), out.end()), out.end());

            for (auto outListIt : out) {
                auto outListMapIt = countMap.find(outListIt);
                if (outListMapIt != countMap.end()) {
                    outListMapIt->second.first = outListMapIt->second.first - 1;
                }
            }
        }
    }

    // make the output degree negative if input degree is negative
    // to mark the vertex as processed
    for (auto& [obj, pair] : countMap) {
        if (pair.first < 0) {
            pair.second = -1;
        }
    }

    removeVertex = degIn.size() != objects.size();
    while (removeVertex) {
        removeVertex = false;

        auto degOutIt = find_if(countMap.begin(),
                                countMap.end(),
                                [](pair<DocumentObject*, pair<int, int>> vertex) -> bool {
                                    return vertex.second.second == 0;
                                });

        if (degOutIt != countMap.end()) {
            removeVertex = true;
            degOut.push_front(degOutIt->first);
            degOutIt->second.second = degOutIt->second.second - 1;

            // we need inlist with unique entries
            auto in = degOutIt->first->getInList();
            std::sort(in.begin(), in.end());
            in.erase(std::unique(in.begin(), in.end()), in.end());

            for (auto inListIt : in) {
                auto inListMapIt = countMap.find(inListIt);
                if (inListMapIt != countMap.end()) {
                    inListMapIt->second.second = inListMapIt->second.second - 1;
                }
            }
        }
    }

    // at this point we have no root object any more
    for (auto countIt : countMap) {
        if (countIt.second.first > 0 && countIt.second.second > 0) {
            degIn.push_back(countIt.first);
        }
    }

    ret.insert(ret.end(), degIn.begin(), degIn.end());
    ret.insert(ret.end(), degOut.begin(), degOut.end());

    return ret;
}

std::vector<DocumentObject*>

DocumentP::topologicalSort(const std::vector<DocumentObject*>& objects) const

{
    // topological sort algorithm described here:
    // https://de.wikipedia.org/wiki/Topologische_Sortierung#Algorithmus_f.C3.BCr_das_Topologische_Sortieren
    vector<DocumentObject*> ret;
    ret.reserve(objects.size());
    map<DocumentObject*, int> countMap;

    for (auto objectIt : objects) {
        // We now support externally linked objects
        // if(!obj->isAttachedToDocument() || obj->getDocument()!=this)
        if (!objectIt->isAttachedToDocument()) {
            continue;
        }
        // we need inlist with unique entries
        auto in = objectIt->getInList();
        std::sort(in.begin(), in.end());
        in.erase(std::unique(in.begin(), in.end()), in.end());

        countMap[objectIt] = in.size();
    }

    auto rootObjeIt = find_if(countMap.begin(),
                              countMap.end(),
                              [](pair<DocumentObject*, int> count) -> bool {
                                  return count.second == 0;
                              });

    if (rootObjeIt == countMap.end()) {
        cerr << "Document::topologicalSort: cyclic dependency detected (no root object)" << '\n';
        return ret;
    }

    while (rootObjeIt != countMap.end()) {
        rootObjeIt->second = rootObjeIt->second - 1;

        // we need outlist with unique entries
        auto out = rootObjeIt->first->getOutList();
        std::sort(out.begin(), out.end());
        out.erase(std::unique(out.begin(), out.end()), out.end());

        for (auto outListIt : out) {
            auto outListMapIt = countMap.find(outListIt);
            if (outListMapIt != countMap.end()) {
                outListMapIt->second = outListMapIt->second - 1;
            }
        }
        ret.push_back(rootObjeIt->first);

        rootObjeIt = find_if(countMap.begin(),
                             countMap.end(),
                             [](pair<DocumentObject*, int> count) -> bool {
                                 return count.second == 0;
                             });
    }

    return ret;
}

std::vector<DocumentObject*> Document::topologicalSort() const

{
    return d->topologicalSort(d->objectArray);
}

const char* Document::getErrorDescription(const DocumentObject* Obj) const

{
    return d->findRecomputeLog(Obj);
}

// call the recompute of the Feature and handle the exceptions and errors.
int Document::_recomputeFeature(DocumentObject* Feat) // NOLINT
{
    FC_LOG("Recomputing " << Feat->getFullName());

    DocumentObjectExecReturn* returnCode = nullptr;
    try {
        returnCode = Feat->ExpressionEngine.execute(PropertyExpressionEngine::ExecuteNonOutput);
        if (returnCode == DocumentObject::StdReturn) {
            returnCode = Feat->recompute();
            if (returnCode == DocumentObject::StdReturn) {
                returnCode =
                    Feat->ExpressionEngine.execute(PropertyExpressionEngine::ExecuteOutput);
            }
        }
    }
    catch (Base::AbortException& e) {
        e.reportException();
        FC_LOG("Failed to recompute " << Feat->getFullName() << ": " << e.what());
        d->addRecomputeLog("User abort", Feat);
        return -1;
    }
    catch (const Base::MemoryException& e) {
        FC_ERR("Memory exception in " << Feat->getFullName() << " thrown: " << e.what());
        d->addRecomputeLog("Out of memory exception", Feat);
        return 1;
    }
    catch (Base::Exception& e) {
        e.reportException();
        FC_LOG("Failed to recompute " << Feat->getFullName() << ": " << e.what());
        d->addRecomputeLog(e.what(), Feat);
        return 1;
    }
    catch (std::exception& e) {
        FC_ERR("Exception in " << Feat->getFullName() << " thrown: " << e.what());
        d->addRecomputeLog(e.what(), Feat);
        return 1;
    }
#ifndef FC_DEBUG
    catch (...) {
        FC_ERR("Unknown exception in " << Feat->getFullName() << " thrown");
        d->addRecomputeLog("Unknown exception!", Feat);
        return 1;
    }
#endif

    if (returnCode == DocumentObject::StdReturn) {
        Feat->resetError();
    }
    else {
        returnCode->Which = Feat;
        d->addRecomputeLog(returnCode);
        FC_LOG("Failed to recompute " << Feat->getFullName() << ": " << returnCode->Why);
        return 1;
    }
    return 0;
}

bool Document::recomputeFeature(DocumentObject* feature, bool recursive)

{
    // delete recompute log
    d->clearRecomputeLog(feature);

    // verify that the feature is (active) part of the document
    if (!feature->isAttachedToDocument()) {
        return false;
    }

    if (recursive) {
        bool hasError = false;
        recompute({feature}, true, &hasError);
        return !hasError;
    }
    _recomputeFeature(feature);
    signalRecomputedObject(*feature);
    return feature->isValid();
}

DocumentObject* Document::addObject(const char* sType,

                                    const char* pObjectName,

                                    const bool isNew,

                                    const char* viewType,

                                    const bool isPartial)

{
    const Base::Type type =
        Base::Type::getTypeIfDerivedFrom(sType, DocumentObject::getClassTypeId(), true);
    if (type.isBad()) {
        std::stringstream str;
        str << "Document::addObject: '" << sType << "' is not a document object type";
        throw Base::TypeError(str.str());
    }

    void* typeInstance = type.createInstance();
    if (!typeInstance) {
        return nullptr;
    }

    auto* pcObject = static_cast<DocumentObject*>(typeInstance);
    pcObject->setDocument(this);

    _addObject(pcObject,
               pObjectName,
               AddObjectOption::SetNewStatus
                   | (isPartial ? AddObjectOption::SetPartialStatus : AddObjectOption::UnsetPartialStatus)
                   | (isNew ? AddObjectOption::DoSetup : AddObjectOption::None)
                   | AddObjectOption::ActivateObject, 
               viewType);

    // return the Object
    return pcObject;
}

std::vector<DocumentObject*>

Document::addObjects(const char* sType, const std::vector<std::string>& objectNames, bool isNew)

{
    Base::Type type =
        Base::Type::getTypeIfDerivedFrom(sType, DocumentObject::getClassTypeId(), true);
    if (type.isBad()) {
        std::stringstream str;
        str << "'" << sType << "' is not a document object type";
        throw Base::TypeError(str.str());
    }

    std::vector<DocumentObject*> objects;
    objects.resize(objectNames.size());
    std::generate(objects.begin(), objects.end(), [&] {
        return static_cast<DocumentObject*>(type.createInstance());
    });
    // the type instance could be a null pointer, it is enough to check the first element
    if (!objects.empty() && !objects[0]) {
        objects.clear();
        return objects;
    }

    for (auto it = objects.begin(); it != objects.end(); ++it) {
        size_t index = std::distance(objects.begin(), it);
        DocumentObject* pcObject = *it;
        pcObject->setDocument(this);

        // Add the object but only activate the last one
        bool isLast = index == (objects.size() - 1);
        _addObject(pcObject,
                   objectNames[index].c_str(),
                   AddObjectOption::SetNewStatus
                       | (isNew ? AddObjectOption::DoSetup : AddObjectOption::None)
                       | (isLast ? AddObjectOption::ActivateObject : AddObjectOption::None));
    }

    return objects;
}

void Document::addObject(DocumentObject* pcObject, const char* pObjectName)

{
    if (pcObject->getDocument()) {
        throw Base::RuntimeError("Document object is already added to a document");
    }

    pcObject->setDocument(this);

    _addObject(pcObject, pObjectName, AddObjectOption::SetNewStatus | AddObjectOption::ActivateObject);
}

void Document::_addObject(DocumentObject* pcObject, const char* pObjectName, AddObjectOptions options, const char* viewType)
{
    // get unique name
    string ObjectName;
    if (!Base::Tools::isNullOrEmpty(pObjectName)) {
        ObjectName = getUniqueObjectName(pObjectName);
    }
    else {
        ObjectName = getUniqueObjectName(pcObject->getTypeId().getName());
    }
 
    // insert in the name map
    d->objectMap[ObjectName] = pcObject;
    d->objectNameManager.addExactName(ObjectName);
    // cache the pointer to the name string in the Object (for performance of
    // DocumentObject::getNameInDocument())
    pcObject->pcNameInDocument = &(d->objectMap.find(ObjectName)->first);
    // Register the current Label even though it might be about to change
    registerLabel(pcObject->Label.getStrValue());

    // generate object id and add to id map + object array
    if (pcObject->_Id == 0) {
        pcObject->_Id = ++d->lastObjectId;
    }
    d->objectIdMap[pcObject->_Id] = pcObject;
    d->objectArray.push_back(pcObject);
     
     // do no transactions if we do a rollback!
    if (!d->rollback) {
        // Undo stuff
        _checkTransaction(nullptr, nullptr, __LINE__);
        if (d->activeUndoTransaction) {
            d->activeUndoTransaction->addObjectDel(pcObject);
        }
     }
    // If we are restoring, don't set the Label object now; it will be restored later. This is to
    // avoid potential duplicate label conflicts later.
    if (options.testFlag(AddObjectOption::SetNewStatus) && !d->StatusBits.test(Restoring)) {
        pcObject->Label.setValue(ObjectName);
    }

    // Call the object-specific initialization
    if (!isPerformingTransaction() && options.testFlag(AddObjectOption::DoSetup)) {
        pcObject->setupObject();
    }
 
    if (options.testFlag(AddObjectOption::SetNewStatus)) {
        pcObject->setStatus(ObjectStatus::New, true);    
    }
    if (options.testFlag(AddObjectOption::SetPartialStatus) || options.testFlag(AddObjectOption::UnsetPartialStatus)) {
        pcObject->setStatus(ObjectStatus::PartialObject, options.testFlag(AddObjectOption::SetPartialStatus));
    }

    if (Base::Tools::isNullOrEmpty(viewType)) {
        viewType = pcObject->getViewProviderNameOverride();
    }
    pcObject->_pcViewProviderName = viewType ? viewType : "";

    signalNewObject(*pcObject);
 
    // do no transactions if we do a rollback!
    if (!d->rollback && d->activeUndoTransaction) {
        signalTransactionAppend(*pcObject, d->activeUndoTransaction);
    }
 
    if (options.testFlag(AddObjectOption::ActivateObject)) {
        d->activeObject = pcObject;
        signalActivatedObject(*pcObject);    
    }
}

bool Document::containsObject(const DocumentObject* pcObject) const

{
    // We could look for the object in objectMap (keyed by object name),
    // or search in objectArray (a O(n) vector search) but looking by Id
    // in objectIdMap would be fastest.
    auto found = d->objectIdMap.find(pcObject->getID());
    return found != d->objectIdMap.end() && found->second == pcObject;
}

/// Remove an object out of the document
void Document::removeObject(const char* sName)

{
    auto pos = d->objectMap.find(sName);
    if (pos == d->objectMap.end()){
        FC_MSG("Object " << sName << " already deleted in document " << getName());
        return;
    }

    if (pos->second->testStatus(ObjectStatus::PendingRecompute)) {
        // TODO: shall we allow removal if there is active undo transaction?
        FC_MSG("pending remove of " << sName << " after recomputing document " << getName());
        d->pendingRemove.emplace_back(pos->second);
        return;
    }

    _removeObject(pos->second, RemoveObjectOption::MayRemoveWhileRecomputing | RemoveObjectOption::MayDestroyOutOfTransaction);
}
void Document::_removeObject(DocumentObject* pcObject, RemoveObjectOptions options)
{
    if (!options.testFlag(RemoveObjectOption::MayRemoveWhileRecomputing) && testStatus(Document::Recomputing)) {
        FC_ERR("Cannot delete " << pcObject->getFullName() << " while recomputing");
        return;
    }
    
    TransactionLocker tlock;

    _checkTransaction(pcObject, nullptr, __LINE__);

    auto pos = d->objectMap.find(pcObject->getNameInDocument());
    if (pos == d->objectMap.end()) {
        FC_ERR("Internal error, could not find " << pcObject->getFullName() << " to remove");
    }

    if (options.testFlag(RemoveObjectOption::PreserveChildrenVisibility) 
        && !d->rollback && d->activeUndoTransaction && pcObject->hasChildElement()) {
        // Preserve link group sub object global visibilities. Normally those
        // claimed object should be hidden in global coordinate space. However,
        // when the group is deleted, the user will naturally try to show the
        // children, which may now in the global space. When the parent is
        // undeleted, having its children shown in both the local and global
        // coordinate space is very confusing. Hence, we preserve the visibility
        // here        
        for (auto& sub : pcObject->getSubObjects()) {
            if (sub.empty()) {
                continue;
            }
            if (sub[sub.size() - 1] != '.') {
                sub += '.';
            }
            auto sobj = pcObject->getSubObject(sub.c_str());
            if (sobj && sobj->getDocument() == this && !sobj->Visibility.getValue()) {
                d->activeUndoTransaction->addObjectChange(sobj, &sobj->Visibility);
            }
        }
    }

    if (d->activeObject == pcObject) {
        d->activeObject = nullptr;
    }

    // Mark the object as about to be removed
    pcObject->setStatus(ObjectStatus::Remove, true);
    if (!d->undoing && !d->rollback) {
        pcObject->unsetupObject();
    }
    signalDeletedObject(*pcObject);
    signalTransactionRemove(*pcObject, d->rollback ? nullptr : d->activeUndoTransaction);
    breakDependency(pcObject, true);

    // TODO Check me if it's needed (2015-09-01, Fat-Zer)
    // remove the tip if needed
    if (Tip.getValue() == pcObject) {
        Tip.setValue(nullptr);
        TipName.setValue("");
    }

    // remove from map
    pcObject->setStatus(ObjectStatus::Remove, false);  // Unset the bit to be on the safe side
    d->objectIdMap.erase(pcObject->_Id);
    d->objectNameManager.removeExactName(pos->first);
    unregisterLabel(pcObject->Label.getStrValue());

    // do no transactions if we do a rollback!
    if (!d->rollback && d->activeUndoTransaction) {
        d->activeUndoTransaction->addObjectNew(pcObject);
    }

    std::unique_ptr<DocumentObject> tobedestroyed;
    if ((options.testFlag(RemoveObjectOption::MayDestroyOutOfTransaction) && !d->rollback && !d->activeUndoTransaction) 
        || (options.testFlag(RemoveObjectOption::DestroyOnRollback) && d->rollback)) {
        // if not saved in undo -> delete object later
        std::unique_ptr<DocumentObject> delobj(pos->second);
        tobedestroyed.swap(delobj);
        tobedestroyed->setStatus(ObjectStatus::Destroy, true);
    }

    for (auto it = d->objectArray.begin();
         it != d->objectArray.end();
         ++it) {
        if (*it == pcObject) {
            d->objectArray.erase(it);
            break;
        }
    }
    
    // In case the object gets deleted the pointer must be nullified
    if (tobedestroyed) {
        tobedestroyed->pcNameInDocument = nullptr;
    }

    // Erase last to avoid invalidating pcObject->pcNameInDocument 
    // when it is still needed in Transaction::addObjectNew
    d->objectMap.erase(pos);
}

void Document::breakDependency(DocumentObject* pcObject, const bool clear) // NOLINT

{
    // Nullify all dependent objects
    PropertyLinkBase::breakLinks(pcObject, d->objectArray, clear);
}

std::vector<DocumentObject*>

Document::copyObject(const std::vector<DocumentObject*>& objs, bool recursive, bool returnAll)

{
    std::vector<DocumentObject*> deps;
    if (!recursive) {
        deps = objs;
    }
    else {
        deps = getDependencyList(objs, DepNoXLinked | DepSort);
    }

    if (!testStatus(TempDoc) && !isSaved() && PropertyXLink::hasXLink(deps)) {
        throw Base::RuntimeError(
            "Document must be saved at least once before link to external objects");
    }

    MergeDocuments md(this);
    // if not copying recursively then suppress possible warnings
    md.setVerbose(recursive);

    unsigned int memsize = 1000;  // ~ for the meta-information
    for (auto it : deps) {
        memsize += it->getMemSize();
    }

    // if less than ~10 MB
    bool use_buffer = (memsize < 0xA00000);
    QByteArray res;
    try {
        res.reserve(memsize);
    }
    catch (const Base::MemoryException&) {
        use_buffer = false;
    }

    std::vector<DocumentObject*> imported;
    if (use_buffer) {
        Base::ByteArrayOStreambuf obuf(res);
        std::ostream ostr(&obuf);
        exportObjects(deps, ostr);

        Base::ByteArrayIStreambuf ibuf(res);
        std::istream istr(nullptr);
        istr.rdbuf(&ibuf);
        imported = md.importObjects(istr);
    }
    else {
        static Base::FileInfo fi(Application::getTempFileName());
        Base::ofstream ostr(fi, std::ios::out | std::ios::binary);
        exportObjects(deps, ostr);
        ostr.close();

        Base::ifstream istr(fi, std::ios::in | std::ios::binary);
        imported = md.importObjects(istr);
    }

    if (returnAll || imported.size() != deps.size()) {
        return imported;
    }

    std::unordered_map<DocumentObject*, size_t> indices;
    size_t i = 0;
    for (auto o : deps) {
        indices[o] = i++;
    }
    std::vector<DocumentObject*> result;
    result.reserve(objs.size());
    for (auto o : objs) {
        result.push_back(imported[indices[o]]);
    }
    return result;
}

std::vector<DocumentObject*>

Document::importLinks(const std::vector<DocumentObject*>& objs)

{
    std::set<DocumentObject*> links;
    getLinksTo(links, nullptr, GetLinkExternal, 0, objs);

    std::vector<DocumentObject*> vecObjs;
    vecObjs.insert(vecObjs.end(), links.begin(), links.end());
    std::vector<DocumentObject*> depObjs = getDependencyList(vecObjs);
    if (depObjs.empty()) {
        FC_ERR("nothing to import");
        return depObjs;
    }

    for (auto it = depObjs.begin(); it != depObjs.end();) {
        auto obj = *it;
        if (obj->getDocument() == this) {
            it = depObjs.erase(it);
            continue;
        }
        ++it;
        if (obj->testStatus(PartialObject)) {
            throw Base::RuntimeError(
                "Cannot import partial loaded object. Please reload the current document");
        }
    }

    Base::FileInfo fi(Application::getTempFileName());
    {
        // save stuff to temp file
        Base::ofstream str(fi, std::ios::out | std::ios::binary);
        MergeDocuments mimeView(this);
        exportObjects(depObjs, str);
        str.close();
    }
    Base::ifstream str(fi, std::ios::in | std::ios::binary);
    MergeDocuments mimeView(this);
    depObjs = mimeView.importObjects(str);
    str.close();
    fi.deleteFile();

    const auto& nameMap = mimeView.getNameMap();

    // First, find all link type properties that needs to be changed
    std::map<Property*, std::unique_ptr<Property>> propMap;
    std::vector<Property*> propList;
    for (auto obj : links) {
        propList.clear();
        obj->getPropertyList(propList);
        for (auto prop : propList) {
            auto linkProp = freecad_cast<PropertyLinkBase*>(prop);
            if (linkProp && !prop->testStatus(Property::Immutable) && !obj->isReadOnly(prop)) {
                auto copy = linkProp->CopyOnImportExternal(nameMap);
                if (copy) {
                    propMap[linkProp].reset(copy);
                }
            }
        }
    }

    // Then change them in one go. Note that we don't make change in previous
    // loop, because a changed link property may break other depending link
    // properties, e.g. a link sub referring to some sub object of an xlink, If
    // that sub object is imported with a different name, and xlink is changed
    // before this link sub, it will break.
    for (auto& v : propMap) {
        v.first->Paste(*v.second);
    }

    return depObjs;
}

DocumentObject* Document::moveObject(DocumentObject* obj, const bool recursive)

{
    if (!obj) {
        return nullptr;
    }
    Document* that = obj->getDocument();
    if (that == this) {
        return nullptr;  // nothing todo
    }

    // True object move without copy is only safe when undo is off on both
    // documents.
    if (!recursive && (d->iUndoMode == 0) && (that->d->iUndoMode == 0) && !that->d->rollback) {
        // all object of the other document that refer to this object must be nullified
        that->breakDependency(obj, false);
        const std::string objname = getUniqueObjectName(obj->getNameInDocument());
        that->_removeObject(obj);
        this->_addObject(obj, objname.c_str());
        obj->setDocument(this);
        return obj;
    }

    std::vector<DocumentObject*> deps;
    if (recursive) {
        deps = getDependencyList({obj}, DepNoXLinked | DepSort);
    }
    else {
        deps.push_back(obj);
    }

    const auto objs = copyObject(deps, false);
    if (objs.empty()) {
        return nullptr;
    }
    // Some object may delete its children if deleted, so we collect the IDs
    // or all depending objects for safety reason.
    std::vector<int> ids;
    ids.reserve(deps.size());
    for (const auto o : deps) {
        ids.push_back(static_cast<int>(o->getID()));
    }

    // We only remove object if it is the moving object or it has no
    // depending objects, i.e. an empty inList, which is why we need to
    // iterate the depending list backwards.
    for (auto iter = ids.rbegin(); iter != ids.rend(); ++iter) {
        const auto o = that->getObjectByID(*iter);
        if (!o) {
            continue;
        }
        if (iter == ids.rbegin() || o->getInList().empty()) {
            that->removeObject(o->getNameInDocument());
        }
    }
    return objs.back();
}

DocumentObject* Document::getActiveObject() const

{
    return d->activeObject;
}

DocumentObject* Document::getObject(const char* Name) const

{
    const auto pos = d->objectMap.find(Name);

    return pos != d->objectMap.end() ?pos->second:nullptr;
}

DocumentObject* Document::getObjectByID(const long id) const

{
    const auto it = d->objectIdMap.find(id);

    return it != d->objectIdMap.end() ?it->second:nullptr;
}


// Note: This method is only used in Tree.cpp slotChangeObject(), see explanation there
bool Document::isIn(const DocumentObject* pFeat) const

{
    for (const auto& [key, object] : d->objectMap) {
        if (object == pFeat) {
            return true;
        }
    }

    return false;
}

const char* Document::getObjectName(const DocumentObject* pFeat) const

{
    for (const auto& [key, object] : d->objectMap) {
        if (object == pFeat) {
            return key.c_str();
        }
    }

    return nullptr;
}

std::string Document::getUniqueObjectName(const char* proposedName) const

{
    if (!proposedName || *proposedName == '\0') {
        return {};
    }
    std::string cleanName = Base::Tools::getIdentifier(proposedName);

    if (!d->objectNameManager.containsName(cleanName)) {
        // Not in use yet, name is OK
        return cleanName;
    }
    return d->objectNameManager.makeUniqueName(cleanName, 3);
}

    bool

Document::haveSameBaseName(const std::string& name, const std::string& label)

{
    // Both Labels and Names use the same decomposition rules for names,
    // i.e. the default one supplied by UniqueNameManager, so we can use either
    // of the name managers to do this test.
    return d->objectNameManager.haveSameBaseName(name, label);
}

std::string Document::getStandardObjectLabel(const char* modelName, int digitCount) const

{
    return d->objectLabelManager.makeUniqueName(modelName, digitCount);
}

std::vector<DocumentObject*> Document::getDependingObjects() const

{
    return getDependencyList(d->objectArray);
}

const std::vector<DocumentObject*>& Document::getObjects() const

{
    return d->objectArray;
}

std::vector<DocumentObject*> Document::getObjectsOfType(const Base::Type& typeId) const

{
    std::vector<DocumentObject*> Objects;
    for (auto it : d->objectArray) {
        if (it->isDerivedFrom(typeId)) {
            Objects.push_back(it);
        }
    }
    return Objects;
}

std::vector<DocumentObject*> Document::getObjectsOfType(const std::vector<Base::Type>& types) const

{
    std::vector<DocumentObject*> Objects;
    for (auto it : d->objectArray) {
        for (auto& typeId : types) {
            if (it->isDerivedFrom(typeId)) {
                Objects.push_back(it);
                break; // Prevent adding several times the same object.
            }
        }
    }
    return Objects;
}

std::vector<DocumentObject*> Document::getObjectsWithExtension(const Base::Type& typeId,

                                                               const bool derived) const

{

    std::vector<DocumentObject*> Objects;
    for (auto it : d->objectArray) {
        if (it->hasExtension(typeId, derived)) {
            Objects.push_back(it);
        }
    }
    return Objects;
}


std::vector<DocumentObject*>

Document::findObjects(const Base::Type& typeId, const char* objname, const char* label) const

{
    boost::cmatch what;
    boost::regex rx_name;
    boost::regex rx_label;

    if (objname) {
        rx_name.set_expression(objname);
    }

    if (label) {
        rx_label.set_expression(label);
    }

    std::vector<DocumentObject*> Objects;
    DocumentObject* found = nullptr;
    for (const auto it : d->objectArray) {
        if (it->isDerivedFrom(typeId)) {
            found = it;

            if (!rx_name.empty() && !boost::regex_search(it->getNameInDocument(), what, rx_name)) {
                found = nullptr;
            }

            if (!rx_label.empty() && !boost::regex_search(it->Label.getValue(), what, rx_label)) {
                found = nullptr;
            }

            if (found) {
                Objects.push_back(found);
            }
        }
    }
    return Objects;
}

int Document::countObjectsOfType(const Base::Type& typeId) const

{
    return std::count_if(d->objectMap.begin(), d->objectMap.end(), [&](const auto& it) {
        return it.second->isDerivedFrom(typeId);
    });
}

int Document::countObjectsOfType(const char* typeName) const

{
    const Base::Type type = Base::Type::fromName(typeName);
    return type.isBad() ? 0 : countObjectsOfType(type);
}

PyObject* Document::getPyObject()

{
    return Py::new_reference_to(d->DocumentPythonObject);
}

std::vector<DocumentObject*> Document::getRootObjects() const

{
    std::vector<DocumentObject*> ret;

    for (auto objectIt : d->objectArray) {
        if (objectIt->getInList().empty()) {
            ret.push_back(objectIt);
        }
    }

    return ret;
}

std::vector<DocumentObject*> Document::getRootObjectsIgnoreLinks() const

{
    std::vector<DocumentObject*> ret;

    for (const auto &objectIt : d->objectArray) {
        auto list = objectIt->getInList();
        bool noParents = list.empty();

        if (!noParents) {
            // App::Document getRootObjects returns the root objects of the dependency graph.
            // So if an object is referenced by an App::Link, it will not be returned by that
            // function. So here, as we want the tree-root level objects, we check if all the
            // parents are links. In which case it's still a root object.
            noParents = std::all_of(list.cbegin(), list.cend(), [](DocumentObject* obj) {
                return obj->isDerivedFrom<Link>();
            });
        }

        if (noParents) {
            ret.push_back(objectIt);
        }
    }

    return ret;
}

void DocumentP::findAllPathsAt(const std::vector<Node>& all_nodes,

                               const size_t id,

                               std::vector<Path>& all_paths,

                               Path tmp)

{
    if (std::ranges::find(tmp, id) != tmp.end()) {
        tmp.push_back(id);
        all_paths.push_back(std::move(tmp));
        return;  // a cycle
    }

    tmp.push_back(id);
    if (all_nodes[id].empty()) {
        all_paths.push_back(std::move(tmp));
        return;
    }

    for (size_t i = 0; i < all_nodes[id].size(); i++) {
        const Path& tmp2(tmp);
        findAllPathsAt(all_nodes, all_nodes[id][i], all_paths, tmp2);
    }
}

std::vector<std::list<DocumentObject*>>
Document::getPathsByOutList(const DocumentObject* from, const DocumentObject* to) const
{
    std::map<const DocumentObject*, size_t> indexMap;
    for (size_t i = 0; i < d->objectArray.size(); ++i) {
        indexMap[d->objectArray[i]] = i;
    }

    std::vector<Node> all_nodes(d->objectArray.size());
    for (size_t i = 0; i < d->objectArray.size(); ++i) {
        const DocumentObject* obj = d->objectArray[i];
        std::vector<DocumentObject*> outList = obj->getOutList();
        for (const auto it : outList) {
            all_nodes[i].push_back(indexMap[it]);
        }
    }

    std::vector<std::list<DocumentObject*>> array;
    if (from == to) {
        return array;
    }

    size_t index_from = indexMap[from];
    size_t index_to = indexMap[to];
    std::vector<Path> all_paths;
    DocumentP::findAllPathsAt(all_nodes, index_from, all_paths, Path());

    for (const Path& it : all_paths) {
        auto jt = std::ranges::find(it, index_to);
        if (jt != it.end()) {
            array.push_back({});
            auto& path = array.back();
            for (auto kt = it.begin(); kt != jt; ++kt) {
                path.push_back(d->objectArray[*kt]);
            }

            path.push_back(d->objectArray[*jt]);
        }
    }

    // remove duplicates
    std::sort(array.begin(), array.end());
    array.erase(std::unique(array.begin(), array.end()), array.end());

    return array;
}

bool Document::mustExecute() const

{
    if (PropertyXLink::hasXLink(this)) {
        bool touched = false;
        buildDependencyList(d->objectArray, 0, nullptr, nullptr, nullptr, &touched);
        return touched;
    }

    for (const auto It : d->objectArray) {
        if (It->isTouched() || It->mustExecute() == 1) {
            return true;
        }
    }
    return false;
}