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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <algorithm>
#include <array>

#include <comphelper/classids.hxx>
#include <comphelper/embeddedobjectcontainer.hxx>
#include <comphelper/lok.hxx>

#include <vcl/svapp.hxx>
#include <editeng/outliner.hxx>
#include <editeng/eeitem.hxx>
#include <svx/svdoutl.hxx>
#include <editeng/editdata.hxx>
#include <editeng/lrspitem.hxx>
#include <editeng/bulletitem.hxx>
#include <svx/svdpagv.hxx>
#include <editeng/fhgtitem.hxx>
#include <editeng/outlobj.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdograf.hxx>
#include <svx/svdopage.hxx>
#include <sfx2/lokhelper.hxx>
#include <editeng/pbinitem.hxx>
#include <svx/svdundo.hxx>
#include <svl/hint.hxx>
#include <editeng/adjustitem.hxx>
#include <editeng/editobj.hxx>
#include <svx/unopage.hxx>
#include <editeng/flditem.hxx>
#include <svx/sdr/contact/displayinfo.hxx>
#include <svx/svditer.hxx>
#include <svx/svdlayer.hxx>
#include <svx/sdtmfitm.hxx>
#include <svx/sdtagitm.hxx>
#include <svx/sdtcfitm.hxx>
#include <svx/xfillit0.hxx>
#include <com/sun/star/animations/XAnimationNode.hpp>
#include <com/sun/star/animations/XTimeContainer.hpp>
#include <com/sun/star/container/XEnumerationAccess.hpp>
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XNodeList.hpp>
#include <com/sun/star/xml/dom/XNamedNodeMap.hpp>
#include <rtl/ustring.hxx>
#include <sal/log.hxx>
#include <o3tl/enumarray.hxx>
#include <o3tl/safeint.hxx>
#include <xmloff/autolayout.hxx>

#include <Outliner.hxx>
#include <app.hrc>
#include <createunopageimpl.hxx>
#include <drawdoc.hxx>
#include <sdmod.hxx>
#include <sdpage.hxx>
#include <sdresid.hxx>
#include <stlsheet.hxx>
#include <strings.hrc>
#include <strings.hxx>
#include <bitmaps.hlst>
#include <glob.hxx>
#include <anminfo.hxx>
#include <undo/undomanager.hxx>
#include <undo/undoobjects.hxx>
#include <svx/sdr/contact/viewobjectcontact.hxx>
#include <svx/sdr/contact/viewcontact.hxx>
#include <svx/sdr/contact/objectcontact.hxx>
#include <svx/unoapi.hxx>
#include <unokywds.hxx>

#include <set>

using namespace ::sd;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace com::sun::star::xml::dom;
using ::com::sun::star::uno::Reference;


sal_uInt16 SdPage::mnLastPageId = 1;

/*************************************************************************
|*
|*      Ctor
|*
\************************************************************************/

SdPage::SdPage(SdDrawDocument& rNewDoc, bool bMasterPage)
:   FmFormPage(rNewDoc, bMasterPage)
,   SdrObjUserCall()
,   mePageKind(PageKind::Standard)
,   meAutoLayout(AUTOLAYOUT_NONE)
,   mbSelected(false)
,   mePresChange(PresChange::Manual)
,   mfTime(1.0)
,   mbSoundOn(false)
,   mbExcluded(false)
,   mbLoopSound(false)
,   mbStopSound(false)
,   mbScaleObjects(true)
,   mbBackgroundFullSize( false )
,   meCharSet(osl_getThreadTextEncoding())
,   mnPaperBin(PAPERBIN_PRINTER_SETTINGS)
,   mpPageLink(nullptr)
,   mnTransitionType(0)
,   mnTransitionSubtype(0)
,   mbTransitionDirection(true)
,   mnTransitionFadeColor(0)
,   mfTransitionDuration(2.0)
,   mbIsPrecious(true)
,   mnPageId(mnLastPageId++)
{
    // The name of the layout of the page is used by SVDRAW to determine the
    // presentation template of the outline objects. Therefore, it already
    // contains the designator for the outline (STR_LAYOUT_OUTLINE).
    maLayoutName = SdResId(STR_LAYOUT_DEFAULT_NAME)+ SD_LT_SEPARATOR STR_LAYOUT_OUTLINE;

    // Stuff that former SetModel did also:
    ConnectLink();
}

