summaryrefslogtreecommitdiff
path: root/svx/source/table/svdotable.cxx
blob: a77655f401661a6b429d7e7f17a6c9547b14c448 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
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
/* -*- 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 <memory>
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
#include <com/sun/star/container/XNamed.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <o3tl/make_unique.hxx>
#include <vcl/canvastools.hxx>
#include <com/sun/star/style/XStyle.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <svl/style.hxx>
#include <editeng/editstat.hxx>
#include <editeng/outlobj.hxx>
#include <svx/svdview.hxx>
#include <sdr/properties/textproperties.hxx>
#include <svx/svdotable.hxx>
#include <svx/svdhdl.hxx>
#include "viewcontactoftableobj.hxx"
#include <svx/svdoutl.hxx>
#include <svx/svddrag.hxx>
#include <svx/svdpagv.hxx>
#include <tablemodel.hxx>
#include <cell.hxx>
#include <svx/xflclit.hxx>
#include "tablelayouter.hxx"
#include <svx/svdetc.hxx>
#include "tablehandles.hxx"
#include <editeng/boxitem.hxx>
#include <svx/framelink.hxx>
#include <svx/sdr/table/tabledesign.hxx>
#include <svx/svdundo.hxx>
#include <svx/strings.hrc>
#include <svx/dialmgr.hxx>
#include <editeng/writingmodeitem.hxx>
#include <editeng/frmdiritem.hxx>
#include <svx/xflhtit.hxx>
#include <svx/xflftrit.hxx>
#include <svx/xfltrit.hxx>
#include <cppuhelper/implbase.hxx>
#include <libxml/xmlwriter.h>


using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::container::XIndexAccess;
using ::com::sun::star::style::XStyle;
using ::com::sun::star::table::XTableRows;
using ::com::sun::star::table::XTableColumns;
using ::com::sun::star::table::XTable;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::util::XModifyBroadcaster;
using sdr::properties::TextProperties;
using sdr::properties::BaseProperties;
using namespace ::com::sun::star;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::style;

namespace sdr { namespace table {

class TableProperties : public TextProperties
{
protected:
    // create a new itemset
    std::unique_ptr<SfxItemSet> CreateObjectSpecificItemSet(SfxItemPool& rPool) override;

public:
    // basic constructor
    explicit TableProperties(SdrObject& rObj );

    // constructor for copying, but using new object
    TableProperties(const TableProperties& rProps, SdrObject& rObj );

    // Clone() operator, normally just calls the local copy constructor
    std::unique_ptr<BaseProperties> Clone(SdrObject& rObj) const override;

    virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = nullptr) override;
};

TableProperties::TableProperties(SdrObject& rObj)
: TextProperties(rObj)
{
}

TableProperties::TableProperties(const TableProperties& rProps, SdrObject& rObj)
: TextProperties(rProps, rObj)
{
}

std::unique_ptr<BaseProperties> TableProperties::Clone(SdrObject& rObj) const
{
    return std::unique_ptr<BaseProperties>(new TableProperties(*this, rObj));
}

void TableProperties::ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem)
{
    if( nWhich == SDRATTR_TEXTDIRECTION )
        AttributeProperties::ItemChange( nWhich, pNewItem );
    else
        TextProperties::ItemChange( nWhich, pNewItem );
}

// create a new itemset
std::unique_ptr<SfxItemSet> TableProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)
{
    return o3tl::make_unique<SfxItemSet>(rPool,

        // range from SdrAttrObj
        svl::Items<SDRATTR_START, SDRATTR_SHADOW_LAST,
        SDRATTR_MISC_FIRST, SDRATTR_MISC_LAST,
        SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION,

        // range for SdrTableObj
        SDRATTR_TABLE_FIRST, SDRATTR_TABLE_LAST,

        // range from SdrTextObj
        EE_ITEMS_START, EE_ITEMS_END>{});
}

class TableObjectGeoData : public SdrTextObjGeoData
{
public:
    tools::Rectangle   maLogicRect;
};

TableStyleSettings::TableStyleSettings()
: mbUseFirstRow(true)
, mbUseLastRow(false)
, mbUseFirstColumn(false)
, mbUseLastColumn(false)
, mbUseRowBanding(true)
, mbUseColumnBanding(false)
{
}

TableStyleSettings::TableStyleSettings( const TableStyleSettings& rStyle )
{
    (*this) = rStyle;
}

TableStyleSettings& TableStyleSettings::operator=(const TableStyleSettings& rStyle)
{
    mbUseFirstRow = rStyle.mbUseFirstRow;
    mbUseLastRow = rStyle.mbUseLastRow;
    mbUseFirstColumn = rStyle.mbUseFirstColumn;
    mbUseLastColumn = rStyle.mbUseLastColumn;
    mbUseRowBanding = rStyle.mbUseRowBanding;
    mbUseColumnBanding = rStyle.mbUseColumnBanding;
    return *this;
}

bool TableStyleSettings::operator==( const TableStyleSettings& rStyle ) const
{
    return
        (mbUseFirstRow == rStyle.mbUseFirstRow) &&
        (mbUseLastRow == rStyle.mbUseLastRow) &&
        (mbUseFirstColumn == rStyle.mbUseFirstColumn) &&
        (mbUseLastColumn == rStyle.mbUseLastColumn) &&
        (mbUseRowBanding == rStyle.mbUseRowBanding) &&
        (mbUseColumnBanding == rStyle.mbUseColumnBanding);
}


class SdrTableObjImpl : public TableDesignUser, public ::cppu::WeakImplHelper< css::util::XModifyListener >
{
public:
    CellRef mxActiveCell;
    TableModelRef mxTable;
    SdrTableObj* mpTableObj;
    std::unique_ptr<TableLayouter> mpLayouter;
    CellPos maEditPos;
    TableStyleSettings maTableStyle;
    Reference< XIndexAccess > mxTableStyle;
    std::vector<std::unique_ptr<SdrUndoAction>> maUndos;
    bool mbSkipChangeLayout;

    void CropTableModelToSelection(const CellPos& rStart, const CellPos& rEnd);

    CellRef getCell( const CellPos& rPos ) const;
    void LayoutTable( tools::Rectangle& rArea, bool bFitWidth, bool bFitHeight );

    void ApplyCellStyles();
    void UpdateCells( tools::Rectangle const & rArea );

    SdrTableObjImpl();
    virtual ~SdrTableObjImpl() override;

    void init( SdrTableObj* pTable, sal_Int32 nColumns, sal_Int32 nRows );
    void dispose();

    sal_Int32 getColumnCount() const;
    /// Get widths of the columns in the table.
    std::vector<sal_Int32> getColumnWidths() const;
    sal_Int32 getRowCount() const;

    void DragEdge( bool mbHorizontal, int nEdge, sal_Int32 nOffset );

    SdrTableObjImpl& operator=( const SdrTableObjImpl& rSource );

    // XModifyListener
    virtual void SAL_CALL modified( const css::lang::EventObject& aEvent ) override;

    // XEventListener
    virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override;

    void update();

    void connectTableStyle();
    void disconnectTableStyle();
    virtual bool isInUse() override;
    void dumpAsXml(struct _xmlTextWriter* pWriter) const;
private:
    static SdrTableObjImpl* lastLayoutTable;
    static tools::Rectangle lastLayoutInputRectangle;
    static tools::Rectangle lastLayoutResultRectangle;
    static bool lastLayoutFitWidth;
    static bool lastLayoutFitHeight;
    static WritingMode lastLayoutMode;
    static sal_Int32 lastRowCount;
    static sal_Int32 lastColCount;
    static std::vector<sal_Int32> lastColWidths;
};

SdrTableObjImpl* SdrTableObjImpl::lastLayoutTable = nullptr;
tools::Rectangle SdrTableObjImpl::lastLayoutInputRectangle;
tools::Rectangle SdrTableObjImpl::lastLayoutResultRectangle;
bool SdrTableObjImpl::lastLayoutFitWidth;
bool SdrTableObjImpl::lastLayoutFitHeight;
WritingMode SdrTableObjImpl::lastLayoutMode;
sal_Int32 SdrTableObjImpl::lastRowCount;
sal_Int32 SdrTableObjImpl::lastColCount;
std::vector<sal_Int32> SdrTableObjImpl::lastColWidths;

SdrTableObjImpl::SdrTableObjImpl()
: mpTableObj( nullptr )
, mbSkipChangeLayout(false)
{
}


SdrTableObjImpl::~SdrTableObjImpl()
{
    if( lastLayoutTable == this )
        lastLayoutTable = nullptr;
}


void SdrTableObjImpl::CropTableModelToSelection(const CellPos& rStart, const CellPos& rEnd)
{
    if(!mxTable.is())
    {
        return;
    }

    const sal_Int32 nColumns(rEnd.mnCol - rStart.mnCol + 1);
    const sal_Int32 nRows(rEnd.mnRow - rStart.mnRow + 1);

    if(nColumns < 1 || nRows < 1 || nColumns > getColumnCount() || nRows > getRowCount())
    {
        return;
    }

    // tdf#116977 First thought was to create the new TableModel, copy data to it and then exchange
    // mxTable and dispose old one. This does *not* work, even when all stuff looks nicely referenced
    // and safe *because* Cell::create gets handed over the current SdrTableObj, hands it to
    // ::Cell and there the local mxTable is initialized using rTableObj.getTable() (!). Due to This,
    // the new created Cells in a new created TableModel based on given mpTableObj *will be disposed*
    // when the old mxTable gets disposed - ARGH!
    // To avoid, change strategy: Remember old TableModel, reset mxTable immediately - this is the
    // SdrTableObjImpl of the current SdrTableObj anyways. Luckily, this works as intended...

    // remember old TableModel
    TableModelRef xOldTable(mxTable);

    // immediately create new one and initialize. This creates ::Cell's which then will use
    // the correct TableModel (accessed through SdrTableObj, but using local mxTable)
    mxTable = new TableModel(mpTableObj);
    mxTable->init(nColumns, nRows);

    // copy cells
    for( sal_Int32 nRow = 0; nRow < nRows; ++nRow )
    {
        for( sal_Int32 nCol = 0; nCol < nColumns; ++nCol ) try
        {
            CellRef xTargetCell( dynamic_cast< Cell* >( mxTable->getCellByPosition( nCol, nRow ).get() ) );
            if( xTargetCell.is() )
                xTargetCell->cloneFrom( dynamic_cast< Cell* >( xOldTable->getCellByPosition( rStart.mnCol + nCol, rStart.mnRow + nRow ).get() ) );
        }
        catch( Exception& )
        {
            OSL_FAIL( "SdrTableObj::CropTableModelToSelection(), exception caught!" );
        }
    }

    // copy row heights
    Reference< XTableRows > xNewRows(mxTable->getRows(), UNO_QUERY_THROW );
    const OUString sHeight( "Height" );
    for( sal_Int32 nRow = 0; nRow < nRows; ++nRow )
    {
        Reference< XPropertySet > xNewSet( xNewRows->getByIndex( nRow ), UNO_QUERY_THROW );
        xNewSet->setPropertyValue( sHeight, Any( mpLayouter->getRowHeight( rStart.mnRow + nRow ) ) );
    }

    // copy column widths
    Reference< XTableColumns > xNewColumns( mxTable->getColumns(), UNO_QUERY_THROW );
    const OUString sWidth( "Width" );
    for( sal_Int32 nCol = 0; nCol < nColumns; ++nCol )
    {
        Reference< XPropertySet > xNewSet( xNewColumns->getByIndex( nCol ), UNO_QUERY_THROW );
        xNewSet->setPropertyValue( sWidth, Any( mpLayouter->getColumnWidth( rStart.mnCol + nCol ) ) );
    }

    // reset layouter which still holds a copy to old TableModel
    mpLayouter.reset();

    // cleanup old TableModel
    {
        Reference< XModifyListener > xListener( static_cast< css::util::XModifyListener* >(this) );
        xOldTable->removeModifyListener( xListener );
        xOldTable->dispose();
        xOldTable.clear();
    }

    // create and hand over to new TableLayouter
    mpLayouter.reset(new TableLayouter( mxTable ));

    // add needed listener to react on changes
    Reference< XModifyListener > xListener( static_cast< css::util::XModifyListener* >(this) );
    mxTable->addModifyListener( xListener );

    // Apply Style to Cells
    ApplyCellStyles();

    // layout cropped table
    LayoutTable( mpTableObj->maRect, false, false );
}

void SdrTableObjImpl::init( SdrTableObj* pTable, sal_Int32 nColumns, sal_Int32 nRows )
{
    mpTableObj = pTable;
    mxTable = new TableModel( pTable );
    mxTable->init( nColumns, nRows );
    Reference< XModifyListener > xListener( static_cast< css::util::XModifyListener* >(this) );
    mxTable->addModifyListener( xListener );
    mpLayouter.reset(new TableLayouter( mxTable ));
    LayoutTable( mpTableObj->maRect, true, true );
    mpTableObj->maLogicRect = mpTableObj->maRect;
}


SdrTableObjImpl& SdrTableObjImpl::operator=( const SdrTableObjImpl& rSource )
{
    if(this == &rSource)
    {
        return *this;
    }

    if(nullptr == mpTableObj || nullptr == rSource.mpTableObj)
    {
        // error: need both SdrObjects to successfully copy data
        return *this;
    }

    // remove evtl. listeners from local
    disconnectTableStyle();

    // reset layouter which holds a copy
    mpLayouter.reset();

    // cleanup local mxTable if used
    if( mxTable.is() )
    {
        Reference< XModifyListener > xListener( static_cast< css::util::XModifyListener* >(this) );
        mxTable->removeModifyListener( xListener );
        mxTable->dispose();
        mxTable.clear();
    }

    // copy TableStyle (short internal data)
    maTableStyle = rSource.maTableStyle;

    // create/copy new mxTable. This will copy all needed cells, too
    mxTable = new TableModel( mpTableObj, rSource.mxTable );

    // create and hand over to new TableLayouter
    mpLayouter.reset(new TableLayouter( mxTable ));

    // add needed listener to react on changes
    Reference< XModifyListener > xListener( static_cast< css::util::XModifyListener* >(this) );
    mxTable->addModifyListener( xListener );

    // handle TableStyle
    Reference< XIndexAccess > xNewTableStyle;
    SdrModel& rSourceSdrModel(rSource.mpTableObj->getSdrModelFromSdrObject());
    SdrModel& rTargetSdrModel(mpTableObj->getSdrModelFromSdrObject());

    if(rSource.mxTableStyle.is() && &rSourceSdrModel == &rTargetSdrModel)
    {
        // source and target model the same -> keep current TableStyle
        xNewTableStyle = rSource.mxTableStyle;
    }

    if(!xNewTableStyle.is() && rSource.mxTableStyle.is()) try
    {
        // search in traget SdrModel for that TableStyle
        const OUString sStyleName( Reference< XNamed >( rSource.mxTableStyle, UNO_QUERY_THROW )->getName() );
        Reference< XStyleFamiliesSupplier > xSFS(rTargetSdrModel.getUnoModel(), UNO_QUERY_THROW );
        Reference< XNameAccess > xFamilyNameAccess( xSFS->getStyleFamilies(), UNO_QUERY_THROW );
        const OUString sFamilyName( "table" );
        Reference< XNameAccess > xTableFamilyAccess( xFamilyNameAccess->getByName( sFamilyName ), UNO_QUERY_THROW );

        if( xTableFamilyAccess->hasByName( sStyleName ) )
        {
            // found table style with the same name
            xTableFamilyAccess->getByName( sStyleName ) >>= xNewTableStyle;
        }
        else
        {
            // copy or? Not found, use 1st existing TableStyle (or none)
            Reference< XIndexAccess > xIndexAccess( xTableFamilyAccess, UNO_QUERY_THROW );
            xIndexAccess->getByIndex( 0 ) >>= xNewTableStyle;
        }
    }
    catch( Exception& )
    {
        OSL_FAIL("svx::SdrTableObjImpl::operator=(), exception caught!");
    }

    // set that TableStyle
    mxTableStyle = xNewTableStyle;

    // Apply Style to Cells
    ApplyCellStyles();

    // copy geometry
    mpTableObj->maRect = mpTableObj->maLogicRect;

    // layout cloned table
    LayoutTable( mpTableObj->maRect, false, false );

    // re-connect to styles (evtl. in new SdrModel)
    connectTableStyle();

    return *this;
}

void SdrTableObjImpl::ApplyCellStyles()
{
    if( !mxTable.is() || !mxTableStyle.is() )
        return;

    const sal_Int32 nColCount = getColumnCount();
    const sal_Int32 nRowCount = getRowCount();

    const TableStyleSettings& rStyle = maTableStyle;

    CellPos aPos;
    for( aPos.mnRow = 0; aPos.mnRow < nRowCount; ++aPos.mnRow )
    {
        const bool bFirstRow = (aPos.mnRow == 0) && rStyle.mbUseFirstRow;
        const bool bLastRow = (aPos.mnRow == nRowCount-1) && rStyle.mbUseLastRow;

        for( aPos.mnCol = 0; aPos.mnCol < nColCount; ++aPos.mnCol )
        {
            Reference< XStyle > xStyle;

            // first and last row win first, if used and available
            if( bFirstRow )
            {
                mxTableStyle->getByIndex(first_row_style) >>= xStyle;
            }
            else if( bLastRow )
            {
                mxTableStyle->getByIndex(last_row_style) >>= xStyle;
            }

            if( !xStyle.is() )
            {
                // next come first and last column, if used and available
                if( rStyle.mbUseFirstColumn && (aPos.mnCol == 0)  )
                {
                    mxTableStyle->getByIndex(first_column_style) >>= xStyle;
                }
                else if( rStyle.mbUseLastColumn && (aPos.mnCol == nColCount-1) )
                {
                    mxTableStyle->getByIndex(last_column_style) >>= xStyle;
                }
            }

            if( !xStyle.is() && rStyle.mbUseRowBanding )
            {
                if( (aPos.mnRow & 1) == 0 )
                {
                    mxTableStyle->getByIndex(even_rows_style) >>= xStyle;
                }
                else
                {
                    mxTableStyle->getByIndex(odd_rows_style) >>= xStyle;
                }
            }

            if( !xStyle.is() && rStyle.mbUseColumnBanding )
            {
                if( (aPos.mnCol & 1) == 0 )
                {
                    mxTableStyle->getByIndex(even_columns_style) >>= xStyle;
                }
                else
                {
                    mxTableStyle->getByIndex(odd_columns_style) >>= xStyle;
                }
            }

            if( !xStyle.is() )
            {
                // use default cell style if non found yet
                mxTableStyle->getByIndex(body_style) >>= xStyle;
            }


            if( xStyle.is() )
            {
                SfxUnoStyleSheet* pStyle = SfxUnoStyleSheet::getUnoStyleSheet(xStyle);

                if( pStyle )
                {
                    CellRef xCell( getCell( aPos ) );
                    if( xCell.is() && ( xCell->GetStyleSheet() != pStyle ) )
                    {
                        xCell->SetStyleSheet( pStyle, true );
                    }
                }
            }
        }
    }
}


void SdrTableObjImpl::dispose()
{
    disconnectTableStyle();
    mxTableStyle.clear();

    mpLayouter.reset();

    if( mxTable.is() )
    {
        Reference< XModifyListener > xListener( static_cast< css::util::XModifyListener* >(this) );
        mxTable->removeModifyListener( xListener );
        mxTable->dispose();
        mxTable.clear();
    }
}


void SdrTableObjImpl::DragEdge( bool mbHorizontal, int nEdge, sal_Int32 nOffset )
{
    if( (nEdge >= 0) && mxTable.is()) try
    {
        const OUString sSize( "Size" );
        if( mbHorizontal )
        {
            if( (nEdge >= 0) && (nEdge <= getRowCount()) )
            {
                sal_Int32 nHeight = mpLayouter->getRowHeight( (!nEdge)?nEdge:(nEdge-1) );
                if(nEdge==0)
                    nHeight -= nOffset;
                else
                    nHeight += nOffset;
                Reference< XIndexAccess > xRows( mxTable->getRows(), UNO_QUERY_THROW );
                Reference< XPropertySet > xRowSet( xRows->getByIndex( (!nEdge)?nEdge:(nEdge-1) ), UNO_QUERY_THROW );
                xRowSet->setPropertyValue( sSize, Any( nHeight ) );
            }
        }
        else
        {
            /*
            fixes fdo#59889 and resizing of table in edge dragging
            Total vertical edges in a NxN table is N+1, indexed from 0 to N and total Columns is N, indexed from 0 to N-1
            In LTR table vertical edge responsible for dragging of column x(x=0 to N-1) is, Edge x+1
            But in RTL table vertical edge responsible for dragging of column x(x=0 to N-1, but from right to left)is, Edge x
            In LTR table dragging of edge 0(for RTL table edge N) does nothing.
            */
            //Todo: Implement Dragging functionality for leftmost edge of table.
            if( (nEdge >= 0) && (nEdge <= getColumnCount()) )
            {
                const bool bRTL = mpTableObj != nullptr && (mpTableObj->GetWritingMode() == WritingMode_RL_TB);
                sal_Int32 nWidth;
                if(bRTL)
                {
                    nWidth = mpLayouter->getColumnWidth( nEdge );
                }
                else
                {
                    nWidth = mpLayouter->getColumnWidth( (!nEdge)?nEdge:(nEdge-1) );
                }
                Reference< XIndexAccess > xCols( mxTable->getColumns(), UNO_QUERY_THROW );
                nWidth += nOffset;
                if(bRTL && nEdge<getColumnCount())
                {
                    Reference< XPropertySet > xColSet( xCols->getByIndex( nEdge ), UNO_QUERY_THROW );
                    xColSet->setPropertyValue( sSize, Any( nWidth ) );
                }
                else if(!bRTL && nEdge>0)
                {
                    Reference< XPropertySet > xColSet( xCols->getByIndex( nEdge-1 ), UNO_QUERY_THROW );
                    xColSet->setPropertyValue( sSize, Any( nWidth ) );
                }
                /* To prevent the table resizing on edge dragging */
                if( nEdge > 0 && nEdge < mxTable->getColumnCount() )
                {

                    if( bRTL )
                        nEdge--;

                    if( (bRTL && (nEdge >= 0)) || (!bRTL && (nEdge < mxTable->getColumnCount())) )
                    {
                        nWidth = mpLayouter->getColumnWidth( nEdge );
                        nWidth = std::max( static_cast<sal_Int32>(nWidth - nOffset), sal_Int32(0) );

                        Reference< XPropertySet > xColSet( xCols->getByIndex( nEdge ), UNO_QUERY_THROW );
                        xColSet->setPropertyValue( sSize, Any( nWidth ) );
                    }
                }
            }
        }
    }
    catch( Exception& )
    {
        OSL_FAIL( "svx::SdrTableObjImpl::DragEdge(), exception caught!" );
    }
}


