File: CellToolBase.cpp

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

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or(at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "CellToolBase.h"
#include "CellToolBase_p.h"

// KSpread
#include "ApplicationSettings.h"
#include "AutoFillStrategy.h"
#include "CalculationSettings.h"
#include "Cell.h"
#include "CellEditor.h"
#include "CellToolOptionWidget.h"
#include "CellView.h"
#include "Damages.h"
#include "database/Database.h"
#include "database/FilterPopup.h"
#include "DragAndDropStrategy.h"
#include "ExternalEditor.h"
#include "HyperlinkStrategy.h"
#include "tests/inspector.h"
#include "LocationComboBox.h"
#include "Map.h"
#include "MergeStrategy.h"
#include "NamedAreaManager.h"
#include "PasteStrategy.h"
#include "RowFormatStorage.h"
#include "SelectionStrategy.h"
#include "Sheet.h"
#include "SheetView.h"
#include "StyleManager.h"

// commands
#include "commands/AutoFilterCommand.h"
#include "commands/BorderColorCommand.h"
#include "commands/CommentCommand.h"
#include "commands/ConditionCommand.h"
#include "commands/CopyCommand.h"
#include "commands/DataManipulators.h"
#include "commands/DeleteCommand.h"
#include "commands/IndentationCommand.h"
#include "commands/LinkCommand.h"
#include "commands/MergeCommand.h"
#include "commands/PageBreakCommand.h"
#include "commands/PasteCommand.h"
#include "commands/PrecisionCommand.h"
#include "commands/RowColumnManipulators.h"
#include "commands/SortManipulator.h"
#include "commands/SpellCheckCommand.h"
#include "commands/StyleCommand.h"
#include "commands/ValidityCommand.h"

// dialogs
#include "dialogs/AddNamedAreaDialog.h"
#include "dialogs/AngleDialog.h"
#include "dialogs/AutoFormatDialog.h"
#include "dialogs/CharacterSelectDialog.h"
#include "dialogs/CommentDialog.h"
#include "dialogs/ConditionalDialog.h"
#include "dialogs/ConsolidateDialog.h"
#include "dialogs/CSVDialog.h"
#include "dialogs/DatabaseDialog.h"
#include "dialogs/DocumentSettingsDialog.h"
#include "dialogs/GoalSeekDialog.h"
#include "dialogs/GotoDialog.h"
#include "dialogs/InsertDialog.h"
#include "dialogs/LayoutDialog.h"
#include "dialogs/LinkDialog.h"
#include "dialogs/ListDialog.h"
#include "dialogs/NamedAreaDialog.h"
#include "dialogs/PasteInsertDialog.h"
#include "dialogs/Resize2Dialog.h"
#include "dialogs/SeriesDialog.h"
#include "dialogs/ShowColRowDialog.h"
#include "dialogs/SortDialog.h"
#include "dialogs/SpecialPasteDialog.h"
#include "dialogs/StyleManagerDialog.h"
#include "dialogs/SubtotalDialog.h"
#include "dialogs/ValidityDialog.h"

// Calligra
#include <KoCanvasBase.h>
#include <KoCanvasController.h>
#include <KoColorPopupAction.h>
#include <KoOdfLoadingContext.h>
#include <KoOdfReadStore.h>
#include <KoOdfStylesReader.h>
#include <KoPointerEvent.h>
#include <KoSelection.h>
#include <KoShape.h>
#include <KoShapeManager.h>
#include <KoStore.h>
#include <KoViewConverter.h>
#include <KoXmlReader.h>
#include <KoXmlNS.h>
#include <KoColor.h>

// KDE
#include <KAction>
#include <KFind>
#include <KFontAction>
#include <KFontSizeAction>
#include <KIcon>
#include <KInputDialog>
#include <KLocale>
#include <KMessageBox>
#include <KReplace>
#include <KStandardAction>
#include <KToggleAction>

// Qt
#include <QBuffer>
#include <QHash>
#include <QMenu>
#include <QPainter>
#include <QSqlDatabase>

#ifndef NDEBUG
#include <QTableView>
#include "SheetModel.h"
#endif

using namespace Calligra::Sheets;

CellToolBase::CellToolBase(KoCanvasBase* canvas)
        : KoInteractionTool(canvas)
        , d(new Private(this))
{
    d->cellEditor = 0;
    d->formulaDialog = 0;
    d->specialCharDialog = 0;
    d->optionWidget = 0;
    d->initialized = false;
    d->popupListChoose = 0;
    d->lastEditorWithFocus = EmbeddedEditor;

    d->findOptions = 0;
    d->findLeftColumn = 0;
    d->findRightColumn = 0;
    d->findTopRow = 0;
    d->findBottomRow = 0;
    d->typeValue = FindOption::Value;
    d->directionValue = FindOption::Row;
    d->find = 0;
    d->replace = 0;
    d->replaceCommand = 0;

    d->searchInSheets.currentSheet = 0;
    d->searchInSheets.firstSheet = 0;

    // Create the extra and ones with extended names for the context menu.
    d->createPopupMenuActions();

    // Create the actions.
    KAction* action = 0;

    // -- cell style actions --

    action = new KAction(KIcon("cell_layout"), i18n("Cell Format..."), this);
    action->setIconText(i18n("Format"));
    addAction("cellStyle", action);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_F));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(cellStyle()));
    action->setToolTip(i18n("Set the cell formatting"));

    action = new KAction(i18n("Default"), this);
    addAction("setDefaultStyle", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(setDefaultStyle()));
    action->setToolTip(i18n("Resets to the default format"));

    action = new KAction(i18n("Style Manager..."), this);
    addAction("styleDialog", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(styleDialog()));
    action->setToolTip(i18n("Edit and organize cell styles"));

    action = new KSelectAction(i18n("Style"), this);
    addAction("setStyle", action);
    action->setToolTip(i18n("Apply a predefined style to the selected cells"));
    connect(action, SIGNAL(triggered(const QString&)), this, SLOT(setStyle(const QString&)));

    action = new KAction(i18n("Create Style From Cell..."), this);
    action->setIconText(i18n("Style From Cell"));
    addAction("createStyleFromCell", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(createStyleFromCell()));
    action->setToolTip(i18n("Create a new style based on the currently selected cell"));

    // -- font actions --

    action = new KToggleAction(KIcon("format-text-bold"), i18n("Bold"), this);
    addAction("bold", action);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_B));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(bold(bool)));

    action = new KToggleAction(KIcon("format-text-italic"), i18n("Italic"), this);
    addAction("italic", action);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_I));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(italic(bool)));

    action = new KToggleAction(KIcon("format-text-underline"), i18n("Underline"), this);
    addAction("underline", action);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_U));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(underline(bool)));

    action = new KToggleAction(KIcon("format-text-strikethrough"), i18n("Strike Out"), this);
    addAction("strikeOut", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(strikeOut(bool)));

    action = new KFontAction(i18n("Select Font..."), this);
    action->setIconText(i18n("Font"));
    addAction("font", action);
    connect(action, SIGNAL(triggered(const QString&)), this, SLOT(font(const QString&)));

    action = new KFontSizeAction(i18n("Select Font Size"), this);
    action->setIconText(i18n("Font Size"));
    addAction("fontSize", action);
    connect(action, SIGNAL(fontSizeChanged(int)), this, SLOT(fontSize(int)));

    action = new KAction(KIcon("format-font-size-more"), i18n("Increase Font Size"), this);
    addAction("increaseFontSize", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(increaseFontSize()));

    action = new KAction(KIcon("format-font-size-less"), i18n("Decrease Font Size"), this);
    addAction("decreaseFontSize", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(decreaseFontSize()));

    action = new KoColorPopupAction(this);
    action->setIcon(KIcon("format-text-color"));
    action->setText(i18n("Text Color"));
    action->setToolTip(i18n("Set the text color"));
    addAction("textColor", action);
    connect(action, SIGNAL(colorChanged(const KoColor &)), this, SLOT(changeTextColor(const KoColor &)));

    // -- horizontal alignment actions --

    QActionGroup* groupAlign = new QActionGroup(this);
    action = new KToggleAction(KIcon("format-justify-left"), i18n("Align Left"), this);
    action->setIconText(i18n("Left"));
    addAction("alignLeft", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(alignLeft(bool)));
    action->setToolTip(i18n("Left justify the cell contents"));
    action->setActionGroup(groupAlign);

    action = new KToggleAction(KIcon("format-justify-center"), i18n("Align Center"), this);
    action->setIconText(i18n("Center"));
    addAction("alignCenter", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(alignCenter(bool)));
    action->setToolTip(i18n("Center the cell contents"));
    action->setActionGroup(groupAlign);

    action = new KToggleAction(KIcon("format-justify-right"), i18n("Align Right"), this);
    action->setIconText(i18n("Right"));
    addAction("alignRight", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(alignRight(bool)));
    action->setToolTip(i18n("Right justify the cell contents"));
    action->setActionGroup(groupAlign);

    // -- vertical alignment actions --

    QActionGroup* groupPos = new QActionGroup(this);
    action = new KToggleAction(KIcon("text_top"), i18n("Align Top"), this);
    action->setIconText(i18n("Top"));
    addAction("alignTop", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(alignTop(bool)));
    action->setToolTip(i18n("Align cell contents along the top of the cell"));
    action->setActionGroup(groupPos);

    action = new KToggleAction(KIcon("middle"), i18n("Align Middle"), this);
    action->setIconText(i18n("Middle"));
    addAction("alignMiddle", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(alignMiddle(bool)));
    action->setToolTip(i18n("Align cell contents centered in the cell"));
    action->setActionGroup(groupPos);

    action = new KToggleAction(KIcon("text_bottom"), i18n("Align Bottom"), this);
    action->setIconText(i18n("Bottom"));
    addAction("alignBottom", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(alignBottom(bool)));
    action->setToolTip(i18n("Align cell contents along the bottom of the cell"));
    action->setActionGroup(groupPos);

    // -- border actions --

    action = new KAction(KIcon("border_left"), i18n("Border Left"), this);
    action->setIconText(i18n("Left"));
    addAction("borderLeft", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(borderLeft()));
    action->setToolTip(i18n("Set a left border to the selected area"));

    action = new KAction(KIcon("border_right"), i18n("Border Right"), this);
    action->setIconText(i18n("Right"));
    addAction("borderRight", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(borderRight()));
    action->setToolTip(i18n("Set a right border to the selected area"));

    action = new KAction(KIcon("border_top"), i18n("Border Top"), this);
    action->setIconText(i18n("Top"));
    addAction("borderTop", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(borderTop()));
    action->setToolTip(i18n("Set a top border to the selected area"));

    action = new KAction(KIcon("border_bottom"), i18n("Border Bottom"), this);
    action->setIconText(i18n("Bottom"));
    addAction("borderBottom", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(borderBottom()));
    action->setToolTip(i18n("Set a bottom border to the selected area"));

    action = new KAction(KIcon("border_all"), i18n("All Borders"), this);
    action->setIconText(i18n("All"));
    addAction("borderAll", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(borderAll()));
    action->setToolTip(i18n("Set a border around all cells in the selected area"));

    action = new KAction(KIcon("border_remove"), i18n("No Borders"), this);
    action->setIconText(i18n("None"));
    addAction("borderRemove", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(borderRemove()));
    action->setToolTip(i18n("Remove all borders in the selected area"));

    action = new KAction(KIcon(("border_outline")), i18n("Border Outline"), this);
    action->setIconText(i18n("Outline"));
    addAction("borderOutline", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(borderOutline()));
    action->setToolTip(i18n("Set a border to the outline of the selected area"));

    action = new KoColorPopupAction(this);
    action->setIcon(KIcon("format-stroke-color"));
    action->setToolTip(i18n("Select a new border color"));
    action->setText(i18n("Border Color"));
    static_cast<KoColorPopupAction*>(action)->setCurrentColor(Qt::black);
    addAction("borderColor", action);
    connect(action, SIGNAL(colorChanged(const KoColor &)), this, SLOT(borderColor(const KoColor &)));

    // -- text layout actions --

    action = new KToggleAction(KIcon("multirow"), i18n("Wrap Text"), this);
    action->setIconText(i18n("Wrap"));
    addAction("wrapText", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(wrapText(bool)));
    action->setToolTip(i18n("Make the cell text wrap onto multiple lines"));

    action = new KToggleAction(KIcon("vertical_text"), i18n("Vertical Text"), this);
    action->setIconText(i18n("Vertical"));
    addAction("verticalText", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(verticalText(bool)));
    action->setToolTip(i18n("Print cell contents vertically"));

    action = new KAction(KIcon(QApplication::isRightToLeft() ? "format-indent-less" : "format-indent-more"), i18n("Increase Indent"), this);
    addAction("increaseIndentation", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(increaseIndentation()));
    action->setToolTip(i18n("Increase the indentation"));

    action = new KAction(KIcon(QApplication::isRightToLeft() ? "format-indent-more" : "format-indent-less"), i18n("Decrease Indent"), this);
    addAction("decreaseIndentation", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(decreaseIndentation()));
    action->setToolTip(i18n("Decrease the indentation"));

    action = new KAction(i18n("Change Angle..."), this);
    action->setIconText(i18n("Angle"));
    addAction("changeAngle", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(changeAngle()));
    action->setToolTip(i18n("Change the angle that cell contents are printed"));

    // -- value format actions --

    action = new KToggleAction(KIcon("percent"), i18n("Percent Format"), this);
    action->setIconText(i18n("Percent"));
    addAction("percent", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(percent(bool)));
    action->setToolTip(i18n("Set the cell formatting to look like a percentage"));

    action = new KToggleAction(KIcon("money"), i18n("Money Format"), this);
    action->setIconText(i18n("Money"));
    addAction("currency", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(currency(bool)));
    action->setToolTip(i18n("Set the cell formatting to look like your local currency"));

    action = new KAction(KIcon("prec_plus"), i18n("Increase Precision"), this);
    addAction("increasePrecision", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(increasePrecision()));
    action->setToolTip(i18n("Increase the decimal precision shown onscreen"));

    action = new KAction(KIcon("prec_minus"), i18n("Decrease Precision"), this);
    addAction("decreasePrecision", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(decreasePrecision()));
    action->setToolTip(i18n("Decrease the decimal precision shown onscreen"));

    // -- misc style attribute actions --

    action = new KAction(KIcon("fontsizeup"), i18n("Upper Case"), this);
    action->setIconText(i18n("Upper"));
    addAction("toUpperCase", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(toUpperCase()));
    action->setToolTip(i18n("Convert all letters to upper case"));

    action = new KAction(KIcon("fontsizedown"), i18n("Lower Case"), this);
    action->setIconText(i18n("Lower"));
    addAction("toLowerCase", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(toLowerCase()));
    action->setToolTip(i18n("Convert all letters to lower case"));

    action = new KAction(KIcon("first_letter_upper"), i18n("Convert First Letter to Upper Case"), this);
    action->setIconText(i18n("First Letter Upper"));
    addAction("firstLetterToUpperCase", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(firstLetterToUpperCase()));
    action->setToolTip(i18n("Capitalize the first letter"));

    action = new KoColorPopupAction(this);
    action->setIcon(KIcon("format-fill-color"));
    action->setToolTip(i18n("Set the background color"));
    action->setText(i18n("Background Color"));
    addAction("backgroundColor", action);
    connect(action, SIGNAL(colorChanged(const KoColor &)), this, SLOT(changeBackgroundColor(const KoColor &)));

    // -- cell merging actions --

    action = new KAction(KIcon("mergecell"), i18n("Merge Cells"), this);
    addAction("mergeCells", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(mergeCells()));
    action->setToolTip(i18n("Merge the selected region"));

    action = new KAction(KIcon("mergecell-horizontal"), i18n("Merge Cells Horizontally"), this);
    action->setToolTip(i18n("Merge the selected region horizontally"));
    addAction("mergeCellsHorizontal", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(mergeCellsHorizontal()));

    action = new KAction(KIcon("mergecell-vertical"), i18n("Merge Cells Vertically"), this);
    action->setToolTip(i18n("Merge the selected region vertically"));
    addAction("mergeCellsVertical", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(mergeCellsVertical()));

    action = new KAction(KIcon("dissociatecell"), i18n("Dissociate Cells"), this);
    action->setToolTip(i18n("Unmerge the selected region"));
    addAction("dissociateCells", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(dissociateCells()));

    // -- column & row actions --

    action = new KAction(KIcon("resizecol"), i18n("Resize Column..."), this);
    addAction("resizeCol", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(resizeColumn()));
    action->setToolTip(i18n("Change the width of a column"));

    action = new KAction(KIcon("insert_table_col"), i18n("Columns"), this);
    action->setIconText(i18n("Insert Columns"));
    action->setToolTip(i18n("Inserts a new column into the spreadsheet"));
    addAction("insertColumn", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(insertColumn()));

    action = new KAction(KIcon("delete_table_col"), i18n("Columns"), this);
    action->setIconText(i18n("Remove Columns"));
    action->setToolTip(i18n("Removes a column from the spreadsheet"));
    addAction("deleteColumn", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(deleteColumn()));

    action = new KAction(KIcon("hide_table_column"), i18n("Hide Columns"), this);
    addAction("hideColumn", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(hideColumn()));
    action->setToolTip(i18n("Hide the column from this"));

    action = new KAction(KIcon("show_table_column"), i18n("Show Columns..."), this);
    addAction("showColumn", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(slotShowColumnDialog()));
    action->setToolTip(i18n("Show hidden columns"));

    action = new KAction(KIcon("adjustcol"), i18n("Equalize Column"), this);
    addAction("equalizeCol", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(equalizeColumn()));
    action->setToolTip(i18n("Resizes selected columns to be the same size"));

    action = new KAction(KIcon("show_sheet_column"), i18n("Show Columns"), this);
    addAction("showSelColumns", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(showColumn()));
    action->setToolTip(i18n("Show hidden columns in the selection"));
    action->setEnabled(false);

    action = new KAction(KIcon("resizerow"), i18n("Resize Row..."), this);
    addAction("resizeRow", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(resizeRow()));
    action->setToolTip(i18n("Change the height of a row"));

    action = new KAction(KIcon("insert_table_row"), i18n("Rows"), this);
    action->setIconText(i18n("Insert Rows"));
    action->setToolTip(i18n("Inserts a new row into the spreadsheet"));
    addAction("insertRow", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(insertRow()));

    action = new KAction(KIcon("delete_table_row"), i18n("Rows"), this);
    action->setIconText(i18n("Remove Rows"));
    action->setToolTip(i18n("Removes a row from the spreadsheet"));
    addAction("deleteRow", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(deleteRow()));

    action = new KAction(KIcon("hide_table_row"), i18n("Hide Rows"), this);
    addAction("hideRow", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(hideRow()));
    action->setToolTip(i18n("Hide a row from this"));

    action = new KAction(KIcon("show_table_row"), i18n("Show Rows..."), this);
    addAction("showRow", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(slotShowRowDialog()));
    action->setToolTip(i18n("Show hidden rows"));

    action = new KAction(KIcon("adjustrow"), i18n("Equalize Row"), this);
    addAction("equalizeRow", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(equalizeRow()));
    action->setToolTip(i18n("Resizes selected rows to be the same size"));

    action = new KAction(KIcon("show_table_row"), i18n("Show Rows"), this);
    addAction("showSelRows", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(showRow()));
    action->setEnabled(false);
    action->setToolTip(i18n("Show hidden rows in the selection"));

    action = new KAction(i18n("Adjust Row && Column"), this);
    addAction("adjust", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(adjust()));
    action->setToolTip(i18n("Adjusts row/column size so that the contents will fit"));

    // -- cell insert/remove actions --

    action = new KAction(KIcon("insertcell"), i18n("Cells..."), this);
    action->setIconText(i18n("Insert Cells..."));
    action->setToolTip(i18n("Insert a blank cell into the spreadsheet"));
    addAction("insertCell", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(insertCells()));

    action = new KAction(KIcon("removecell"), i18n("Cells..."), this);
    action->setIconText(i18n("Remove Cells..."));
    action->setToolTip(i18n("Removes the cells from the spreadsheet"));
    addAction("deleteCell", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(deleteCells()));

    // -- cell content actions --

    action = new KAction(KIcon("deletecell"), i18n("All"), this);
    action->setIconText(i18n("Clear All"));
    action->setToolTip(i18n("Clear all contents and formatting of the current cell"));
    addAction("clearAll", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(clearAll()));

    action = new KAction(KIcon("edit-clear"), i18n("Contents"), this);
    action->setIconText(i18n("Clear Contents"));
    action->setToolTip(i18n("Remove the contents of the current cell"));
    addAction("clearContents", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(clearContents()));

    action = new KAction(KIcon("comment"), i18n("Comment..."), this);
    action->setToolTip(i18n("Edit a comment for this cell"));
    addAction("comment", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(comment()));

    action = new KAction(KIcon("removecomment"), i18n("Comment"), this);
    action->setIconText(i18n("Remove Comment"));
    action->setToolTip(i18n("Remove this cell's comment"));
    addAction("clearComment", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(clearComment()));

    action = new KAction(i18n("Conditional Styles..."), this);
    action->setToolTip(i18n("Set cell style based on certain conditions"));
    addAction("conditional", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(conditional()));

    action = new KAction(i18n("Conditional Styles"), this);
    action->setIconText(i18n("Remove Conditional Styles"));
    action->setToolTip(i18n("Remove the conditional cell styles"));
    addAction("clearConditional", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(clearConditionalStyles()));

    action = new KAction(KIcon("insert-link"), i18n("&Link..."), this);
    addAction("insertHyperlink", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(insertHyperlink()));
    action->setToolTip(i18n("Insert an Internet hyperlink"));

    action = new KAction(i18n("Link"), this);
    action->setIconText(i18n("Remove Link"));
    action->setToolTip(i18n("Remove a link"));
    addAction("clearHyperlink", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(clearHyperlink()));

    action = new KAction(i18n("Validity..."), this);
    action->setToolTip(i18n("Set tests to confirm cell data is valid"));
    addAction("validity", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(validity()));

    action = new KAction(i18n("Validity"), this);
    action->setIconText(i18n("Remove Validity"));
    action->setToolTip(i18n("Remove the validity tests on this cell"));
    addAction("clearValidity", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(clearValidity()));

    // -- sorting/filtering action --

    action = new KAction(i18n("&Sort..."), this);
    addAction("sort", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(sort()));
    action->setToolTip(i18n("Sort a group of cells"));

    action = new KAction(KIcon("view-sort-descending"), i18n("Sort &Decreasing"), this);
    addAction("sortDec", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(sortDec()));
    action->setToolTip(i18n("Sort a group of cells in decreasing(last to first) order"));

    action = new KAction(KIcon("view-sort-ascending"), i18n("Sort &Increasing"), this);
    addAction("sortInc", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(sortInc()));
    action->setToolTip(i18n("Sort a group of cells in ascending(first to last) order"));

    action = new KAction(KIcon("view-filter"), i18n("&Auto-Filter"), this);
    addAction("autoFilter", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(autoFilter()));
    action->setToolTip(i18n("Add an automatic filter to a cell range"));

    // -- fill actions --

    action = new KAction(/*KIcon("arrow-left"), */i18n("&Left"), this);
    addAction("fillLeft", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(fillLeft()));

    action = new KAction(/*KIcon("arrow-right"), */i18n("&Right"), this);
    addAction("fillRight", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(fillRight()));

    action = new KAction(/*KIcon("arrow-up"), */i18n("&Up"), this);
    addAction("fillUp", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(fillUp()));

    action = new KAction(/*KIcon("arrow-down"), */i18n("&Down"), this);
    addAction("fillDown", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(fillDown()));

    action = new KAction(KIcon("black_sum"), i18n("Autosum"), this);
    addAction("autoSum", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(autoSum()));
    action->setToolTip(i18n("Insert the 'sum' function"));

    // -- data insert actions --

    action = new KAction(KIcon("series"), i18n("&Series..."), this);
    addAction("insertSeries", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(insertSeries()));
    action ->setToolTip(i18n("Insert a series"));

    action = new KAction(KIcon("funct"), i18n("&Function..."), this);
    addAction("insertFormula", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(insertFormula()));
    action->setToolTip(i18n("Insert math expression"));

    action = new KAction(KIcon("accessories-character-map"), i18n("S&pecial Character..."), this);
    addAction("insertSpecialChar", action);
    action->setToolTip(i18n("Insert one or more symbols or letters not found on the keyboard"));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(insertSpecialChar()));