namespace
{
    void clearChildNodes(css::uno::Reference<css::animations::XAnimationNode> const & rAnimationNode)
    {
        css::uno::Reference<css::container::XEnumerationAccess > xEnumerationAccess(rAnimationNode, UNO_QUERY);
        if (!xEnumerationAccess.is())
            return;
        css::uno::Reference<css::container::XEnumeration> xEnumeration = xEnumerationAccess->createEnumeration();
        if (!xEnumeration.is())
            return;
        while (xEnumeration->hasMoreElements())
        {
            css::uno::Reference<css::animations::XAnimationNode> xChildNode(xEnumeration->nextElement(), UNO_QUERY);
            if (!xChildNode.is())
                continue;
            clearChildNodes(xChildNode);
            css::uno::Reference<css::animations::XTimeContainer> xAnimationNode(rAnimationNode, UNO_QUERY);
            if (!xAnimationNode.is())
            {
                SAL_WARN("sd.core", "can't remove node child, possible leak");
                continue;
            }
            xAnimationNode->removeChild(xChildNode);
        }
    }
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

SdPage::~SdPage()
{
    DisconnectLink();

    EndListenOutlineText();

    clearChildNodes(mxAnimationNode);

    // clear SdrObjects with broadcasting
    ClearSdrObjList();
}

namespace {

struct OrdNumSorter
{
    bool operator()( SdrObject const * p1, SdrObject const * p2 )
    {
        return p1->GetOrdNum() < p2->GetOrdNum();
    }
};

}

/** returns the nIndex'th object from the given PresObjKind, index starts with 1 */
SdrObject* SdPage::GetPresObj(PresObjKind eObjKind, int nIndex, bool bFuzzySearch /* = false */ )
{
    // first sort all matching shapes with z-order
    std::vector< SdrObject* > aMatches;

    SdrObject* pObj = nullptr;
    maPresentationShapeList.seekShape(0);

    while( (pObj = maPresentationShapeList.getNextShape()) )
    {
        SdAnimationInfo* pInfo = SdDrawDocument::GetShapeUserData(*pObj);
        if( pInfo )
        {
            bool bFound = false;
            if( pInfo->mePresObjKind == eObjKind )
            {
                bFound = true;
            }
            else if( bFuzzySearch && (eObjKind == PresObjKind::Outline) )
            {
                switch( pInfo->mePresObjKind )
                {
                case PresObjKind::Graphic:
                case PresObjKind::Object:
                case PresObjKind::Chart:
                case PresObjKind::OrgChart:
                case PresObjKind::Table:
                case PresObjKind::Calc:
                case PresObjKind::Media:
                    bFound = true;
                    break;
                default:
                    break;
                }
            }
            if( bFound )
            {
                aMatches.push_back( pObj );
            }
        }
    }

    if( nIndex > 0 )
        nIndex--;

    if( (nIndex >= 0) && ( aMatches.size() > o3tl::make_unsigned(nIndex)) )
    {
        if( aMatches.size() > 1 )
            std::nth_element( aMatches.begin(), aMatches.begin() + nIndex, aMatches.end(),
                              OrdNumSorter() );
        return aMatches[nIndex];
    }

    return nullptr;
}

/** create background properties */
void SdPage::EnsureMasterPageDefaultBackground()
{
    if(!mbMaster)
        return;

    // no hard attributes on MasterPage attributes
    getSdrPageProperties().ClearItem();
    SfxStyleSheet* pSheetForPresObj = GetStyleSheetForMasterPageBackground();

    if(pSheetForPresObj)
    {
        // set StyleSheet for background fill attributes
        getSdrPageProperties().SetStyleSheet(pSheetForPresObj);
    }
    else
    {
        // no style found, assert and set at least drawing::FillStyle_NONE
        OSL_FAIL("No Style for MasterPageBackground fill found (!)");
        getSdrPageProperties().PutItem(XFillStyleItem(drawing::FillStyle_NONE));
    }
}

/** creates a presentation object with the given PresObjKind on this page. A user call will be set
*/
SdrObject* SdPage::CreatePresObj(PresObjKind eObjKind, bool bVertical, const ::tools::Rectangle& rRect )
{
    SfxUndoManager* pUndoManager(static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetUndoManager());
    const bool bUndo = pUndoManager && pUndoManager->IsInListAction() && IsInserted();

    SdrObject* pSdrObj = nullptr;

    bool bForceText = false;    // forces the shape text to be set even if it's empty
    bool bEmptyPresObj = true;

    switch( eObjKind )
    {
        case PresObjKind::Title:
        {
            pSdrObj = new SdrRectObj(getSdrModelFromSdrPage(), OBJ_TITLETEXT);

            if (mbMaster)
            {
                pSdrObj->SetNotVisibleAsMaster(true);
            }
        }
        break;

        case PresObjKind::Outline:
        {
            pSdrObj = new SdrRectObj(getSdrModelFromSdrPage(), OBJ_OUTLINETEXT);

            if (mbMaster)
            {
                pSdrObj->SetNotVisibleAsMaster(true);
            }
        }
        break;

        case PresObjKind::Notes:
        {
            pSdrObj = new SdrRectObj(getSdrModelFromSdrPage(), OBJ_TEXT);

            if (mbMaster)
            {
                pSdrObj->SetNotVisibleAsMaster(true);
            }
        }
        break;

        case PresObjKind::Text:
        {
            pSdrObj = new SdrRectObj(getSdrModelFromSdrPage(), OBJ_TEXT);
        }
        break;

        case PresObjKind::Graphic:
        {
            BitmapEx aBmpEx(BMP_PRESOBJ_GRAPHIC);
            Graphic  aGraphic( aBmpEx );
            OutputDevice &aOutDev = *Application::GetDefaultDevice();
            aOutDev.Push();

            aOutDev.SetMapMode( aGraphic.GetPrefMapMode() );
            Size aSizePix = aOutDev.LogicToPixel( aGraphic.GetPrefSize() );
            aOutDev.SetMapMode(MapMode(MapUnit::Map100thMM));

            Size aSize = aOutDev.PixelToLogic(aSizePix);
            Point aPnt (0, 0);
            ::tools::Rectangle aRect (aPnt, aSize);
            pSdrObj = new SdrGrafObj(getSdrModelFromSdrPage(), aGraphic, aRect);
            aOutDev.Pop();
        }
        break;

        case PresObjKind::Media:
        case PresObjKind::Object:
        {
            pSdrObj = new SdrOle2Obj(getSdrModelFromSdrPage());
            BitmapEx aBmpEx(BMP_PRESOBJ_OBJECT);
            Graphic aGraphic( aBmpEx );
            static_cast<SdrOle2Obj*>(pSdrObj)->SetGraphic(aGraphic);
        }
        break;

        case PresObjKind::Chart:
        {
            pSdrObj = new SdrOle2Obj(getSdrModelFromSdrPage());
            static_cast<SdrOle2Obj*>(pSdrObj)->SetProgName( "StarChart" );
            BitmapEx aBmpEx(BMP_PRESOBJ_CHART);
            Graphic aGraphic( aBmpEx );
            static_cast<SdrOle2Obj*>(pSdrObj)->SetGraphic(aGraphic);
        }
        break;

        case PresObjKind::OrgChart:
        {
            pSdrObj = new SdrOle2Obj(getSdrModelFromSdrPage());
            static_cast<SdrOle2Obj*>(pSdrObj)->SetProgName( "StarOrg" );
            BitmapEx aBmpEx(BMP_PRESOBJ_ORGCHART);
            Graphic aGraphic( aBmpEx );
            static_cast<SdrOle2Obj*>(pSdrObj)->SetGraphic(aGraphic);
        }
        break;

        case PresObjKind::Table:
        case PresObjKind::Calc:
        {
            pSdrObj = new SdrOle2Obj(getSdrModelFromSdrPage());
            static_cast<SdrOle2Obj*>(pSdrObj)->SetProgName( "StarCalc" );
            BitmapEx aBmpEx(BMP_PRESOBJ_TABLE);
            Graphic aGraphic( aBmpEx );
            static_cast<SdrOle2Obj*>(pSdrObj)->SetGraphic(aGraphic);
        }
        break;

        case PresObjKind::Handout:
        {
            // Save the first standard page at SdrPageObj
            // #i105146# We want no content to be displayed for PageKind::Handout,
            // so just never set a page as content
            pSdrObj = new SdrPageObj(getSdrModelFromSdrPage(), nullptr);
        }
        break;

        case PresObjKind::Page:
        {
            // Save note pages at SdrPageObj
            sal_uInt16 nDestPageNum(GetPageNum());

            if(nDestPageNum)
            {
                // decrement only when != 0, else we get a 0xffff
                nDestPageNum -= 1;
            }

            if (nDestPageNum < getSdrModelFromSdrPage().GetPageCount())
            {
                pSdrObj = new SdrPageObj(getSdrModelFromSdrPage(), getSdrModelFromSdrPage().GetPage(nDestPageNum));
            }
            else
            {
                pSdrObj = new SdrPageObj(getSdrModelFromSdrPage());
            }

            pSdrObj->SetResizeProtect(true);
        }
        break;

        case PresObjKind::Header:
        case PresObjKind::Footer:
        case PresObjKind::DateTime:
        case PresObjKind::SlideNumber:
        {
            pSdrObj = new SdrRectObj(getSdrModelFromSdrPage(), OBJ_TEXT);
            bEmptyPresObj = false;
            bForceText = true;
        }
        break;
        default:
            break;
    }

    if (pSdrObj)
    {
        pSdrObj->SetEmptyPresObj(bEmptyPresObj);
        pSdrObj->SetLogicRect(rRect);

        InsertObject(pSdrObj);

        if ( dynamic_cast< const SdrTextObj *>( pSdrObj ) !=  nullptr )
        {
            // Tell the object EARLY that it is vertical to have the
            // defaults for AutoGrowWidth/Height reversed
            if(bVertical)
                static_cast<SdrTextObj*>(pSdrObj)->SetVerticalWriting(true);

            SfxItemSet aTempAttr(static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetPool());
            if( bVertical )
                aTempAttr.Put( makeSdrTextMinFrameWidthItem( rRect.GetSize().Width() ) );
            else
                aTempAttr.Put( makeSdrTextMinFrameHeightItem( rRect.GetSize().Height() ) );

            if (mbMaster)
            {
                // The size of presentation objects on the master page have to
                // be freely selectable by the user.

                // potential problem: This action was still NOT
                // adapted for vertical text. This sure needs to be done.
                if(bVertical)
                    aTempAttr.Put(makeSdrTextAutoGrowWidthItem(false));
                else
                    aTempAttr.Put(makeSdrTextAutoGrowHeightItem(false));
            }

            // check if we need another vertical adjustment than the default
            SdrTextVertAdjust eV = SDRTEXTVERTADJUST_TOP;

            if( (eObjKind == PresObjKind::Footer) && (mePageKind != PageKind::Standard) )
            {
                eV = SDRTEXTVERTADJUST_BOTTOM;
            }
            else if( (eObjKind == PresObjKind::SlideNumber) && (mePageKind != PageKind::Standard) )
            {
                eV = SDRTEXTVERTADJUST_BOTTOM;
            }

            if( eV != SDRTEXTVERTADJUST_TOP )
                aTempAttr.Put(SdrTextVertAdjustItem(eV));

            pSdrObj->SetMergedItemSet(aTempAttr);

            pSdrObj->SetLogicRect(rRect);
        }

        OUString aString = GetPresObjText(eObjKind);
        if( (!aString.isEmpty() || bForceText) && dynamic_cast< const SdrTextObj *>( pSdrObj ) !=  nullptr )
        {
            SdrOutliner* pOutliner = static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetInternalOutliner();

            OutlinerMode nOutlMode = pOutliner->GetMode();
            pOutliner->Init( OutlinerMode::TextObject );
            pOutliner->SetStyleSheet( 0, nullptr );
            pOutliner->SetVertical( bVertical );

            SetObjText( static_cast<SdrTextObj*>(pSdrObj), pOutliner, eObjKind, aString );

            pOutliner->Init( nOutlMode );
            pOutliner->SetStyleSheet( 0, nullptr );
        }

        if( (eObjKind == PresObjKind::Header) || (eObjKind == PresObjKind::Footer) || (eObjKind == PresObjKind::SlideNumber) || (eObjKind == PresObjKind::DateTime) )
        {
            SfxItemSet aTempAttr(static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetPool());
            aTempAttr.Put( SvxFontHeightItem( 493, 100, EE_CHAR_FONTHEIGHT ) );
            aTempAttr.Put( SvxFontHeightItem( 493, 100, EE_CHAR_FONTHEIGHT_CTL ) );
            aTempAttr.Put( SvxFontHeightItem( 493, 100, EE_CHAR_FONTHEIGHT_CJK ) );

            SvxAdjust eH = SvxAdjust::Left;

            if( (eObjKind == PresObjKind::DateTime) && (mePageKind != PageKind::Standard ) )
            {
                eH = SvxAdjust::Right;
            }
            else if( (eObjKind == PresObjKind::Footer) && (mePageKind == PageKind::Standard ) )
            {
                eH = SvxAdjust::Center;
            }
            else if( eObjKind == PresObjKind::SlideNumber )
            {
                eH = SvxAdjust::Right;
            }

            if( eH != SvxAdjust::Left )
                aTempAttr.Put(SvxAdjustItem(eH, EE_PARA_JUST ));

            pSdrObj->SetMergedItemSet(aTempAttr);
        }

        if (mbMaster)
        {
            SdrLayerAdmin& rLayerAdmin(getSdrModelFromSdrPage().GetLayerAdmin());

            // background objects of the master page
            pSdrObj->SetLayer( rLayerAdmin.GetLayerID(sUNO_LayerName_background_objects) );
        }

        // Subscribe object at the style sheet
        // Set style only when one was found (as in 5.2)
        if( mePageKind != PageKind::Handout )
        {
            SfxStyleSheet* pSheetForPresObj = GetStyleSheetForPresObj(eObjKind);
            if(pSheetForPresObj)
                pSdrObj->SetStyleSheet(pSheetForPresObj, false);
        }

        if (eObjKind == PresObjKind::Outline)
        {
            for (sal_uInt16 nLevel = 1; nLevel < 10; nLevel++)
            {
                OUString aName( maLayoutName + " " + OUString::number( nLevel ) );
                SfxStyleSheet* pSheet = static_cast<SfxStyleSheet*>(getSdrModelFromSdrPage().GetStyleSheetPool()->Find(aName, SfxStyleFamily::Page));
                DBG_ASSERT(pSheet, "StyleSheet for outline object not found");
                if (pSheet)
                    pSdrObj->StartListening(*pSheet, DuplicateHandling::Allow);
            }
        }

        if ( eObjKind == PresObjKind::Object   ||
             eObjKind == PresObjKind::Chart    ||
             eObjKind == PresObjKind::OrgChart ||
             eObjKind == PresObjKind::Calc    ||
             eObjKind == PresObjKind::Graphic )
        {
            SfxItemSet aSet( static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetPool() );
            aSet.Put( makeSdrTextContourFrameItem( true ) );
            aSet.Put( SvxAdjustItem( SvxAdjust::Center, EE_PARA_JUST ) );

            pSdrObj->SetMergedItemSet(aSet);
        }

        if( bUndo )
        {
            pUndoManager->AddUndoAction(getSdrModelFromSdrPage().GetSdrUndoFactory().CreateUndoNewObject(*pSdrObj));

            pUndoManager->AddUndoAction( std::make_unique<UndoObjectPresentationKind>( *pSdrObj ) );
            pUndoManager->AddUndoAction( std::make_unique<UndoObjectUserCall>(*pSdrObj) );
        }

        InsertPresObj(pSdrObj, eObjKind);
        pSdrObj->SetUserCall(this);

        pSdrObj->RecalcBoundRect();
    }

    return pSdrObj;
}

/*************************************************************************
|*
|* Creates presentation objects on the master page.
|* All presentation objects get a UserCall to the page.
|*
\************************************************************************/

SfxStyleSheet* SdPage::GetStyleSheetForMasterPageBackground() const
{
    OUString aName(GetLayoutName());
    OUString aSep( SD_LT_SEPARATOR );
    sal_Int32 nPos = aName.indexOf(aSep);

    if (nPos != -1)
    {
        nPos = nPos + aSep.getLength();
        aName = aName.copy(0, nPos);
    }

    aName += STR_LAYOUT_BACKGROUND;

    SfxStyleSheetBasePool* pStShPool = getSdrModelFromSdrPage().GetStyleSheetPool();
    SfxStyleSheetBase*     pResult   = pStShPool->Find(aName, SfxStyleFamily::Page);
    return static_cast<SfxStyleSheet*>(pResult);
}

SfxStyleSheet* SdPage::GetStyleSheetForPresObj(PresObjKind eObjKind) const
{
    OUString aName(GetLayoutName());
    OUString aSep( SD_LT_SEPARATOR );
    sal_Int32 nPos = aName.indexOf(aSep);
    if (nPos != -1)
    {
        nPos = nPos + aSep.getLength();
        aName = aName.copy(0, nPos);
    }

    switch (eObjKind)
    {
        case PresObjKind::Outline:
        {
            aName = GetLayoutName() + " " + OUString::number( 1 );
        }
        break;

        case PresObjKind::Title:
            aName += STR_LAYOUT_TITLE;
            break;

        case PresObjKind::Notes:
            aName += STR_LAYOUT_NOTES;
            break;

        case PresObjKind::Text:
            aName += STR_LAYOUT_SUBTITLE;
            break;

        case PresObjKind::Header:
        case PresObjKind::Footer:
        case PresObjKind::DateTime:
        case PresObjKind::SlideNumber:
            aName += STR_LAYOUT_BACKGROUNDOBJECTS;
            break;

        default:
            break;
    }

    SfxStyleSheetBasePool* pStShPool = getSdrModelFromSdrPage().GetStyleSheetPool();
    SfxStyleSheetBase*     pResult   = pStShPool->Find(aName, SfxStyleFamily::Page);
    return static_cast<SfxStyleSheet*>(pResult);
}

/** returns the presentation style with the given helpid from this masterpage or this
    slides masterpage */
SdStyleSheet* SdPage::getPresentationStyle( sal_uInt32 nHelpId ) const
{
    OUString aStyleName( GetLayoutName() );
    const OUString aSep( SD_LT_SEPARATOR );
    sal_Int32 nIndex = aStyleName.indexOf(aSep);
    if( nIndex != -1 )
        aStyleName = aStyleName.copy(0, nIndex + aSep.getLength());

    const char *pNameId;
    bool bOutline = false;
    switch( nHelpId )
    {
    case HID_PSEUDOSHEET_TITLE:             pNameId = STR_LAYOUT_TITLE;             break;
    case HID_PSEUDOSHEET_SUBTITLE:          pNameId = STR_LAYOUT_SUBTITLE;          break;
    case HID_PSEUDOSHEET_OUTLINE1:
    case HID_PSEUDOSHEET_OUTLINE2:
    case HID_PSEUDOSHEET_OUTLINE3:
    case HID_PSEUDOSHEET_OUTLINE4:
    case HID_PSEUDOSHEET_OUTLINE5:
    case HID_PSEUDOSHEET_OUTLINE6:
    case HID_PSEUDOSHEET_OUTLINE7:
    case HID_PSEUDOSHEET_OUTLINE8:
    case HID_PSEUDOSHEET_OUTLINE9:          pNameId = STR_LAYOUT_OUTLINE; bOutline = true; break;
    case HID_PSEUDOSHEET_BACKGROUNDOBJECTS: pNameId = STR_LAYOUT_BACKGROUNDOBJECTS; break;
    case HID_PSEUDOSHEET_BACKGROUND:        pNameId = STR_LAYOUT_BACKGROUND;        break;
    case HID_PSEUDOSHEET_NOTES:             pNameId = STR_LAYOUT_NOTES;             break;

    default:
        OSL_FAIL( "SdPage::getPresentationStyle(), illegal argument!" );
        return nullptr;
    }
    aStyleName += OUString::createFromAscii(pNameId);
    if (bOutline)
    {
        aStyleName += " " +
            OUString::number( sal_Int32( nHelpId - HID_PSEUDOSHEET_OUTLINE ));
    }

    SfxStyleSheetBasePool* pStShPool = getSdrModelFromSdrPage().GetStyleSheetPool();
    SfxStyleSheetBase*     pResult   = pStShPool->Find(aStyleName, SfxStyleFamily::Page);
    return dynamic_cast<SdStyleSheet*>(pResult);
}

/*************************************************************************
|*
|* The presentation object rObj has changed and is no longer referenced by the
|* presentation object of the master page.
|* The UserCall is deleted.
|*
\************************************************************************/

void SdPage::Changed(const SdrObject& rObj, SdrUserCallType eType, const ::tools::Rectangle& )
{
    if (maLockAutoLayoutArrangement.isLocked())
        return;

    switch (eType)
    {
        case SdrUserCallType::MoveOnly:
        case SdrUserCallType::Resize:
        {
            if ( getSdrModelFromSdrPage().isLocked())
                break;

            if (!mbMaster)
            {
                if (rObj.GetUserCall())
                {
                    SdrObject& _rObj = const_cast<SdrObject&>(rObj);
                    SfxUndoManager* pUndoManager
                        = static_cast<SdDrawDocument&>(getSdrModelFromSdrPage())
                              .GetUndoManager();
                    const bool bUndo
                        = pUndoManager && pUndoManager->IsInListAction() && IsInserted();

                    if (bUndo)
                        pUndoManager->AddUndoAction(
                            std::make_unique<UndoObjectUserCall>(_rObj));

                    // Object was resized by user and does not listen to its slide anymore
                    _rObj.SetUserCall(nullptr);
                }
            }
            else
            {
                // Object of the master page changed, therefore adjust
                // object on all pages
                sal_uInt16 nPageCount = static_cast<SdDrawDocument&>(getSdrModelFromSdrPage())
                                            .GetSdPageCount(mePageKind);

                for (sal_uInt16 i = 0; i < nPageCount; i++)
                {
                    SdPage* pLoopPage = static_cast<SdDrawDocument&>(getSdrModelFromSdrPage())
                                            .GetSdPage(i, mePageKind);

                    if (pLoopPage && this == &(pLoopPage->TRG_GetMasterPage()))
                    {
                        // Page listens to this master page, therefore
                        // adjust AutoLayout
                        pLoopPage->SetAutoLayout(pLoopPage->GetAutoLayout());
                    }
                }
            }
        }
        break;

        case SdrUserCallType::Delete:
        case SdrUserCallType::Removed:
        default:
            break;
    }
}

/*************************************************************************
|*
|* Creates on a master page: background, title- and layout area
|*
\************************************************************************/

void SdPage::CreateTitleAndLayout(bool bInit, bool bCreate )
{
    SfxUndoManager* pUndoManager(static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetUndoManager());
    const bool bUndo = pUndoManager && pUndoManager->IsInListAction() && IsInserted();

    SdPage* pMasterPage = this;

    if (!mbMaster)
    {
        pMasterPage = static_cast<SdPage*>(&(TRG_GetMasterPage()));
    }

    if (!pMasterPage)
    {
        return;
    }

    /**************************************************************************
    * create background, title- and layout area
    **************************************************************************/
    if( mePageKind == PageKind::Standard )
    {
        pMasterPage->EnsureMasterPageDefaultBackground();
    }

    if (static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetDocumentType() != DocumentType::Impress)
        return;

    if( mePageKind == PageKind::Handout && bInit )
    {
        // handout template

        // delete all available handout presentation objects
        SdrObject *pObj=nullptr;
        while( (pObj = pMasterPage->GetPresObj(PresObjKind::Handout)) != nullptr )
        {
            pMasterPage->RemoveObject(pObj->GetOrdNum());

            if( bUndo )
            {
                pUndoManager->AddUndoAction(getSdrModelFromSdrPage().GetSdrUndoFactory().CreateUndoDeleteObject(*pObj));
            }
            else
            {
                SdrObject::Free( pObj );
            }
        }

        std::vector< ::tools::Rectangle > aAreas;
        CalculateHandoutAreas( static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()), pMasterPage->GetAutoLayout(), false, aAreas );

        const bool bSkip = pMasterPage->GetAutoLayout() == AUTOLAYOUT_HANDOUT3;
        std::vector< ::tools::Rectangle >::iterator iter( aAreas.begin() );

        while( iter != aAreas.end() )
        {
            SdrPageObj* pPageObj = static_cast<SdrPageObj*>(pMasterPage->CreatePresObj(PresObjKind::Handout, false, (*iter++)) );
            // #i105146# We want no content to be displayed for PageKind::Handout,
            // so just never set a page as content
            pPageObj->SetReferencedPage(nullptr);

            if( bSkip && iter != aAreas.end() )
                ++iter;
        }
    }

    if( mePageKind != PageKind::Handout )
    {
        SdrObject* pMasterTitle = pMasterPage->GetPresObj( PresObjKind::Title );
        if( pMasterTitle == nullptr )
            pMasterPage->CreateDefaultPresObj(PresObjKind::Title);

        SdrObject* pMasterOutline = pMasterPage->GetPresObj( mePageKind==PageKind::Notes ? PresObjKind::Notes : PresObjKind::Outline );
        if( pMasterOutline == nullptr )
            pMasterPage->CreateDefaultPresObj( mePageKind == PageKind::Standard ? PresObjKind::Outline : PresObjKind::Notes );
    }

    // create header&footer objects

    if( !bCreate )
        return;

    if( mePageKind != PageKind::Standard )
    {
        SdrObject* pHeader = pMasterPage->GetPresObj( PresObjKind::Header );
        if( pHeader == nullptr )
            pMasterPage->CreateDefaultPresObj( PresObjKind::Header );
    }

    SdrObject* pDate   = pMasterPage->GetPresObj( PresObjKind::DateTime );
    if( pDate == nullptr )
        pMasterPage->CreateDefaultPresObj( PresObjKind::DateTime );

    SdrObject* pFooter = pMasterPage->GetPresObj( PresObjKind::Footer );
    if( pFooter == nullptr )
        pMasterPage->CreateDefaultPresObj( PresObjKind::Footer );