// XModifyListener


void SAL_CALL SdrTableObjImpl::modified( const css::lang::EventObject& /*aEvent*/ )
{
    update();
}

void SdrTableObjImpl::update()
{
    // source can be the table model itself or the assigned table template
    TableModelNotifyGuard aGuard( mxTable.get() );
    if( mpTableObj )
    {
        if( (maEditPos.mnRow >= getRowCount()) || (maEditPos.mnCol >= getColumnCount()) || (getCell( maEditPos ) != mxActiveCell) )
        {
            if(maEditPos.mnRow >= getRowCount())
                maEditPos.mnRow = getRowCount()-1;

            if(maEditPos.mnCol >= getColumnCount())
                maEditPos.mnCol = getColumnCount()-1;

            mpTableObj->setActiveCell( maEditPos );
        }

        ApplyCellStyles();

        mpTableObj->maRect = mpTableObj->maLogicRect;
        LayoutTable( mpTableObj->maRect, false, false );

        mpTableObj->SetRectsDirty();
        mpTableObj->ActionChanged();
        mpTableObj->BroadcastObjectChange();
    }
}


void SdrTableObjImpl::connectTableStyle()
{
    if( mxTableStyle.is() )
    {
        Reference< XModifyBroadcaster > xBroadcaster( mxTableStyle, UNO_QUERY );
        if( xBroadcaster.is() )
        {
            Reference< XModifyListener > xListener( static_cast< css::util::XModifyListener* >(this) );
            xBroadcaster->addModifyListener( xListener );
        }
    }
}