#ifndef QT_NO_SQL
    action = new KAction(KIcon("network-server-database"), i18n("From &Database..."), this);
    action->setIconText(i18n("Database"));
    addAction("insertFromDatabase", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(insertFromDatabase()));
    action->setToolTip(i18n("Insert data from a SQL database"));
#endif

    action = new KAction(KIcon("text-plain"), i18n("From &Text File..."), this);
    action->setIconText(i18n("Text File"));
    addAction("insertFromTextfile", action);
    connect(action, SIGNAL(triggered(bool)), this,  SLOT(insertFromTextfile()));
    action->setToolTip(i18n("Insert data from a text file to the current cursor position/selection"));

    action = new KAction(KIcon("klipper"), i18n("From &Clipboard..."), this);
    action->setIconText(i18n("Clipboard"));
    addAction("insertFromClipboard", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(insertFromClipboard()));
    action->setToolTip(i18n("Insert CSV data from the clipboard to the current cursor position/selection"));

    action = new KAction(i18n("&Text to Columns..."), this);
    addAction("textToColumns", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(textToColumns()));
    action->setToolTip(i18n("Expand the content of cells to multiple columns"));

    action = new KAction(i18n("Custom Lists..."), this);
    addAction("sortList", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(sortList()));
    action->setToolTip(i18n("Create custom lists for sorting or autofill"));

    action = new KAction(i18n("&Consolidate..."), this);
    addAction("consolidate", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(consolidate()));
    action->setToolTip(i18n("Create a region of summary data from a group of similar regions"));

    action = new KAction(i18n("&Goal Seek..."), this);
    addAction("goalSeek", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(goalSeek()));
    action->setToolTip(i18n("Repeating calculation to find a specific value"));

    action = new KAction(i18n("&Subtotals..."), this);
    addAction("subtotals", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(subtotals()));
    action->setToolTip(i18n("Create different kind of subtotals to a list or database"));

    action = new KAction(i18n("Area Name..."), this);
    addAction("setAreaName", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(setAreaName()));
    action->setToolTip(i18n("Set a name for a region of the spreadsheet"));

    action = new KAction(i18n("Named Areas..."), this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_G));
    action->setIconText(i18n("Named Areas"));
    action->setIcon(KIcon("bookmarks"));
    action->setToolTip(i18n("Edit or select named areas"));
    addAction("namedAreaDialog", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(namedAreaDialog()));

    action = new KSelectAction(i18n("Formula Selection"), this);
    addAction("formulaSelection", action);
    action->setToolTip(i18n("Insert a function"));
    QStringList functionList;
    functionList.append("SUM");
    functionList.append("AVERAGE");
    functionList.append("IF");
    functionList.append("COUNT");
    functionList.append("MIN");
    functionList.append("MAX");
    functionList.append(i18n("Others..."));
    static_cast<KSelectAction*>(action)->setItems(functionList);
    static_cast<KSelectAction*>(action)->setComboWidth(80);
    static_cast<KSelectAction*>(action)->setCurrentItem(0);
    connect(action, SIGNAL(triggered(const QString&)), this, SLOT(formulaSelection(const QString&)));

    // -- general editing actions --

    action = new KAction(KIcon("cell_edit"), i18n("Modify Cell"), this);
    addAction("editCell", action);
    action->setShortcuts(QList<QKeySequence>() << Qt::Key_F2 << QKeySequence(Qt::CTRL + Qt::Key_M));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(edit()));
    action->setToolTip(i18n("Edit the highlighted cell"));

    action = KStandardAction::cut(this, SLOT(cut()), this);
    action->setToolTip(i18n("Move the cell object to the clipboard"));
    addAction("cut", action);

    action = KStandardAction::copy(this, SLOT(copy()), this);
    action->setToolTip(i18n("Copy the cell object to the clipboard"));
    addAction("copy", action);

    action = KStandardAction::paste(this, SLOT(paste()), this);
    action->setToolTip(i18n("Paste the contents of the clipboard at the cursor"));
    addAction("paste", action);

    action = new KAction(KIcon("special_paste"), i18n("Special Paste..."), this);
    addAction("specialPaste", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(specialPaste()));
    action->setToolTip(i18n("Paste the contents of the clipboard with special options"));

    action = new KAction(KIcon("insertcellcopy"), i18n("Paste with Insertion"), this);
    addAction("pasteWithInsertion", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(pasteWithInsertion()));
    action->setToolTip(i18n("Inserts a cell from the clipboard into the spreadsheet"));

    action = KStandardAction::selectAll(this, SLOT(selectAll()), this);
    action->setToolTip(i18n("Selects all cells in the current sheet"));
    addAction("selectAll", action);

    action = KStandardAction::find(this, SLOT(find()), this);
    addAction("edit_find", action);

    action = KStandardAction::findNext(this, SLOT(findNext()), this);
    addAction("edit_find_next", action);

    action = KStandardAction::findPrev(this, SLOT(findPrevious()), this);
    addAction("edit_find_last", action);

    action = KStandardAction::replace(this, SLOT(replace()), this);
    addAction("edit_replace", action);

    // -- misc actions --

    action = new KAction(KIcon("go-jump"), i18n("Goto Cell..."), this);
    action->setIconText(i18n("Goto"));
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_G));
    addAction("gotoCell", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(gotoCell()));
    action->setToolTip(i18n("Move to a particular cell"));

    action = KStandardAction::spelling(this, SLOT(spellCheck()), this);
    action->setToolTip(i18n("Check the spelling"));
    addAction("tools_spelling", action);

    action = new KAction(KIcon("inspector"), i18n("Run Inspector..."), this);
    addAction("inspector", action);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_I));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(inspector()));