    SdrObject* pNumber = pMasterPage->GetPresObj( PresObjKind::SlideNumber );
    if( pNumber == nullptr )
        pMasterPage->CreateDefaultPresObj( PresObjKind::SlideNumber );
}

namespace {

static const o3tl::enumarray<PageKind, char const *> PageKindVector = {
    "PageKind::Standard", "PageKind::Notes", "PageKind::Handout"
};

static const o3tl::enumarray<PresObjKind, const char*> PresObjKindVector = {
    "PRESOBJ_NONE", "PRESOBJ_TITLE", "PRESOBJ_OUTLINE",
    "PRESOBJ_TEXT" ,"PRESOBJ_GRAPHIC" , "PRESOBJ_OBJECT",
    "PRESOBJ_CHART", "PRESOBJ_ORGCHART", "PRESOBJ_TABLE",
    "PRESOBJ_PAGE", "PRESOBJ_HANDOUT",
    "PRESOBJ_NOTES","PRESOBJ_HEADER", "PRESOBJ_FOOTER",
    "PRESOBJ_DATETIME", "PRESOBJ_SLIDENUMBER", "PRESOBJ_CALC",
    "PRESOBJ_MEDIA"
};

void getPresObjProp( const SdPage& rPage, const char* sObjKind, const char* sPageKind, double presObjPropValue[] )
{
    bool bNoObjectFound = true;  //used to break from outer loop

    const std::vector< Reference<XNode> >& objectInfo = static_cast< const SdDrawDocument& >(rPage.getSdrModelFromSdrPage()).GetObjectVector();
    for( const Reference<XNode>& objectNode : objectInfo )
    {
        if(bNoObjectFound)
        {
            Reference<XNamedNodeMap> objectattrlist = objectNode->getAttributes();
            Reference<XNode> objectattr = objectattrlist->getNamedItem("type");
            OUString sObjType = objectattr->getNodeValue();

            if (sObjType.equalsAscii(sObjKind))
            {
                Reference<XNodeList> objectChildren = objectNode->getChildNodes();
                const int objSize = objectChildren->getLength();

                for( int j=0; j< objSize; j++)
                {
                    Reference<XNode> obj = objectChildren->item(j);
                    OUString nodename = obj->getNodeName();

                    //check whether child is blank 'text-node' or 'object-prop' node
                    if(nodename == "object-prop")
                    {
                        Reference<XNamedNodeMap> ObjAttributes = obj->getAttributes();
                        Reference<XNode> ObjPageKind = ObjAttributes->getNamedItem("pagekind");
                        OUString sObjPageKind = ObjPageKind->getNodeValue();

                        if (sObjPageKind.equalsAscii(sPageKind))
                        {
                            Reference<XNode> ObjSizeHeight = ObjAttributes->getNamedItem("relative-height");
                            OUString sValue = ObjSizeHeight->getNodeValue();
                            presObjPropValue[0] = sValue.toDouble();

                            Reference<XNode> ObjSizeWidth = ObjAttributes->getNamedItem("relative-width");
                            sValue = ObjSizeWidth->getNodeValue();
                            presObjPropValue[1] = sValue.toDouble();

                            Reference<XNode> ObjPosX = ObjAttributes->getNamedItem("relative-posX");
                            sValue = ObjPosX->getNodeValue();
                            presObjPropValue[2] = sValue.toDouble();

                            Reference<XNode> ObjPosY = ObjAttributes->getNamedItem("relative-posY");
                            sValue = ObjPosY->getNodeValue();
                            presObjPropValue[3] = sValue.toDouble();

                            bNoObjectFound = false;
                            break;
                        }
                    }
                }
            }
        }
        else
            break;
    }
}

}

SdrObject* SdPage::CreateDefaultPresObj(PresObjKind eObjKind)
{
    if( eObjKind == PresObjKind::Title )
    {
        ::tools::Rectangle aTitleRect( GetTitleRect() );
        return CreatePresObj(PresObjKind::Title, false, aTitleRect);
    }
    else if( eObjKind == PresObjKind::Outline )
    {
        ::tools::Rectangle aLayoutRect( GetLayoutRect() );
        return CreatePresObj( PresObjKind::Outline, false, aLayoutRect);
    }
    else if( eObjKind == PresObjKind::Notes )
    {
        ::tools::Rectangle aLayoutRect( GetLayoutRect() );
        return CreatePresObj( PresObjKind::Notes, false, aLayoutRect);
    }
    else if( (eObjKind == PresObjKind::Footer) || (eObjKind == PresObjKind::DateTime) || (eObjKind == PresObjKind::SlideNumber) || (eObjKind == PresObjKind::Header ) )
    {
        double propvalue[] = {0,0,0,0};
        const char* sObjKind = PresObjKindVector[eObjKind];
        const char* sPageKind = PageKindVector[mePageKind];
        // create footer objects for standard master page
        if( mePageKind == PageKind::Standard )
        {
            const long nLftBorder = GetLeftBorder();
            const long nUppBorder = GetUpperBorder();

            Point aPos ( nLftBorder, nUppBorder );
            Size aSize ( GetSize() );

            aSize.AdjustWidth( -(nLftBorder + GetRightBorder()) );
            aSize.AdjustHeight( -(nUppBorder + GetLowerBorder()) );

            getPresObjProp( *this, sObjKind, sPageKind, propvalue);
            aPos.AdjustX(long( aSize.Width() * propvalue[2] ) );
            aPos.AdjustY(long( aSize.Height() * propvalue[3] ) );
            aSize.setWidth( long( aSize.Width() * propvalue[1] ) );
            aSize.setHeight( long( aSize.Height() * propvalue[0] ) );

            if(eObjKind == PresObjKind::Header )
            {
                OSL_FAIL( "SdPage::CreateDefaultPresObj() - can't create a header placeholder for a master slide" );
                return nullptr;
            }
            else
            {
                ::tools::Rectangle aRect( aPos, aSize );
                return CreatePresObj( eObjKind, false, aRect );
            }
        }
        else
        {
            // create header&footer objects for handout and notes master
            Size aPageSize ( GetSize() );
            aPageSize.AdjustWidth( -(GetLeftBorder() + GetRightBorder()) );
            aPageSize.AdjustHeight( -(GetUpperBorder() + GetLowerBorder()) );

            Point aPosition ( GetLeftBorder(), GetUpperBorder() );

            getPresObjProp( *this, sObjKind, sPageKind, propvalue);
            int NOTES_HEADER_FOOTER_WIDTH = long(aPageSize.Width() * propvalue[1]);
            int NOTES_HEADER_FOOTER_HEIGHT = long(aPageSize.Height() * propvalue[0]);
            Size aSize( NOTES_HEADER_FOOTER_WIDTH, NOTES_HEADER_FOOTER_HEIGHT );
            Point aPos ( 0 ,0 );
            if( propvalue[2] == 0 )
                aPos.setX( aPosition.X() );
            else
                aPos.setX( aPosition.X() + long( aPageSize.Width() - NOTES_HEADER_FOOTER_WIDTH ) );
            if( propvalue[3] == 0 )
                aPos.setY( aPosition.Y() );
            else
                aPos.setY( aPosition.Y() + long( aPageSize.Height() - NOTES_HEADER_FOOTER_HEIGHT ) );

            ::tools::Rectangle aRect( aPos, aSize );
            return CreatePresObj( eObjKind, false, aRect );
        }
    }
    else
    {
        OSL_FAIL("SdPage::CreateDefaultPresObj() - unknown PRESOBJ kind" );
        return nullptr;
    }
}

void SdPage::DestroyDefaultPresObj(PresObjKind eObjKind)
{
    SdrObject* pObject = GetPresObj( eObjKind );

    if( pObject )
    {
        SdDrawDocument* pDoc(static_cast< SdDrawDocument* >(&getSdrModelFromSdrPage()));
        const bool bUndo = pDoc->IsUndoEnabled();
        if( bUndo )
            pDoc->AddUndo(pDoc->GetSdrUndoFactory().CreateUndoDeleteObject(*pObject));
        SdrObjList* pOL = pObject->getParentSdrObjListFromSdrObject();
        pOL->RemoveObject(pObject->GetOrdNumDirect());

        if( !bUndo )
            SdrObject::Free(pObject);
    }
}

/*************************************************************************
|*
|* return title area
|*
\************************************************************************/

::tools::Rectangle SdPage::GetTitleRect() const
{
    ::tools::Rectangle aTitleRect;

    if (mePageKind != PageKind::Handout)
    {
        double propvalue[] = {0,0,0,0};

        /******************************************************************
        * standard- or note page: title area
        ******************************************************************/
        Point aTitlePos ( GetLeftBorder(), GetUpperBorder() );
        Size aTitleSize ( GetSize() );
        aTitleSize.AdjustWidth( -(GetLeftBorder() + GetRightBorder()) );
        aTitleSize.AdjustHeight( -(GetUpperBorder() + GetLowerBorder()) );
        const char* sPageKind = PageKindVector[mePageKind];

        if (mePageKind == PageKind::Standard)
         {
            getPresObjProp( *this , "PRESOBJ_TITLE" ,sPageKind, propvalue);
            aTitlePos.AdjustX(long( aTitleSize.Width() * propvalue[2] ) );
            aTitlePos.AdjustY(long( aTitleSize.Height() * propvalue[3] ) );
            aTitleSize.setWidth( long( aTitleSize.Width() * propvalue[1] ) );
            aTitleSize.setHeight( long( aTitleSize.Height() * propvalue[0] ) );
        }
        else if (mePageKind == PageKind::Notes)
        {
            Point aPos = aTitlePos;
            getPresObjProp( *this, "PRESOBJ_TITLE" ,sPageKind, propvalue);
            aPos.AdjustX(long( aTitleSize.Width() * propvalue[2] ) );
            aPos.AdjustY(long( aTitleSize.Height() * propvalue[3] ) );

            // limit height
            aTitleSize.setHeight( long( aTitleSize.Height() * propvalue[0] ) );
            aTitleSize.setWidth( long( aTitleSize.Width() * propvalue[1] ) );

            Size aPartArea = aTitleSize;
            Size aSize;
            sal_uInt16 nDestPageNum(GetPageNum());
            SdrPage* pRefPage = nullptr;

            if(nDestPageNum)
            {
                // only decrement if != 0, else we get 0xffff
                nDestPageNum -= 1;
            }

            if(nDestPageNum < getSdrModelFromSdrPage().GetPageCount())
            {
                pRefPage = getSdrModelFromSdrPage().GetPage(nDestPageNum);
            }

            if ( pRefPage )
            {
                // scale actually page size into handout rectangle
                double fH = pRefPage->GetWidth() == 0
                    ? 0 : static_cast<double>(aPartArea.Width())  / pRefPage->GetWidth();
                double fV = pRefPage->GetHeight() == 0
                    ? 0 : static_cast<double>(aPartArea.Height()) / pRefPage->GetHeight();

                if ( fH > fV )
                    fH = fV;
                aSize.setWidth( static_cast<long>(fH * pRefPage->GetWidth()) );
                aSize.setHeight( static_cast<long>(fH * pRefPage->GetHeight()) );

                aPos.AdjustX((aPartArea.Width() - aSize.Width()) / 2 );
                aPos.AdjustY((aPartArea.Height()- aSize.Height())/ 2 );
            }

            aTitlePos = aPos;
            aTitleSize = aSize;
        }

        aTitleRect.SetPos(aTitlePos);
        aTitleRect.SetSize(aTitleSize);
    }

    return aTitleRect;
}

/*************************************************************************
|*
|* return outline area
|*
\************************************************************************/

::tools::Rectangle SdPage::GetLayoutRect() const
{
    ::tools::Rectangle aLayoutRect;

    if (mePageKind != PageKind::Handout)
    {
        double propvalue[] = {0,0,0,0};

        Point aLayoutPos ( GetLeftBorder(), GetUpperBorder() );
        Size aLayoutSize ( GetSize() );
        aLayoutSize.AdjustWidth( -(GetLeftBorder() + GetRightBorder()) );
        aLayoutSize.AdjustHeight( -(GetUpperBorder() + GetLowerBorder()) );
        const char* sPageKind = PageKindVector[mePageKind];

        if (mePageKind == PageKind::Standard)
        {
            getPresObjProp( *this ,"PRESOBJ_OUTLINE", sPageKind, propvalue);
            aLayoutPos.AdjustX(long( aLayoutSize.Width() * propvalue[2] ) );
            aLayoutPos.AdjustY(long( aLayoutSize.Height() * propvalue[3] ) );
            aLayoutSize.setWidth( long( aLayoutSize.Width() * propvalue[1] ) );
            aLayoutSize.setHeight( long( aLayoutSize.Height() * propvalue[0] ) );
            aLayoutRect.SetPos(aLayoutPos);
            aLayoutRect.SetSize(aLayoutSize);
        }
        else if (mePageKind == PageKind::Notes)
        {
            getPresObjProp( *this, "PRESOBJ_NOTES", sPageKind, propvalue);
            aLayoutPos.AdjustX(long( aLayoutSize.Width() * propvalue[2] ) );
            aLayoutPos.AdjustY(long( aLayoutSize.Height() * propvalue[3] ) );
            aLayoutSize.setWidth( long( aLayoutSize.Width() * propvalue[1] ) );
            aLayoutSize.setHeight( long( aLayoutSize.Height() * propvalue[0] ) );
            aLayoutRect.SetPos(aLayoutPos);
            aLayoutRect.SetSize(aLayoutSize);
        }
    }

    return aLayoutRect;
}

/**************************************************************************
|*
|* assign an AutoLayout
|*
\*************************************************************************/

const int MAX_PRESOBJS = 7; // maximum number of presentation objects per layout
const int VERTICAL = 0x8000;

static constexpr PresObjKind operator|(PresObjKind e, int x)
{
    return static_cast<PresObjKind>(static_cast<int>(e) | x);
}

namespace {

struct LayoutDescriptor
{
    PresObjKind meKind[MAX_PRESOBJS];
    bool mbVertical[MAX_PRESOBJS];

    LayoutDescriptor( PresObjKind k0 = PresObjKind::NONE, PresObjKind k1 = PresObjKind::NONE, PresObjKind k2 = PresObjKind::NONE, PresObjKind k3 = PresObjKind::NONE, PresObjKind k4 = PresObjKind::NONE, PresObjKind k5 = PresObjKind::NONE, PresObjKind k6 = PresObjKind::NONE );
};

}

LayoutDescriptor::LayoutDescriptor( PresObjKind k0, PresObjKind k1, PresObjKind k2, PresObjKind k3, PresObjKind k4, PresObjKind k5, PresObjKind k6 )
{
    auto removeVertical = [&] (PresObjKind k) { return static_cast<PresObjKind>(static_cast<int>(k) & ~VERTICAL); };
    auto isVertical = [&] (PresObjKind k) { return bool(static_cast<int>(k) & VERTICAL); };
    meKind[0] = removeVertical(k0); mbVertical[0] = isVertical(k0);
    meKind[1] = removeVertical(k1); mbVertical[1] = isVertical(k1);
    meKind[2] = removeVertical(k2); mbVertical[2] = isVertical(k2);
    meKind[3] = removeVertical(k3); mbVertical[3] = isVertical(k3);
    meKind[4] = removeVertical(k4); mbVertical[4] = isVertical(k4);
    meKind[5] = removeVertical(k5); mbVertical[5] = isVertical(k5);
    meKind[6] = removeVertical(k6); mbVertical[6] = isVertical(k6);
}