void SdrTableObjImpl::disconnectTableStyle()
{
    if( mxTableStyle.is() )
    {
        Reference< XModifyBroadcaster > xBroadcaster( mxTableStyle, UNO_QUERY );
        if( xBroadcaster.is() )
        {
            Reference< XModifyListener > xListener( static_cast< css::util::XModifyListener* >(this) );
            xBroadcaster->removeModifyListener( xListener );
        }
    }
}


bool SdrTableObjImpl::isInUse()
{
    return mpTableObj && mpTableObj->IsInserted();
}

void SdrTableObjImpl::dumpAsXml(xmlTextWriterPtr pWriter) const
{
    xmlTextWriterStartElement(pWriter, BAD_CAST("SdrTableObjImpl"));
    if (mpLayouter)
        mpLayouter->dumpAsXml(pWriter);
    mxTable->dumpAsXml(pWriter);
    xmlTextWriterEndElement(pWriter);
}


// XEventListener


void SAL_CALL SdrTableObjImpl::disposing( const css::lang::EventObject& /*Source*/ )
{
    mxActiveCell.clear();
    mxTable.clear();
    mpLayouter.reset();
    mpTableObj = nullptr;
}


CellRef SdrTableObjImpl::getCell(  const CellPos& rPos  ) const
{
    CellRef xCell;
    if( mxTable.is() ) try
    {
        xCell.set( dynamic_cast< Cell* >( mxTable->getCellByPosition( rPos.mnCol, rPos.mnRow ).get() ) );
    }
    catch( Exception& )
    {
        OSL_FAIL( "svx::SdrTableObjImpl::getCell(), exception caught!" );
    }
    return xCell;
}


sal_Int32 SdrTableObjImpl::getColumnCount() const
{
    return mxTable.is() ? mxTable->getColumnCount() : 0;
}

std::vector<sal_Int32> SdrTableObjImpl::getColumnWidths() const
{
    std::vector<sal_Int32> aRet;

    if (mxTable.is())
        aRet = mxTable->getColumnWidths();

    return aRet;
}

sal_Int32 SdrTableObjImpl::getRowCount() const
{
    return mxTable.is() ? mxTable->getRowCount() : 0;
}

void SdrTableObjImpl::LayoutTable( tools::Rectangle& rArea, bool bFitWidth, bool bFitHeight )
{
    if(mpLayouter)
    {
        // Optimization: SdrTableObj::SetChanged() can call this very often, repeatedly
        // with the same settings, noticeably increasing load time. Skip if already done.
        bool bInteractiveMightGrowBecauseTextChanged =
            mpTableObj->IsReallyEdited() && (mpTableObj->IsAutoGrowHeight() || mpTableObj->IsAutoGrowWidth());
        WritingMode writingMode = mpTableObj->GetWritingMode();
        if( bInteractiveMightGrowBecauseTextChanged
            || lastLayoutTable != this || lastLayoutInputRectangle != rArea
            || lastLayoutFitWidth != bFitWidth || lastLayoutFitHeight != bFitHeight
            || lastLayoutMode != writingMode
            || lastRowCount != getRowCount()
            || lastColCount != getColumnCount()
            || lastColWidths != getColumnWidths() )
        {
            lastLayoutTable = this;
            lastLayoutInputRectangle = rArea;
            lastLayoutFitWidth = bFitWidth;
            lastLayoutFitHeight = bFitHeight;
            lastLayoutMode = writingMode;
            lastRowCount = getRowCount();
            lastColCount = getColumnCount();
            // Column resize, when the total width and column count of the
            // table is unchanged, but re-layout is still needed.
            lastColWidths = getColumnWidths();
            TableModelNotifyGuard aGuard( mxTable.get() );
            mpLayouter->LayoutTable( rArea, bFitWidth, bFitHeight );
            lastLayoutResultRectangle = rArea;
        }
        else
        {
            rArea = lastLayoutResultRectangle;
            mpLayouter->UpdateBorderLayout();
        }
    }
}

void SdrTableObjImpl::UpdateCells( tools::Rectangle const & rArea )
{
    if( mpLayouter && mxTable.is() )
    {
        TableModelNotifyGuard aGuard( mxTable.get() );
        mpLayouter->updateCells( rArea );
        mxTable->setModified(true);
    }
}


// BaseProperties section


std::unique_ptr<sdr::properties::BaseProperties> SdrTableObj::CreateObjectSpecificProperties()
{
    return o3tl::make_unique<TableProperties>(*this);
}


// DrawContact section


std::unique_ptr<sdr::contact::ViewContact> SdrTableObj::CreateObjectSpecificViewContact()
{
    return o3tl::make_unique<sdr::contact::ViewContactOfTableObj>(*this);
}

SdrTableObj::SdrTableObj(SdrModel& rSdrModel)
:   SdrTextObj(rSdrModel)
{
    init( 1, 1 );
}

SdrTableObj::SdrTableObj(
    SdrModel& rSdrModel,
    const ::tools::Rectangle& rNewRect,
    sal_Int32 nColumns,
    sal_Int32 nRows)
:   SdrTextObj(rSdrModel, rNewRect)
    ,maLogicRect(rNewRect)
{
    if( nColumns <= 0 )
        nColumns = 1;

    if( nRows <= 0 )
        nRows = 1;

    init( nColumns, nRows );
}


void SdrTableObj::init( sal_Int32 nColumns, sal_Int32 nRows )
{
    bClosedObj = true;

    mpImpl = new SdrTableObjImpl;
    mpImpl->init( this, nColumns, nRows );

    // Stuff done from old SetModel:
    if( !maLogicRect.IsEmpty() )
    {
        maRect = maLogicRect;
        mpImpl->LayoutTable( maRect, false, false );
    }
}


SdrTableObj::~SdrTableObj()
{
    mpImpl->dispose();
}


// table stuff


Reference< XTable > SdrTableObj::getTable() const
{
    return Reference< XTable >( mpImpl->mxTable.get() );
}