#ifndef NDEBUG
    action = new KAction(KIcon("table"), i18n("Show QTableView..."), this);
    addAction("qTableView", action);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_T));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(qTableView()));
#endif

    action = new KAction(i18n("Auto-Format..."), this);
    addAction("sheetFormat", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(sheetFormat()));
    action->setToolTip(i18n("Set the worksheet formatting"));

    action = new KAction(i18n("Document Settings..."), this);
    addAction("documentSettingsDialog", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(documentSettingsDialog()));
    action->setToolTip(i18n("Show document settings dialog"));

    action = new KToggleAction(i18n("Break Before Column"), this);
    addAction("format_break_before_column", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(breakBeforeColumn(bool)));
    action->setIconText(i18n("Column Break"));
    action->setToolTip(i18n("Set a manual page break before the column"));

    action = new KToggleAction(i18n("Break Before Row"), this);
    addAction("format_break_before_row", action);
    connect(action, SIGNAL(triggered(bool)), this, SLOT(breakBeforeRow(bool)));
    action->setIconText(i18n("Row Break"));
    action->setToolTip(i18n("Set a manual page break before the row"));

    // Editor actions:
    // Set up the permutation of the reference fixations action.
    action = new KAction(i18n("Permute reference fixation"), this);
    addAction("permuteFixation", action);
    action->setShortcut(Qt::Key_F4);
    // connect on creation of the embedded editor
    action->setIconText(i18n("Permute fixation"));
    action->setToolTip(i18n("Permute the fixation of the reference at the text cursor"));

    setTextMode(true);
}

CellToolBase::~CellToolBase()
{
    delete d->formulaDialog;
    delete d->popupListChoose;
    qDeleteAll(d->popupMenuActions);
    qDeleteAll(actions());
    delete d;
}

void CellToolBase::paint(QPainter &painter, const KoViewConverter &viewConverter)
{
    KoShape::applyConversion(painter, viewConverter);
    painter.translate(offset()); // the table shape offset
    const QRectF paintRect = QRectF(QPointF(), size());

    /* paint the selection */
    d->paintReferenceSelection(painter, paintRect);
    d->paintSelection(painter, paintRect);
}

void CellToolBase::paintReferenceSelection(QPainter &painter, const QRectF &paintRect)
{
    d->paintReferenceSelection(painter, paintRect);
}

void CellToolBase::paintSelection(QPainter &painter, const QRectF &paintRect)
{
    d->paintSelection(painter, paintRect);
}

void CellToolBase::mousePressEvent(KoPointerEvent* event)
{
    KoInteractionTool::mousePressEvent(event);
}

void CellToolBase::mouseMoveEvent(KoPointerEvent* event)
{
    // Special handling for drag'n'drop.
    if (DragAndDropStrategy *const strategy = dynamic_cast<DragAndDropStrategy*>(currentStrategy())) {
        // FIXME Stefan: QDrag*Event and QDropEvent are not handled by KoInteractionTool YET:
        // Cancel the strategy after the drag has started.
        if (strategy->dragStarted()) {
            cancelCurrentStrategy();
        }
        KoInteractionTool::mouseMoveEvent(event);
        return;
    }
    // Indicators are not necessary if there's a strategy.
    if (currentStrategy()) {
        return KoInteractionTool::mouseMoveEvent(event);
    }

    Sheet *const sheet = selection()->activeSheet();

    // Get info about where the event occurred.
    QPointF position = event->point - offset(); // the shape offset, not the scrolling one.

    // Diagonal cursor, if the selection handle was hit.
    if (SelectionStrategy::hitTestReferenceSizeGrip(canvas(), selection(), position) ||
        SelectionStrategy::hitTestSelectionSizeGrip(canvas(), selection(), position)) {
        if (selection()->activeSheet()->layoutDirection() == Qt::RightToLeft) {
            useCursor(Qt::SizeBDiagCursor);
        } else {
            useCursor(Qt::SizeFDiagCursor);
        }
        return KoInteractionTool::mouseMoveEvent(event);
    }

    // Hand cursor, if the selected area was hit.
    if (!selection()->referenceSelectionMode()) {
        const Region::ConstIterator end(selection()->constEnd());
        for (Region::ConstIterator it(selection()->constBegin()); it != end; ++it) {
            const QRect range = (*it)->rect();
            if (sheet->cellCoordinatesToDocument(range).contains(position)) {
                useCursor(Qt::PointingHandCursor);
                return KoInteractionTool::mouseMoveEvent(event);
            }
        }
    }

    // In which cell did the user click?
    qreal xpos;
    qreal ypos;
    const int col = this->selection()->activeSheet()->leftColumn(position.x(), xpos);
    const int row = this->selection()->activeSheet()->topRow(position.y(), ypos);
    // Check boundaries.
    if (col < 1 || row < 1 || col > maxCol() || row > maxRow()) {
        kDebug(36005) << "col or row is out of range:" << "col:" << col << " row:" << row;
    } else {
        const Cell cell = Cell(selection()->activeSheet(), col, row).masterCell();
        SheetView* const sheetView = this->sheetView(selection()->activeSheet());

        QString url;
        const CellView& cellView = sheetView->cellView(col, row);
        if (selection()->activeSheet()->layoutDirection() == Qt::RightToLeft) {
            url = cellView.testAnchor(sheetView, cell, cell.width() - position.x() + xpos, position.y() - ypos);
        } else {
            url = cellView.testAnchor(sheetView, cell, position.x() - xpos, position.y() - ypos);
        }
        if (!url.isEmpty()) {
            useCursor(Qt::PointingHandCursor);
            return KoInteractionTool::mouseMoveEvent(event);
        }
    }

    // Reset to normal cursor.
    useCursor(Qt::ArrowCursor);
    KoInteractionTool::mouseMoveEvent(event);
}

void CellToolBase::mouseReleaseEvent(KoPointerEvent* event)
{
    KoInteractionTool::mouseReleaseEvent(event);
    scrollToCell(selection()->cursor());
}

void CellToolBase::mouseDoubleClickEvent(KoPointerEvent* event)
{
    Q_UNUSED(event)
    cancelCurrentStrategy();
    scrollToCell(selection()->cursor());
    createEditor(false /* keep content */);
}

void CellToolBase::keyPressEvent(QKeyEvent* event)
{
    register Sheet * const sheet = selection()->activeSheet();
    if (!sheet) {
        return;
    }

    // Don't handle the remaining special keys.
    if (event->modifiers() & (Qt::AltModifier | Qt::ControlModifier) &&
            (event->key() != Qt::Key_Down) &&
            (event->key() != Qt::Key_Up) &&
            (event->key() != Qt::Key_Right) &&
            (event->key() != Qt::Key_Left) &&
            (event->key() != Qt::Key_Home) &&
            (event->key() != Qt::Key_Enter) &&
            (event->key() != Qt::Key_Return)) {
        event->ignore(); // QKeyEvent
        return;
    }

    // Check for formatting key combination CTRL + ...
    // Qt::Key_Exclam, Qt::Key_At, Qt::Key_Ampersand, Qt::Key_Dollar
    // Qt::Key_Percent, Qt::Key_AsciiCircum, Qt::Key_NumberSign
    if (d->formatKeyPress(event)) {
        return;
    }

#if 0
    // TODO move this to the contextMenuEvent of the view.
    // keyPressEvent() is not called with the contextMenuKey,
    // it's handled separately by Qt.
    if (event->key() == KGlobalSettings::contextMenuKey()) {
        int row = d->canvas->selection()->marker().y();
        int col = d->canvas->selection()->marker().x();
        QPointF p(sheet->columnPosition(col), sheet->rowPosition(row));
        d->canvas->view()->openPopupMenu(d->canvas->mapToGlobal(p.toPoint()));
    }
#endif
    switch (event->key()) {
    case Qt::Key_Return:
    case Qt::Key_Enter:
        d->processEnterKey(event);
        return;
        break;
    case Qt::Key_Down:
    case Qt::Key_Up:
    case Qt::Key_Left:
    case Qt::Key_Right:
    case Qt::Key_Tab: /* a tab behaves just like a right/left arrow */
    case Qt::Key_Backtab:  /* and so does Shift+Tab */
        if (event->modifiers() & Qt::ControlModifier) {
            if (!d->processControlArrowKey(event))
                return;
        } else {
            d->processArrowKey(event);
            return;
        }
        break;

    case Qt::Key_Escape:
        d->processEscapeKey(event);
        return;
        break;

    case Qt::Key_Home:
        if (!d->processHomeKey(event))
            return;
        break;

    case Qt::Key_End:
        if (!d->processEndKey(event))
            return;
        break;

    case Qt::Key_PageUp:  /* Page Up */
        if (!d->processPriorKey(event))
            return;
        break;

    case Qt::Key_PageDown:   /* Page Down */
        if (!d->processNextKey(event))
            return;
        break;

    default:
        d->processOtherKey(event);
        return;
        break;
    }
}

void CellToolBase::inputMethodEvent(QInputMethodEvent * event)
{
    // Send it to the embedded editor.
    if (editor()) {
        QApplication::sendEvent(editor()->widget(), event);
    }
}

void CellToolBase::activate(ToolActivation toolActivation, const QSet<KoShape*> &shapes)
{
    Q_UNUSED(toolActivation);
    Q_UNUSED(shapes);

    if (!d->initialized) {
        init();
        d->initialized = true;
    }

    useCursor(Qt::ArrowCursor);

    // paint the selection rectangle
    selection()->update();

    // Initialize cell style selection action.
    const StyleManager* styleManager = selection()->activeSheet()->map()->styleManager();
    static_cast<KSelectAction*>(this->action("setStyle"))->setItems(styleManager->styleNames());

    // Establish connections.
    connect(selection(), SIGNAL(changed(const Region&)),
            this, SLOT(selectionChanged(const Region&)));
    connect(selection(), SIGNAL(closeEditor(bool, bool)),
            this, SLOT(deleteEditor(bool, bool)));
    connect(selection(), SIGNAL(modified(const Region&)),
            this, SLOT(updateEditor()));
    connect(selection(), SIGNAL(activeSheetChanged(Sheet*)),
            this, SLOT(activeSheetChanged(Sheet*)));
    connect(selection(), SIGNAL(requestFocusEditor()),
            this, SLOT(focusEditorRequested()));
    connect(selection(), SIGNAL(documentReadWriteToggled(bool)),
            this, SLOT(documentReadWriteToggled(bool)));
    connect(selection(), SIGNAL(sheetProtectionToggled(bool)),
            this, SLOT(sheetProtectionToggled(bool)));
}

void CellToolBase::deactivate()
{
    // Disconnect.
    disconnect(selection(), 0, this, 0);
    // close the cell editor
    deleteEditor(true); // save changes
    // clear the selection rectangle
    selection()->update();
}

void CellToolBase::init()
{
}

QList <QWidget*> CellToolBase::createOptionWidgets()
{
    QList<QWidget *> widgets;
    d->optionWidget = new CellToolOptionWidget(this);

    connect(selection()->activeSheet()->map()->namedAreaManager(), SIGNAL(namedAreaAdded(const QString&)),
            d->optionWidget->locationComboBox(), SLOT(slotAddAreaName(const QString&)));
    connect(selection()->activeSheet()->map()->namedAreaManager(), SIGNAL(namedAreaRemoved(const QString&)),
            d->optionWidget->locationComboBox(), SLOT(slotRemoveAreaName(const QString&)));

    selection()->update(); // initialize the location combobox
    d->optionWidget->setWindowTitle(i18n("Cell Editor"));
    widgets.append(d->optionWidget);
    return widgets;
}