static const LayoutDescriptor& GetLayoutDescriptor( AutoLayout eLayout )
{
    static const LayoutDescriptor aLayouts[AUTOLAYOUT_END-AUTOLAYOUT_START] =
    {
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Text ),                                 // AUTOLAYOUT_TITLE
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline ),                              // AUTOLAYOUT_TITLE_CONTENT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline ),                              // AUTOLAYOUT_CHART
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline ),             // AUTOLAYOUT_TITLE_2CONTENT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline ),             // AUTOLAYOUT_TEXTCHART
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline ),                              // AUTOLAYOUT_ORG
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline ),             // AUTOLAYOUT_TEXTCLbIP
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline ),             // AUTOLAYOUT_CHARTTEXT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline ),                              // AUTOLAYOUT_TAB
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline ),             // AUTOLAYOUT_CLIPTEXT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline ),             // AUTOLAYOUT_TEXTOBJ
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Object ),                               // AUTOLAYOUT_OBJ
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline, PresObjKind::Outline ),    // AUTOLAYOUT_TITLE_CONTENT_2CONTENT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline ),             // AUTOLAYOUT_TEXTOBJ
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline ),             // AUTOLAYOUT_TITLE_CONTENT_OVER_CONTENT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline, PresObjKind::Outline ),    // AUTOLAYOUT_TITLE_2CONTENT_CONTENT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline, PresObjKind::Outline ),    // AUTOLAYOUT_TITLE_2CONTENT_OVER_CONTENT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline ),             // AUTOLAYOUT_TEXTOVEROBJ
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline,                   // AUTOLAYOUT_TITLE_4CONTENT
            PresObjKind::Outline, PresObjKind::Outline ),
        LayoutDescriptor( PresObjKind::Title, PresObjKind::NONE ),                                 // AUTOLAYOUT_TITLE_ONLY
        LayoutDescriptor( PresObjKind::NONE ),                                                // AUTOLAYOUT_NONE
        LayoutDescriptor( PresObjKind::Page, PresObjKind::Notes ),                                 // AUTOLAYOUT_NOTES
        LayoutDescriptor( ),                                                              // AUTOLAYOUT_HANDOUT1
        LayoutDescriptor( ),                                                              // AUTOLAYOUT_HANDOUT2
        LayoutDescriptor( ),                                                              // AUTOLAYOUT_HANDOUT3
        LayoutDescriptor( ),                                                              // AUTOLAYOUT_HANDOUT4
        LayoutDescriptor( ),                                                              // AUTOLAYOUT_HANDOUT6
        LayoutDescriptor( PresObjKind::Title|VERTICAL, PresObjKind::Outline|VERTICAL, PresObjKind::Outline ),// AUTOLAYOUT_VTITLE_VCONTENT_OVER_VCONTENT
        LayoutDescriptor( PresObjKind::Title|VERTICAL, PresObjKind::Outline|VERTICAL ),            // AUTOLAYOUT_VTITLE_VCONTENT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline|VERTICAL ),                     // AUTOLAYOUT_TITLE_VCONTENT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline|VERTICAL, PresObjKind::Outline|VERTICAL ),   // AUTOLAYOUT_TITLE_2VTEXT
        LayoutDescriptor( ),                                                              // AUTOLAYOUT_HANDOUT9
        LayoutDescriptor( PresObjKind::Text, PresObjKind::NONE ),                                 // AUTOLAYOUT_ONLY_TEXT
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline,               // AUTOLAYOUT_4CLIPART
            PresObjKind::Graphic, PresObjKind::Graphic ),
        LayoutDescriptor( PresObjKind::Title, PresObjKind::Outline, PresObjKind::Outline,              // AUTOLAYOUT_TITLE_6CONTENT
            PresObjKind::Outline, PresObjKind::Outline, PresObjKind::Outline, PresObjKind::Outline )
    };

    if( (eLayout < AUTOLAYOUT_START) || (eLayout >= AUTOLAYOUT_END) )
        eLayout = AUTOLAYOUT_NONE;

    return aLayouts[ eLayout - AUTOLAYOUT_START ];
}

static OUString enumtoString(AutoLayout aut)
{
    OUString retstr;
    switch (aut)
    {
        case AUTOLAYOUT_TITLE_CONTENT:
            retstr="AUTOLAYOUT_TITLE_CONTENT";
            break;
        case AUTOLAYOUT_TITLE_CONTENT_OVER_CONTENT:
            retstr="AUTOLAYOUT_TITLE_CONTENT_OVER_CONTENT";
            break;
        case AUTOLAYOUT_TITLE_CONTENT_2CONTENT:
            retstr="AUTOLAYOUT_TITLE_CONTENT_2CONTENT";
            break;
        case AUTOLAYOUT_TITLE_4CONTENT:
            retstr="AUTOLAYOUT_TITLE_4CONTENT";
            break;
        case AUTOLAYOUT_ONLY_TEXT:
            retstr="AUTOLAYOUT_ONLY_TEXT";
            break;
        case AUTOLAYOUT_TITLE_ONLY:
            retstr="AUTOLAYOUT_TITLE_ONLY";
            break;
        case AUTOLAYOUT_TITLE_6CONTENT:
            retstr="AUTOLAYOUT_TITLE_6CONTENT";
            break;
        case AUTOLAYOUT_START:
            retstr="AUTOLAYOUT_START";
            break;
        case AUTOLAYOUT_TITLE_2CONTENT_CONTENT:
            retstr="AUTOLAYOUT_TITLE_2CONTENT_CONTENT";
            break;
        case AUTOLAYOUT_TITLE_2CONTENT_OVER_CONTENT:
            retstr="AUTOLAYOUT_TITLE_2CONTENT_OVER_CONTENT";
            break;
        case AUTOLAYOUT_TITLE_2CONTENT:
            retstr="AUTOLAYOUT_TITLE_2CONTENT";
            break;
        case AUTOLAYOUT_VTITLE_VCONTENT:
            retstr="AUTOLAYOUT_VTITLE_VCONTENT";
            break;
        case AUTOLAYOUT_VTITLE_VCONTENT_OVER_VCONTENT:
            retstr="AUTOLAYOUT_VTITLE_VCONTENT_OVER_VCONTENT";
            break;
        case AUTOLAYOUT_TITLE_VCONTENT:
            retstr="AUTOLAYOUT_TITLE_VCONTENT";
            break;
        case AUTOLAYOUT_TITLE_2VTEXT:
            retstr="AUTOLAYOUT_TITLE_2VTEXT";
            break;
        default:
            retstr="unknown";
            break;
        // case AUTOLAYOUT_TITLE_4SCONTENT:            return "AUTOLAYOUT_TITLE_4SCONTENT";
    }
    return retstr;
}

static void CalcAutoLayoutRectangles( SdPage const & rPage,::tools::Rectangle* rRectangle ,const OUString& sLayoutType )
{
    ::tools::Rectangle aTitleRect;
    ::tools::Rectangle aLayoutRect;

    if( rPage.GetPageKind() != PageKind::Handout )
    {
        SdPage& rMasterPage = static_cast<SdPage&>(rPage.TRG_GetMasterPage());
        SdrObject* pMasterTitle = rMasterPage.GetPresObj( PresObjKind::Title );
        SdrObject* pMasterSubTitle = rMasterPage.GetPresObj( PresObjKind::Text );
        SdrObject* pMasterOutline = rMasterPage.GetPresObj( rPage.GetPageKind()==PageKind::Notes ? PresObjKind::Notes : PresObjKind::Outline );

        if( pMasterTitle )
            aTitleRect = pMasterTitle->GetLogicRect();

        if (aTitleRect.IsEmpty() )
            aTitleRect = rPage.GetTitleRect();
        if( pMasterSubTitle )
            aLayoutRect = pMasterSubTitle->GetLogicRect();
        else if( pMasterOutline )
            aLayoutRect = pMasterOutline->GetLogicRect();

        if (aLayoutRect.IsEmpty() )
            aLayoutRect = rPage.GetLayoutRect();
    }

    rRectangle[0] = aTitleRect;
    for( int i = 1; i < MAX_PRESOBJS; i++ )
        rRectangle[i] = aLayoutRect;

    const Point aTitlePos( aTitleRect.TopLeft() );
    const Size  aLayoutSize( aLayoutRect.GetSize() );
    const Point aLayoutPos( aLayoutRect.TopLeft() );
    double propvalue[] = {0,0,0,0};

    const std::vector< Reference<XNode> >& layoutInfo = static_cast< const SdDrawDocument& >(rPage.getSdrModelFromSdrPage()).GetLayoutVector();
    auto aIter = std::find_if(layoutInfo.begin(), layoutInfo.end(),
        [&sLayoutType](const Reference<XNode>& layoutNode) {
            Reference<XNamedNodeMap> layoutAttrList = layoutNode->getAttributes();

            // get the attribute value of layout (i.e it's type)
            OUString sLayoutAttName = layoutAttrList->getNamedItem("type")->getNodeValue();
            return sLayoutAttName == sLayoutType;
        });
    if (aIter == layoutInfo.end())
        return;

    int count=0;
    Reference<XNode> layoutNode = *aIter;
    Reference<XNodeList> layoutChildren = layoutNode->getChildNodes();
    const int presobjsize = layoutChildren->getLength();
    for( int j=0; j< presobjsize ; j++)
    {
        OUString nodename;
        Reference<XNode> presobj = layoutChildren->item(j);
        nodename=presobj->getNodeName();

        //check whether child is blank 'text-node' or 'presobj' node
        if(nodename == "presobj")
        {
            // TODO: rework sd to permit arbitrary number of presentation objects
            assert(count < MAX_PRESOBJS);

            Reference<XNamedNodeMap> presObjAttributes = presobj->getAttributes();

            Reference<XNode> presObjSizeHeight = presObjAttributes->getNamedItem("relative-height");
            OUString sValue = presObjSizeHeight->getNodeValue();
            propvalue[0] = sValue.toDouble();

            Reference<XNode> presObjSizeWidth = presObjAttributes->getNamedItem("relative-width");
            sValue = presObjSizeWidth->getNodeValue();
            propvalue[1] = sValue.toDouble();

            Reference<XNode> presObjPosX = presObjAttributes->getNamedItem("relative-posX");
            sValue = presObjPosX->getNodeValue();
            propvalue[2] = sValue.toDouble();

            Reference<XNode> presObjPosY = presObjAttributes->getNamedItem("relative-posY");
            sValue = presObjPosY->getNodeValue();
            propvalue[3] = sValue.toDouble();

            if(count == 0)
            {
                Size aSize ( aTitleRect.GetSize() );
                aSize.setHeight( basegfx::fround(aSize.Height() * propvalue[0]) );
                aSize.setWidth( basegfx::fround(aSize.Width() * propvalue[1]) );
                Point aPos( basegfx::fround(aTitlePos.X() +(aSize.Width() * propvalue[2])),
                            basegfx::fround(aTitlePos.Y() + (aSize.Height() * propvalue[3])) );
                rRectangle[count] = ::tools::Rectangle(aPos, aSize);
                count = count+1;
            }
            else
            {
                Size aSize( basegfx::fround(aLayoutSize.Width() * propvalue[1]),
                            basegfx::fround(aLayoutSize.Height() * propvalue[0]) );
                Point aPos( basegfx::fround(aLayoutPos.X() +(aSize.Width() * propvalue[2])),
                            basegfx::fround(aLayoutPos.Y() + (aSize.Height() * propvalue[3])) );
                rRectangle[count] = ::tools::Rectangle (aPos, aSize);
                count = count+1;
            }
        }
    }
}

static void findAutoLayoutShapesImpl( SdPage& rPage, const LayoutDescriptor& rDescriptor, std::array<SdrObject*, MAX_PRESOBJS>& rShapes, bool bInit, bool bSwitchLayout )
{
    // init list of indexes for each presentation shape kind
    // this is used to find subsequent shapes with the same presentation shape kind
    o3tl::enumarray<PresObjKind,int> PresObjIndex;
    PresObjIndex.fill(1);

    bool bMissing = false;

    // for each entry in the layoutdescriptor, arrange a presentation shape
    for (int i = 0; (i < MAX_PRESOBJS) && (rDescriptor.meKind[i] != PresObjKind::NONE); i++)
    {
        PresObjKind eKind = rDescriptor.meKind[i];
        SdrObject* pObj = nullptr;
        while( (pObj = rPage.GetPresObj( eKind, PresObjIndex[eKind], true )) != nullptr )
        {
            PresObjIndex[eKind]++; // on next search for eKind, find next shape with same eKind

            if( !bSwitchLayout || !pObj->IsEmptyPresObj() )
            {
                rShapes[i] = pObj;
                break;
            }
        }

        if( !pObj )
            bMissing = true;
    }

    if( !(bMissing && bInit) )
        return;

    // for each entry in the layoutdescriptor, look for an alternative shape
    for (int i = 0; (i < MAX_PRESOBJS) && (rDescriptor.meKind[i] != PresObjKind::NONE); i++)
    {
        if( rShapes[i] )
            continue;

        PresObjKind eKind = rDescriptor.meKind[i];

        SdrObject* pObj = nullptr;
        bool bFound = false;

        const size_t nShapeCount = rPage.GetObjCount();
        for(size_t nShapeIndex = 0; nShapeIndex < nShapeCount && !bFound; ++nShapeIndex )
        {
            pObj = rPage.GetObj(nShapeIndex);

            if( pObj->IsEmptyPresObj() )
                continue;

            if( pObj->GetObjInventor() != SdrInventor::Default )
                continue;

            // do not reuse shapes that are already part of the layout
            if( std::find( rShapes.begin(), rShapes.end(), pObj ) != rShapes.end() )
                continue;

            bool bPresStyle = pObj->GetStyleSheet() && (pObj->GetStyleSheet()->GetFamily() == SfxStyleFamily::Page);
            SdrObjKind eSdrObjKind = static_cast< SdrObjKind >( pObj->GetObjIdentifier() );

            switch( eKind )
            {
            case PresObjKind::Title:
                bFound = eSdrObjKind == OBJ_TITLETEXT;
                break;
            case PresObjKind::Table:
                bFound = eSdrObjKind == OBJ_TABLE;
                break;
            case PresObjKind::Media:
                bFound = eSdrObjKind == OBJ_MEDIA;
                break;
            case PresObjKind::Outline:
                bFound = (eSdrObjKind == OBJ_OUTLINETEXT) ||
                         ((eSdrObjKind == OBJ_TEXT) && bPresStyle) ||
                         (eSdrObjKind == OBJ_TABLE) || (eSdrObjKind == OBJ_MEDIA) || (eSdrObjKind == OBJ_GRAF) || (eSdrObjKind == OBJ_OLE2);
                break;
            case PresObjKind::Graphic:
                bFound = eSdrObjKind == OBJ_GRAF;
                break;
            case PresObjKind::Object:
                if( eSdrObjKind == OBJ_OLE2 )
                {
                    SdrOle2Obj* pOle2 = dynamic_cast< SdrOle2Obj* >( pObj );
                    if( pOle2 )
                    {
                        if( pOle2->IsEmpty() )
                            bFound = true;
                        else
                        {
                            ::comphelper::IEmbeddedHelper* pPersist(rPage.getSdrModelFromSdrPage().GetPersist());

                            if( pPersist )
                            {
                                uno::Reference < embed::XEmbeddedObject > xObject = pPersist->getEmbeddedObjectContainer().
                                        GetEmbeddedObject( static_cast< SdrOle2Obj* >( pObj )->GetPersistName() );

                                // TODO CL->KA: Why is this not working anymore?
                                if( xObject.is() )
                                {
                                    SvGlobalName aClassId( xObject->getClassID() );

                                    const SvGlobalName aAppletClassId( SO3_APPLET_CLASSID );
                                    const SvGlobalName aPluginClassId( SO3_PLUGIN_CLASSID );
                                    const SvGlobalName aIFrameClassId( SO3_IFRAME_CLASSID );

                                    if( aPluginClassId != aClassId && aAppletClassId != aClassId && aIFrameClassId != aClassId )
                                    {
                                        bFound = true;
                                    }
                                }
                            }
                         }
                     }
                }
                break;
            case PresObjKind::Chart:
            case PresObjKind::Calc:
                if( eSdrObjKind == OBJ_OLE2 )
                {
                    SdrOle2Obj* pOle2 = dynamic_cast< SdrOle2Obj* >( pObj );
                    if( pOle2 )
                    {
                        if(
                            ((eKind == PresObjKind::Chart) &&
                                ( pOle2->GetProgName() == "StarChart" || pOle2->IsChart() ) )
                            ||
                            ((eKind == PresObjKind::Calc) &&
                                ( pOle2->GetProgName() == "StarCalc" || pOle2->IsCalc() ) ) )
                        {
                            bFound = true;
                        }
                    }
                    break;
                }
                else if( eSdrObjKind == OBJ_TABLE )
                {
                    bFound = true;
                }
                break;
            case PresObjKind::Page:
            case PresObjKind::Handout:
                bFound = eSdrObjKind == OBJ_PAGE;
                break;
            case PresObjKind::Notes:
            case PresObjKind::Text:
                bFound = (bPresStyle && (eSdrObjKind == OBJ_TEXT)) || (eSdrObjKind == OBJ_OUTLINETEXT);
                break;
            default:
                break;
            }
        }

        if( bFound )
            rShapes[i] = pObj;
    }
}