bool SdrTableObj::isValid( const CellPos& rPos ) const
{
    return (rPos.mnCol >= 0) && (rPos.mnCol < mpImpl->getColumnCount()) && (rPos.mnRow >= 0) && (rPos.mnRow < mpImpl->getRowCount());
}


CellPos SdrTableObj::getFirstCell()
{
    return CellPos( 0,0 );
}


CellPos SdrTableObj::getLastCell() const
{
    CellPos aPos;
    if( mpImpl->mxTable.is() )
    {
        aPos.mnCol = mpImpl->getColumnCount()-1;
        aPos.mnRow = mpImpl->getRowCount()-1;
    }
    return aPos;
}


CellPos SdrTableObj::getLeftCell( const CellPos& rPos, bool bEdgeTravel ) const
{
    switch( GetWritingMode() )
    {
    default:
    case WritingMode_LR_TB:
        return getPreviousCell( rPos, bEdgeTravel );
    case WritingMode_RL_TB:
        return getNextCell( rPos, bEdgeTravel );
    case WritingMode_TB_RL:
        return getPreviousRow( rPos, bEdgeTravel );
    }
}


CellPos SdrTableObj::getRightCell( const CellPos& rPos, bool bEdgeTravel  ) const
{
    switch( GetWritingMode() )
    {
    default:
    case WritingMode_LR_TB:
        return getNextCell( rPos, bEdgeTravel );
    case WritingMode_RL_TB:
        return getPreviousCell( rPos, bEdgeTravel );
    case WritingMode_TB_RL:
        return getNextRow( rPos, bEdgeTravel );
    }
}


CellPos SdrTableObj::getUpCell( const CellPos& rPos, bool bEdgeTravel ) const
{
    switch( GetWritingMode() )
    {
    default:
    case WritingMode_LR_TB:
    case WritingMode_RL_TB:
        return getPreviousRow( rPos, bEdgeTravel );
    case WritingMode_TB_RL:
        return getPreviousCell( rPos, bEdgeTravel );
    }
}


CellPos SdrTableObj::getDownCell( const CellPos& rPos, bool bEdgeTravel ) const
{
    switch( GetWritingMode() )
    {
    default:
    case WritingMode_LR_TB:
    case WritingMode_RL_TB:
        return getNextRow( rPos, bEdgeTravel );
    case WritingMode_TB_RL:
        return getNextCell( rPos, bEdgeTravel );
    }
}


CellPos SdrTableObj::getPreviousCell( const CellPos& rPos, bool bEdgeTravel ) const
{
    CellPos aPos( rPos );
    if( mpImpl.is() )
    {
        CellRef xCell( mpImpl->getCell( aPos ) );
        if( xCell.is() && xCell->isMerged() )
        {
            sal_Int32 nTemp = 0;
            findMergeOrigin( mpImpl->mxTable.get(), aPos.mnCol, aPos.mnRow, aPos.mnCol, nTemp );
        }

        if( aPos.mnCol > 0 )
        {
            --aPos.mnCol;
        }

        else if( bEdgeTravel && (aPos.mnRow > 0) )
        {
            aPos.mnCol = mpImpl->mxTable->getColumnCount()-1;
            --aPos.mnRow;
        }
    }
    return aPos;
}


CellPos SdrTableObj::getNextCell( const CellPos& rPos, bool bEdgeTravel ) const
{
    CellPos aPos( rPos );
    if( mpImpl.is() )
    {
        CellRef xCell( mpImpl->getCell( aPos ) );
        if( xCell.is() )
        {
            if( xCell->isMerged() )
            {
                findMergeOrigin( mpImpl->mxTable, aPos.mnCol, aPos.mnRow, aPos.mnCol, aPos.mnRow );

                xCell = mpImpl->getCell(aPos);

                if( xCell.is() )
                {
                    aPos.mnCol += xCell->getColumnSpan();
                    aPos.mnRow = rPos.mnRow;
                }
            }
            else
            {
                aPos.mnCol += xCell->getColumnSpan();
            }

            if( aPos.mnCol < mpImpl->mxTable->getColumnCount() )
                return aPos;

            if( bEdgeTravel && ((aPos.mnRow + 1) < mpImpl->getRowCount()) )
            {
                aPos.mnCol = 0;
                aPos.mnRow += 1;
                return aPos;
            }
        }
    }

    // last cell reached, no traveling possible
    return rPos;
}


CellPos SdrTableObj::getPreviousRow( const CellPos& rPos, bool bEdgeTravel ) const
{
    CellPos aPos( rPos );
    if( mpImpl.is() )
    {
        CellRef xCell( mpImpl->getCell( aPos ) );
        if( xCell.is() )
        {
            if( xCell->isMerged() )
            {
                sal_Int32 nTemp = 0;
                findMergeOrigin( mpImpl->mxTable, aPos.mnCol, aPos.mnRow, nTemp, aPos.mnRow );
            }
        }

        if( aPos.mnRow > 0 )
        {
            --aPos.mnRow;
        }
        else if( bEdgeTravel && (aPos.mnCol > 0) )
        {
            aPos.mnRow = mpImpl->mxTable->getRowCount()-1;
            --aPos.mnCol;
        }
    }
    return aPos;
}


CellPos SdrTableObj::getNextRow( const CellPos& rPos, bool bEdgeTravel ) const
{
    CellPos aPos( rPos );

    if( mpImpl.is() )
    {
        CellRef xCell( mpImpl->getCell( rPos ) );
        if( xCell.is() )
        {
            if( xCell->isMerged() )
            {
                findMergeOrigin( mpImpl->mxTable, aPos.mnCol, aPos.mnRow, aPos.mnCol, aPos.mnRow );
                xCell = mpImpl->getCell(aPos);
                aPos.mnCol = rPos.mnCol;
            }

            if( xCell.is() )
                aPos.mnRow += xCell->getRowSpan();

            if( aPos.mnRow < mpImpl->mxTable->getRowCount() )
                return aPos;

            if( bEdgeTravel && (aPos.mnCol + 1) < mpImpl->mxTable->getColumnCount() )
            {
                aPos.mnRow = 0;
                aPos.mnCol += 1;

                while( aPos.mnCol < mpImpl->mxTable->getColumnCount() )
                {
                    xCell = mpImpl->getCell( aPos );
                    if( xCell.is() && !xCell->isMerged() )
                        return aPos;
                    aPos.mnCol += 1;
                }
            }
        }
    }

    // last position reached, no more traveling possible
    return rPos;
}


const TableStyleSettings& SdrTableObj::getTableStyleSettings() const
{
    if( mpImpl.is())
    {
        return mpImpl->maTableStyle;
    }
    else
    {
        static TableStyleSettings aTmp;
        return aTmp;
    }
}


void SdrTableObj::setTableStyleSettings( const TableStyleSettings& rStyle )
{
    if( mpImpl.is() )
    {
        mpImpl->maTableStyle = rStyle;
        mpImpl->update();
    }
}


TableHitKind SdrTableObj::CheckTableHit( const Point& rPos, sal_Int32& rnX, sal_Int32& rnY, const sal_uInt16 aTol ) const
{
    if( !mpImpl.is() || !mpImpl->mxTable.is() )
        return TableHitKind::NONE;

    rnX = 0;
    rnY = 0;

    const sal_Int32 nColCount = mpImpl->getColumnCount();
    const sal_Int32 nRowCount = mpImpl->getRowCount();

    sal_Int32 nX = rPos.X() - maRect.Left();
    sal_Int32 nY = rPos.Y() - maRect.Top();

    if( (nX < 0) || (nX > maRect.GetWidth()) || (nY < 0) || (nY > maRect.GetHeight() ) )
        return TableHitKind::NONE;

    // get vertical edge number and check for a hit
    const bool bRTL = (GetWritingMode() == WritingMode_RL_TB);
    bool bVrtHit = false;
    if( nX >= 0 )
    {
        if( !bRTL )
        {
            while( rnX <= nColCount )
            {
                if( nX - aTol <= 0 )
                {
                    bVrtHit = true;
                    break;
                }

                if( rnX == nColCount )
                    break;

                nX -= mpImpl->mpLayouter->getColumnWidth( rnX );
                if( nX < 0 )
                    break;
                rnX++;
            }
        }
        else
        {
            rnX = nColCount;
            while( rnX >= 0 )
            {
                if( nX - aTol <= 0 )
                {
                    bVrtHit = true;
                    break;
                }

                if( rnX == 0 )
                    break;

                rnX--;
                nX -= mpImpl->mpLayouter->getColumnWidth( rnX );
                if( nX < 0 )
                    break;
            }
        }
    }

    // rnX is now the edge number left to the pointer, if it was hit bHrzHit is also true

    // get vertical edge number and check for a hit
    bool bHrzHit = false;
    if( nY >= 0 )
    {
        while( rnY <= nRowCount )
        {
            if( nY - aTol <= 0 )
            {
                bHrzHit = true;
                break;
            }

            if( rnY == nRowCount )
                break;

            nY -= mpImpl->mpLayouter->getRowHeight(rnY);
            if( nY < 0 )
                break;
            rnY++;
        }
    }

    // rnY is now the edge number above the pointer, if it was hit bVrtHit is also true

    if( bVrtHit && mpImpl->mpLayouter->isEdgeVisible( rnX, rnY, false ) )
        return TableHitKind::VerticallBorder;

    if( bHrzHit && mpImpl->mpLayouter->isEdgeVisible( rnX, rnY, true ) )
        return TableHitKind::HorizontalBorder;

    CellRef xCell( mpImpl->getCell( CellPos( rnX, rnY ) ) );
    if( xCell.is() && xCell->isMerged() )
        findMergeOrigin( mpImpl->mxTable.get(), rnX, rnY, rnX, rnY );

    if( xCell.is() )
    {
        nX += mpImpl->mpLayouter->getColumnWidth( rnX );
        //Fix for fdo#62673 : non-editable cell in table on cell merge
        sal_Int32 i=0;
        while(xCell.is() && xCell->isMerged())
        {
            nX += mpImpl->mpLayouter->getColumnWidth( rnX+i );
            i++;
            if(rnX+i < nColCount)
                xCell=mpImpl->getCell( CellPos( rnX+i, rnY) );
            else
                break;
        }

        if( nX < xCell->GetTextLeftDistance() )
            return TableHitKind::Cell;
    }

    return TableHitKind::CellTextArea;
}