KoInteractionStrategy* CellToolBase::createStrategy(KoPointerEvent* event)
{
    // Get info about where the event occurred.
    QPointF position = event->point - offset(); // the shape offset, not the scrolling one.

    // Autofilling or merging, if the selection handle was hit.
    if (SelectionStrategy::hitTestSelectionSizeGrip(canvas(), selection(), position)) {
        if (event->button() == Qt::LeftButton)
            return new AutoFillStrategy(this, event->point, event->modifiers());
        else if (event->button() == Qt::MidButton)
            return new MergeStrategy(this, event->point, event->modifiers());
    }

    // Pasting with the middle mouse button.
    if (event->button() == Qt::MidButton) {
        return new PasteStrategy(this, event->point, event->modifiers());
    }

    // Check, if the selected area was hit.
    bool hitSelection = false;
    Region::ConstIterator end = selection()->constEnd();
    for (Region::ConstIterator it = selection()->constBegin(); it != end; ++it) {
        const QRect range = (*it)->rect();
        if (selection()->activeSheet()->cellCoordinatesToDocument(range).contains(position)) {
            // Context menu with the right mouse button.
            if (event->button() == Qt::RightButton) {
                // Setup the context menu.
                setPopupActionList(d->popupActionList());
                event->ignore();
                return 0; // Act directly; no further strategy needed.
            }
            hitSelection = true;
            break;
        }
    }

    // In which cell did the user click?
    qreal xpos;
    qreal ypos;
    const int col = this->selection()->activeSheet()->leftColumn(position.x(), xpos);
    const int row = this->selection()->activeSheet()->topRow(position.y(), ypos);
    // Check boundaries.
    if (col > maxCol() || row > maxRow()) {
        kDebug(36005) << "col or row is out of range:" << "col:" << col << " row:" << row;
    } else {
        // Context menu with the right mouse button.
        if (event->button() == Qt::RightButton) {
            selection()->initialize(QPoint(col, row), selection()->activeSheet());
            // Setup the context menu.
            setPopupActionList(d->popupActionList());
            event->ignore();
            return 0; // Act directly; no further strategy needed.
        } else {
            const Cell cell = Cell(selection()->activeSheet(), col, row).masterCell();
            SheetView* const sheetView = this->sheetView(selection()->activeSheet());

            // Filter button hit.
            const double offsetX = canvas()->canvasController()->canvasOffsetX();
            const double offsetY = canvas()->canvasController()->canvasOffsetY();
            const QPointF p1 = QPointF(xpos, ypos) - offset(); // the shape offset, not the scrolling one.
            const QSizeF s1(cell.width(), cell.height());
            const QRectF cellRect = canvas()->viewConverter()->documentToView(QRectF(p1, s1));
            const QRect cellViewRect = cellRect.translated(offsetX, offsetY).toRect();
            if (sheetView->cellView(col, row).hitTestFilterButton(cell, cellViewRect, event->pos())) {
                Database database = cell.database();
                FilterPopup::showPopup(canvas()->canvasWidget(), cell, cellViewRect, &database);
                return 0; // Act directly; no further strategy needed.
            }

            // Hyperlink hit.
            QString url;
            const CellView& cellView = sheetView->cellView(col, row);
            if (selection()->activeSheet()->layoutDirection() == Qt::RightToLeft) {
                url = cellView.testAnchor(sheetView, cell, cell.width() - position.x() + xpos, position.y() - ypos);
            } else {
                url = cellView.testAnchor(sheetView, cell, position.x() - xpos, position.y() - ypos);
            }
            if (!url.isEmpty()) {
                return new HyperlinkStrategy(this, event->point,
                                             event->modifiers(), url, cellView.textRect());
            }
        }
    }

    // Drag & drop, if the selected area was hit.
    const bool controlPressed = event->modifiers() & Qt::ControlModifier;
    if (hitSelection && !controlPressed && !selection()->referenceSelectionMode()) {
        return new DragAndDropStrategy(this, event->point, event->modifiers());
    }

    return new SelectionStrategy(this, event->point, event->modifiers());
}

void CellToolBase::selectionChanged(const Region& region)
{
    Q_UNUSED(region);
    if (!d->optionWidget) {
        return;
    }
    // Update the editor, if the reference selection is enabled.
    if (editor() && selection()->referenceSelectionMode()) {
        // First, update the formula expression. This will send a signal with
        // the new expression to the external editor, which does not have focus
        // yet (the canvas has). If it would have, it would also send a signal
        // to inform the embedded editor about a changed text.
        editor()->selectionChanged();
        // Focus the embedded or external editor after updating the expression.
        focusEditorRequested();
        return;
    }

    // State of manual page breaks before columns/rows.
    bool columnBreakChecked = false;
    bool columnBreakEnabled = false;
    bool rowBreakChecked = false;
    bool rowBreakEnabled = false;
    const Region::ConstIterator end(selection()->constEnd());
    for (Region::ConstIterator it = selection()->constBegin(); it != end; ++it) {
        const Sheet *const sheet = (*it)->sheet();
        if (!sheet) {
            continue;
        }
        const QRect range = (*it)->rect();
        const int column = range.left();
        const int row = range.top();
        columnBreakChecked |= sheet->columnFormat(column)->hasPageBreak();
        columnBreakEnabled |= (column != 1);
        rowBreakChecked |= sheet->rowFormats()->hasPageBreak(row);
        rowBreakEnabled |= (row != 1);
    }
    action("format_break_before_column")->setChecked(columnBreakChecked);
    action("format_break_before_column")->setEnabled(columnBreakEnabled);
    action("format_break_before_row")->setChecked(rowBreakChecked);
    action("format_break_before_row")->setEnabled(rowBreakEnabled);

    const Cell cell = Cell(selection()->activeSheet(), selection()->cursor());
    if (!cell) {
        return;
    }
    d->updateEditor(cell);
    d->updateActions(cell);

    if (selection()->activeSheet()->isProtected()) {
        const Style style = cell.style();
        if (style.notProtected()) {
            if (selection()->isSingular()) {
                if (!action("bold")->isEnabled()) {
                    d->setProtectedActionsEnabled(true);
                }
            } else { // more than one cell
                if (action("bold")->isEnabled()) {
                    d->setProtectedActionsEnabled(false);
                }
            }
        } else {
            if (action("bold")->isEnabled()) {
                d->setProtectedActionsEnabled(false);
            }
        }
    }
}

void CellToolBase::scrollToCell(const QPoint &location)
{
    Sheet *const sheet = selection()->activeSheet();

    // Adjust the maximum accessed column and row for the scrollbars.
    sheetView(sheet)->updateAccessedCellRange(location);

    // The cell geometry expanded by some pixels in each direction.
    const Cell cell = Cell(sheet, location).masterCell();
    const double xpos = sheet->columnPosition(cell.cellPosition().x());
    const double ypos = sheet->rowPosition(cell.cellPosition().y());
    const double pixelWidth = canvas()->viewConverter()->viewToDocumentX(1);
    const double pixelHeight = canvas()->viewConverter()->viewToDocumentY(1);
    QRectF rect(xpos, ypos, cell.width(), cell.height());
    rect.adjust(-2*pixelWidth, -2*pixelHeight, +2*pixelWidth, +2*pixelHeight);
    rect = rect & QRectF(QPointF(0.0, 0.0), sheet->documentSize());

    // Scroll to cell.
    canvas()->canvasController()->ensureVisible(canvas()->viewConverter()->documentToView(rect), true);
}

CellEditorBase* CellToolBase::editor() const
{
    return d->cellEditor;
}

void CellToolBase::setLastEditorWithFocus(Editor editor)
{
    d->lastEditorWithFocus = editor;
}

bool CellToolBase::createEditor(bool clear, bool focus)
{
    const Cell cell(selection()->activeSheet(), selection()->marker());
    if (selection()->activeSheet()->isProtected() && !cell.style().notProtected())
        return false;

    if (!editor()) {
        d->cellEditor = new CellEditor(this, canvas()->canvasWidget());
        d->cellEditor->setEditorFont(cell.style().font(), true, canvas()->viewConverter());
        connect(action("permuteFixation"), SIGNAL(triggered(bool)),
                d->cellEditor, SLOT(permuteFixation()));
    if(d->optionWidget && d->optionWidget->editor()) {
        connect(d->cellEditor, SIGNAL(textChanged(const QString &)),
                d->optionWidget->editor(), SLOT(setText(const QString &)));
        connect(d->optionWidget->editor(), SIGNAL(textChanged(const QString &)),
                d->cellEditor, SLOT(setText(const QString &)));
        d->optionWidget->applyButton()->setEnabled(true);
        d->optionWidget->cancelButton()->setEnabled(true);
    }

        double w = cell.width();
        double h = cell.height();
        double min_w = cell.width();
        double min_h = cell.height();

        double xpos = selection()->activeSheet()->columnPosition(selection()->marker().x());
        xpos += canvas()->viewConverter()->viewToDocumentX(canvas()->canvasController()->canvasOffsetX());

        Qt::LayoutDirection sheetDir = selection()->activeSheet()->layoutDirection();
        bool rtlText = cell.displayText().isRightToLeft();

        // if sheet and cell direction don't match, then the editor's location
        // needs to be shifted backwards so that it's right above the cell's text
        if (w > 0 && ((sheetDir == Qt::RightToLeft && !rtlText) ||
                      (sheetDir == Qt::LeftToRight && rtlText)))
            xpos -= w - min_w;

        // paint editor above correct cell if sheet direction is RTL
        if (sheetDir == Qt::RightToLeft) {
            double dwidth = canvas()->viewConverter()->viewToDocumentX(canvas()->canvasWidget()->width());
            double w2 = qMax(w, min_w);
            xpos = dwidth - w2 - xpos;
        }

        double ypos = selection()->activeSheet()->rowPosition(selection()->marker().y());
        ypos += canvas()->viewConverter()->viewToDocumentY(canvas()->canvasController()->canvasOffsetY());

        // Setup the editor's palette.
        const Style style = cell.effectiveStyle();
        QPalette editorPalette(d->cellEditor->palette());
        QColor color = style.fontColor();
        if (!color.isValid())
            color = canvas()->canvasWidget()->palette().text().color();
        editorPalette.setColor(QPalette::Text, color);
        color = style.backgroundColor();
        if (!color.isValid())
            color = editorPalette.base().color();
        editorPalette.setColor(QPalette::Background, color);
        d->cellEditor->setPalette(editorPalette);

        // apply (table shape) offset
        xpos += offset().x();
        ypos += offset().y();

        const QRectF rect(xpos + 0.5, ypos + 0.5, w - 0.5, h - 0.5); //needed to circumvent rounding issue with height/width
        const QRectF zoomedRect = canvas()->viewConverter()->documentToView(rect);
        d->cellEditor->setGeometry(zoomedRect.toRect().adjusted(1, 1, -1, -1));
        d->cellEditor->setMinimumSize(QSize((int)canvas()->viewConverter()->documentToViewX(min_w) - 1,
                                       (int)canvas()->viewConverter()->documentToViewY(min_h) - 1));
        d->cellEditor->show();

        // Laurent 2001-12-05
        // Don't add focus when we create a new editor and
        // we select text in edit widget otherwise we don't delete
        // selected text.
        if (focus)
            d->cellEditor->setFocus();

        // clear the selection rectangle
        selection()->update();
    }

    if (!clear && !cell.isNull())
        d->cellEditor->setText(cell.userInput());
    return true;
}

void CellToolBase::deleteEditor(bool saveChanges, bool expandMatrix)
{
    if (!d->cellEditor) {
        return;
    }
    const QString userInput = d->cellEditor->toPlainText();
    d->cellEditor->hide();
    // Delete the cell editor first and after that update the document.
    // That means we get a synchronous repaint after the cell editor
    // widget is gone. Otherwise we may get painting errors.
    delete d->cellEditor;
    d->cellEditor = 0;

    delete d->formulaDialog;
    d->formulaDialog = 0;

    if (saveChanges) {
        applyUserInput(userInput, expandMatrix);
    } else {
        selection()->update();
    }
    d->optionWidget->applyButton()->setEnabled(false);
    d->optionWidget->cancelButton()->setEnabled(false);
    canvas()->canvasWidget()->setFocus();
}

void CellToolBase::activeSheetChanged(Sheet* sheet)
{
#ifdef NDEBUG
    Q_UNUSED(sheet);
#else
    Q_ASSERT(selection()->activeSheet() == sheet);
#endif
    if (!selection()->referenceSelectionMode()) {
        return;
    }
    if (editor()) {
        if (selection()->originSheet() != selection()->activeSheet()) {
            editor()->widget()->hide();
        } else {
            editor()->widget()->show();
        }
    }
    focusEditorRequested();
}

void CellToolBase::updateEditor()
{
    if (!d->optionWidget) {
        return;
    }
    const Cell cell = Cell(selection()->activeSheet(), selection()->cursor());
    if (!cell) {
        return;
    }
    d->updateEditor(cell);
}

void CellToolBase::focusEditorRequested()
{
    // Nothing to do, if not in editing mode.
    if (!editor()) {
        return;
    }
    // If we are in editing mode, we redirect the focus to the CellEditor or ExternalEditor.
    // This screws up <Tab> though (David)
    if (selection()->originSheet() != selection()->activeSheet()) {
        // Always focus the external editor, if not on the origin sheet.
        d->optionWidget->editor()->setFocus();
    } else {
        // Focus the last active editor, if on the origin sheet.
        if (d->lastEditorWithFocus == EmbeddedEditor) {
            editor()->widget()->setFocus();
        } else {
            d->optionWidget->editor()->setFocus();
        }
    }
}

void CellToolBase::applyUserInput(const QString &userInput, bool expandMatrix)
{
    QString text = userInput;
    if (!text.isEmpty() && text.at(0) == '=') {
        //a formula
        int openParenthese = text.count('(');
        int closeParenthese = text.count(')');
        int diff = qAbs(openParenthese - closeParenthese);
        if (openParenthese > closeParenthese) {
            for (int i = 0; i < diff; i++) {
                text += ')';
            }
        }
    }
    DataManipulator* command = new DataManipulator();
    command->setSheet(selection()->activeSheet());
    command->setValue(Value(text));
    command->setParsing(true);
    command->setExpandMatrix(expandMatrix);
    command->add(expandMatrix ? *selection() : Region(selection()->cursor(), selection()->activeSheet()));
    command->execute(canvas());

    if (expandMatrix && selection()->isSingular())
        selection()->initialize(*command);

    Cell cell = Cell(selection()->activeSheet(), selection()->marker());
    if (cell.value().isString() && !text.isEmpty() && !text.at(0).isDigit() && !cell.isFormula()) {
        selection()->activeSheet()->map()->addStringCompletion(text);
    }
}