void SdPage::SetAutoLayout(AutoLayout eLayout, bool bInit, bool bCreate )
{
    sd::ScopeLockGuard aGuard( maLockAutoLayoutArrangement );

    const bool bSwitchLayout = eLayout != GetAutoLayout();

    SfxUndoManager* pUndoManager(static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetUndoManager());
    const bool bUndo = pUndoManager && pUndoManager->IsInListAction() && IsInserted();

    meAutoLayout = eLayout;

    // if needed, creates and initialises the presentation shapes on this slides master page
    CreateTitleAndLayout(bInit, bCreate);

    if((meAutoLayout == AUTOLAYOUT_NONE && maPresentationShapeList.isEmpty()) || mbMaster)
    {
        // MasterPage or no layout and no presentation shapes available, nothing to do
        return;
    }

    ::tools::Rectangle aRectangle[MAX_PRESOBJS];
    const LayoutDescriptor& aDescriptor = GetLayoutDescriptor( meAutoLayout );
    OUString sLayoutName( enumtoString(meAutoLayout) );
    CalcAutoLayoutRectangles( *this, aRectangle, sLayoutName);

    o3tl::sorted_vector< SdrObject* > aUsedPresentationObjects;

    std::array<SdrObject*, MAX_PRESOBJS > aLayoutShapes;
    aLayoutShapes.fill(nullptr);
    findAutoLayoutShapesImpl( *this, aDescriptor, aLayoutShapes, bInit, bSwitchLayout );

    // for each entry in the layoutdescriptor, arrange a presentation shape
    for (int i = 0; (i < MAX_PRESOBJS) && (aDescriptor.meKind[i] != PresObjKind::NONE); i++)
    {
        PresObjKind eKind = aDescriptor.meKind[i];
        SdrObject* pObj = InsertAutoLayoutShape( aLayoutShapes[i], eKind, aDescriptor.mbVertical[i], aRectangle[i], bInit );
        if( pObj )
            aUsedPresentationObjects.insert(pObj); // remember that we used this empty shape
    }

    // now delete all empty presentation objects that are no longer used by the new layout
    if( !bInit )
        return;

    SdrObject* pObj = nullptr;
    maPresentationShapeList.seekShape(0);

    while( (pObj = maPresentationShapeList.getNextShape()) )
    {
        if( aUsedPresentationObjects.count(pObj) == 0 )
        {

            if( pObj->IsEmptyPresObj() )
            {
                if( bUndo )
                    pUndoManager->AddUndoAction(getSdrModelFromSdrPage().GetSdrUndoFactory().CreateUndoDeleteObject(*pObj));

                RemoveObject( pObj->GetOrdNum() );

                if( !bUndo )
                    SdrObject::Free( pObj );
            }
/* #i108541# keep non empty pres obj as pres obj even if they are not part of the current layout */
        }
    }
}

/*************************************************************************
|*
|* insert object
|*
\************************************************************************/

void SdPage::NbcInsertObject(SdrObject* pObj, size_t nPos)
{
    FmFormPage::NbcInsertObject(pObj, nPos);

    static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).InsertObject(pObj);

    SdrLayerID nId = pObj->GetLayer();
    if( mbMaster )
    {
        if( nId == SdrLayerID(0) )
            pObj->NbcSetLayer( SdrLayerID(2) );     // wrong layer. corrected to BackgroundObj layer
    }
    else
    {
        if( nId == SdrLayerID(2) )
            pObj->NbcSetLayer( SdrLayerID(0) );     // wrong layer. corrected to layout layer
    }
}

/*************************************************************************
|*
|* remove object
|*
\************************************************************************/

SdrObject* SdPage::RemoveObject(size_t nObjNum)
{
    onRemoveObject(GetObj( nObjNum ));
    return FmFormPage::RemoveObject(nObjNum);
}

/*************************************************************************
|*
|* remove object without broadcast
|*
\************************************************************************/

SdrObject* SdPage::NbcRemoveObject(size_t nObjNum)
{
    onRemoveObject(GetObj( nObjNum ));
    return FmFormPage::NbcRemoveObject(nObjNum);
}

// Also override ReplaceObject methods to realize when
// objects are removed with this mechanism instead of RemoveObject
SdrObject* SdPage::ReplaceObject(SdrObject* pNewObj, size_t nObjNum)
{
    onRemoveObject(GetObj( nObjNum ));
    return FmFormPage::ReplaceObject(pNewObj, nObjNum);
}

// called after a shape is removed or replaced from this slide

void SdPage::onRemoveObject( SdrObject* pObject )
{
    if( pObject )
    {
        RemovePresObj(pObject);

        static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).RemoveObject(pObject);

        removeAnimations( pObject );
    }
}

void SdPage::SetSize(const Size& aSize)
{
    Size aOldSize = GetSize();

    if (aSize != aOldSize)
    {
        FmFormPage::SetSize(aSize);
    }
}

void SdPage::SetBorder(sal_Int32 nLft, sal_Int32 nUpp, sal_Int32 nRgt, sal_Int32 nLwr)
{
    if (nLft != GetLeftBorder() || nUpp != GetUpperBorder() ||
        nRgt != GetRightBorder() || nLwr != GetLowerBorder() )
    {
        FmFormPage::SetBorder(nLft, nUpp, nRgt, nLwr);
    }
}

void SdPage::SetLeftBorder(sal_Int32 nBorder)
{
    if (nBorder != GetLeftBorder() )
    {
        FmFormPage::SetLeftBorder(nBorder);
    }
}

void SdPage::SetRightBorder(sal_Int32 nBorder)
{
    if (nBorder != GetRightBorder() )
    {
        FmFormPage::SetRightBorder(nBorder);
    }
}

void SdPage::SetUpperBorder(sal_Int32 nBorder)
{
    if (nBorder != GetUpperBorder() )
    {
        FmFormPage::SetUpperBorder(nBorder);
    }
}

void SdPage::SetLowerBorder(sal_Int32 nBorder)
{
    if (nBorder != GetLowerBorder() )
    {
        FmFormPage::SetLowerBorder(nBorder);
    }
}

/*************************************************************************
|*
|* Sets BackgroundFullSize and then calls AdjustBackground
|*
\************************************************************************/

void SdPage::SetBackgroundFullSize( bool bIn )
{
    if( bIn != mbBackgroundFullSize )
    {
        mbBackgroundFullSize = bIn;
    }
}

/*************************************************************************
|*
|* Adjust all objects to new page size.
|*
|* bScaleAllObj: all objects are scaled into the new area within the page
|* margins. We scale the position and size. For presentation objects on the
|* master page, we also scale the font height of the presentation template.
|*
\************************************************************************/

void SdPage::ScaleObjects(const Size& rNewPageSize, const ::tools::Rectangle& rNewBorderRect, bool bScaleAllObj)
{
    sd::ScopeLockGuard aGuard( maLockAutoLayoutArrangement );

    mbScaleObjects = bScaleAllObj;
    SdrObject* pObj = nullptr;
    Point aRefPnt(0, 0);
    Size aNewPageSize(rNewPageSize);
    sal_Int32 nLeft  = rNewBorderRect.Left();
    sal_Int32 nRight = rNewBorderRect.Right();
    sal_Int32 nUpper = rNewBorderRect.Top();
    sal_Int32 nLower = rNewBorderRect.Bottom();

    // negative values are fixed values
    // -> use up to date values
    if (aNewPageSize.Width() < 0)
    {
        aNewPageSize.setWidth( GetWidth() );
    }
    if (aNewPageSize.Height() < 0)
    {
        aNewPageSize.setHeight( GetHeight() );
    }
    if (nLeft < 0)
    {
        nLeft = GetLeftBorder();
    }
    if (nRight < 0)
    {
        nRight = GetRightBorder();
    }
    if (nUpper < 0)
    {
        nUpper = GetUpperBorder();
    }
    if (nLower < 0)
    {
        nLower = GetLowerBorder();
    }

    Size aBackgroundSize(aNewPageSize);

    if (mbScaleObjects)
    {
        aBackgroundSize.AdjustWidth( -(nLeft  + nRight) );
        aBackgroundSize.AdjustHeight( -(nUpper + nLower) );
        aNewPageSize = aBackgroundSize;
    }

    long nOldWidth  = GetWidth() - GetLeftBorder() - GetRightBorder();
    long nOldHeight = GetHeight() - GetUpperBorder() - GetLowerBorder();

    Fraction aFractX(aNewPageSize.Width(), nOldWidth);
    Fraction aFractY(aNewPageSize.Height(), nOldHeight);

    const size_t nObjCnt = (mbScaleObjects ? GetObjCount() : 0);

    for (size_t nObj = 0; nObj < nObjCnt; ++nObj)
    {
        bool bIsPresObjOnMaster = false;

        // all Objects
        pObj = GetObj(nObj);

        if (mbMaster && IsPresObj(pObj))
        {
            // There is a presentation object on the master page
            bIsPresObjOnMaster = true;
        }

        if (pObj)
        {
            // remember aTopLeft as original TopLeft
            Point aTopLeft(pObj->GetCurrentBoundRect().TopLeft());

            if (!pObj->IsEdgeObj())
            {
                /**************************************************************
                * Scale objects
                **************************************************************/
                if (mbScaleObjects)
                {
                    // use aTopLeft as original TopLeft
                    aRefPnt = aTopLeft;
                }

                pObj->Resize(aRefPnt, aFractX, aFractY);

                if (mbScaleObjects)
                {
                    SdrObjKind eObjKind = static_cast<SdrObjKind>(pObj->GetObjIdentifier());

                    if (bIsPresObjOnMaster)
                    {
                        /**********************************************************
                        * presentation template: adjust test height
                        **********************************************************/

                        if (pObj == GetPresObj(PresObjKind::Title, 0))
                        {
                            SfxStyleSheet* pTitleSheet = GetStyleSheetForPresObj(PresObjKind::Title);

                            if (pTitleSheet)
                            {
                                SfxItemSet& rSet = pTitleSheet->GetItemSet();

                                const SvxFontHeightItem& rOldHgt = rSet.Get(EE_CHAR_FONTHEIGHT);
                                sal_uLong nFontHeight = rOldHgt.GetHeight();
                                nFontHeight = long(nFontHeight * static_cast<double>(aFractY));
                                rSet.Put(SvxFontHeightItem(nFontHeight, 100, EE_CHAR_FONTHEIGHT));

                                if( SfxItemState::DEFAULT == rSet.GetItemState( EE_CHAR_FONTHEIGHT_CJK ) )
                                {
                                    const SvxFontHeightItem& rOldHgt2 = rSet.Get(EE_CHAR_FONTHEIGHT_CJK);
                                    nFontHeight = rOldHgt2.GetHeight();
                                    nFontHeight = long(nFontHeight * static_cast<double>(aFractY));
                                    rSet.Put(SvxFontHeightItem(nFontHeight, 100, EE_CHAR_FONTHEIGHT_CJK));
                                }

                                if( SfxItemState::DEFAULT == rSet.GetItemState( EE_CHAR_FONTHEIGHT_CTL ) )
                                {
                                    const SvxFontHeightItem& rOldHgt2 = rSet.Get(EE_CHAR_FONTHEIGHT_CTL);
                                    nFontHeight = rOldHgt2.GetHeight();
                                    nFontHeight = long(nFontHeight * static_cast<double>(aFractY));
                                    rSet.Put(SvxFontHeightItem(nFontHeight, 100, EE_CHAR_FONTHEIGHT_CTL));
                                }

                                pTitleSheet->Broadcast(SfxHint(SfxHintId::DataChanged));
                            }
                        }
                        else if (pObj == GetPresObj(PresObjKind::Outline, 0))
                        {
                            OUString aName(GetLayoutName() + " ");

                            for (sal_Int32 i=1; i<=9; i++)
                            {
                                OUString sLayoutName( aName + OUString::number( i ) );
                                SfxStyleSheet* pOutlineSheet = static_cast<SfxStyleSheet*>(static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetStyleSheetPool()->Find(sLayoutName, SfxStyleFamily::Page));

                                if (pOutlineSheet)
                                {
                                    // Calculate new font height
                                    SfxItemSet aTempSet(pOutlineSheet->GetItemSet());

                                    const SvxFontHeightItem& rOldHgt = aTempSet.Get(EE_CHAR_FONTHEIGHT);
                                    sal_uLong nFontHeight = rOldHgt.GetHeight();
                                    nFontHeight = long(nFontHeight * static_cast<double>(aFractY));
                                    aTempSet.Put(SvxFontHeightItem(nFontHeight, 100, EE_CHAR_FONTHEIGHT));

                                    if( SfxItemState::DEFAULT == aTempSet.GetItemState( EE_CHAR_FONTHEIGHT_CJK ) )
                                    {
                                        const SvxFontHeightItem& rOldHgt2 = aTempSet.Get(EE_CHAR_FONTHEIGHT_CJK);
                                        nFontHeight = rOldHgt2.GetHeight();
                                        nFontHeight = long(nFontHeight * static_cast<double>(aFractY));
                                        aTempSet.Put(SvxFontHeightItem(nFontHeight, 100, EE_CHAR_FONTHEIGHT_CJK));
                                    }

                                    if( SfxItemState::DEFAULT == aTempSet.GetItemState( EE_CHAR_FONTHEIGHT_CTL ) )
                                    {
                                        const SvxFontHeightItem& rOldHgt2 = aTempSet.Get(EE_CHAR_FONTHEIGHT_CTL);
                                        nFontHeight = rOldHgt2.GetHeight();
                                        nFontHeight = long(nFontHeight * static_cast<double>(aFractY));
                                        aTempSet.Put(SvxFontHeightItem(nFontHeight, 100, EE_CHAR_FONTHEIGHT_CTL));
                                    }

                                    // adjust bullet
                                    static_cast<SdStyleSheet*>(pOutlineSheet)->AdjustToFontHeight(aTempSet, false);

                                    // Special treatment: reset the INVALIDS to
                                    // NULL pointer (otherwise we have INVALID's
                                    // or pointer to the DefaultItems in the
                                    // template; both would suppress the
                                    // attribute inheritance)
                                    aTempSet.ClearInvalidItems();

                                    // Special treatment: only the valid parts
                                    // of the BulletItems
                                    if (aTempSet.GetItemState(EE_PARA_BULLET) == SfxItemState::DEFAULT)
                                    {
                                        SvxBulletItem aOldBulItem( pOutlineSheet->GetItemSet().Get(EE_PARA_BULLET) );
                                        const SvxBulletItem& rNewBulItem = aTempSet.Get(EE_PARA_BULLET);
                                        aOldBulItem.CopyValidProperties(rNewBulItem);
                                        aTempSet.Put(aOldBulItem);
                                    }

                                    pOutlineSheet->GetItemSet().Put(aTempSet);
                                    pOutlineSheet->Broadcast(SfxHint(SfxHintId::DataChanged));
                                }
                            }
                        }
                        else if (pObj == GetPresObj(PresObjKind::Notes, 0))
                        {
                            SfxStyleSheet* pNotesSheet = GetStyleSheetForPresObj(PresObjKind::Notes);

                            if (pNotesSheet)
                            {
                                sal_uLong nHeight = pObj->GetLogicRect().GetSize().Height();
                                sal_uLong nFontHeight = static_cast<sal_uLong>(nHeight * 0.0741);
                                SfxItemSet& rSet = pNotesSheet->GetItemSet();
                                rSet.Put( SvxFontHeightItem(nFontHeight, 100, EE_CHAR_FONTHEIGHT ));
                                rSet.Put( SvxFontHeightItem(nFontHeight, 100, EE_CHAR_FONTHEIGHT_CJK ));
                                rSet.Put( SvxFontHeightItem(nFontHeight, 100, EE_CHAR_FONTHEIGHT_CTL ));
                                pNotesSheet->Broadcast(SfxHint(SfxHintId::DataChanged));
                            }
                        }
                    }
                    else if ( eObjKind != OBJ_TITLETEXT   &&
                              eObjKind != OBJ_OUTLINETEXT &&
                              dynamic_cast< const SdrTextObj *>( pObj ) !=  nullptr       &&
                              pObj->GetOutlinerParaObject() )
                    {
                        /******************************************************
                        * normal text object: adjust text height
                        ******************************************************/
                        SvtScriptType nScriptType = pObj->GetOutlinerParaObject()->GetTextObject().GetScriptType();
                        sal_uInt16 nWhich = EE_CHAR_FONTHEIGHT;
                        if ( nScriptType == SvtScriptType::ASIAN )
                            nWhich = EE_CHAR_FONTHEIGHT_CJK;
                        else if ( nScriptType == SvtScriptType::COMPLEX )
                            nWhich = EE_CHAR_FONTHEIGHT_CTL;

                        // use more modern method to scale the text height
                        sal_uInt32 nFontHeight = static_cast<const SvxFontHeightItem&>(pObj->GetMergedItem(nWhich)).GetHeight();
                        sal_uInt32 nNewFontHeight = sal_uInt32(static_cast<double>(nFontHeight) * static_cast<double>(aFractY));

                        pObj->SetMergedItem(SvxFontHeightItem(nNewFontHeight, 100, nWhich));
                    }
                }
            }

            if (mbScaleObjects && !pObj->IsEdgeObj())
            {
                /**************************************************************
                * scale object position
                **************************************************************/
                Point aNewPos;

                // corrected scaling; only distances may be scaled
                // use aTopLeft as original TopLeft
                aNewPos.setX( long((aTopLeft.X() - GetLeftBorder()) * static_cast<double>(aFractX)) + nLeft );
                aNewPos.setY( long((aTopLeft.Y() - GetUpperBorder()) * static_cast<double>(aFractY)) + nUpper );

                Size aVec(aNewPos.X() - aTopLeft.X(), aNewPos.Y() - aTopLeft.Y());

                if (aVec.Height() != 0 || aVec.Width() != 0)
                {
                    pObj->NbcMove(aVec);
                }

                pObj->SetChanged();
                pObj->BroadcastObjectChange();
            }
        }
    }
}