const SfxItemSet& SdrTableObj::GetActiveCellItemSet() const
{
    return getActiveCell()->GetItemSet();
}

void SdrTableObj::setTableStyle( const Reference< XIndexAccess >& xTableStyle )
{
    if( mpImpl.is() && (mpImpl->mxTableStyle != xTableStyle) )
    {
        mpImpl->disconnectTableStyle();
        mpImpl->mxTableStyle = xTableStyle;
        mpImpl->connectTableStyle();
        mpImpl->update();
    }
}


const Reference< XIndexAccess >& SdrTableObj::getTableStyle() const
{
    if( mpImpl.is() )
    {
        return mpImpl->mxTableStyle;
    }
    else
    {
        static Reference< XIndexAccess > aTmp;
        return aTmp;
    }
}


// text stuff


/** returns the currently active text. */
SdrText* SdrTableObj::getActiveText() const
{
    return dynamic_cast< SdrText* >( getActiveCell().get() );
}


/** returns the nth available text. */
SdrText* SdrTableObj::getText( sal_Int32 nIndex ) const
{
    if( mpImpl->mxTable.is() )
    {
        const sal_Int32 nColCount = mpImpl->getColumnCount();
        if( nColCount )
        {
            CellPos aPos( nIndex % nColCount, nIndex / nColCount );

            CellRef xCell( mpImpl->getCell( aPos ) );
            return dynamic_cast< SdrText* >( xCell.get() );
        }
    }
    return nullptr;
}


/** returns the number of texts available for this object. */
sal_Int32 SdrTableObj::getTextCount() const
{
    if( mpImpl->mxTable.is() )
    {
        const sal_Int32 nColCount = mpImpl->getColumnCount();
        const sal_Int32 nRowCount = mpImpl->getRowCount();

        return nColCount * nRowCount;
    }
    else
    {
        return 0;
    }
}


/** changes the current active text */
void SdrTableObj::setActiveText( sal_Int32 nIndex )
{
    if( mpImpl.is() && mpImpl->mxTable.is() )
    {
        const sal_Int32 nColCount = mpImpl->mxTable->getColumnCount();
        if( nColCount )
        {
            CellPos aPos( nIndex % nColCount, nIndex / nColCount );
            if( isValid( aPos ) )
                setActiveCell( aPos );
        }
    }
}


/** returns the index of the text that contains the given point or -1 */
sal_Int32 SdrTableObj::CheckTextHit(const Point& rPnt) const
{
    if( mpImpl.is() && mpImpl->mxTable.is() )
    {
        CellPos aPos;
        if( CheckTableHit( rPnt, aPos.mnCol, aPos.mnRow ) == TableHitKind::CellTextArea )
            return aPos.mnRow * mpImpl->mxTable->getColumnCount() + aPos.mnCol;
    }

    return 0;
}

SdrOutliner* SdrTableObj::GetCellTextEditOutliner( const Cell& rCell ) const
{
    if( mpImpl.is() && (mpImpl->getCell( mpImpl->maEditPos ).get() == &rCell) )
        return pEdtOutl;
    else
        return nullptr;
}

const TableLayouter& SdrTableObj::getTableLayouter() const
{
    assert(mpImpl.is() && mpImpl->mpLayouter && "getTableLayouter() error: no mpImpl or mpLayouter (!)");
    return *(mpImpl->mpLayouter);
}

bool SdrTableObj::IsAutoGrowHeight() const
{
    return true;
}

bool SdrTableObj::IsAutoGrowWidth() const
{
    return true;
}

bool SdrTableObj::HasText() const
{
    return true;
}

bool SdrTableObj::IsTextEditActive( const CellPos& rPos )
{
    return pEdtOutl && mpImpl.is() && (rPos == mpImpl->maEditPos);
}


void SdrTableObj::onEditOutlinerStatusEvent( EditStatus* pEditStatus )
{
    if( (pEditStatus->GetStatusWord() & EditStatusFlags::TextHeightChanged) && mpImpl.is() && mpImpl->mpLayouter )
    {
        tools::Rectangle aRect0( maRect );
        maRect = maLogicRect;
        mpImpl->LayoutTable( maRect, false, false );
        SetRectsDirty();
        ActionChanged();
        BroadcastObjectChange();
        if (aRect0 != maRect)
            SendUserCall(SdrUserCallType::Resize,aRect0);
    }
}


void SdrTableObj::TakeObjInfo(SdrObjTransformInfoRec& rInfo) const
{
    rInfo.bResizeFreeAllowed=true;
    rInfo.bResizePropAllowed=true;
    rInfo.bRotateFreeAllowed=false;
    rInfo.bRotate90Allowed  =false;
    rInfo.bMirrorFreeAllowed=false;
    rInfo.bMirror45Allowed  =false;
    rInfo.bMirror90Allowed  =false;

    // allow transparence
    rInfo.bTransparenceAllowed = true;

    rInfo.bShearAllowed     =false;
    rInfo.bEdgeRadiusAllowed=false;
    rInfo.bCanConvToPath    =false;
    rInfo.bCanConvToPoly    =false;
    rInfo.bCanConvToPathLineToArea=false;
    rInfo.bCanConvToPolyLineToArea=false;
    rInfo.bCanConvToContour = false;
}


sal_uInt16 SdrTableObj::GetObjIdentifier() const
{
    return static_cast<sal_uInt16>(OBJ_TABLE);
}

void SdrTableObj::TakeTextRect( SdrOutliner& rOutliner, tools::Rectangle& rTextRect, bool bNoEditText, tools::Rectangle* pAnchorRect, bool /*bLineWidth*/ ) const
{
    if( mpImpl.is() )
        TakeTextRect( mpImpl->maEditPos, rOutliner, rTextRect, bNoEditText, pAnchorRect );
}


void SdrTableObj::TakeTextRect( const CellPos& rPos, SdrOutliner& rOutliner, tools::Rectangle& rTextRect, bool bNoEditText, tools::Rectangle* pAnchorRect ) const
{
    if( !mpImpl.is())
        return;

    CellRef xCell( mpImpl->getCell( rPos ) );
    if( !xCell.is() )
        return;

    tools::Rectangle aAnkRect;
    TakeTextAnchorRect( rPos, aAnkRect );

    SdrTextVertAdjust eVAdj=xCell->GetTextVerticalAdjust();

    EEControlBits nStat0=rOutliner.GetControlWord();
    nStat0 |= EEControlBits::AUTOPAGESIZE;
    rOutliner.SetControlWord(nStat0);
    rOutliner.SetMinAutoPaperSize(Size());
    rOutliner.SetMaxAutoPaperSize(aAnkRect.GetSize());
    rOutliner.SetPaperSize(aAnkRect.GetSize());

    // #103516# New try with _BLOCK for hor and ver after completely
    // supporting full width for vertical text.
//  if( SDRTEXTHORZADJUST_BLOCK == eHAdj && !IsVerticalWriting())
//  {
        rOutliner.SetMinAutoPaperSize(Size(aAnkRect.GetWidth(), 0));
//  }
//  else if(SDRTEXTVERTADJUST_BLOCK == eVAdj && IsVerticalWriting())
//  {
//      rOutliner.SetMinAutoPaperSize(Size(0, aAnkRect.GetHeight()));
//  }


    // set text at outliner, maybe from edit outliner
    OutlinerParaObject* pPara= xCell->GetOutlinerParaObject();
    if (pEdtOutl && !bNoEditText && mpImpl->mxActiveCell == xCell )
        pPara=pEdtOutl->CreateParaObject().release();

    if (pPara)
    {
        const bool bHitTest(&getSdrModelFromSdrObject().GetHitTestOutliner() == &rOutliner);
        const SdrTextObj* pTestObj(rOutliner.GetTextObj());

        if( !pTestObj || !bHitTest || (pTestObj != this) || (pTestObj->GetOutlinerParaObject() != xCell->GetOutlinerParaObject()) )
        {
            if( bHitTest ) // #i33696# take back fix #i27510#
                rOutliner.SetTextObj( this );

            rOutliner.SetUpdateMode(true);
            rOutliner.SetText(*pPara);
        }
    }
    else
    {
        rOutliner.SetTextObj( nullptr );
    }

    if (pEdtOutl && !bNoEditText && pPara && mpImpl->mxActiveCell == xCell )
        delete pPara;

    rOutliner.SetUpdateMode(true);
    rOutliner.SetControlWord(nStat0);

    Point aTextPos(aAnkRect.TopLeft());
    Size aTextSiz(rOutliner.GetPaperSize());
    if (eVAdj==SDRTEXTVERTADJUST_CENTER || eVAdj==SDRTEXTVERTADJUST_BOTTOM)
    {
        long nFreeHgt=aAnkRect.GetHeight()-aTextSiz.Height();
        if (eVAdj==SDRTEXTVERTADJUST_CENTER)
            aTextPos.AdjustY(nFreeHgt/2 );
        if (eVAdj==SDRTEXTVERTADJUST_BOTTOM)
            aTextPos.AdjustY(nFreeHgt );
    }

    if (pAnchorRect)
        *pAnchorRect=aAnkRect;

    rTextRect=tools::Rectangle(aTextPos,aTextSiz);
}


const CellRef& SdrTableObj::getActiveCell() const
{
    if( mpImpl.is() )
    {
        if( !mpImpl->mxActiveCell.is() )
        {
            CellPos aPos;
            const_cast< SdrTableObj* >(this)->setActiveCell( aPos );
        }
        return mpImpl->mxActiveCell;
    }
    else
    {
        static CellRef xCell;
        return xCell;
    }
}


sal_Int32 SdrTableObj::getColumnCount() const
{
    return mpImpl.is() ? mpImpl->getColumnCount() : 0;
}