void CellToolBase::documentReadWriteToggled(bool readWrite)
{
    if (!d->optionWidget) {
        return;
    }
    d->setProtectedActionsEnabled(readWrite);
}

void CellToolBase::sheetProtectionToggled(bool protect)
{
    if (!d->optionWidget) {
        return;
    }
    d->setProtectedActionsEnabled(!protect);
}

void CellToolBase::cellStyle()
{
    QPointer<CellFormatDialog> dialog = new CellFormatDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::setDefaultStyle()
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setDefault();
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::styleDialog()
{
    Map* const map = selection()->activeSheet()->map();
    StyleManager* const styleManager = map->styleManager();
    QPointer<StyleManagerDialog> dialog = new StyleManagerDialog(canvas()->canvasWidget(), selection(), styleManager);
    dialog->exec();
    delete dialog;

    static_cast<KSelectAction*>(action("setStyle"))->setItems(styleManager->styleNames());
    if (selection()->activeSheet())
        map->addDamage(new CellDamage(selection()->activeSheet(), Region(1, 1, maxCol(), maxRow()), CellDamage::Appearance));
    canvas()->canvasWidget()->update();
}

void CellToolBase::setStyle(const QString& stylename)
{
    kDebug() << "CellToolBase::setStyle(" << stylename << ")";
    if (selection()->activeSheet()->map()->styleManager()->style(stylename)) {
        StyleCommand* command = new StyleCommand();
        command->setSheet(selection()->activeSheet());
        command->setParentName(stylename);
        command->add(*selection());
        command->execute(canvas());
    }
}

void CellToolBase::createStyleFromCell()
{
    QPoint p(selection()->marker());
    Cell cell = Cell(selection()->activeSheet(), p.x(), p.y());

    bool ok = false;
    QString styleName("");

    while (true) {
        styleName = KInputDialog::getText(i18n("Create Style From Cell"),
                                          i18n("Enter name:"), styleName, &ok, canvas()->canvasWidget());

        if (!ok) // User pushed an OK button.
            return;

        styleName = styleName.trimmed();

        if (styleName.length() < 1) {
            KMessageBox::sorry(canvas()->canvasWidget(), i18n("The style name cannot be empty."));
            continue;
        }

        if (selection()->activeSheet()->map()->styleManager()->style(styleName) != 0) {
            KMessageBox::sorry(canvas()->canvasWidget(), i18n("A style with this name already exists."));
            continue;
        }
        break;
    }

    const Style cellStyle = cell.style();
    CustomStyle*  style = new CustomStyle(styleName);
    style->merge(cellStyle);

    selection()->activeSheet()->map()->styleManager()->insertStyle(style);
    cell.setStyle(*style);
    QStringList functionList(static_cast<KSelectAction*>(action("setStyle"))->items());
    functionList.push_back(styleName);
    static_cast<KSelectAction*>(action("setStyle"))->setItems(functionList);
}

void CellToolBase::bold(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Font"));
    command->setFontBold(enable);
    command->add(*selection());
    command->execute(canvas());
    if (editor()) {
        const Cell cell = Cell(selection()->activeSheet(), selection()->marker());
        editor()->setEditorFont(cell.style().font(), true, canvas()->viewConverter());
    }
}

void CellToolBase::underline(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Font"));
    command->setFontUnderline(enable);
    command->add(*selection());
    command->execute(canvas());
    if (editor()) {
        const Cell cell = Cell(selection()->activeSheet(), selection()->marker());
        editor()->setEditorFont(cell.style().font(), true, canvas()->viewConverter());
    }
}

void CellToolBase::strikeOut(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Font"));
    command->setFontStrike(enable);
    command->add(*selection());
    command->execute(canvas());
    if (editor()) {
        const Cell cell = Cell(selection()->activeSheet(), selection()->marker());
        editor()->setEditorFont(cell.style().font(), true, canvas()->viewConverter());
    }
}


void CellToolBase::italic(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Font"));
    command->setFontItalic(enable);
    command->add(*selection());
    command->execute(canvas());
    if (editor()) {
        const Cell cell = Cell(selection()->activeSheet(), selection()->marker());
        editor()->setEditorFont(cell.style().font(), true, canvas()->viewConverter());
    }
}

void CellToolBase::font(const QString& font)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Font"));
    command->setFontFamily(font.toLatin1());
    command->add(*selection());
    command->execute(canvas());
    // Don't leave the focus in the toolbars combo box ...
    if (editor()) {
        const Style style = Cell(selection()->activeSheet(), selection()->marker()).style();
        editor()->setEditorFont(style.font(), true, canvas()->viewConverter());
        focusEditorRequested();
    } else {
        canvas()->canvasWidget()->setFocus();
    }
}

void CellToolBase::fontSize(int size)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Font"));
    command->setFontSize(size);
    command->add(*selection());
    command->execute(canvas());
    // Don't leave the focus in the toolbars combo box ...
    if (editor()) {
        const Cell cell(selection()->activeSheet(), selection()->marker());
        editor()->setEditorFont(cell.style().font(), true, canvas()->viewConverter());
        focusEditorRequested();
    } else {
        canvas()->canvasWidget()->setFocus();
    }
}