static SdrObject* convertPresentationObjectImpl(SdPage& rPage, SdrObject* pSourceObj, PresObjKind& eObjKind, bool bVertical, const ::tools::Rectangle& rRect)
{
    SdDrawDocument& rModel(static_cast< SdDrawDocument& >(rPage.getSdrModelFromSdrPage()));
    if( !pSourceObj )
        return pSourceObj;

    SfxUndoManager* pUndoManager = rModel.GetUndoManager();
    const bool bUndo = pUndoManager && pUndoManager->IsInListAction() && rPage.IsInserted();

    SdrObject* pNewObj = pSourceObj;
    if((eObjKind == PresObjKind::Outline) && (pSourceObj->GetObjIdentifier() == OBJ_TEXT) )
    {
        pNewObj = rPage.CreatePresObj(PresObjKind::Outline, bVertical, rRect);

        // Set text of the subtitle into PRESOBJ_OUTLINE
        OutlinerParaObject* pOutlParaObj = pSourceObj->GetOutlinerParaObject();

        if(pOutlParaObj)
        {
            // assign text
            SdOutliner* pOutl = rModel.GetInternalOutliner();
            pOutl->Clear();
            pOutl->SetText( *pOutlParaObj );
            std::unique_ptr<OutlinerParaObject> pNew = pOutl->CreateParaObject();
            pOutlParaObj = pNew.get();
            pNewObj->SetOutlinerParaObject( std::move(pNew) );
            pOutl->Clear();
            pNewObj->SetEmptyPresObj(false);

            for (sal_uInt16 nLevel = 1; nLevel < 10; nLevel++)
            {
                // assign new template
                OUString aName( rPage.GetLayoutName() + " " + OUString::number( nLevel ) );
                SfxStyleSheet* pSheet = static_cast<SfxStyleSheet*>( rModel.GetStyleSheetPool()->Find(aName, SfxStyleFamily::Page) );

                if (pSheet && nLevel == 1)
                {
                    SfxStyleSheet* pSubtitleSheet = rPage.GetStyleSheetForPresObj(PresObjKind::Text);

                    if (pSubtitleSheet)
                        pOutlParaObj->ChangeStyleSheetName(SfxStyleFamily::Page, pSubtitleSheet->GetName(), pSheet->GetName());
                }
            }

            // Remove LRSpace item
            SfxItemSet aSet(rModel.GetPool(), svl::Items<EE_PARA_LRSPACE, EE_PARA_LRSPACE>{} );

            aSet.Put(pNewObj->GetMergedItemSet());

            aSet.ClearItem(EE_PARA_LRSPACE);

            pNewObj->SetMergedItemSet(aSet);

            if( bUndo )
                pUndoManager->AddUndoAction( rModel.GetSdrUndoFactory().CreateUndoDeleteObject(*pSourceObj) );

            // Remove outline shape from page
            rPage.RemoveObject( pSourceObj->GetOrdNum() );

            if( !bUndo )
                SdrObject::Free( pSourceObj );
        }
    }
    else if((eObjKind == PresObjKind::Text) && (pSourceObj->GetObjIdentifier() == OBJ_OUTLINETEXT) )
    {
        // is there an outline shape we can use to replace empty subtitle shape?
        pNewObj = rPage.CreatePresObj(PresObjKind::Text, bVertical, rRect);

        // Set text of the outline object into PRESOBJ_TITLE
        OutlinerParaObject* pOutlParaObj = pSourceObj->GetOutlinerParaObject();

        if(pOutlParaObj)
        {
            // assign text
            SdOutliner* pOutl = rModel.GetInternalOutliner();
            pOutl->Clear();
            pOutl->SetText( *pOutlParaObj );
            pNewObj->SetOutlinerParaObject( pOutl->CreateParaObject() );
            pOutl->Clear();
            pNewObj->SetEmptyPresObj(false);

            // reset left indent
            SfxItemSet aSet(rModel.GetPool(), svl::Items<EE_PARA_LRSPACE, EE_PARA_LRSPACE>{} );

            aSet.Put(pNewObj->GetMergedItemSet());

            const SvxLRSpaceItem& rLRItem = aSet.Get(EE_PARA_LRSPACE);
            SvxLRSpaceItem aNewLRItem(rLRItem);
            aNewLRItem.SetTextLeft(0);
            aSet.Put(aNewLRItem);

            pNewObj->SetMergedItemSet(aSet);

            SfxStyleSheet* pSheet = rPage.GetStyleSheetForPresObj(PresObjKind::Text);
            if (pSheet)
                pNewObj->SetStyleSheet(pSheet, true);

            // Remove subtitle shape from page
            if( bUndo )
                pUndoManager->AddUndoAction(rModel.GetSdrUndoFactory().CreateUndoDeleteObject(*pSourceObj));

            rPage.RemoveObject( pSourceObj->GetOrdNum() );

            if( !bUndo )
                SdrObject::Free( pSourceObj );
        }
    }
    else if((eObjKind == PresObjKind::Outline) && (pSourceObj->GetObjIdentifier() != OBJ_OUTLINETEXT) )
    {
        switch( pSourceObj->GetObjIdentifier() )
        {
        case OBJ_TABLE: eObjKind = PresObjKind::Table; break;
        case OBJ_MEDIA: eObjKind = PresObjKind::Media; break;
        case OBJ_GRAF: eObjKind = PresObjKind::Graphic; break;
        case OBJ_OLE2: eObjKind = PresObjKind::Object; break;
        }
    }

    return pNewObj;
}

/** reuses or creates a presentation shape for an auto layout that fits the given parameter

    @param  eObjKind
        The kind of presentation shape we like to have
    @param  nIndex
        If > 1 we skip the first nIndex-1 shapes with the presentation shape kind eObjKind while
        looking for an existing presentation shape
    @param  bVertical
        If true, the shape is created vertical if bInit is true
    @param  rRect
        The rectangle that should be used to transform the shape
    @param  bInit
        If true the shape is created if not found
    @returns
        A presentation shape that was either found or created with the given parameters
*/
SdrObject* SdPage::InsertAutoLayoutShape(SdrObject* pObj, PresObjKind eObjKind, bool bVertical, const ::tools::Rectangle& rRect, bool bInit)
{
    SfxUndoManager* pUndoManager(static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetUndoManager());
    const bool bUndo = pUndoManager && pUndoManager->IsInListAction() && IsInserted();

    if (!pObj && bInit)
    {
        pObj = CreatePresObj(eObjKind, bVertical, rRect);
    }
    else if ( pObj && (pObj->GetUserCall() || bInit) )
    {
        // convert object if shape type does not match kind (f.e. converting outline text to subtitle text)
        if( bInit )
            pObj = convertPresentationObjectImpl(*this, pObj, eObjKind, bVertical, rRect);

        if( bUndo )
        {
            pUndoManager->AddUndoAction( getSdrModelFromSdrPage().GetSdrUndoFactory().CreateUndoGeoObject( *pObj ) );
            pUndoManager->AddUndoAction( getSdrModelFromSdrPage().GetSdrUndoFactory().CreateUndoAttrObject( *pObj, true, true ) );
            pUndoManager->AddUndoAction( std::make_unique<UndoObjectUserCall>( *pObj ) );
        }

        pObj->AdjustToMaxRect(rRect);

        pObj->SetUserCall(this);

        SdrTextObj* pTextObject = dynamic_cast< SdrTextObj* >(pObj);
        if( pTextObject )
        {
            if( pTextObject->IsVerticalWriting() != bVertical )
            {
                pTextObject->SetVerticalWriting( bVertical );

                // here make sure the correct anchoring is used when the object
                // is re-used but orientation is changed
                if(PresObjKind::Outline == eObjKind)
                    pTextObject->SetMergedItem(SdrTextHorzAdjustItem( bVertical ? SDRTEXTHORZADJUST_RIGHT : SDRTEXTHORZADJUST_BLOCK ));
            }

            if( !mbMaster && (pTextObject->GetObjIdentifier() != OBJ_TABLE) )
            {
                if ( pTextObject->IsAutoGrowHeight() )
                {
                    // switch off AutoGrowHeight, set new MinHeight
                    SfxItemSet aTempAttr( static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetPool() );
                    SdrMetricItem aMinHeight( makeSdrTextMinFrameHeightItem(rRect.GetSize().Height()) );
                    aTempAttr.Put( aMinHeight );
                    aTempAttr.Put( makeSdrTextAutoGrowHeightItem(false) );
                    pTextObject->SetMergedItemSet(aTempAttr);
                    pTextObject->SetLogicRect(rRect);

                    // switch on AutoGrowHeight
                    SfxItemSet aAttr( static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetPool() );
                    aAttr.Put( makeSdrTextAutoGrowHeightItem(true) );

                    pTextObject->SetMergedItemSet(aAttr);
                }

                if ( pTextObject->IsAutoGrowWidth() )
                {
                    // switch off AutoGrowWidth , set new MinWidth
                    SfxItemSet aTempAttr( static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetPool() );
                    SdrMetricItem aMinWidth( makeSdrTextMinFrameWidthItem(rRect.GetSize().Width()) );
                    aTempAttr.Put( aMinWidth );
                    aTempAttr.Put( makeSdrTextAutoGrowWidthItem(false) );
                    pTextObject->SetMergedItemSet(aTempAttr);
                    pTextObject->SetLogicRect(rRect);

                    // switch on AutoGrowWidth
                    SfxItemSet aAttr( static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetPool() );
                    aAttr.Put( makeSdrTextAutoGrowWidthItem(true) );
                    pTextObject->SetMergedItemSet(aAttr);
                }
            }
        }
    }

    if(pObj && bInit )
    {
        if( !IsPresObj( pObj ) )
        {
            if( bUndo )
                pUndoManager->AddUndoAction( std::make_unique<UndoObjectPresentationKind>( *pObj ) );

            InsertPresObj( pObj, eObjKind );
        }

        // make adjustments for vertical title and outline shapes
        if( bVertical && (( eObjKind == PresObjKind::Title) || (eObjKind == PresObjKind::Outline)))
        {
            SfxItemSet aNewSet(pObj->GetMergedItemSet());
            aNewSet.Put( makeSdrTextAutoGrowWidthItem(true) );
            aNewSet.Put( makeSdrTextAutoGrowHeightItem(false) );
            if( eObjKind == PresObjKind::Outline )
            {
                aNewSet.Put( SdrTextVertAdjustItem(SDRTEXTVERTADJUST_TOP) );
                aNewSet.Put( SdrTextHorzAdjustItem(SDRTEXTHORZADJUST_RIGHT) );
            }
            pObj->SetMergedItemSet(aNewSet);
        }
    }

    if ( pObj && (pObj->GetUserCall() || bInit) && ( pObj->IsEmptyPresObj() || dynamic_cast< const SdrGrafObj *>( pObj ) ==  nullptr ) )
        pObj->AdjustToMaxRect(rRect);

    return pObj;
}