void SdrTableObj::setActiveCell( const CellPos& rPos )
{
    if( mpImpl.is() && mpImpl->mxTable.is() ) try
    {
        mpImpl->mxActiveCell.set( dynamic_cast< Cell* >( mpImpl->mxTable->getCellByPosition( rPos.mnCol, rPos.mnRow ).get() ) );
        if( mpImpl->mxActiveCell.is() && mpImpl->mxActiveCell->isMerged() )
        {
            CellPos aOrigin;
            findMergeOrigin( mpImpl->mxTable.get(), rPos.mnCol, rPos.mnRow, aOrigin.mnCol, aOrigin.mnRow );
            mpImpl->mxActiveCell.set( dynamic_cast< Cell* >( mpImpl->mxTable->getCellByPosition( aOrigin.mnCol, aOrigin.mnRow ).get() ) );
            mpImpl->maEditPos = aOrigin;
        }
        else
        {
            mpImpl->maEditPos = rPos;
        }
    }
    catch( Exception& )
    {
        OSL_FAIL("SdrTableObj::setActiveCell(), exception caught!");
    }
}


void SdrTableObj::getActiveCellPos( CellPos& rPos ) const
{
    rPos = mpImpl->maEditPos;
}


void SdrTableObj::getCellBounds( const CellPos& rPos, ::tools::Rectangle& rCellRect )
{
    if( mpImpl.is() )
    {
        CellRef xCell( mpImpl->getCell( rPos ) );
        if( xCell.is() )
            rCellRect = xCell->getCellRect();
    }
}


void SdrTableObj::TakeTextAnchorRect(tools::Rectangle& rAnchorRect) const
{
    if( mpImpl.is() )
        TakeTextAnchorRect( mpImpl->maEditPos, rAnchorRect );
}


void SdrTableObj::TakeTextAnchorRect( const CellPos& rPos, tools::Rectangle& rAnchorRect ) const
{
    tools::Rectangle aAnkRect(maRect);

    if( mpImpl.is() )
    {
        CellRef xCell( mpImpl->getCell( rPos ) );
        if( xCell.is() )
            xCell->TakeTextAnchorRect( aAnkRect );
    }

    ImpJustifyRect(aAnkRect);
    rAnchorRect=aAnkRect;
}


void SdrTableObj::TakeTextEditArea(Size* pPaperMin, Size* pPaperMax, tools::Rectangle* pViewInit, tools::Rectangle* pViewMin) const
{
    if( mpImpl.is() )
        TakeTextEditArea( mpImpl->maEditPos, pPaperMin, pPaperMax, pViewInit, pViewMin );
}


void SdrTableObj::TakeTextEditArea( const CellPos& rPos, Size* pPaperMin, Size* pPaperMax, tools::Rectangle* pViewInit, tools::Rectangle* pViewMin ) const
{
    Size aPaperMin,aPaperMax;
    tools::Rectangle aViewInit;
    TakeTextAnchorRect( rPos, aViewInit );

    Size aAnkSiz(aViewInit.GetSize());
    aAnkSiz.AdjustWidth( -1 ); aAnkSiz.AdjustHeight( -1 ); // because GetSize() increments by one

    Size aMaxSiz(aAnkSiz.Width(),1000000);
    Size aTmpSiz(getSdrModelFromSdrObject().GetMaxObjSize());
    if (aTmpSiz.Height()!=0)
        aMaxSiz.setHeight(aTmpSiz.Height() );

    CellRef xCell( mpImpl->getCell( rPos ) );
    SdrTextVertAdjust eVAdj = xCell.is() ? xCell->GetTextVerticalAdjust() : SDRTEXTVERTADJUST_TOP;

    aPaperMax=aMaxSiz;

        aPaperMin.setWidth( aAnkSiz.Width() );

    if (pViewMin!=nullptr)
    {
        *pViewMin=aViewInit;
        long nYFree=aAnkSiz.Height()-aPaperMin.Height();

        if (eVAdj==SDRTEXTVERTADJUST_TOP)
        {
            pViewMin->AdjustBottom( -nYFree );
        }
        else if (eVAdj==SDRTEXTVERTADJUST_BOTTOM)
        {
            pViewMin->AdjustTop(nYFree );
        }
        else
        {
            pViewMin->AdjustTop(nYFree/2 );
            pViewMin->SetBottom(pViewMin->Top()+aPaperMin.Height() );
        }
    }


    if(IsVerticalWriting())
        aPaperMin.setWidth( 0 );
    else
        aPaperMin.setHeight( 0 );

    if (pPaperMin!=nullptr) *pPaperMin=aPaperMin;
    if (pPaperMax!=nullptr) *pPaperMax=aPaperMax;
    if (pViewInit!=nullptr) *pViewInit=aViewInit;
}


EEAnchorMode SdrTableObj::GetOutlinerViewAnchorMode() const
{
    EEAnchorMode eRet=EEAnchorMode::TopLeft;
    CellRef xCell( getActiveCell() );
    if( xCell.is() )
    {
        SdrTextVertAdjust eV=xCell->GetTextVerticalAdjust();

        {
            if (eV==SDRTEXTVERTADJUST_TOP)
            {
                eRet=EEAnchorMode::TopLeft;
            }
            else if (eV==SDRTEXTVERTADJUST_BOTTOM)
            {
                eRet=EEAnchorMode::BottomLeft;
            }
            else
            {
                eRet=EEAnchorMode::VCenterLeft;
            }
        }
    }
    return eRet;
}


OUString SdrTableObj::TakeObjNameSingul() const
{
    OUStringBuffer sName(SvxResId(STR_ObjNameSingulTable));

    OUString aName(GetName());
    if (!aName.isEmpty())
    {
        sName.append(' ');
        sName.append('\'');
        sName.append(aName);
        sName.append('\'');
    }

    return sName.makeStringAndClear();
}


OUString SdrTableObj::TakeObjNamePlural() const
{
    return SvxResId(STR_ObjNamePluralTable);
}


SdrTableObj* SdrTableObj::CloneSdrObject(SdrModel& rTargetModel) const
{
    return CloneHelper< SdrTableObj >(rTargetModel);
}

SdrTableObj& SdrTableObj::operator=(const SdrTableObj& rObj)
{
    if( this == &rObj )
    {
        return *this;
    }

    // call parent
    // before SdrObject::operator= was called which is wrong from
    // the derivation hierarchy and may leave quite some entries
    // uninitialized. Changed to SdrTextObj::operator=, but had to adapt
    // usage of pNewOutlinerParaObject/mpText there due to nullptr access
    SdrTextObj::operator=(rObj);

    TableModelNotifyGuard aGuard( mpImpl.is() ? mpImpl->mxTable.get() : nullptr );

    maLogicRect = rObj.maLogicRect;
    maRect = rObj.maRect;
    aGeo = rObj.aGeo;
    eTextKind = rObj.eTextKind;
    bTextFrame = rObj.bTextFrame;
    aTextSize = rObj.aTextSize;
    bTextSizeDirty = rObj.bTextSizeDirty;
    bNoShear = rObj.bNoShear;
    bDisableAutoWidthOnDragging = rObj.bDisableAutoWidthOnDragging;

    // use SdrTableObjImpl::operator= now to
    // copy model data and other stuff (see there)
    *mpImpl = *rObj.mpImpl;

    return *this;
}


const tools::Rectangle& SdrTableObj::GetSnapRect() const
{
    return maRect;
}


void SdrTableObj::NbcSetSnapRect(const tools::Rectangle& rRect)
{
    NbcSetLogicRect( rRect );
}


const tools::Rectangle& SdrTableObj::GetLogicRect() const
{
    return maLogicRect;
}


void SdrTableObj::RecalcSnapRect()
{
}


bool SdrTableObj::BegTextEdit(SdrOutliner& rOutl)
{
    if( pEdtOutl != nullptr )
        return false;

    pEdtOutl=&rOutl;

    mbInEditMode = true;

    rOutl.Init( OutlinerMode::TextObject );
    rOutl.SetRefDevice(getSdrModelFromSdrObject().GetRefDevice());

    bool bUpdMerk=rOutl.GetUpdateMode();
    if (bUpdMerk) rOutl.SetUpdateMode(false);
    Size aPaperMin;
    Size aPaperMax;
    tools::Rectangle aEditArea;
    TakeTextEditArea(&aPaperMin,&aPaperMax,&aEditArea,nullptr);

    rOutl.SetMinAutoPaperSize(aPaperMin);
    rOutl.SetMaxAutoPaperSize(aPaperMax);
    rOutl.SetPaperSize(aPaperMax);

    if (bUpdMerk) rOutl.SetUpdateMode(true);

    EEControlBits nStat=rOutl.GetControlWord();
    nStat   |= EEControlBits::AUTOPAGESIZE;
    nStat   &=~EEControlBits::STRETCHING;
    rOutl.SetControlWord(nStat);

    OutlinerParaObject* pPara = GetOutlinerParaObject();
    if(pPara)
        rOutl.SetText(*pPara);

    rOutl.UpdateFields();
    rOutl.ClearModifyFlag();

    return true;
}


void SdrTableObj::EndTextEdit(SdrOutliner& rOutl)
{

    if (getSdrModelFromSdrObject().IsUndoEnabled() && !mpImpl->maUndos.empty())
    {
        // These actions should be on the undo stack after text edit.
        for (std::unique_ptr<SdrUndoAction>& pAction : mpImpl->maUndos)
            getSdrModelFromSdrObject().AddUndo(pAction.release());
        mpImpl->maUndos.clear();

        getSdrModelFromSdrObject().AddUndo(getSdrModelFromSdrObject().GetSdrUndoFactory().CreateUndoGeoObject(*this));
    }

    if(rOutl.IsModified())
    {
        std::unique_ptr<OutlinerParaObject> pNewText;
        Paragraph* p1stPara = rOutl.GetParagraph( 0 );
        sal_Int32 nParaCnt = rOutl.GetParagraphCount();

        if(p1stPara)
        {
            // to remove the grey field background
            rOutl.UpdateFields();

            // create new text object
            pNewText = rOutl.CreateParaObject( 0, nParaCnt );
        }
        SetOutlinerParaObject(std::move(pNewText));
    }

    pEdtOutl = nullptr;
    rOutl.Clear();
    EEControlBits nStat = rOutl.GetControlWord();
    nStat &= ~EEControlBits::AUTOPAGESIZE;
    rOutl.SetControlWord(nStat);

    mbInEditMode = false;
}