void CellToolBase::increaseFontSize()
{
    const Style style = Cell(selection()->activeSheet(), selection()->marker()).style();
    const int size = style.fontSize();

    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Font"));
    command->setFontSize(size + 1);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::decreaseFontSize()
{
    const Style style = Cell(selection()->activeSheet(), selection()->marker()).style();
    const int size = style.fontSize();

    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Font"));
    command->setFontSize(size - 1);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::changeTextColor(const KoColor &color)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Text Color"));
    command->setFontColor(color.toQColor());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::alignLeft(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Horizontal Alignment"));
    command->setHorizontalAlignment(enable ? Style::Left : Style::HAlignUndefined);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::alignRight(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Horizontal Alignment"));
    command->setHorizontalAlignment(enable ? Style::Right : Style::HAlignUndefined);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::alignCenter(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Horizontal Alignment"));
    command->setHorizontalAlignment(enable ? Style::Center : Style::HAlignUndefined);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::alignTop(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Vertical Alignment"));
    command->setVerticalAlignment(enable ? Style::Top : Style::VAlignUndefined);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::alignBottom(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Vertical Alignment"));
    command->setVerticalAlignment(enable ? Style::Bottom : Style::VAlignUndefined);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::alignMiddle(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Vertical Alignment"));
    command->setVerticalAlignment(enable ? Style::Middle : Style::VAlignUndefined);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::borderLeft()
{
    QColor color = static_cast<KoColorPopupAction*>(action("borderColor"))->currentColor();
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Border"));
    if (selection()->activeSheet()->layoutDirection() == Qt::RightToLeft)
        command->setRightBorderPen(QPen(color, 1, Qt::SolidLine));
    else
        command->setLeftBorderPen(QPen(color, 1, Qt::SolidLine));
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::borderRight()
{
    QColor color = static_cast<KoColorPopupAction*>(action("borderColor"))->currentColor();
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Border"));
    if (selection()->activeSheet()->layoutDirection() == Qt::RightToLeft)
        command->setLeftBorderPen(QPen(color, 1, Qt::SolidLine));
    else
        command->setRightBorderPen(QPen(color, 1, Qt::SolidLine));
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::borderTop()
{
    QColor color = static_cast<KoColorPopupAction*>(action("borderColor"))->currentColor();
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Border"));
    command->setTopBorderPen(QPen(color, 1, Qt::SolidLine));
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::borderBottom()
{
    QColor color = static_cast<KoColorPopupAction*>(action("borderColor"))->currentColor();
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Border"));
    command->setBottomBorderPen(QPen(color, 1, Qt::SolidLine));
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::borderAll()
{
    QColor color = static_cast<KoColorPopupAction*>(action("borderColor"))->currentColor();
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Border"));
    command->setTopBorderPen(QPen(color, 1, Qt::SolidLine));
    command->setBottomBorderPen(QPen(color, 1, Qt::SolidLine));
    command->setLeftBorderPen(QPen(color, 1, Qt::SolidLine));
    command->setRightBorderPen(QPen(color, 1, Qt::SolidLine));
    command->setHorizontalPen(QPen(color, 1, Qt::SolidLine));
    command->setVerticalPen(QPen(color, 1, Qt::SolidLine));
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::borderRemove()
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Border"));
    command->setTopBorderPen(QPen(Qt::NoPen));
    command->setBottomBorderPen(QPen(Qt::NoPen));
    command->setLeftBorderPen(QPen(Qt::NoPen));
    command->setRightBorderPen(QPen(Qt::NoPen));
    command->setHorizontalPen(QPen(Qt::NoPen));
    command->setVerticalPen(QPen(Qt::NoPen));
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::borderOutline()
{
    QColor color = static_cast<KoColorPopupAction*>(action("borderColor"))->currentColor();
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Border"));
    command->setTopBorderPen(QPen(color, 1, Qt::SolidLine));
    command->setBottomBorderPen(QPen(color, 1, Qt::SolidLine));
    command->setLeftBorderPen(QPen(color, 1, Qt::SolidLine));
    command->setRightBorderPen(QPen(color, 1, Qt::SolidLine));
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::borderColor(const KoColor &color)
{
    BorderColorCommand* command = new BorderColorCommand();
    command->setSheet(selection()->activeSheet());
    command->setColor(color.toQColor());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::wrapText(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Wrap Text"));
    command->setMultiRow(enable);
    command->setVerticalText(false);
    command->setAngle(0);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::verticalText(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Vertical Text"));
    command->setVerticalText(enable);
    command->setMultiRow(false);
    command->setAngle(0);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::increaseIndentation()
{
    IndentationCommand* command = new IndentationCommand();
    command->setSheet(selection()->activeSheet());
    command->add(*selection());
    if (!command->execute())
        delete command;
}

void CellToolBase::decreaseIndentation()
{
    IndentationCommand* command = new IndentationCommand();
    command->setSheet(selection()->activeSheet());
    command->setReverse(true);
    command->add(*selection());
    if (!command->execute())
        delete command;
}

void CellToolBase::changeAngle()
{
    QPointer<AngleDialog> dialog = new AngleDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::percent(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Format Percent"));
    command->setFormatType(enable ? Format::Percentage : Format::Generic);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::currency(bool enable)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Format Money"));
    command->setFormatType(enable ? Format::Money : Format::Generic);
    command->setPrecision(enable ?  selection()->activeSheet()->map()->calculationSettings()->locale()->fracDigits() : 0);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::increasePrecision()
{
    PrecisionCommand* command = new PrecisionCommand();
    command->setSheet(selection()->activeSheet());
    command->add(*selection());
    if (!command->execute())
        delete command;
}

void CellToolBase::decreasePrecision()
{
    PrecisionCommand* command = new PrecisionCommand();
    command->setSheet(selection()->activeSheet());
    command->setReverse(true);
    command->add(*selection());
    if (!command->execute())
        delete command;
}

void CellToolBase::toUpperCase()
{
    CaseManipulator* command = new CaseManipulator;
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Switch to uppercase"));
    command->changeMode(CaseManipulator::Upper);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::toLowerCase()
{
    CaseManipulator* command = new CaseManipulator;
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Switch to lowercase"));
    command->changeMode(CaseManipulator::Lower);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::firstLetterToUpperCase()
{
    CaseManipulator* command = new CaseManipulator;
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "First letter uppercase"));
    command->changeMode(CaseManipulator::FirstUpper);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::changeBackgroundColor(const KoColor &color)
{
    StyleCommand* command = new StyleCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Change Background Color"));
    command->setBackgroundColor(color.toQColor());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::mergeCells()
{
    // sanity check
    if (selection()->activeSheet()->isProtected()) {
        return;
    }
    if (selection()->activeSheet()->map()->isProtected()) {
        return;
    }
    MergeCommand* const command = new MergeCommand();
    command->setSheet(selection()->activeSheet());
    command->setSelection(selection());
    command->setHorizontalMerge(false);
    command->setVerticalMerge(false);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::mergeCellsHorizontal()
{
    // sanity check
    if (selection()->activeSheet()->isProtected()) {
        return;
    }
    if (selection()->activeSheet()->map()->isProtected()) {
        return;
    }
    MergeCommand* const command = new MergeCommand();
    command->setSheet(selection()->activeSheet());
    command->setHorizontalMerge(true);
    command->setVerticalMerge(false);
    command->setSelection(selection());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::mergeCellsVertical()
{
    // sanity check
    if (selection()->activeSheet()->isProtected()) {
        return;
    }
    if (selection()->activeSheet()->map()->isProtected()) {
        return;
    }
    MergeCommand* const command = new MergeCommand();
    command->setSheet(selection()->activeSheet());
    command->setHorizontalMerge(false);
    command->setVerticalMerge(true);
    command->setSelection(selection());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::dissociateCells()
{
    // sanity check
    if (selection()->activeSheet()->isProtected()) {
        return;
    }
    if (selection()->activeSheet()->map()->isProtected()) {
        return;
    }
    MergeCommand* const command = new MergeCommand();
    command->setSheet(selection()->activeSheet());
    command->setReverse(true);
    command->setSelection(selection());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::resizeColumn()
{
    if (selection()->isRowSelected())
        KMessageBox::error(canvas()->canvasWidget(), i18n("Area is too large."));
    else {
        QPointer<ResizeColumn> dialog = new ResizeColumn(canvas()->canvasWidget(), selection());
        dialog->exec();
        delete dialog;
    }
}

void CellToolBase::insertColumn()
{
    InsertDeleteColumnManipulator* command = new InsertDeleteColumnManipulator();
    command->setSheet(selection()->activeSheet());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::deleteColumn()
{
    InsertDeleteColumnManipulator* command = new InsertDeleteColumnManipulator();
    command->setSheet(selection()->activeSheet());
    command->setReverse(true);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::hideColumn()
{
    if (selection()->isRowSelected()) {
        KMessageBox::error(canvas()->canvasWidget(), i18n("Area is too large."));
        return;
    }

    HideShowManipulator* command = new HideShowManipulator();
    command->setSheet(selection()->activeSheet());
    command->setManipulateColumns(true);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::showColumn()
{
    if (selection()->isRowSelected()) {
        KMessageBox::error(canvas()->canvasWidget(), i18n("Area is too large."));
        return;
    }

    HideShowManipulator* command = new HideShowManipulator();
    command->setSheet(selection()->activeSheet());
    command->setManipulateColumns(true);
    command->setReverse(true);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::slotShowColumnDialog()
{
    QPointer<ShowColRow> dialog = new ShowColRow(canvas()->canvasWidget(), selection(), ShowColRow::Column);
    dialog->exec();
    delete dialog;
}

void CellToolBase::equalizeColumn()
{
    if (selection()->isRowSelected())
        KMessageBox::error(canvas()->canvasWidget(), i18n("Area is too large."));
    else {
        const QRect range = selection()->lastRange();
        const ColumnFormat* columnFormat = selection()->activeSheet()->columnFormat(range.left());
        double size = columnFormat->width();
        if (range.left() == range.right())
            return;
        for (int i = range.left() + 1; i <= range.right(); ++i)
            size = qMax(selection()->activeSheet()->columnFormat(i)->width(), size);

        if (size != 0.0) {
            ResizeColumnManipulator* command = new ResizeColumnManipulator();
            command->setSheet(selection()->activeSheet());
            command->setSize(qMax(2.0, size));
            command->add(*selection());
            if (!command->execute())
                delete command;
        } else { // hide
            HideShowManipulator* command = new HideShowManipulator();
            command->setSheet(selection()->activeSheet());
            command->setManipulateColumns(true);
            command->add(*selection());
            if (!command->execute())
                delete command;
        }
    }
}

void CellToolBase::adjustColumn()
{
    AdjustColumnRowManipulator* command = new AdjustColumnRowManipulator();
    command->setSheet(selection()->activeSheet());
    command->setAdjustColumn(true);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::resizeRow()
{
    if (selection()->isColumnSelected())
        KMessageBox::error(canvas()->canvasWidget(), i18n("Area is too large."));
    else {
        QPointer<ResizeRow> dialog = new ResizeRow(canvas()->canvasWidget(), selection());
        dialog->exec();
        delete dialog;
    }
}

void CellToolBase::insertRow()
{
    InsertDeleteRowManipulator* command = new InsertDeleteRowManipulator();
    command->setSheet(selection()->activeSheet());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::deleteRow()
{
    InsertDeleteRowManipulator* command = new InsertDeleteRowManipulator();
    command->setSheet(selection()->activeSheet());
    command->setReverse(true);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::hideRow()
{
    if (selection()->isColumnSelected()) {
        KMessageBox::error(canvas()->canvasWidget(), i18n("Area is too large."));
        return;
    }

    HideShowManipulator* command = new HideShowManipulator();
    command->setSheet(selection()->activeSheet());
    command->setManipulateRows(true);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::showRow()
{
    if (selection()->isColumnSelected()) {
        KMessageBox::error(canvas()->canvasWidget(), i18n("Area is too large."));
        return;
    }

    HideShowManipulator* command = new HideShowManipulator();
    command->setSheet(selection()->activeSheet());
    command->setManipulateRows(true);
    command->setReverse(true);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::slotShowRowDialog()
{
    QPointer<ShowColRow> dialog = new ShowColRow(canvas()->canvasWidget(), selection(), ShowColRow::Row);
    dialog->exec();
    delete dialog;
}

void CellToolBase::equalizeRow()
{
    if (selection()->isColumnSelected())
        KMessageBox::error(canvas()->canvasWidget(), i18n("Area is too large."));
    else {
        const QRect range = selection()->lastRange();
        qreal size = selection()->activeSheet()->rowFormats()->rowHeight(range.top());
        if (range.top() == range.bottom())
            return;
        for (int i = range.top() + 1; i <= range.bottom(); ++i) {
            int lastRow;
            size = qMax(selection()->activeSheet()->rowFormats()->rowHeight(i, &lastRow), static_cast<qreal>(size));
            i = lastRow;
        }

        if (size != 0.0) {
            ResizeRowManipulator* command = new ResizeRowManipulator();
            command->setSheet(selection()->activeSheet());
            command->setSize(qMax(qreal(2.0), size));
            command->add(*selection());
            if (!command->execute())
                delete command;
        } else { // hide
            HideShowManipulator* command = new HideShowManipulator();
            command->setSheet(selection()->activeSheet());
            command->setManipulateRows(true);
            command->add(*selection());
            if (!command->execute())
                delete command;
        }
    }
}

void CellToolBase::adjustRow()
{
    AdjustColumnRowManipulator* command = new AdjustColumnRowManipulator();
    command->setSheet(selection()->activeSheet());
    command->setAdjustRow(true);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::adjust()
{
    AdjustColumnRowManipulator* command = new AdjustColumnRowManipulator();
    command->setSheet(selection()->activeSheet());
    command->setAdjustColumn(true);
    command->setAdjustRow(true);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::insertCells()
{
    QPointer<InsertDialog> dialog = new InsertDialog(canvas()->canvasWidget(), selection(), InsertDialog::Insert);
    dialog->exec();
    delete dialog;
}

void CellToolBase::deleteCells()
{
    QPointer<InsertDialog> dialog = new InsertDialog(canvas()->canvasWidget(), selection(), InsertDialog::Remove);
    dialog->exec();
    delete dialog;
}

void CellToolBase::clearAll()
{
    DeleteCommand* command = new DeleteCommand();
    command->setSheet(selection()->activeSheet());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::clearContents()
{
    // TODO Stefan: Actually this check belongs into the command!
    if (selection()->activeSheet()->areaIsEmpty(*selection()))
        return;

    DataManipulator* command = new DataManipulator();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Clear Text"));
    // parsing gets set only so that parseUserInput is called as it should be,
    // no actual parsing shall be done
    command->setParsing(true);
    command->setValue(Value(""));
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::comment()
{
    QPointer<CommentDialog> dialog = new CommentDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::clearComment()
{
    // TODO Stefan: Actually this check belongs into the command!
    if (selection()->activeSheet()->areaIsEmpty(*selection(), Sheet::Comment))
        return;

    CommentCommand* command = new CommentCommand();
    command->setSheet(selection()->activeSheet());
    command->setText(i18nc("(qtundo-format)", "Remove Comment"));
    command->setComment(QString());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::conditional()
{
    QPointer<ConditionalDialog> dialog = new ConditionalDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::clearConditionalStyles()
{
    // TODO Stefan: Actually this check belongs into the command!
    if (selection()->activeSheet()->areaIsEmpty(*selection(), Sheet::ConditionalCellAttribute))
        return;

    CondtionCommand* command = new CondtionCommand();
    command->setSheet(selection()->activeSheet());
    command->setConditionList(QLinkedList<Conditional>());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::insertHyperlink()
{
    selection()->emitAboutToModify();

    QPoint marker(selection()->marker());
    Cell cell(selection()->activeSheet(), marker);

    QPointer<LinkDialog> dialog = new LinkDialog(canvas()->canvasWidget(), selection());
    dialog->setWindowTitle(i18n("Insert Link"));
    if (!cell.isNull()) {
        dialog->setText(cell.userInput());
        if (!cell.link().isEmpty()) {
            dialog->setWindowTitle(i18n("Edit Link"));
            dialog->setLink(cell.link());
        }
    }

    if (dialog->exec() == KDialog::Accepted) {
        cell = Cell(selection()->activeSheet(), marker);

        LinkCommand* command = new LinkCommand(cell, dialog->text(), dialog->link());
        canvas()->addCommand(command);

        //refresh editWidget
        selection()->emitModified();
    }
    delete dialog;
}

void CellToolBase::clearHyperlink()
{
    QPoint marker(selection()->marker());
    Cell cell(selection()->activeSheet(), marker);
    if (!cell)
        return;
    if (cell.link().isEmpty())
        return;

    LinkCommand* command = new LinkCommand(cell, QString(), QString());
    canvas()->addCommand(command);

    selection()->emitModified();
}

void CellToolBase::validity()
{
    QPointer<ValidityDialog> dialog = new ValidityDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::clearValidity()
{
    // TODO Stefan: Actually this check belongs into the command!
    if (selection()->activeSheet()->areaIsEmpty(*selection(), Sheet::Validity))
        return;

    ValidityCommand* command = new ValidityCommand();
    command->setSheet(selection()->activeSheet());
    command->setValidity(Validity()); // empty object removes validity
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::sort()
{
    if (selection()->isSingular()) {
        KMessageBox::error(canvas()->canvasWidget(), i18n("You must select multiple cells."));
        return;
    }

    QPointer<SortDialog> dialog = new SortDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::sortInc()
{
    if (selection()->isSingular()) {
        KMessageBox::error(canvas()->canvasWidget(), i18n("You must select multiple cells."));
        return;
    }

    SortManipulator* command = new SortManipulator();
    command->setSheet(selection()->activeSheet());

    // Entire row(s) selected ? Or just one row ? Sort by columns if yes.
    QRect range = selection()->lastRange();
    bool sortCols = selection()->isRowSelected();
    sortCols = sortCols || (range.top() == range.bottom());
    command->setSortRows(!sortCols);
    command->addCriterion(0, Qt::AscendingOrder, Qt::CaseInsensitive);
    command->add(*selection());
    command->execute(canvas());

    selection()->emitModified();
}

void CellToolBase::sortDec()
{
    if (selection()->isSingular()) {
        KMessageBox::error(canvas()->canvasWidget(), i18n("You must select multiple cells."));
        return;
    }

    SortManipulator* command = new SortManipulator();
    command->setSheet(selection()->activeSheet());

    // Entire row(s) selected ? Or just one row ? Sort by rows if yes.
    QRect range = selection()->lastRange();
    bool sortCols = selection()->isRowSelected();
    sortCols = sortCols || (range.top() == range.bottom());
    command->setSortRows(!sortCols);
    command->addCriterion(0, Qt::DescendingOrder, Qt::CaseInsensitive);
    command->add(*selection());
    command->execute(canvas());

    selection()->emitModified();
}

void CellToolBase::autoFilter()
{
    AutoFilterCommand* command = new AutoFilterCommand();
    command->setSheet(selection()->activeSheet());
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::fillLeft()
{
    FillManipulator* command = new FillManipulator();
    command->setSheet(selection()->activeSheet());
    command->setDirection(FillManipulator::Left);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::fillRight()
{
    FillManipulator* command = new FillManipulator();
    command->setSheet(selection()->activeSheet());
    command->setDirection(FillManipulator::Right);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::fillUp()
{
    FillManipulator* command = new FillManipulator();
    command->setSheet(selection()->activeSheet());
    command->setDirection(FillManipulator::Up);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::fillDown()
{
    FillManipulator* command = new FillManipulator();
    command->setSheet(selection()->activeSheet());
    command->setDirection(FillManipulator::Down);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::autoSum()
{
    selection()->emitAboutToModify();

    //Get the selected range and remove the current cell from it(as that is
    //where the result of the autosum will be stored - perhaps change
    //this behaviour??)
    QRect sel = selection()->lastRange();

    if (sel.height() > 1) {
        if (selection()->marker().y() == sel.top())
            sel.setTop(sel.top() + 1);
        if (selection()->marker().y() == sel.bottom())
            sel.setBottom(sel.bottom() - 1);
    } else {
        if (sel.width() > 1) {
            if (selection()->marker().x() == sel.left())
                sel.setLeft(sel.left() + 1);

            if (selection()->marker().x() == sel.right())
                sel.setRight(sel.right() - 1);
        } else {
            sel = QRect();

            // only 1 cell selected
            // try to automagically find cells the user wants to sum up

            int start = -1, end = -1;

            if ((selection()->marker().y() > 1) && Cell(selection()->activeSheet(), selection()->marker().x(), selection()->marker().y() - 1).value().isNumber()) {
                // check cells above the current one
                start = end = selection()->marker().y() - 1;
                for (start--; (start > 0) && Cell(selection()->activeSheet(), selection()->marker().x(), start).value().isNumber(); start--) ;

                const Region region(QRect(QPoint(selection()->marker().x(), start + 1),
                                          QPoint(selection()->marker().x(), end)), selection()->activeSheet());
                const QString str = region.name(selection()->activeSheet());

                createEditor();
                editor()->setText("=SUM(" + str + ')');
                editor()->setCursorPosition(5 + str.length());
                return;
            } else if ((selection()->marker().x() > 1) && Cell(selection()->activeSheet(), selection()->marker().x() - 1, selection()->marker().y()).value().isNumber()) {
                // check cells to the left of the current one
                start = end = selection()->marker().x() - 1;
                for (start--; (start > 0) && Cell(selection()->activeSheet(), start, selection()->marker().y()).value().isNumber(); start--) ;

                const Region region(QRect(QPoint(start + 1, selection()->marker().y()),
                                          QPoint(end, selection()->marker().y())), selection()->activeSheet());
                const QString str = region.name(selection()->activeSheet());

                createEditor();
                editor()->setText("=SUM(" + str + ')');
                editor()->setCursorPosition(5 + str.length());
                return;
            }
        }
    }

    if ((sel.width() > 1) && (sel.height() > 1))
        sel = QRect();

    createEditor();

    const Region region(sel, selection()->activeSheet());
    if (region.isValid()) {
        editor()->setText("=SUM(" + region.name(selection()->activeSheet()) + ')');
        deleteEditor(true);
    } else {
        selection()->startReferenceSelection();
        editor()->setText("=SUM()");
        editor()->setCursorPosition(5);
    }
}

void CellToolBase::insertSeries()
{
    selection()->emitAboutToModify();
    QPointer<SeriesDialog> dialog = new SeriesDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::insertSpecialChar()
{
    QString fontFamily = Cell(selection()->activeSheet(), selection()->marker()).style().fontFamily();
    QChar c = ' ';

    if (d->specialCharDialog == 0) {
        d->specialCharDialog = new CharacterSelectDialog(canvas()->canvasWidget(), "SpecialCharDialog", fontFamily, c, false);
        connect(d->specialCharDialog, SIGNAL(insertChar(QChar, const QString&)),
                this, SLOT(specialChar(QChar, const QString&)));
        connect(d->specialCharDialog, SIGNAL(finished()),
                this, SLOT(specialCharDialogClosed()));
    }
    d->specialCharDialog->show();
}

void CellToolBase::specialCharDialogClosed()
{
    if (d->specialCharDialog) {
        disconnect(d->specialCharDialog, SIGNAL(insertChar(QChar, const QString&)),
                   this, SLOT(specialChar(QChar, const QString&)));
        disconnect(d->specialCharDialog, SIGNAL(finished()),
                   this, SLOT(specialCharDialogClosed()));
        d->specialCharDialog->deleteLater();
        d->specialCharDialog = 0;
    }
}

void CellToolBase::specialChar(QChar character, const QString& fontName)
{
    const Style style = Cell(selection()->activeSheet(), selection()->marker()).style();
    if (style.fontFamily() != fontName) {
        Style newStyle;
        newStyle.setFontFamily(fontName);
        selection()->activeSheet()->cellStorage()->setStyle(Region(selection()->marker()), newStyle);
    }
    QKeyEvent keyEvent(QEvent::KeyPress, 0, Qt::NoModifier, QString(character));
    if (!editor()) {
        createEditor();
    }
    QApplication::sendEvent(editor()->widget(), &keyEvent);
}

void CellToolBase::insertFormula()
{
    if (! d->formulaDialog) {
        if (! createEditor())
            return;
        d->formulaDialog = new FormulaDialog(canvas()->canvasWidget(), selection(), editor());
    }
    d->formulaDialog->show(); // dialog deletes itself later
}

void CellToolBase::insertFromDatabase()
{
#ifndef QT_NO_SQL
    selection()->emitAboutToModify();

    QStringList str = QSqlDatabase::drivers();
    if (str.isEmpty()) {
        KMessageBox::error(canvas()->canvasWidget(), i18n("No database drivers available.  To use this feature you need "
                           "to install the necessary Qt 3 database drivers."));
        return;
    }

    QPointer<DatabaseDialog> dialog = new DatabaseDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
#endif
}

void CellToolBase::insertFromTextfile()
{
    selection()->emitAboutToModify();

    QPointer<CSVDialog> dialog = new CSVDialog(canvas()->canvasWidget(), selection(), CSVDialog::File);
    dialog->setDecimalSymbol(selection()->activeSheet()->map()->calculationSettings()->locale()->decimalSymbol());
    dialog->setThousandsSeparator(selection()->activeSheet()->map()->calculationSettings()->locale()->thousandsSeparator());
    if (!dialog->canceled())
        dialog->exec();
    delete dialog;
}

void CellToolBase::insertFromClipboard()
{
    selection()->emitAboutToModify();

    QPointer<CSVDialog> dialog = new CSVDialog(canvas()->canvasWidget(), selection(), CSVDialog::Clipboard);
    dialog->setDecimalSymbol(selection()->activeSheet()->map()->calculationSettings()->locale()->decimalSymbol());
    dialog->setThousandsSeparator(selection()->activeSheet()->map()->calculationSettings()->locale()->thousandsSeparator());
    QString oldDelimiter = dialog->delimiter();
    dialog->setDelimiter(QString());
    if (!dialog->canceled())
        dialog->exec();
    dialog->setDelimiter(oldDelimiter);
    delete dialog;
}

void CellToolBase::textToColumns()
{
    selection()->emitAboutToModify();

    QRect area = selection()->lastRange();
    area.setRight(area.left()); // only use the first column
    Region oldSelection = *selection(); // store
    selection()->initialize(area);

    QPointer<CSVDialog> dialog = new CSVDialog(canvas()->canvasWidget(), selection(), CSVDialog::Column);
    dialog->setDecimalSymbol(selection()->activeSheet()->map()->calculationSettings()->locale()->decimalSymbol());
    dialog->setThousandsSeparator(selection()->activeSheet()->map()->calculationSettings()->locale()->thousandsSeparator());
    if (!dialog->canceled())
        dialog->exec();
    else
        selection()->initialize(oldSelection);
    delete dialog;
}

void CellToolBase::sortList()
{
    QPointer<ListDialog> dialog = new ListDialog(canvas()->canvasWidget());
    dialog->exec();
    delete dialog;
}

void CellToolBase::consolidate()
{
    selection()->emitAboutToModify();
    ConsolidateDialog * dialog = new ConsolidateDialog(canvas()->canvasWidget(), selection());
    dialog->show(); // dialog deletes itself later
}

void CellToolBase::goalSeek()
{
    selection()->emitAboutToModify();

    GoalSeekDialog* dialog = new GoalSeekDialog(canvas()->canvasWidget(), selection());
    dialog->show(); // dialog deletes itself later
}

void CellToolBase::subtotals()
{
    if ((selection()->lastRange().width() < 2) || (selection()->lastRange().height() < 2)) {
        KMessageBox::error(canvas()->canvasWidget(), i18n("You must select multiple cells."));
        return;
    }

    QPointer<SubtotalDialog> dialog = new SubtotalDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::setAreaName()
{
    QPointer<AddNamedAreaDialog> dialog = new AddNamedAreaDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::namedAreaDialog()
{
    QPointer<NamedAreaDialog> dialog = new NamedAreaDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::formulaSelection(const QString& expression)
{
    if (expression == i18n("Others...")) {
        insertFormula();
        return;
    }

    createEditor();
    FormulaDialog* dialog = new FormulaDialog(canvas()->canvasWidget(), selection(), editor(), expression);
    dialog->show(); // dialog deletes itself later
}

void CellToolBase::edit()
{
    // Not yet in edit mode?
    if (!editor()) {
        createEditor(false /* keep content */);
    } else {
        // Switch focus.
        if (editor()->widget()->hasFocus()) {
            d->optionWidget->editor()->setFocus();
        } else {
            editor()->widget()->setFocus();
        }
    }
}

void CellToolBase::cut()
{
    if (!editor()) {
        QDomDocument doc = CopyCommand::saveAsXml(*selection(), true);
        doc.documentElement().setAttribute("cut", selection()->Region::name());

        // Save to buffer
        QBuffer buffer;
        buffer.open(QIODevice::WriteOnly);
        QTextStream str(&buffer);
        str.setCodec("UTF-8");
        str << doc;
        buffer.close();

        QMimeData* mimeData = new QMimeData();
        mimeData->setText(CopyCommand::saveAsPlainText(*selection()));
        mimeData->setData("application/x-kspread-snippet", buffer.buffer());

        QApplication::clipboard()->setMimeData(mimeData);

        DeleteCommand* command = new DeleteCommand();
        command->setText(i18nc("(qtundo-format)", "Cut"));
        command->setSheet(selection()->activeSheet());
        command->add(*selection());
        command->execute();
    } else {
        editor()->cut();
    }
    selection()->emitModified();
}

void CellToolBase::copy() const
{
    Selection* selection = const_cast<CellToolBase*>(this)->selection();
    if (!editor()) {
        QDomDocument doc = CopyCommand::saveAsXml(*selection);

        // Save to buffer
        QBuffer buffer;
        buffer.open(QIODevice::WriteOnly);
        QTextStream str(&buffer);
        str.setCodec("UTF-8");
        str << doc;
        buffer.close();

        QMimeData* mimeData = new QMimeData();
        mimeData->setText(CopyCommand::saveAsPlainText(*selection));
        mimeData->setData("application/x-kspread-snippet", buffer.buffer());

        QApplication::clipboard()->setMimeData(mimeData);
    } else {
        editor()->copy();
    }
}

bool CellToolBase::paste()
{
    if (!selection()->activeSheet()->map()->isReadWrite()) // don't paste into a read only document
        return false;

    const QMimeData* mimeData = QApplication::clipboard()->mimeData(QClipboard::Clipboard);

    if (mimeData->hasFormat("application/vnd.oasis.opendocument.spreadsheet")) {
        QByteArray returnedTypeMime = "application/vnd.oasis.opendocument.spreadsheet";
        QByteArray arr = mimeData->data(returnedTypeMime);
        if (arr.isEmpty())
            return false;
        QBuffer buffer(&arr);
        KoStore * store = KoStore::createStore(&buffer, KoStore::Read);

        KoOdfReadStore odfStore(store); // does not delete the store on destruction
        KoXmlDocument doc;
        QString errorMessage;
        bool ok = odfStore.loadAndParse("content.xml", doc, errorMessage);
        if (!ok) {
            kError(32001) << "Error parsing content.xml: " << errorMessage << endl;
	    delete store;
            return false;
        }

        KoOdfStylesReader stylesReader;
        KoXmlDocument stylesDoc;
        (void)odfStore.loadAndParse("styles.xml", stylesDoc, errorMessage);
        // Load styles from style.xml
        stylesReader.createStyleMap(stylesDoc, true);
        // Also load styles from content.xml
        stylesReader.createStyleMap(doc, false);

        // from KSpreadDoc::loadOdf:
        KoXmlElement content = doc.documentElement();
        KoXmlElement realBody(KoXml::namedItemNS(content, KoXmlNS::office, "body"));
        if (realBody.isNull()) {
            kDebug(36005) << "Invalid OASIS OpenDocument file. No office:body tag found.";
	    delete store;
            return false;
        }
        KoXmlElement body = KoXml::namedItemNS(realBody, KoXmlNS::office, "spreadsheet");

        if (body.isNull()) {
            kError(36005) << "No office:spreadsheet found!" << endl;
            KoXmlElement childElem;
            QString localName;
            forEachElement(childElem, realBody) {
                localName = childElem.localName();
            }
            delete store;
            return false;
        }

        KoOdfLoadingContext context(stylesReader, store);
        Q_ASSERT(!stylesReader.officeStyle().isNull());

        //load in first
        selection()->activeSheet()->map()->styleManager()->loadOdfStyleTemplate(stylesReader);

        // all <sheet:sheet> goes to workbook
        bool result = selection()->activeSheet()->map()->loadOdf(body, context);

        if (!result) {
	    delete store;
            return false;
	}
        selection()->activeSheet()->map()->namedAreaManager()->loadOdf(body);
	delete store;
    }

    if (!editor()) {
        const QMimeData* mimedata = QApplication::clipboard()->mimeData();
        if (!mimedata->hasFormat("application/x-kspread-snippet") &&
            !mimedata->hasHtml() && mimedata->hasText() &&
            mimeData->text().split('\n').count() >= 2 )
        {
            insertFromClipboard();
       } else {
            //kDebug(36005) <<"Pasting. Rect=" << selection()->lastRange() <<" bytes";
            PasteCommand *const command = new PasteCommand();
            command->setSheet(selection()->activeSheet());
            command->add(*selection());
            command->setMimeData(mimedata);
            command->setPasteFC(true);
            command->execute(canvas());
        }
        d->updateEditor(Cell(selection()->activeSheet(), selection()->cursor()));
    } else {
        editor()->paste();
    }
    selection()->emitModified();
    return true;
}

void CellToolBase::specialPaste()
{
    QPointer<SpecialPasteDialog> dialog = new SpecialPasteDialog(canvas()->canvasWidget(), selection());
    if (dialog->exec()) {
        selection()->emitModified();
    }
    delete dialog;
}

void CellToolBase::pasteWithInsertion()
{
    const QMimeData *const mimeData = QApplication::clipboard()->mimeData();
    if (!PasteCommand::unknownShiftDirection(mimeData)) {
        PasteCommand *const command = new PasteCommand();
        command->setSheet(selection()->activeSheet());
        command->add(*selection());
        command->setMimeData(mimeData);
        command->setInsertionMode(PasteCommand::ShiftCells);
        command->execute(canvas());
    } else {
        QPointer<PasteInsertDialog> dialog= new PasteInsertDialog(canvas()->canvasWidget(), selection());
        dialog->exec();
        delete dialog;
    }
    d->updateEditor(Cell(selection()->activeSheet(), selection()->cursor()));
}

void CellToolBase::deleteSelection()
{
    clearContents();
}

void CellToolBase::selectAll()
{
    selection()->selectAll();
}

void CellToolBase::find()
{
    QPointer<FindDlg> dialog = new FindDlg(canvas()->canvasWidget(), "Find", d->findOptions, d->findStrings);
    dialog->setHasSelection(!selection()->isSingular());
    dialog->setHasCursor(true);
    if (KFindDialog::Accepted != dialog->exec())
        return;

    // Save for next time
    d->findOptions = dialog->options();
    d->findStrings = dialog->findHistory();
    d->typeValue = dialog->searchType();
    d->directionValue = dialog->searchDirection();

    // Create the KFind object
    delete d->find;
    delete d->replace;
    d->find = new KFind(dialog->pattern(), dialog->options(), canvas()->canvasWidget());
    d->replace = 0;
    d->replaceCommand = 0;

    d->searchInSheets.currentSheet = selection()->activeSheet();
    d->searchInSheets.firstSheet = d->searchInSheets.currentSheet;

    initFindReplace();
    findNext();
    delete dialog;
}

// Initialize a find or replace operation, using d->find or d->replace,
// and d->findOptions.
void CellToolBase::initFindReplace()
{
    KFind* findObj = d->find ? d->find : d->replace;
    Q_ASSERT(findObj);
    connect(findObj, SIGNAL(highlight(const QString &, int, int)),
            this, SLOT(slotHighlight(const QString &, int, int)));
    connect(findObj, SIGNAL(findNext()),
            this, SLOT(findNext()));

    bool bck = d->findOptions & KFind::FindBackwards;
    Sheet* currentSheet = d->searchInSheets.currentSheet;

    QRect region = (d->findOptions & KFind::SelectedText)
                   ? selection()->lastRange()
                   : QRect(1, 1, currentSheet->cellStorage()->columns(), currentSheet->cellStorage()->rows()); // All cells

    int colStart = !bck ? region.left() : region.right();
    int colEnd = !bck ? region.right() : region.left();
    int rowStart = !bck ? region.top() : region.bottom();
    int rowEnd = !bck ? region.bottom() : region.top();

    d->findLeftColumn = region.left();
    d->findRightColumn = region.right();
    d->findTopRow = region.top();
    d->findBottomRow = region.bottom();

    d->findStart = QPoint(colStart, rowStart);
    d->findPos = (d->findOptions & KFind::FromCursor) ? selection()->marker() : d->findStart;
    d->findEnd = QPoint(colEnd, rowEnd);
    //kDebug() << d->findPos <<" to" << d->findEnd;
    //kDebug() <<"leftcol=" << d->findLeftColumn <<" rightcol=" << d->findRightColumn;
}

void CellToolBase::findNext()
{
    KFind* findObj = d->find ? d->find : d->replace;
    if (!findObj)  {
        find();
        return;
    }
    KFind::Result res = KFind::NoMatch;
    Cell cell = findNextCell();
    bool forw = !(d->findOptions & KFind::FindBackwards);
    while (res == KFind::NoMatch && !cell.isNull()) {
        if (findObj->needData()) {
            if (d->typeValue == FindOption::Note)
                findObj->setData(cell.comment());
            else
                findObj->setData(cell.userInput());
            d->findPos = QPoint(cell.column(), cell.row());
            //kDebug() <<"setData(cell" << d->findPos << ')';
        }

        // Let KFind inspect the text fragment, and display a dialog if a match is found
        if (d->find)
            res = d->find->find();
        else
            res = d->replace->replace();

        if (res == KFind::NoMatch)  {
            // Go to next cell, skipping unwanted cells
            if (d->directionValue == FindOption::Row) {
                if (forw)
                    ++d->findPos.rx();
                else
                    --d->findPos.rx();
            } else {
                if (forw)
                    ++d->findPos.ry();
                else
                    --d->findPos.ry();
            }
            cell = findNextCell();
        }
    }

    if (res == KFind::NoMatch) {
        //emitUndoRedo();
        //removeHighlight();
        if (findObj->shouldRestart()) {
            d->findOptions &= ~KFind::FromCursor;
            d->findPos = d->findStart;
            findObj->resetCounts();
            findNext();
        } else { // done, close the 'find next' dialog
            if (d->find)
                d->find->closeFindNextDialog();
            else {
                canvas()->addCommand(d->replaceCommand);
                d->replaceCommand = 0;
                d->replace->closeReplaceNextDialog();
            }
        }
    }
    else if (!cell.isNull()) {
        // move to the cell
        if (cell.sheet() != selection()->activeSheet())
            selection()->emitVisibleSheetRequested(cell.sheet());
        selection()->initialize (Region (cell.column(), cell.row(), cell.sheet()), cell.sheet());
        scrollToCell (selection()->cursor());
    }
}

Cell CellToolBase::nextFindValidCell(int col, int row)
{
    Cell cell = Cell(d->searchInSheets.currentSheet, col, row);
    if (cell.isDefault() || cell.isPartOfMerged() || cell.isFormula())
        cell = Cell();
    if (d->typeValue == FindOption::Note && !cell.isNull() && cell.comment().isEmpty())
        cell = Cell();
    return cell;
}

Cell CellToolBase::findNextCell()
{
    // cellStorage()->firstInRow / cellStorage()->nextInRow would be faster at doing that,
    // but it doesn't seem to be easy to combine it with 'start a column d->find.x()'...

    Sheet* sheet = d->searchInSheets.currentSheet;
    Cell cell;
    bool forw = !(d->findOptions & KFind::FindBackwards);
    int col = d->findPos.x();
    int row = d->findPos.y();
    int maxRow = sheet->cellStorage()->rows();
    // kDebug() <<"findNextCell starting at" << col << ',' << row <<"   forw=" << forw;

    if (d->directionValue == FindOption::Row) {
        while (!cell && row != d->findEnd.y() && (forw ? row < maxRow : row >= 0)) {
            while (!cell && (forw ? col <= d->findRightColumn : col >= d->findLeftColumn)) {
                cell = nextFindValidCell(col, row);
                if (forw) ++col;
                else --col;
            }
            if (!cell.isNull())
                break;
            // Prepare looking in the next row
            if (forw)  {
                col = d->findLeftColumn;
                ++row;
            } else {
                col = d->findRightColumn;
                --row;
            }
            //kDebug() <<"next row:" << col << ',' << row;
        }
    } else {
        while (!cell && (forw ? col <= d->findRightColumn : col >= d->findLeftColumn)) {
            while (!cell && row != d->findEnd.y() && (forw ? row < maxRow : row >= 0)) {
                cell = nextFindValidCell(col, row);
                if (forw) ++row;
                else --row;
            }
            if (!cell.isNull())
                break;
            // Prepare looking in the next col
            if (forw)  {
                row = d->findTopRow;
                ++col;
            } else {
                row = d->findBottomRow;
                --col;
            }
            //kDebug() <<"next row:" << col << ',' << row;
        }
    }
    // if (!cell)
    // No more next cell - TODO go to next sheet (if not looking in a selection)
    // (and make d->findEnd(max, max) in that case...)
    // kDebug() <<" returning" << cell;
    return cell;
}

void CellToolBase::findPrevious()
{
    KFind* findObj = d->find ? d->find : d->replace;
    if (!findObj)  {
        find();
        return;
    }
    //kDebug() <<"findPrevious";
    int opt = d->findOptions;
    bool forw = !(opt & KFind::FindBackwards);
    if (forw)
        d->findOptions = (opt | KFind::FindBackwards);
    else
        d->findOptions = (opt & ~KFind::FindBackwards);

    findNext();

    d->findOptions = opt; // restore initial options
}

void CellToolBase::replace()
{
    QPointer<SearchDlg> dialog = new SearchDlg(canvas()->canvasWidget(), "Replace", d->findOptions, d->findStrings, d->replaceStrings);
    dialog->setHasSelection(!selection()->isSingular());
    dialog->setHasCursor(true);
    if (KReplaceDialog::Accepted != dialog->exec())
        return;

    d->findOptions = dialog->options();
    d->findStrings = dialog->findHistory();
    d->replaceStrings = dialog->replacementHistory();
    d->typeValue = dialog->searchType();

    delete d->find;
    delete d->replace;
    d->find = 0;
    // NOTE Stefan: Avoid beginning of line replacements with nothing which
    //              will lead to an infinite loop (Bug #125535). The reason
    //              for this is unclear to me, but who cares and who would
    //              want to do something like this, häh?!
    if (dialog->pattern() == "^" && dialog->replacement().isEmpty())
        return;
    d->replace = new KReplace(dialog->pattern(), dialog->replacement(), dialog->options());

    d->searchInSheets.currentSheet = selection()->activeSheet();
    d->searchInSheets.firstSheet = d->searchInSheets.currentSheet;
    initFindReplace();
    connect(d->replace, SIGNAL(replace(const QString &, int, int, int)),
            this, SLOT(slotReplace(const QString &, int, int, int)));

    d->replaceCommand = new KUndo2Command(i18nc("(qtundo-format)", "Replace"));

    findNext();
    delete dialog;

#if 0
    // Refresh the editWidget
    // TODO - after a replacement only?
    Cell cell = Cell(activeSheet(), selection()->marker());
    if (cell.userInput() != 0)
        d->editWidget->setText(cell.userInput());
    else
        d->editWidget->setText("");
#endif
}

void CellToolBase::slotHighlight(const QString &/*text*/, int /*matchingIndex*/, int /*matchedLength*/)
{
    selection()->initialize(d->findPos);
    KDialog *dialog = 0;
    if (d->find)
        dialog = d->find->findNextDialog();
    else
        dialog = d->replace->replaceNextDialog();
    kDebug() << " baseDialog :" << dialog;
    QRect globalRect(d->findPos, d->findEnd);
    globalRect.moveTopLeft(canvas()->canvasWidget()->mapToGlobal(globalRect.topLeft()));
    KDialog::avoidArea(dialog, QRect(d->findPos, d->findEnd));
}

void CellToolBase::slotReplace(const QString &newText, int, int, int)
{
    if (d->typeValue == FindOption::Value) {
        DataManipulator* command = new DataManipulator(d->replaceCommand);
        command->setParsing(true);
        command->setSheet(d->searchInSheets.currentSheet);
        command->setValue(Value(newText));
        command->add(Region(d->findPos, d->searchInSheets.currentSheet));
    } else if (d->typeValue == FindOption::Note) {
        CommentCommand* command = new CommentCommand(d->replaceCommand);
        command->setComment(newText);
        command->setSheet(d->searchInSheets.currentSheet);
        command->add(Region(d->findPos, d->searchInSheets.currentSheet));
    }
}

void CellToolBase::gotoCell()
{
    QPointer<GotoDialog> dialog = new GotoDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
    scrollToCell(selection()->cursor());
}

void CellToolBase::spellCheck()
{
    SpellCheckCommand* command = new SpellCheckCommand(*selection(), canvas());
    command->start();
}

void CellToolBase::inspector()
{
    // useful to inspect objects
    Cell cell(selection()->activeSheet(), selection()->marker());
    QPointer<Calligra::Sheets::Inspector> ins = new Calligra::Sheets::Inspector(cell);
    ins->exec();
    delete ins;
}

void CellToolBase::qTableView()
{
#ifndef NDEBUG
    QPointer<KDialog> dialog = new KDialog(canvas()->canvasWidget());
    QTableView* const view = new QTableView(dialog);
    SheetModel* const model = new SheetModel(selection()->activeSheet());
    view->setModel(model);
    dialog->setCaption("Read{Only,Write}TableModel Test");
    dialog->setMainWidget(view);
    dialog->exec();
    delete dialog;
    delete model;
#endif
}

void CellToolBase::sheetFormat()
{
    QPointer<AutoFormatDialog> dialog = new AutoFormatDialog(canvas()->canvasWidget(), selection());
    dialog->exec();
    delete dialog;
}

void CellToolBase::listChoosePopupMenu()
{
    if (!selection()->activeSheet()->map()->isReadWrite()) {
        return;
    }

    delete d->popupListChoose;
    d->popupListChoose = new QMenu();

    const Sheet *const sheet = selection()->activeSheet();
    const Cell cursorCell(sheet, selection()->cursor());
    const QString text = cursorCell.userInput();
    const CellStorage *const storage = sheet->cellStorage();

    QStringList itemList;
    const Region::ConstIterator end(selection()->constEnd());
    for (Region::ConstIterator it(selection()->constBegin()); it != end; ++it) {
        const QRect range = (*it)->rect();
        if (cursorCell.column() < range.left() || cursorCell.column() > range.right()) {
            continue; // next range
        }
        Cell cell;
        if (range.top() == 1) {
            cell = storage->firstInColumn(cursorCell.column(), CellStorage::Values);
        } else {
            cell = storage->nextInColumn(cursorCell.column(), range.top() - 1, CellStorage::Values);
        }
        while (!cell.isNull() && cell.row() <= range.bottom()) {
            if (!cell.isPartOfMerged() && !(cell == cursorCell)) {
                const QString userInput = cell.userInput();
                if (cell.value().isString() && userInput != text && !userInput.isEmpty()) {
                    if (itemList.indexOf(userInput) == -1) {
                        itemList.append(userInput);
                    }
                }
            }
            cell = storage->nextInColumn(cell.column(), cell.row(), CellStorage::Values);
        }
    }

    for (QStringList::Iterator it = itemList.begin(); it != itemList.end(); ++it) {
        d->popupListChoose->addAction((*it));
    }

    if (itemList.isEmpty()) {
        return;
    }
    double tx = sheet->columnPosition(selection()->marker().x());
    double ty = sheet->rowPosition(selection()->marker().y());
    double h = cursorCell.height();
    if (sheetView(sheet)->obscuresCells(selection()->marker())) {
        const CellView& cellView = sheetView(sheet)->cellView(selection()->marker().x(), selection()->marker().y());
        h = cellView.cellHeight();
    }
    ty += h;

    if (selection()->activeSheet()->layoutDirection() == Qt::RightToLeft) {
        tx = canvas()->canvasWidget()->width() - tx;
    }

    QPoint p((int)tx, (int)ty);
    QPoint p2 = canvas()->canvasWidget()->mapToGlobal(p);

    if (selection()->activeSheet()->layoutDirection() == Qt::RightToLeft) {
        p2.setX(p2.x() - d->popupListChoose->sizeHint().width() + 1);
    }

    d->popupListChoose->popup(p2);
    connect(d->popupListChoose, SIGNAL(triggered(QAction*)),
            this, SLOT(listChooseItemSelected(QAction*)));
}


void CellToolBase::listChooseItemSelected(QAction* action)
{
    const Cell cell(selection()->activeSheet(), selection()->marker());
    if (action->text() == cell.userInput())
        return;

    DataManipulator *command = new DataManipulator;
    command->setSheet(selection()->activeSheet());
    command->setValue(Value(action->text()));
    command->setParsing(true);
    command->add(selection()->marker());
    command->execute(canvas());
}

void CellToolBase::documentSettingsDialog()
{
    QPointer<DocumentSettingsDialog> dialog = new DocumentSettingsDialog(selection(), canvas()->canvasWidget());
    dialog->exec();
    delete dialog;
}

void CellToolBase::breakBeforeColumn(bool enable)
{
    PageBreakCommand *command = new PageBreakCommand();
    command->setSheet(selection()->activeSheet());
    command->setMode(PageBreakCommand::BreakBeforeColumn);
    command->setReverse(!enable);
    command->add(*selection());
    command->execute(canvas());
}

void CellToolBase::breakBeforeRow(bool enable)
{
    PageBreakCommand *command = new PageBreakCommand();
    command->setSheet(selection()->activeSheet());
    command->setMode(PageBreakCommand::BreakBeforeRow);
    command->setReverse(!enable);
    command->add(*selection());
    command->execute(canvas());
}