/*************************************************************************
|*
|* Returns the PresObjKind of an object
|*
\************************************************************************/

PresObjKind SdPage::GetPresObjKind(SdrObject* pObj) const
{
    PresObjKind eKind = PresObjKind::NONE;
    if( (pObj != nullptr) && (maPresentationShapeList.hasShape(*pObj)) )
    {
        SdAnimationInfo* pInfo = SdDrawDocument::GetShapeUserData(*pObj);
        if( pInfo )
            eKind = pInfo->mePresObjKind;
    }

    return eKind;
}

bool SdPage::IsPresObj(const SdrObject* pObj)
{
    return pObj && maPresentationShapeList.hasShape( const_cast<SdrObject&>(*pObj) );
}

void SdPage::RemovePresObj(const SdrObject* pObj)
{
    if( pObj && maPresentationShapeList.hasShape(const_cast<SdrObject&>(*pObj)) )
    {
        SdAnimationInfo* pInfo = SdDrawDocument::GetShapeUserData(const_cast<SdrObject&>(*pObj));
        if( pInfo )
            pInfo->mePresObjKind = PresObjKind::NONE;
        maPresentationShapeList.removeShape(const_cast<SdrObject&>(*pObj));
    }
}

void SdPage::InsertPresObj(SdrObject* pObj, PresObjKind eKind )
{
    DBG_ASSERT( pObj, "sd::SdPage::InsertPresObj(), invalid presentation object inserted!" );
    DBG_ASSERT( !IsPresObj(pObj), "sd::SdPage::InsertPresObj(), presentation object inserted twice!" );
    if( pObj )
    {
        SdAnimationInfo* pInfo = SdDrawDocument::GetShapeUserData(*pObj, true);
        if( pInfo )
            pInfo->mePresObjKind = eKind;
        maPresentationShapeList.addShape(*pObj);
    }
}

/*************************************************************************
|*
|* Set the text of an object
|*
\************************************************************************/

void SdPage::SetObjText(SdrTextObj* pObj, SdrOutliner* pOutliner, PresObjKind eObjKind, const OUString& rString )
{
    if ( !pObj )
        return;

    DBG_ASSERT( dynamic_cast< const SdrTextObj *>( pObj ) !=  nullptr, "SetObjText: No SdrTextObj!" );
    ::Outliner* pOutl = pOutliner;

    if (!pOutliner)
    {
        SfxItemPool* pPool(static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).GetDrawOutliner().GetEmptyItemSet().GetPool());
        pOutl = new ::Outliner( pPool, OutlinerMode::OutlineObject );
        pOutl->SetRefDevice( SD_MOD()->GetVirtualRefDevice() );
        pOutl->SetEditTextObjectPool(pPool);
        pOutl->SetStyleSheetPool(static_cast<SfxStyleSheetPool*>(getSdrModelFromSdrPage().GetStyleSheetPool()));
        pOutl->EnableUndo(false);
        pOutl->SetUpdateMode( false );
    }

    OutlinerMode nOutlMode = pOutl->GetMode();
    Size aPaperSize = pOutl->GetPaperSize();
    bool bUpdateMode = pOutl->GetUpdateMode();
    pOutl->SetUpdateMode(false);
    pOutl->SetParaAttribs( 0, pOutl->GetEmptyItemSet() );

    // Always set the object's StyleSheet at the Outliner to
    // use the current objects StyleSheet. Thus it's the same as in
    // SetText(...).
    // Moved this implementation from where SetObjText(...) was called
    // to inside this method to work even when outliner is fetched here.
    pOutl->SetStyleSheet(0, pObj->GetStyleSheet());

    OUString aString;

    switch( eObjKind )
    {
        case PresObjKind::Outline:
        {
            pOutl->Init( OutlinerMode::OutlineObject );

            aString += "\t" + rString;

            if (mbMaster)
            {
                pOutl->SetStyleSheet( 0, GetStyleSheetForPresObj(eObjKind) );
                aString += "\n\t\t" +
                    SdResId(STR_PRESOBJ_MPOUTLLAYER2) +
                    "\n\t\t\t" +
                    SdResId(STR_PRESOBJ_MPOUTLLAYER3) +
                    "\n\t\t\t\t" +
                    SdResId(STR_PRESOBJ_MPOUTLLAYER4) +
                    "\n\t\t\t\t\t" +
                    SdResId(STR_PRESOBJ_MPOUTLLAYER5) +
                    "\n\t\t\t\t\t\t" +
                    SdResId(STR_PRESOBJ_MPOUTLLAYER6) +
                    "\n\t\t\t\t\t\t\t" +
                    SdResId(STR_PRESOBJ_MPOUTLLAYER7);

            }
        }
        break;

        case PresObjKind::Title:
        {
            pOutl->Init( OutlinerMode::TitleObject );
            aString += rString;
        }
        break;

        default:
        {
            pOutl->Init( OutlinerMode::TextObject );
            aString += rString;

            // check if we need to add a text field
            std::unique_ptr<SvxFieldData> pData;

            switch( eObjKind )
            {
            case PresObjKind::Header:
                pData.reset(new SvxHeaderField());
                break;
            case PresObjKind::Footer:
                pData .reset(new SvxFooterField());
                break;
            case PresObjKind::SlideNumber:
                pData.reset(new SvxPageField());
                break;
            case PresObjKind::DateTime:
                pData.reset(new SvxDateTimeField());
                break;
            default:
                break;
            }

            if( pData )
            {
                ESelection e;
                SvxFieldItem aField( *pData, EE_FEATURE_FIELD );
                pOutl->QuickInsertField(aField,e);
            }
        }
        break;
    }

    pOutl->SetPaperSize( pObj->GetLogicRect().GetSize() );

    if( !aString.isEmpty() )
        pOutl->SetText( aString, pOutl->GetParagraph( 0 ) );

    pObj->SetOutlinerParaObject( pOutl->CreateParaObject() );

    if (!pOutliner)
    {
        delete pOutl;
        pOutl = nullptr;
    }
    else
    {
        // restore the outliner
        pOutl->Init( nOutlMode );
        pOutl->SetParaAttribs( 0, pOutl->GetEmptyItemSet() );
        pOutl->SetUpdateMode( bUpdateMode );
        pOutl->SetPaperSize( aPaperSize );
    }
}

/*************************************************************************
|*
|* Set the name of the layout
|*
\************************************************************************/
void SdPage::SetLayoutName(const OUString& aName)
{
    maLayoutName = aName;

    if( mbMaster )
    {
        sal_Int32 nPos = maLayoutName.indexOf(SD_LT_SEPARATOR);
        if (nPos != -1)
            FmFormPage::SetName(maLayoutName.copy(0, nPos));
    }
}

/*************************************************************************
|*
|* Return the page name and generates it if necessary
|*
\************************************************************************/

const OUString& SdPage::GetName() const
{
    OUString aCreatedPageName( maCreatedPageName );
    if (GetRealName().isEmpty())
    {
        if ((mePageKind == PageKind::Standard || mePageKind == PageKind::Notes) && !mbMaster)
        {
            // default name for handout pages
            sal_uInt16  nNum = (GetPageNum() + 1) / 2;

            aCreatedPageName = SdResId(STR_PAGE) + " ";
            if (static_cast<SdDrawDocument&>(getSdrModelFromSdrPage()).GetDocumentType() == DocumentType::Draw )
                 aCreatedPageName = SdResId(STR_PAGE_NAME) + " ";

            if( getSdrModelFromSdrPage().GetPageNumType() == css::style::NumberingType::NUMBER_NONE )
            {
                // if the document has number none as a formatting
                // for page numbers we still default to arabic numbering
                // to keep the default page names unique
                aCreatedPageName += OUString::number( static_cast<sal_Int32>(nNum) );
            }
            else
            {
                aCreatedPageName += static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).CreatePageNumValue(nNum);
            }
        }
        else
        {
            /******************************************************************
            * default name for note pages
            ******************************************************************/
            aCreatedPageName = SdResId(STR_LAYOUT_DEFAULT_NAME);
        }
    }
    else
    {
        aCreatedPageName = GetRealName();
    }

    if (mePageKind == PageKind::Notes)
    {
        aCreatedPageName += " " + SdResId(STR_NOTES);
    }
    else if (mePageKind == PageKind::Handout && mbMaster)
    {
        aCreatedPageName += " (" + SdResId(STR_HANDOUT) + ")";
    }

    const_cast< SdPage* >(this)->maCreatedPageName = aCreatedPageName;
    return maCreatedPageName;
}

void SdPage::SetOrientation( Orientation /*eOrient*/)
{
    // Do nothing
}

Orientation SdPage::GetOrientation() const
{
    Size aSize = GetSize();
    if ( aSize.getWidth() > aSize.getHeight() )
    {
        return Orientation::Landscape;
    }
    else
    {
        return Orientation::Portrait;
    }
}

/*************************************************************************
|*
|* returns the default text of a PresObjektes
|*
\************************************************************************/

OUString SdPage::GetPresObjText(PresObjKind eObjKind) const
{
    OUString aString;

#if defined(IOS) || defined(ANDROID)
    bool isMobileDevice = true;<--- Assignment 'isMobileDevice=true', assigned value is 1<--- Assignment 'isMobileDevice=true', assigned value is 1<--- Assignment 'isMobileDevice=true', assigned value is 1<--- Assignment 'isMobileDevice=true', assigned value is 1<--- Assignment 'isMobileDevice=true', assigned value is 1<--- Assignment 'isMobileDevice=true', assigned value is 1<--- Assignment 'isMobileDevice=true', assigned value is 1<--- Assignment 'isMobileDevice=true', assigned value is 1
#else
    bool isMobileDevice = false;
    if (const SfxViewShell* pCurrentViewShell = SfxViewShell::Current())
        isMobileDevice = pCurrentViewShell->isLOKMobilePhone() || pCurrentViewShell->isLOKMobilePhone();
#endif

    if (eObjKind == PresObjKind::Title)
    {
        if (mbMaster)
        {
            if (mePageKind != PageKind::Notes)
            {
                if (isMobileDevice)<--- Condition 'isMobileDevice' is always true
                    aString = SdResId(STR_PRESOBJ_MPTITLE_MOBILE);
                else
                    aString = SdResId(STR_PRESOBJ_MPTITLE);
            }
            else
            {
                if (isMobileDevice)<--- Condition 'isMobileDevice' is always true
                    aString = SdResId(STR_PRESOBJ_MPNOTESTITLE_MOBILE);
                else
                    aString = SdResId(STR_PRESOBJ_MPNOTESTITLE);
            }
        }
        else if (isMobileDevice)<--- Condition 'isMobileDevice' is always true
            aString = SdResId(STR_PRESOBJ_TITLE_MOBILE);
        else
            aString = SdResId(STR_PRESOBJ_TITLE);
    }
    else if (eObjKind == PresObjKind::Outline)
    {
        if (mbMaster)
        {
            if (isMobileDevice)<--- Condition 'isMobileDevice' is always true
                aString = SdResId(STR_PRESOBJ_MPOUTLINE_MOBILE);
            else
                aString = SdResId(STR_PRESOBJ_MPOUTLINE);
        }
        else if (isMobileDevice)<--- Condition 'isMobileDevice' is always true
            aString = SdResId(STR_PRESOBJ_OUTLINE_MOBILE);
        else
            aString = SdResId(STR_PRESOBJ_OUTLINE);
    }
    else if (eObjKind == PresObjKind::Notes)
    {
        if (mbMaster)
        {
            if (isMobileDevice)<--- Condition 'isMobileDevice' is always true
                aString = SdResId(STR_PRESOBJ_MPNOTESTEXT_MOBILE);
            else
                aString = SdResId(STR_PRESOBJ_MPNOTESTEXT);
        }
        else if (isMobileDevice)<--- Condition 'isMobileDevice' is always true
            aString = SdResId(STR_PRESOBJ_NOTESTEXT_MOBILE);
        else
            aString = SdResId(STR_PRESOBJ_NOTESTEXT);
    }
    else if (eObjKind == PresObjKind::Text)
    {
        if (isMobileDevice)<--- Condition 'isMobileDevice' is always true
            aString = SdResId(STR_PRESOBJ_TEXT_MOBILE);
        else
            aString = SdResId(STR_PRESOBJ_TEXT);
    }
    else if (eObjKind == PresObjKind::Graphic)
    {
        aString = SdResId( STR_PRESOBJ_GRAPHIC );
    }
    else if (eObjKind == PresObjKind::Object)
    {
        aString = SdResId( STR_PRESOBJ_OBJECT );
    }
    else if (eObjKind == PresObjKind::Chart)
    {
        aString = SdResId( STR_PRESOBJ_CHART );
    }
    else if (eObjKind == PresObjKind::OrgChart)
    {
        aString = SdResId( STR_PRESOBJ_ORGCHART );
    }
    else if (eObjKind == PresObjKind::Calc)
    {
        aString = SdResId( STR_PRESOBJ_TABLE );
    }

    return aString;
}

uno::Reference< uno::XInterface > SdPage::createUnoPage()
{
    return createUnoPageImpl( this );
}

/** returns the SdPage implementation for the given XDrawPage or 0 if not available */
SdPage* SdPage::getImplementation( const css::uno::Reference< css::drawing::XDrawPage >& xPage )
{
    try
    {
        auto pUnoPage = comphelper::getUnoTunnelImplementation<SvxDrawPage>(xPage);
        if( pUnoPage )
            return static_cast< SdPage* >( pUnoPage->GetSdrPage() );
    }
    catch( css::uno::Exception& )
    {
        OSL_FAIL("sd::SdPage::getImplementation(), exception caught!" );
    }

    return nullptr;
}

sal_Int64 SdPage::GetHashCode() const
{
    return sal::static_int_cast<sal_Int64>(reinterpret_cast<sal_IntPtr>(this));
}

void SdPage::SetName (const OUString& rName)
{
    OUString aOldName( GetName() );
    FmFormPage::SetName (rName);
    static_cast< SdDrawDocument& >(getSdrModelFromSdrPage()).UpdatePageRelativeURLs(aOldName, rName);
    ActionChanged();
}

const HeaderFooterSettings& SdPage::getHeaderFooterSettings() const
{
    if( mePageKind == PageKind::Handout && !mbMaster )
    {
        return static_cast<SdPage&>(TRG_GetMasterPage()).maHeaderFooterSettings;
    }
    else
    {
        return maHeaderFooterSettings;
    }
}