OutlinerParaObject* SdrTableObj::GetOutlinerParaObject() const
{
    CellRef xCell( getActiveCell() );
    if( xCell.is() )
        return xCell->GetOutlinerParaObject();
    else
        return nullptr;
}


void SdrTableObj::NbcSetOutlinerParaObject( std::unique_ptr<OutlinerParaObject> pTextObject)
{
    CellRef xCell( getActiveCell() );
    if( xCell.is() )
    {
        // Update HitTestOutliner
        const SdrTextObj* pTestObj(getSdrModelFromSdrObject().GetHitTestOutliner().GetTextObj());

        if(pTestObj && pTestObj->GetOutlinerParaObject() == xCell->GetOutlinerParaObject())
        {
            getSdrModelFromSdrObject().GetHitTestOutliner().SetTextObj(nullptr);
        }

        xCell->SetOutlinerParaObject( std::move(pTextObject) );
        SetTextSizeDirty();
        NbcAdjustTextFrameWidthAndHeight();
    }
}


void SdrTableObj::NbcSetLogicRect(const tools::Rectangle& rRect)
{
    maLogicRect=rRect;
    ImpJustifyRect(maLogicRect);
    const bool bWidth = maLogicRect.getWidth() != maRect.getWidth();
    const bool bHeight = maLogicRect.getHeight() != maRect.getHeight();
    maRect = maLogicRect;
    if (mpImpl->mbSkipChangeLayout)
        // Avoid distributing newly available space between existing cells.
        NbcAdjustTextFrameWidthAndHeight();
    else
        NbcAdjustTextFrameWidthAndHeight(!bHeight, !bWidth);
    SetRectsDirty();
}


void SdrTableObj::AdjustToMaxRect( const tools::Rectangle& rMaxRect, bool /* bShrinkOnly = false */ )
{
    tools::Rectangle aAdjustRect( rMaxRect );
    aAdjustRect.setHeight( GetLogicRect().getHeight() );
    SetLogicRect( aAdjustRect );
}


void SdrTableObj::NbcMove(const Size& rSiz)
{
    maLogicRect.Move(rSiz);
    SdrTextObj::NbcMove( rSiz );
    if( mpImpl.is() )
        mpImpl->UpdateCells( maRect );
}


void SdrTableObj::NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact)
{
    tools::Rectangle aOldRect( maLogicRect );
    ResizeRect(maLogicRect,rRef,xFact,yFact);

    maRect = maLogicRect;
    NbcAdjustTextFrameWidthAndHeight( maLogicRect.GetHeight() == aOldRect.GetHeight(), maLogicRect.GetWidth() == aOldRect.GetWidth() );
    SetRectsDirty();
}


bool SdrTableObj::AdjustTextFrameWidthAndHeight()
{
    tools::Rectangle aNewRect(maLogicRect);
    bool bRet=AdjustTextFrameWidthAndHeight(aNewRect);
    if (bRet)
    {
        tools::Rectangle aBoundRect0;
        if (pUserCall!=nullptr)
            aBoundRect0=GetLastBoundRect();
        maRect = aNewRect;
        SetRectsDirty();
        SetChanged();
        BroadcastObjectChange();
        SendUserCall(SdrUserCallType::Resize,aBoundRect0);
    }
    return bRet;
}


bool SdrTableObj::AdjustTextFrameWidthAndHeight(tools::Rectangle& rR, bool bHeight, bool bWidth) const
{
    if(rR.IsEmpty() || !mpImpl.is() || !mpImpl->mxTable.is())
        return false;

    tools::Rectangle aRectangle( rR );
    mpImpl->LayoutTable( aRectangle, !bWidth, !bHeight );

    if( aRectangle != rR )
    {
        rR = aRectangle;
        return true;
    }
    else
    {
        return false;
    }
}


void SdrTableObj::NbcReformatText()
{
    NbcAdjustTextFrameWidthAndHeight();
}


void SdrTableObj::ReformatText()
{
    tools::Rectangle aBoundRect0;
    if (pUserCall!=nullptr)
        aBoundRect0=GetLastBoundRect();
    NbcReformatText();
    SetChanged();
    BroadcastObjectChange();
    SendUserCall(SdrUserCallType::Resize,aBoundRect0);
}


bool SdrTableObj::IsVerticalWriting() const
{
    const SvxWritingModeItem* pModeItem = &GetObjectItem( SDRATTR_TEXTDIRECTION );
    return pModeItem && pModeItem->GetValue() == css::text::WritingMode_TB_RL;
}


void SdrTableObj::SetVerticalWriting(bool bVertical)
{
    if(bVertical != IsVerticalWriting() )
    {
        SvxWritingModeItem aModeItem( css::text::WritingMode_LR_TB, SDRATTR_TEXTDIRECTION );
        SetObjectItem( aModeItem );
    }
}


WritingMode SdrTableObj::GetWritingMode() const
{
    SfxStyleSheet* pStyle = GetStyleSheet();
    if ( !pStyle )
        return WritingMode_LR_TB;

    WritingMode eWritingMode = WritingMode_LR_TB;
    const SfxItemSet &rSet = pStyle->GetItemSet();
    const SfxPoolItem *pItem;

    if ( rSet.GetItemState( SDRATTR_TEXTDIRECTION, false, &pItem ) == SfxItemState::SET )
        eWritingMode = static_cast< const SvxWritingModeItem * >( pItem )->GetValue();

    if ( ( eWritingMode != WritingMode_TB_RL ) &&
         ( rSet.GetItemState( EE_PARA_WRITINGDIR, false, &pItem ) == SfxItemState::SET ) )
    {
        if ( static_cast< const SvxFrameDirectionItem * >( pItem )->GetValue() == SvxFrameDirection::Horizontal_LR_TB )
            eWritingMode = WritingMode_LR_TB;
        else
            eWritingMode = WritingMode_RL_TB;
    }

    return eWritingMode;
}

void SdrTableObj::AddUndo(SdrUndoAction* pUndo)
{
    mpImpl->maUndos.push_back(std::unique_ptr<SdrUndoAction>(pUndo));
}

void SdrTableObj::SetSkipChangeLayout(bool bSkipChangeLayout)
{
    mpImpl->mbSkipChangeLayout = bSkipChangeLayout;
}

bool SdrTableObj::IsReallyEdited() const
{
    return pEdtOutl && pEdtOutl->IsModified();
}

bool SdrTableObj::IsFontwork() const
{
    return false;
}

sal_uInt32 SdrTableObj::GetHdlCount() const
{
    sal_uInt32 nCount = SdrTextObj::GetHdlCount();
    const sal_Int32 nRowCount = mpImpl->getRowCount();
    const sal_Int32 nColCount = mpImpl->getColumnCount();

    if( nRowCount && nColCount )
        nCount += nRowCount + nColCount + 2 + 1;

    return nCount;
}

void SdrTableObj::AddToHdlList(SdrHdlList& rHdlList) const
{
    const sal_Int32 nRowCount = mpImpl->getRowCount();
    const sal_Int32 nColCount = mpImpl->getColumnCount();

    // first add row handles
    std::vector< TableEdgeHdl* > aRowEdges( nRowCount + 1 );

    for( sal_Int32 nRow = 0; nRow <= nRowCount; nRow++ )
    {
        sal_Int32 nEdgeMin, nEdgeMax;
        const sal_Int32 nEdge = mpImpl->mpLayouter->getHorizontalEdge( nRow, &nEdgeMin, &nEdgeMax );
        nEdgeMin -= nEdge;
        nEdgeMax -= nEdge;

        Point aPoint( maRect.TopLeft() );
        aPoint.AdjustY(nEdge );

        TableEdgeHdl* pHdl= new TableEdgeHdl(aPoint,true,nEdgeMin,nEdgeMax,nColCount+1);
        pHdl->SetPointNum( nRow );
        rHdlList.AddHdl( pHdl );
        aRowEdges[nRow] = pHdl;
    }

    // second add column handles
    std::vector< TableEdgeHdl* > aColEdges( nColCount + 1 );

    for( sal_Int32 nCol = 0; nCol <= nColCount; nCol++ )
    {
        sal_Int32 nEdgeMin, nEdgeMax;
        const sal_Int32 nEdge = mpImpl->mpLayouter->getVerticalEdge( nCol, &nEdgeMin, &nEdgeMax );
        nEdgeMin -= nEdge;
        nEdgeMax -= nEdge;

        Point aPoint( maRect.TopLeft() );
        aPoint.AdjustX(nEdge );

        TableEdgeHdl* pHdl = new TableEdgeHdl(aPoint,false,nEdgeMin,nEdgeMax, nRowCount+1);
        pHdl->SetPointNum( nCol );
        rHdlList.AddHdl( pHdl );
        aColEdges[nCol] = pHdl;
    }

    // now add visible edges to row and column handles
    if( mpImpl->mpLayouter )
    {
        TableLayouter& rLayouter = *mpImpl->mpLayouter;

        sal_Int32 nY = 0;

        for( sal_Int32 nRow = 0; nRow <= nRowCount; ++nRow )
        {
            const sal_Int32 nRowHeight = (nRow == nRowCount) ? 0 : rLayouter.getRowHeight(nRow);
            sal_Int32 nX = 0;

            for( sal_Int32 nCol = 0; nCol <= nColCount; ++nCol )
            {
                const sal_Int32 nColWidth = (nCol == nColCount) ? 0 : rLayouter.getColumnWidth(nCol);

                if( nRowHeight > 0 )
                {
                    if( rLayouter.isEdgeVisible( nCol, nRow, false ) )
                        aColEdges[nCol]->SetEdge( nRow, nY, nY + nRowHeight, (rLayouter.getBorderLine( nCol, nRow, false ) == nullptr) ? Visible : Invisible);
                }

                if( nColWidth > 0 )
                {
                    if( rLayouter.isEdgeVisible( nCol, nRow, true ) )
                        aRowEdges[nRow]->SetEdge( nCol, nX, nX + nColWidth, (rLayouter.getBorderLine( nCol, nRow, true ) == nullptr) ? Visible : Invisible);
                }

                nX += nColWidth;
            }

            nY += nRowHeight;
        }
    }

    // add remaining handles
    SdrHdl* pH=nullptr;
    rHdlList.AddHdl( pH = new TableBorderHdl( maRect, !IsTextEditActive() ) ); pH->SetMoveOutside( true );
    rHdlList.AddHdl( pH = new SdrHdl(maRect.TopLeft(),SdrHdlKind::UpperLeft) ); pH->SetMoveOutside( true );
    rHdlList.AddHdl( pH = new SdrHdl(maRect.TopCenter(),SdrHdlKind::Upper) ); pH->SetMoveOutside( true );
    rHdlList.AddHdl( pH = new SdrHdl(maRect.TopRight(),SdrHdlKind::UpperRight) ); pH->SetMoveOutside( true );
    rHdlList.AddHdl( pH = new SdrHdl(maRect.LeftCenter(),SdrHdlKind::Left) ); pH->SetMoveOutside( true );
    rHdlList.AddHdl( pH = new SdrHdl(maRect.RightCenter(),SdrHdlKind::Right) ); pH->SetMoveOutside( true );
    rHdlList.AddHdl( pH = new SdrHdl(maRect.BottomLeft(),SdrHdlKind::LowerLeft) ); pH->SetMoveOutside( true );
    rHdlList.AddHdl( pH = new SdrHdl(maRect.BottomCenter(),SdrHdlKind::Lower) ); pH->SetMoveOutside( true );
    rHdlList.AddHdl( pH = new SdrHdl(maRect.BottomRight(),SdrHdlKind::LowerRight) ); pH->SetMoveOutside( true );

    const size_t nHdlCount = rHdlList.GetHdlCount();
    for( size_t nHdl = 0; nHdl < nHdlCount; ++nHdl )
        rHdlList.GetHdl(nHdl)->SetObj(const_cast<SdrTableObj*>(this));
}

// Dragging

bool SdrTableObj::hasSpecialDrag() const
{
    return true;
}

bool SdrTableObj::beginSpecialDrag(SdrDragStat& rDrag) const
{
    const SdrHdl* pHdl = rDrag.GetHdl();
    const SdrHdlKind eHdl((pHdl == nullptr) ? SdrHdlKind::Move : pHdl->GetKind());

    switch( eHdl )
    {
        case SdrHdlKind::UpperLeft:
        case SdrHdlKind::Upper:
        case SdrHdlKind::UpperRight:
        case SdrHdlKind::Left:
        case SdrHdlKind::Right:
        case SdrHdlKind::LowerLeft:
        case SdrHdlKind::Lower:
        case SdrHdlKind::LowerRight:
        case SdrHdlKind::Move:
        {
            break;
        }

        case SdrHdlKind::User:
        {
            rDrag.SetEndDragChangesAttributes(false);
            rDrag.SetNoSnap();
            break;
        }

        default:
        {
            return false;
        }
    }

    return true;
}

bool SdrTableObj::applySpecialDrag(SdrDragStat& rDrag)
{
    bool bRet(true);
    const SdrHdl* pHdl = rDrag.GetHdl();
    const SdrHdlKind eHdl((pHdl == nullptr) ? SdrHdlKind::Move : pHdl->GetKind());

    switch( eHdl )
    {
        case SdrHdlKind::UpperLeft:
        case SdrHdlKind::Upper:
        case SdrHdlKind::UpperRight:
        case SdrHdlKind::Left:
        case SdrHdlKind::Right:
        case SdrHdlKind::LowerLeft:
        case SdrHdlKind::Lower:
        case SdrHdlKind::LowerRight:
        {
            const tools::Rectangle aNewRectangle(ImpDragCalcRect(rDrag));

            if (aNewRectangle != maRect)
            {
                   NbcSetLogicRect(aNewRectangle);
            }

            break;
        }

        case SdrHdlKind::Move:
        {
               NbcMove( Size( rDrag.GetDX(), rDrag.GetDY() ) );
            break;
        }

        case SdrHdlKind::User:
        {
            rDrag.SetEndDragChangesAttributes(false);
            rDrag.SetNoSnap();
            const TableEdgeHdl* pEdgeHdl = dynamic_cast< const TableEdgeHdl* >( pHdl );

            if( pEdgeHdl )
            {
                if( IsInserted() )
                {
                    rDrag.SetEndDragChangesAttributes(true);
                    rDrag.SetEndDragChangesLayout(true);
                }

                mpImpl->DragEdge( pEdgeHdl->IsHorizontalEdge(), pEdgeHdl->GetPointNum(), pEdgeHdl->GetValidDragOffset( rDrag ) );
            }
            break;
        }

        default:
        {
            bRet = false;
        }
    }

    return bRet;
}

basegfx::B2DPolyPolygon SdrTableObj::getSpecialDragPoly(const SdrDragStat& rDrag) const
{
    basegfx::B2DPolyPolygon aRetval;
    const SdrHdl* pHdl = rDrag.GetHdl();

    if( pHdl && (SdrHdlKind::User == pHdl->GetKind()) )
    {
        const TableEdgeHdl* pEdgeHdl = dynamic_cast< const TableEdgeHdl* >( pHdl );

        if( pEdgeHdl )
        {
            aRetval = pEdgeHdl->getSpecialDragPoly( rDrag );
        }
    }

    return aRetval;
}


// Create


bool SdrTableObj::BegCreate(SdrDragStat& rStat)
{
    rStat.SetOrtho4Possible();
    tools::Rectangle aRect1(rStat.GetStart(), rStat.GetNow());
    aRect1.Justify();
    rStat.SetActionRect(aRect1);
    maRect = aRect1;
    return true;
}


bool SdrTableObj::MovCreate(SdrDragStat& rStat)
{
    tools::Rectangle aRect1;
    rStat.TakeCreateRect(aRect1);
    ImpJustifyRect(aRect1);
    rStat.SetActionRect(aRect1);
    maRect = aRect1; // for ObjName
    SetBoundRectDirty();
    bSnapRectDirty=true;
    return true;
}


bool SdrTableObj::EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd)
{
    rStat.TakeCreateRect(maRect);
    ImpJustifyRect(maRect);
    return (eCmd==SdrCreateCmd::ForceEnd || rStat.GetPointCount()>=2);
}

void SdrTableObj::BrkCreate(SdrDragStat& /*rStat*/)
{
}


bool SdrTableObj::BckCreate(SdrDragStat& /*rStat*/)
{
    return true;
}


basegfx::B2DPolyPolygon SdrTableObj::TakeCreatePoly(const SdrDragStat& rDrag) const
{
    tools::Rectangle aRect1;
    rDrag.TakeCreateRect(aRect1);
    aRect1.Justify();

    basegfx::B2DPolyPolygon aRetval;
    const basegfx::B2DRange aRange(aRect1.Left(), aRect1.Top(), aRect1.Right(), aRect1.Bottom());
    aRetval.append(basegfx::utils::createPolygonFromRect(aRange));
    return aRetval;
}


Pointer SdrTableObj::GetCreatePointer() const
{
    return Pointer(PointerStyle::Cross);
}


void SdrTableObj::createCell( CellRef& xNewCell )
{
    xNewCell = Cell::create( *this );
}


SdrObjGeoData *SdrTableObj::NewGeoData() const
{
    return new TableObjectGeoData;
}


void SdrTableObj::SaveGeoData(SdrObjGeoData& rGeo) const
{
    DBG_ASSERT( dynamic_cast< TableObjectGeoData* >( &rGeo ), "svx::SdrTableObj::SaveGeoData(), illegal geo data!" );
    SdrTextObj::SaveGeoData (rGeo);

    static_cast<TableObjectGeoData &>(rGeo).maLogicRect = maLogicRect;
}


void SdrTableObj::RestGeoData(const SdrObjGeoData& rGeo)
{
    DBG_ASSERT( dynamic_cast< const TableObjectGeoData* >( &rGeo ), "svx::SdrTableObj::SaveGeoData(), illegal geo data!" );

    maLogicRect = static_cast<const TableObjectGeoData &>(rGeo).maLogicRect;

    SdrTextObj::RestGeoData (rGeo);

    if( mpImpl.is() )
        mpImpl->LayoutTable(maRect, false, false);
    ActionChanged();
}

void SdrTableObj::CropTableModelToSelection(const CellPos& rStart, const CellPos& rEnd)
{
    if(!mpImpl.is())
    {
        return;
    }

    mpImpl->CropTableModelToSelection(rStart, rEnd);
}

void SdrTableObj::DistributeColumns( sal_Int32 nFirstColumn, sal_Int32 nLastColumn, const bool bOptimize )
{
    if( mpImpl.is() && mpImpl->mpLayouter )
    {
        TableModelNotifyGuard aGuard( mpImpl->mxTable.get() );
        mpImpl->mpLayouter->DistributeColumns( maRect, nFirstColumn, nLastColumn, bOptimize );
    }
}


void SdrTableObj::DistributeRows( sal_Int32 nFirstRow, sal_Int32 nLastRow, const bool bOptimize )
{
    if( mpImpl.is() && mpImpl->mpLayouter )
    {
        TableModelNotifyGuard aGuard( mpImpl->mxTable.get() );
        mpImpl->mpLayouter->DistributeRows( maRect, nFirstRow, nLastRow, bOptimize );
    }
}


void SdrTableObj::SetChanged()
{
    if( mpImpl.is() )
    {
        mpImpl->LayoutTable( maRect, false, false );
    }

    ::SdrTextObj::SetChanged();
}


void SdrTableObj::uno_lock()
{
    if( mpImpl.is() && mpImpl->mxTable.is() )
        mpImpl->mxTable->lockBroadcasts();
}


void SdrTableObj::uno_unlock()
{
    if( mpImpl.is() && mpImpl->mxTable.is() )
        mpImpl->mxTable->unlockBroadcasts();
}

void SdrTableObj::dumpAsXml(xmlTextWriterPtr pWriter) const
{
    xmlTextWriterStartElement(pWriter, BAD_CAST("SdrTableObj"));
    xmlTextWriterWriteFormatAttribute(pWriter, BAD_CAST("ptr"), "%p", this);

    SdrObject::dumpAsXml(pWriter);

    mpImpl->dumpAsXml(pWriter);

    xmlTextWriterEndElement(pWriter);
}

} }

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