void SdPage::setHeaderFooterSettings( const sd::HeaderFooterSettings& rNewSettings )
{
    if( mePageKind == PageKind::Handout && !mbMaster )
    {
        static_cast<SdPage&>(TRG_GetMasterPage()).maHeaderFooterSettings = rNewSettings;
    }
    else
    {
        maHeaderFooterSettings = rNewSettings;
    }

    SetChanged();

    if(!TRG_HasMasterPage())
        return;

    TRG_GetMasterPageDescriptorViewContact().ActionChanged();

    // #i119056# For HeaderFooterSettings SdrObjects are used, but the properties
    // used are not part of their model data, but kept in SD. This data is applied
    // using a 'backdoor' on primitive creation. Thus, the normal mechanism to detect
    // object changes does not work here. It is necessary to trigger updates here
    // directly. BroadcastObjectChange used for PagePreview invalidations,
    // flushViewObjectContacts used to invalidate and flush all visualizations in
    // edit views.
    SdPage* pMasterPage = dynamic_cast< SdPage* >(&TRG_GetMasterPage());

    if(!pMasterPage)
        return;

    SdrObject* pCandidate = pMasterPage->GetPresObj( PresObjKind::Header );

    if(pCandidate)
    {
        pCandidate->BroadcastObjectChange();
        pCandidate->GetViewContact().flushViewObjectContacts();
    }

    pCandidate = pMasterPage->GetPresObj( PresObjKind::DateTime );

    if(pCandidate)
    {
        pCandidate->BroadcastObjectChange();
        pCandidate->GetViewContact().flushViewObjectContacts();
    }

    pCandidate = pMasterPage->GetPresObj( PresObjKind::Footer );

    if(pCandidate)
    {
        pCandidate->BroadcastObjectChange();
        pCandidate->GetViewContact().flushViewObjectContacts();
    }

    pCandidate = pMasterPage->GetPresObj( PresObjKind::SlideNumber );

    if(pCandidate)
    {
        pCandidate->BroadcastObjectChange();
        pCandidate->GetViewContact().flushViewObjectContacts();
    }
}

bool SdPage::checkVisibility(
    const sdr::contact::ViewObjectContact& rOriginal,
    const sdr::contact::DisplayInfo& rDisplayInfo,
    bool bEdit )
{
    if( !FmFormPage::checkVisibility( rOriginal, rDisplayInfo, bEdit ) )
        return false;

    SdrObject* pObj = rOriginal.GetViewContact().TryToGetSdrObject();
    if( pObj == nullptr )
        return false;

    const SdrPage* pVisualizedPage = GetSdrPageFromXDrawPage(rOriginal.GetObjectContact().getViewInformation2D().getVisualizedPage());
    const bool bIsPrinting(rOriginal.GetObjectContact().isOutputToPrinter() || rOriginal.GetObjectContact().isOutputToPDFFile());
    const SdrPageView* pPageView = rOriginal.GetObjectContact().TryToGetSdrPageView();
    const bool bIsInsidePageObj(pPageView && pPageView->GetPage() != pVisualizedPage);

    // empty presentation objects only visible during edit mode
    if( (bIsPrinting || !bEdit || bIsInsidePageObj ) && pObj->IsEmptyPresObj() )
    {
        if( (pObj->GetObjInventor() != SdrInventor::Default) || ( (pObj->GetObjIdentifier() != OBJ_RECT) && (pObj->GetObjIdentifier() != OBJ_PAGE) ) )
            return false;
    }

    if( ( pObj->GetObjInventor() == SdrInventor::Default ) && ( pObj->GetObjIdentifier() == OBJ_TEXT ) )
    {
        const SdPage* pCheckPage = dynamic_cast< const SdPage* >(pObj->getSdrPageFromSdrObject());

        if( pCheckPage )
        {
            PresObjKind eKind = pCheckPage->GetPresObjKind(pObj);

            if((eKind == PresObjKind::Footer) || (eKind == PresObjKind::Header) || (eKind == PresObjKind::DateTime) || (eKind == PresObjKind::SlideNumber) )
            {
                const bool bSubContentProcessing(rDisplayInfo.GetSubContentActive());

                if( bSubContentProcessing || ( pCheckPage->GetPageKind() == PageKind::Handout && bIsPrinting ) )
                {
                    // use the page that is currently processed
                    const SdPage* pVisualizedSdPage = dynamic_cast< const SdPage* >(pVisualizedPage);

                    if( pVisualizedSdPage )
                    {
                        // if we are not on a masterpage, see if we have to draw this header&footer object at all
                        const sd::HeaderFooterSettings& rSettings = pVisualizedSdPage->getHeaderFooterSettings();

                        switch( eKind )
                        {
                        case PresObjKind::Footer:
                            return rSettings.mbFooterVisible;
                        case PresObjKind::Header:
                            return rSettings.mbHeaderVisible;
                        case PresObjKind::DateTime:
                            return rSettings.mbDateTimeVisible;
                        case PresObjKind::SlideNumber:
                            return rSettings.mbSlideNumberVisible;
                        default:
                            break;
                        }
                    }
                }
            } // check for placeholders on master
            else if( (eKind != PresObjKind::NONE) && pCheckPage->IsMasterPage() && ( pVisualizedPage != pCheckPage ) )
            {
                // presentation objects on master slide are always invisible if slide is shown.
                return false;
            }
        }
    }

    // i63977, do not print SdrpageObjs from master pages
    if( ( pObj->GetObjInventor() == SdrInventor::Default ) && ( pObj->GetObjIdentifier() == OBJ_PAGE ) )
    {
        if( pObj->getSdrPageFromSdrObject() && pObj->getSdrPageFromSdrObject()->IsMasterPage() )
            return false;
    }

    return true;
}

bool SdPage::RestoreDefaultText( SdrObject* pObj )
{
    bool bRet = false;

    SdrTextObj* pTextObj = dynamic_cast< SdrTextObj* >( pObj );

    if( pTextObj )
    {
        PresObjKind ePresObjKind = GetPresObjKind(pTextObj);

        if (ePresObjKind == PresObjKind::Title   ||
            ePresObjKind == PresObjKind::Outline ||
            ePresObjKind == PresObjKind::Notes   ||
            ePresObjKind == PresObjKind::Text)
        {
            OUString aString( GetPresObjText(ePresObjKind) );

            if (!aString.isEmpty())
            {
                bool bVertical = false;
                OutlinerParaObject* pOldPara = pTextObj->GetOutlinerParaObject();
                if( pOldPara )
                    bVertical = pOldPara->IsVertical();  // is old para object vertical?

                SetObjText( pTextObj, nullptr, ePresObjKind, aString );

                if( pOldPara )
                {
                    // Here, only the vertical flag for the
                    // OutlinerParaObjects needs to be changed. The
                    // AutoGrowWidth/Height items still exist in the
                    // not changed object.
                    if(pTextObj->GetOutlinerParaObject()
                        && pTextObj->GetOutlinerParaObject()->IsVertical() != bVertical)
                    {
                        ::tools::Rectangle aObjectRect = pTextObj->GetSnapRect();
                        pTextObj->GetOutlinerParaObject()->SetVertical(bVertical);
                        pTextObj->SetSnapRect(aObjectRect);
                    }
                }

                pTextObj->SetTextEditOutliner( nullptr );  // to make stylesheet settings work
                pTextObj->NbcSetStyleSheet( GetStyleSheetForPresObj(ePresObjKind), true );
                pTextObj->SetEmptyPresObj(true);
                bRet = true;
            }
        }
    }
    return bRet;
}

void SdPage::CalculateHandoutAreas( SdDrawDocument& rModel, AutoLayout eLayout, bool bHorizontal, std::vector< ::tools::Rectangle >& rAreas )
{
    SdPage& rHandoutMaster = *rModel.GetMasterSdPage( 0, PageKind::Handout );

    static const sal_uInt16 aOffsets[5][9] =
    {
        { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, // AUTOLAYOUT_HANDOUT9, Portrait, Horizontal order
        { 0, 2, 4, 1, 3, 5, 0, 0, 0 }, // AUTOLAYOUT_HANDOUT3, Landscape, Vertical
        { 0, 2, 1, 3, 0, 0, 0, 0, 0 }, // AUTOLAYOUT_HANDOUT4, Landscape, Vertical
        { 0, 3, 1, 4, 2, 5, 0, 0, 0 }, // AUTOLAYOUT_HANDOUT4, Portrait, Vertical
        { 0, 3, 6, 1, 4, 7, 2, 5, 8 }, // AUTOLAYOUT_HANDOUT9, Landscape, Vertical
    };

    const sal_uInt16* pOffsets = aOffsets[0];

    Size aArea = rHandoutMaster.GetSize();
    const bool bLandscape = aArea.Width() > aArea.Height();

    if( eLayout == AUTOLAYOUT_NONE )
    {
        // use layout from handout master
        SdrObjListIter aShapeIter(&rHandoutMaster);

        std::vector< ::tools::Rectangle > vSlidesAreas;
        while ( aShapeIter.IsMore() )
        {
            SdrPageObj* pPageObj = dynamic_cast<SdrPageObj*>( aShapeIter.Next() );
            // get slide rectangles
            if (pPageObj)
                vSlidesAreas.push_back( pPageObj->GetCurrentBoundRect() );
        }

        if ( !bHorizontal || vSlidesAreas.size() < 4 )
        { // top to bottom, then right
            rAreas.swap( vSlidesAreas );
        }
        else
        { // left to right, then down
            switch ( vSlidesAreas.size() )
            {
                case 4:
                    pOffsets = aOffsets[2];
                    break;

                default:
                    [[fallthrough]];
                case 6:
                    pOffsets = aOffsets[ bLandscape ? 3 : 1 ];
                    break;

                case 9:
                    pOffsets = aOffsets[4];
                    break;
            }

            rAreas.resize( static_cast<size_t>(vSlidesAreas.size()) );

            for( const ::tools::Rectangle& rRect : vSlidesAreas )
            {
                rAreas[*pOffsets++] = rRect;
            }
        }
    }
    else
    {
        const long nGapW = 1000; // gap is 1cm
        const long nGapH = 1000;

        long nLeftBorder = rHandoutMaster.GetLeftBorder();
        long nRightBorder = rHandoutMaster.GetRightBorder();
        long nTopBorder = rHandoutMaster.GetUpperBorder();
        long nBottomBorder = rHandoutMaster.GetLowerBorder();

        const long nHeaderFooterHeight = static_cast< long >( (aArea.Height() - nTopBorder - nLeftBorder) * 0.05  );

        nTopBorder += nHeaderFooterHeight;
        nBottomBorder += nHeaderFooterHeight;

        long nX = nGapW + nLeftBorder;
        long nY = nGapH + nTopBorder;

        aArea.AdjustWidth( -(nGapW * 2 + nLeftBorder + nRightBorder) );
        aArea.AdjustHeight( -(nGapH * 2 + nTopBorder + nBottomBorder) );

        sal_uInt16  nColCnt = 0, nRowCnt = 0;
        switch ( eLayout )
        {
            case AUTOLAYOUT_HANDOUT1:
                nColCnt = 1; nRowCnt = 1;
                break;

            case AUTOLAYOUT_HANDOUT2:
                if( bLandscape )
                {
                    nColCnt = 2; nRowCnt = 1;
                }
                else
                {
                    nColCnt = 1; nRowCnt = 2;
                }
                break;

            case AUTOLAYOUT_HANDOUT3:
                if( bLandscape )
                {
                    nColCnt = 3; nRowCnt = 2;
                }
                else
                {
                    nColCnt = 2; nRowCnt = 3;
                }
                pOffsets = aOffsets[ bLandscape ? 1 : 0 ];
                break;

            case AUTOLAYOUT_HANDOUT4:
                nColCnt = 2; nRowCnt = 2;
                pOffsets = aOffsets[ bHorizontal ? 0 : 2 ];
                break;

            case AUTOLAYOUT_HANDOUT6:
                if( bLandscape )
                {
                    nColCnt = 3; nRowCnt = 2;
                }
                else
                {
                    nColCnt = 2; nRowCnt = 3;
                }
                if( !bHorizontal )
                    pOffsets = aOffsets[ bLandscape ? 1 : 3 ];
                break;

            default:
            case AUTOLAYOUT_HANDOUT9:
                nColCnt = 3; nRowCnt = 3;

                if( !bHorizontal )
                    pOffsets = aOffsets[4];
                break;
        }

        rAreas.resize(static_cast<size_t>(nColCnt) * nRowCnt);

        Size aPartArea, aSize;
        aPartArea.setWidth( (aArea.Width()  - ((nColCnt-1) * nGapW) ) / nColCnt );
        aPartArea.setHeight( (aArea.Height() - ((nRowCnt-1) * nGapH) ) / nRowCnt );

        SdrPage* pFirstPage = rModel.GetMasterSdPage(0, PageKind::Standard);
        if (pFirstPage && pFirstPage->GetWidth() && pFirstPage->GetHeight())
        {
            // scale actual size into handout rect
            double fScale = static_cast<double>(aPartArea.Width()) / static_cast<double>(pFirstPage->GetWidth());

            aSize.setHeight( static_cast<long>(fScale * pFirstPage->GetHeight() ) );
            if( aSize.Height() > aPartArea.Height() )
            {
                fScale = static_cast<double>(aPartArea.Height()) / static_cast<double>(pFirstPage->GetHeight());
                aSize.setHeight( aPartArea.Height() );
                aSize.setWidth( static_cast<long>(fScale * pFirstPage->GetWidth()) );
            }
            else
            {
                aSize.setWidth( aPartArea.Width() );
            }

            nX += (aPartArea.Width() - aSize.Width()) / 2;
            nY += (aPartArea.Height()- aSize.Height())/ 2;
        }
        else
        {
            aSize = aPartArea;
        }

        Point aPos( nX, nY );

        const bool bRTL = rModel.GetDefaultWritingMode() == css::text::WritingMode_RL_TB;

        const long nOffsetX = (aPartArea.Width() + nGapW) * (bRTL ? -1 : 1);
        const long nOffsetY = aPartArea.Height() + nGapH;
        const long nStartX = bRTL ? nOffsetX*(1 - nColCnt) + nX : nX;

        for(sal_uInt16 nRow = 0; nRow < nRowCnt; nRow++)
        {
            aPos.setX( nStartX );
            for(sal_uInt16 nCol = 0; nCol < nColCnt; nCol++)
            {
                rAreas[*pOffsets++] = ::tools::Rectangle(aPos, aSize);
                aPos.AdjustX(nOffsetX );
            }

            aPos.AdjustY(nOffsetY );
        }
    }
}

void SdPage::SetPrecious (const bool bIsPrecious)
{
    mbIsPrecious = bIsPrecious;
}

HeaderFooterSettings::HeaderFooterSettings()
{
    mbHeaderVisible = true;
    mbFooterVisible = true;
    mbSlideNumberVisible = false;
    mbDateTimeVisible = true;
    mbDateTimeIsFixed = true;
    meDateFormat = SvxDateFormat::A;
    meTimeFormat = SvxTimeFormat::AppDefault;
}

bool HeaderFooterSettings::operator==( const HeaderFooterSettings& rSettings ) const
{
    return (mbHeaderVisible == rSettings.mbHeaderVisible) &&
           (maHeaderText == rSettings.maHeaderText) &&
           (mbFooterVisible == rSettings.mbFooterVisible) &&
           (maFooterText == rSettings.maFooterText) &&
           (mbSlideNumberVisible == rSettings.mbSlideNumberVisible) &&
           (mbDateTimeVisible == rSettings.mbDateTimeVisible) &&
           (mbDateTimeIsFixed == rSettings.mbDateTimeIsFixed) &&
           (meDateFormat == rSettings.meDateFormat) &&
           (meTimeFormat == rSettings.meTimeFormat) &&
           (maDateTimeText == rSettings.maDateTimeText);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */