summaryrefslogtreecommitdiffstats
path: root/kspread/kspread_canvas.cc
blob: 3f482e273941267b36d2501c6aed76bce1947ae3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
/* This file is part of the KDE project

   Copyright 2006 Robert Knight <robertknight@gmail.com>
   Copyright 2006 Inge Wallin <inge@lysator.liu.se>
   Copyright 2006 Stefan Nikolaus <stefan.nikolaus@kdemail.net>
   Copyright 1999-2002,2004 Laurent Montel <montel@kde.org>
   Copyright 2002-2005 Ariya Hidayat <ariya@kde.org>
   Copyright 1999-2004 David Faure <faure@kde.org>
   Copyright 2004-2005 Meni Livne <livne@kde.org>
   Copyright 2001-2003 Philipp Mueller <philipp.mueller@gmx.de>
   Copyright 2002-2003 Norbert Andres <nandres@web.de>
   Copyright 2003 Hamish Rodda <rodda@kde.org>
   Copyright 2003 Joseph Wenninger <jowenn@kde.org>
   Copyright 2003 Lukas Tinkl <lukas@kde.org>
   Copyright 2000-2002 Werner Trobin <trobin@kde.org>
   Copyright 2002 Harri Porten <porten@kde.org>
   Copyright 2002 John Dailey <dailey@vt.edu>
   Copyright 2002 Daniel Naber <daniel.naber@t-online.de>
   Copyright 1999-2000 Torben Weis <weis@kde.org>
   Copyright 1999-2000 Stephan Kulow <coolo@kde.org>
   Copyright 2000 Bernd Wuebben <wuebben@kde.org>
   Copyright 2000 Wilco Greven <greven@kde.org>
   Copyright 2000 Simon Hausmann <hausmann@kde.org
   Copyright 1999 Michael Reiher <michael.reiher.gmx.de>
   Copyright 1999 Boris Wedl <boris.wedl@kfunigraz.ac.at>
   Copyright 1999 Reginald Stadlbauer <reggie@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 <assert.h>
#include <float.h>
#include <stdlib.h>

#include <tqapplication.h>
#include <tqbuffer.h>
#include <tqclipboard.h>
#include <tqdrawutil.h>
#include <tqlabel.h>
#include <tqpoint.h>
#include <tqscrollbar.h>
#include <tqtimer.h>
#include <tqtooltip.h>
#include <tqwidgetlist.h>

#include <kcursor.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kmultipledrag.h>
#include <krun.h>
#include <kmimetype.h>
#include <ksharedptr.h>
#include <kwordwrap.h>

#include <KoOasisStore.h>
#include <KoSpeaker.h>
#include <KoStore.h>
#include <KoStoreDrag.h>
#include <KoXmlWriter.h>
#include <KoDocumentChild.h>
#include <KoRect.h>

#include "commands.h"
#include "kspread_doc.h"
#include "kspread_editors.h"
#include "kspread_global.h"
#include "kspread_locale.h"
#include "kspread_map.h"
#include "kspread_sheet.h"
#include "kspread_undo.h"
#include "kspread_util.h"
#include "kspread_view.h"
#include "selection.h"

#include "kspread_canvas.h"

// TODO Stefan: undefine/remove, if non-contiguous selections don't work
//              properly or if we are sure, that they do. ;-)
#define NONCONTIGUOUSSELECTION

#define MIN_SIZE 10

using namespace KSpread;

class Canvas::Private
{
  public:
    ComboboxLocationEditWidget *posWidget;
    KSpread::EditWidget *editWidget;
    KSpread::CellEditor *cellEditor;

    View *view;
    TQTimer* scrollTimer;

    // Non visible range left from current screen
    // Example: If the first visible column is 'E', then xOffset stores
    // the width of the invisible columns 'A' to 'D'.
    double xOffset;

    // Non visible range on top of the current screen
    // Example: If the first visible row is '5', then yOffset stores
    // the height of the invisible rows '1' to '4'.
    double yOffset;

    // Used to draw the grey grid that is usually only visible on the
    // screen, but not by printing on paper.
    TQPen defaultGridPen;

    // see setLastEditorWithFocus, lastEditorWithFocus
    Canvas::EditorType focusEditorType;

    TQLabel *validationInfo;

    // true if the user is to choose a cell.
    bool chooseCell;

    // True when the mouse button is pressed
    bool mousePressed;

    // If the user is dragging around with the mouse then this tells us what he is doing.
    // The user may want to mark cells or he started in the lower right corner
    // of the marker which is something special. The values for the 2 above
    // methods are called 'Mark' and 'ResizeCell' or 'AutoFill' depending
    // on the mouse button used. By default this variable holds
    // the value 'NoAction'.
    Canvas::MouseActions mouseAction;

    // If we use the lower right corner of the marker to start autofilling, then this
    // rectangle conatins all cells that were already marker when the user started
    // to mark the rectangle which he wants to become autofilled.
    TQRect autoFillSource;

    // Start coordinates for drag and drop
    TQPoint dragStart;
    bool dragging;

    // Used to indicate whether the user started drawing a rubber band rectangle
    bool rubberBandStarted;
    TQPoint rubberBandStart;
    TQPoint rubberBandEnd;

    // If the mouse is over some anchor ( in the sense of HTML anchors )
    TQString anchor;

    bool mouseSelectedObject;
    bool drawContour;
    ModifyType modType;
    /**
     * Saves the last mouse position during mouse move events.
     */
    TQPoint m_savedMousePos;

    //---- stuff needed for resizing ----
    /// object which gets resized
    EmbeddedObject *m_resizeObject;
    /// ratio of the object ( width / height )
    double m_ratio;
    bool m_isResizing;
    /// The last position of the mouse during moving
    KoPoint m_origMousePos;

    //---- stuff needed for moving ----
    bool m_isMoving;
    KoPoint m_moveStartPoint;

    /// size of the object at when resizing is started
    KoRect m_rectBeforeResize;
    /// Start position for move with mouse
    KoPoint m_moveStartPosMouse;

    /// object which is selected and should be shown above all the other objects
    EmbeddedObject * m_objectDisplayAbove;

   // bool mouseOverHighlightRangeSizeGrip;

    // The row and column of 1) the last cell under mouse pointer, 2) the last focused cell, and
    // the last spoken cell.
    int prevSpokenPointerRow;
    int prevSpokenPointerCol;
    int prevSpokenFocusRow;
    int prevSpokenFocusCol;
    int prevSpokenRow;
    int prevSpokenCol;
};



/****************************************************************
 *
 * Canvas
 *
 ****************************************************************/

Canvas::Canvas (View *_view)
  : TQWidget( _view, "", /*WNorthWestGravity*/ WStaticContents| WResizeNoErase | WRepaintNoErase )
{
  d = new Private;

  d->cellEditor = 0;
  d->chooseCell = false;
  d->validationInfo = 0L;

  TQWidget::setFocusPolicy( TQ_StrongFocus );

  d->dragStart = TQPoint( -1, -1 );
  d->dragging = false;


  d->defaultGridPen.setColor( lightGray );
  d->defaultGridPen.setWidth( 1 );
  d->defaultGridPen.setStyle( Qt::SolidLine );

  d->xOffset = 0.0;
  d->yOffset = 0.0;
  d->view = _view;
  // m_eAction = DefaultAction;
  d->mouseAction = NoAction;
  d->rubberBandStarted = false;
  // m_bEditDirtyFlag = false;

  //Now built afterwards(David)
  //d->editWidget = d->view->editWidget();
  d->posWidget = d->view->posWidget();

  setBackgroundMode( PaletteBase );

  setMouseTracking( true );
  d->mousePressed = false;
  d->mouseSelectedObject = false;
  d->drawContour = false;
  d->modType = MT_NONE;

  d->m_resizeObject = 0L;
  d->m_ratio = 0.0;
  d->m_isMoving = false;
  d->m_objectDisplayAbove = false;
  d->m_isResizing = false;

  d->prevSpokenPointerRow = -1;
  d->prevSpokenPointerCol = -1;
  d->prevSpokenFocusRow = -1;
  d->prevSpokenFocusCol = -1;
  d->prevSpokenRow = -1;
  d->prevSpokenCol = -1;

  d->scrollTimer = new TQTimer( this );
  connect (d->scrollTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( doAutoScroll() ) );

  if( d->view)
  {
    connect( d->view, TQT_SIGNAL( autoScroll( const TQPoint & )), this, TQT_SLOT( slotAutoScroll( const TQPoint &)));
  }
  if (kospeaker)
  {
    connect (kospeaker, TQT_SIGNAL(customSpeakWidget(TQWidget*, const TQPoint&, uint)),
      this, TQT_SLOT(speakCell(TQWidget*, const TQPoint&, uint)));
  }

  setFocus();
  installEventFilter( this );
  (void)new ToolTip( this );
  setAcceptDrops( true );
  setInputMethodEnabled( true ); // ensure using the InputMethod

  setWFlags(TQt::WNoAutoErase);
}

Canvas::~Canvas()
{
  delete d->scrollTimer;
  delete d->validationInfo;
  delete d;
}

KSpread::View* Canvas::view() const
{
  return d->view;
}

Doc* Canvas::doc() const
{
  return d->view->doc();
}

void Canvas::setEditWidget( KSpread::EditWidget * ew )
{
  d->editWidget = ew;
}

KSpread::EditWidget* Canvas::editWidget() const
{
  return d->editWidget;
}

CellEditor* Canvas::editor() const
{
  return d->cellEditor;
}

double Canvas::xOffset() const
{
  return d->xOffset;
}

double Canvas::yOffset() const
{
  return d->yOffset;
}

void Canvas::setXOffset( double _xOffset )
{
  d->xOffset = _xOffset;
}

void Canvas::setYOffset( double _yOffset )
{
  d->yOffset = _yOffset;
}

const TQPen& Canvas::defaultGridPen() const
{
  return d->defaultGridPen;
}

void Canvas::setLastEditorWithFocus( Canvas::EditorType type )
{
  d->focusEditorType = type;
}

Canvas::EditorType Canvas::lastEditorWithFocus() const
{
  return d->focusEditorType;
}


bool Canvas::eventFilter( TQObject *o, TQEvent *e )
{
  /* this canvas event filter acts on events sent to the line edit as well
     as events to this filter itself.
  */
  if ( !o || !e )
    return true;
  switch ( e->type() )
  {
  case TQEvent::KeyPress:
  {
    TQKeyEvent * keyev = TQT_TQKEYEVENT(e);
    if ((keyev->key()==Key_Tab) || (keyev->key()==Key_Backtab))
    {
      keyPressEvent ( keyev );
      return true;
    }
    break;
  }
  case TQEvent::IMStart:
  case TQEvent::IMCompose:
  case TQEvent::IMEnd:
  {
      TQIMEvent * imev = static_cast<TQIMEvent *>(e);
      processIMEvent( imev );
      break;
  }
  default:
    break;
  }
  return false;
}

bool Canvas::focusNextPrevChild( bool )
{
    return true; // Don't allow to go out of the canvas widget by pressing "Tab"
}

Selection* Canvas::selectionInfo() const
{
  return d->view->selectionInfo();
}

Selection* Canvas::choice() const
{
  return d->view->choice();
}

TQRect Canvas::selection() const
{
  return d->view->selectionInfo()->selection();
}

TQPoint Canvas::marker() const
{
    return d->view->selectionInfo()->marker();
}

int Canvas::markerColumn() const
{
    return d->view->selectionInfo()->marker().x();
}

int Canvas::markerRow() const
{
    return d->view->selectionInfo()->marker().y();
}

double Canvas::zoom() const
{
  return d->view->zoom();
}

void Canvas::setChooseMode(bool state)
{
  d->chooseCell = state;
}

bool Canvas::chooseMode() const
{
  return d->chooseCell;
}

void Canvas::startChoose()
{
  if ( d->chooseCell )
    return;

  choice()->clear();
  choice()->setSheet(activeSheet());

  // It is important to enable this AFTER we set the rect!
  d->chooseCell = true;
}

void Canvas::startChoose( const TQRect& rect )
{
  if (d->chooseCell)
    return;

  choice()->setSheet(activeSheet());
  choice()->initialize(rect);

  // It is important to enable this AFTER we set the rect!
  d->chooseCell = true;
}

void Canvas::endChoose()
{
  // While entering a formula the choose mode is turned on and off.
  // Clear the choice even if we are not in choose mode. Otherwise,
  // cell references will stay highlighted.
  if (!choice()->isEmpty())
  {
    choice()->clear();
    update();
  }

  if ( !d->chooseCell )
    return;

  d->chooseCell = false;

  Sheet *sheet = choice()->sheet();
  if (sheet)
  {
    d->view->setActiveSheet(sheet);
  }
}

HBorder* Canvas::hBorderWidget() const
{
  return d->view->hBorderWidget();
}

VBorder* Canvas::vBorderWidget() const
{
  return d->view->vBorderWidget();
}

TQScrollBar* Canvas::horzScrollBar() const
{
  return d->view->horzScrollBar();
}

TQScrollBar* Canvas::vertScrollBar() const
{
  return d->view->vertScrollBar();
}

Sheet* Canvas::findSheet( const TQString& _name ) const
{
  return d->view->doc()->map()->findSheet( _name );
}

Sheet* Canvas::activeSheet() const
{
  return d->view->activeSheet();
}

void Canvas::validateSelection()
{
  Sheet* sheet = activeSheet();
  if (!sheet)
  {
    return;
  }

    if ( selectionInfo()->isSingular() )
    {
        int col = selectionInfo()->marker().x();
        int row = selectionInfo()->marker().y();
        Cell * cell = sheet->cellAt( col,row );
        if ( cell && cell->getValidity(0) && cell->getValidity()->displayValidationInformation)
        {
            TQString title = cell->getValidity(0)->titleInfo;
            TQString message = cell->getValidity(0)->messageInfo;
            if ( title.isEmpty() && message.isEmpty() )
                return;

            if ( !d->validationInfo )
                d->validationInfo = new TQLabel(  this );
            kdDebug()<<" display info validation\n";
            double u = cell->dblWidth( col );
            double v = cell->dblHeight( row );
            double xpos = sheet->dblColumnPos( markerColumn() ) - xOffset();
            double ypos = sheet->dblRowPos( markerRow() ) - yOffset();
            // Special treatment for obscured cells.
            if ( cell->isObscured() && cell->isPartOfMerged() )
            {
                cell = cell->obscuringCells().first();
                int moveX = cell->column();
                int moveY = cell->row();

                // Use the obscuring cells dimensions
                u = cell->dblWidth( moveX );
                v = cell->dblHeight( moveY );
                xpos = sheet->dblColumnPos( moveX );
                ypos = sheet->dblRowPos( moveY );
            }
            //d->validationInfo->setGeometry( 3, y + 3, len + 2, hei + 2 );
            d->validationInfo->tqsetAlignment( TQt::AlignVCenter );
            TQPainter painter;
            painter.begin( this );
            int len = 0;
            int hei = 0;
            TQString resultText;
            if ( !title.isEmpty() )
            {
                len = painter.fontMetrics().width( title );
                hei = painter.fontMetrics().height();
                resultText = title + "\n";
            }
            if ( !message.isEmpty() )
            {
                int i = 0;
                int pos = 0;
                TQString t;
                do
                {
                    i = message.find( "\n", pos );
                    if ( i == -1 )
                        t = message.mid( pos, message.length() - pos );
                    else
                    {
                        t = message.mid( pos, i - pos );
                        pos = i + 1;
                    }
                    hei += painter.fontMetrics().height();
                    len = TQMAX( len, painter.fontMetrics().width( t ) );
                }
                while ( i != -1 );
                resultText += message;
            }
            painter.end();
            d->validationInfo->setText( resultText );

            KoRect unzoomedMarker( xpos - xOffset()+u,
                                   ypos - yOffset()+v,
                                   len,
                                   hei );
            TQRect marker( d->view->doc()->zoomRect( unzoomedMarker ) );

            d->validationInfo->setGeometry( marker );
            d->validationInfo->show();
        }
        else
        {
            delete d->validationInfo;
            d->validationInfo = 0L;
        }
    }
    else
    {
        delete d->validationInfo;
        d->validationInfo = 0L;
    }
}


void Canvas::scrollToCell(TQPoint location) const
{
  Sheet* sheet = activeSheet();
  if (sheet == NULL)
    return;

  if (d->view->isLoading())
    return;

 // kdDebug(36001) << "------------------------------------------------" << endl;
 // kdDebug(36001) << "scrollToCell(): at location [" << location.x() << ","
 // 		 << location.y() << "]" << endl;

  /* we don't need this cell ptr, but this call is necessary to update the
     scroll bar correctly.  I don't like having that as part of the cellAt function
     but I suppose that's ok for now.
  */
  Cell* cell = sheet->cellAt(location.x(), location.y(), true);
  Q_UNUSED(cell);

  double  unzoomedWidth  = d->view->doc()->unzoomItX( width() );
  double  unzoomedHeight = d->view->doc()->unzoomItY( height() );

  //kdDebug(36001) << "Unzoomed view size: [" << unzoomedWidth << ","
 //		 << unzoomedHeight << "]" << endl;

  // xpos is the position of the cell in the current window in unzoomed
  // document coordinates.
  double xpos;
  if ( sheet->layoutDirection()==Sheet::LeftToRight )
    xpos = sheet->dblColumnPos( location.x() ) - xOffset();
  else
    xpos = unzoomedWidth - sheet->dblColumnPos( location.x() ) + xOffset();
  double ypos = sheet->dblRowPos( location.y() ) - yOffset();

  //kdDebug(36001) << "Position: [" << xpos << "," << ypos << "]" << endl;

  double minY = 40.0;
  double maxY = unzoomedHeight - 40.0;
  //kdDebug(36001) << "Canvas::scrollToCell : height=" << height() << endl;
  //kdDebug(36001) << "Canvas::scrollToCell : width=" << width() << endl;

  if ( sheet->layoutDirection()==Sheet::RightToLeft ) {
    // Right to left sheet.

    double minX = unzoomedWidth - 100.0; // less than that, we scroll
    double maxX = 100.0; // more than that, we scroll

    // kdDebug() << "rtl2: XPos: " << xpos << ", min: " << minX << ", maxX: " << maxX << ", Offset: " << xOffset() << endl;

    // Do we need to scroll left?
    if ( xpos > minX )
      horzScrollBar()->setValue( horzScrollBar()->maxValue() -
                                  d->view->doc()->zoomItX( xOffset() - xpos + minX ) );

    // Do we need to scroll right?
    else if ( xpos < maxX )
    {
      double horzScrollBarValue = xOffset() - xpos + maxX;
      double horzScrollBarValueMax = sheet->sizeMaxX() - unzoomedWidth;

      //We don't want to display any area > KS_colMax widths
      if ( horzScrollBarValue > horzScrollBarValueMax )
        horzScrollBarValue = horzScrollBarValueMax;

      horzScrollBar()->setValue( horzScrollBar()->maxValue() -
                                  d->view->doc()->zoomItX( horzScrollBarValue ) );
    }
  }
  else {
    // Left to right sheet.

    double minX = 100.0; // less than that, we scroll
    double maxX = unzoomedWidth - 100.0; // more than that, we scroll

   // kdDebug() << "ltr: XPos: " << xpos << ", min: " << minX << ", maxX: " << maxX << endl;

    // Do we need to scroll left?
    if ( xpos < minX )
      horzScrollBar()->setValue( d->view->doc()->zoomItX( xOffset() + xpos - minX ) );

    // Do we need to scroll right?
    else if ( xpos > maxX )
    {
      double horzScrollBarValue = xOffset() + xpos - maxX;
      double horzScrollBarValueMax = sheet->sizeMaxX() - unzoomedWidth;

      //We don't want to display any area > KS_colMax widths
      if ( horzScrollBarValue > horzScrollBarValueMax )
        horzScrollBarValue = horzScrollBarValueMax;

      horzScrollBar()->setValue( d->view->doc()->zoomItX( horzScrollBarValue ) );
    }
  }
//   kdDebug() << "ltr: YPos: " << ypos << ", min: " << minY << ", maxY: " << maxY << endl;

  // do we need to scroll up
  if ( ypos < minY )
    vertScrollBar()->setValue( d->view->doc()->zoomItY( yOffset() + ypos - minY ) );

  // do we need to scroll down
  else if ( ypos > maxY )
  {
    double vertScrollBarValue = yOffset() + ypos - maxY;
    double vertScrollBarValueMax = sheet->sizeMaxY() - unzoomedHeight;

    //We don't want to display any area > KS_rowMax heights
    if ( vertScrollBarValue > vertScrollBarValueMax )
      vertScrollBarValue = vertScrollBarValueMax;

    vertScrollBar()->setValue( d->view->doc()->zoomItY( vertScrollBarValue ) );
  }
}

void Canvas::slotScrollHorz( int _value )
{
  Sheet * sheet = activeSheet();

  if ( sheet == 0L )
    return;

  kdDebug(36001) << "slotScrollHorz: value = " << _value << endl;
  //kdDebug(36001) << kdBacktrace() << endl;

  if ( sheet->layoutDirection()==Sheet::RightToLeft )
    _value = horzScrollBar()->maxValue() - _value;

  double unzoomedValue = d->view->doc()->unzoomItX( _value );
  double dwidth = d->view->doc()->unzoomItX( width() );

  d->view->doc()->emitBeginOperation(false);

  if ( unzoomedValue < 0.0 ) {
    kdDebug (36001)
      << "Canvas::slotScrollHorz: value out of range (unzoomedValue: "
      << unzoomedValue << ")" << endl;
    unzoomedValue = 0.0;
  }

  double xpos = sheet->dblColumnPos( TQMIN( KS_colMax, d->view->activeSheet()->maxColumn()+10 ) ) - d->xOffset;
  if ( unzoomedValue > ( xpos + d->xOffset ) )
    unzoomedValue = xpos + d->xOffset;

  sheet->enableScrollBarUpdates( false );

  // Relative movement
  int dx = d->view->doc()->zoomItX( d->xOffset - unzoomedValue );


  /* what cells will need painted now? */
  TQRect area = visibleCells();
  double tmp;
  if (dx > 0)
  {
    area.setRight( area.left() );
    area.setLeft( sheet->leftColumn( unzoomedValue, tmp ) );
  }
  else
  {
    area.setLeft( area.right() );
    area.setRight( sheet->rightColumn( dwidth  + unzoomedValue ) );
  }

  sheet->setRegionPaintDirty(area);

  // New absolute position
  kdDebug(36001) << "slotScrollHorz(): XOffset before setting: "
		 << d->xOffset << endl;
  d->xOffset = unzoomedValue;
  kdDebug(36001) << "slotScrollHorz(): XOffset after setting: "
		 << d->xOffset << endl;

  if ( sheet->layoutDirection()==Sheet::RightToLeft )
    dx = -dx;

  scroll( dx, 0 );

  hBorderWidget()->scroll( dx, 0 );

  sheet->enableScrollBarUpdates( true );

  d->view->doc()->emitEndOperation( sheet->visibleRect( this ) );
}

void Canvas::slotScrollVert( int _value )
{
  if ( activeSheet() == 0L )
    return;

  d->view->doc()->emitBeginOperation(false);
  double unzoomedValue = d->view->doc()->unzoomItY( _value );

  if ( unzoomedValue < 0 )
  {
    unzoomedValue = 0;
    kdDebug (36001) << "Canvas::slotScrollVert: value out of range (unzoomedValue: " <<
                       unzoomedValue << ")" << endl;
  }

  double ypos = activeSheet()->dblRowPos( TQMIN( KS_rowMax, d->view->activeSheet()->maxRow()+10 ) );
  if ( unzoomedValue > ypos )
      unzoomedValue = ypos;

  activeSheet()->enableScrollBarUpdates( false );

  // Relative movement
  int dy = d->view->doc()->zoomItY( d->yOffset - unzoomedValue );


  /* what cells will need painted now? */
  TQRect area = visibleCells();
  double tmp;
  if (dy > 0)
  {
    area.setBottom(area.top());
    area.setTop(activeSheet()->topRow(unzoomedValue, tmp));
  }
  else
  {
    area.setTop(area.bottom());
    area.setBottom(activeSheet()->bottomRow(d->view->doc()->unzoomItY(height()) +
                                            unzoomedValue));
  }

  activeSheet()->setRegionPaintDirty( area );

  // New absolute position
  d->yOffset = unzoomedValue;
  scroll( 0, dy );
  vBorderWidget()->scroll( 0, dy );

  activeSheet()->enableScrollBarUpdates( true );

  d->view->doc()->emitEndOperation( activeSheet()->visibleRect( this ) );
}

void Canvas::slotMaxColumn( int _max_column )
{
  int oldValue = horzScrollBar()->maxValue() - horzScrollBar()->value();
  double xpos = activeSheet()->dblColumnPos( TQMIN( KS_colMax, _max_column + 10 ) ) - xOffset();
  double unzoomWidth = d->view->doc()->unzoomItX( width() );

  //Don't go beyond the maximum column range (KS_colMax)
  double sizeMaxX = activeSheet()->sizeMaxX();
  if ( xpos > sizeMaxX - xOffset() - unzoomWidth )
    xpos = sizeMaxX - xOffset() - unzoomWidth;

  horzScrollBar()->setRange( 0, d->view->doc()->zoomItX( xpos + xOffset() ) );

  if ( activeSheet()->layoutDirection()==Sheet::RightToLeft )
    horzScrollBar()->setValue( horzScrollBar()->maxValue() - oldValue );
}

void Canvas::slotMaxRow( int _max_row )
{
  double ypos = activeSheet()->dblRowPos( TQMIN( KS_rowMax, _max_row + 10 ) ) - yOffset();
  double unzoomHeight = d->view->doc()->unzoomItY( height() );

  //Don't go beyond the maximum row range (KS_rowMax)
  double sizeMaxY = activeSheet()->sizeMaxY();
  if ( ypos > sizeMaxY - yOffset() - unzoomHeight )
    ypos = sizeMaxY - yOffset() - unzoomHeight;

  vertScrollBar()->setRange( 0, d->view->doc()->zoomItY( ypos + yOffset() ) );
}

void Canvas::mouseMoveEvent( TQMouseEvent * _ev )
{
  // Dont allow modifications if document is readonly. Selecting is no modification
  if ( (!d->view->koDocument()->isReadWrite()) && (d->mouseAction!=Mark))
    return;

  if ( d->mousePressed && d->modType != MT_NONE )
  {
    KoPoint docPoint ( doc()->unzoomPoint( _ev->pos() ) );
    docPoint += KoPoint( xOffset(), yOffset() );

    if ( d->modType == MT_MOVE )
    {
      if ( !d->m_isMoving )
      {
        d->m_moveStartPoint = objectRect( false ).topLeft();
        d->m_isMoving = true;
      }
      moveObjectsByMouse( docPoint, _ev->state() & AltButton || _ev->state() & ControlButton );
    }
    else if ( d->m_resizeObject )
    {
      if ( !d->m_isResizing )
        d->m_isResizing = true;

      bool keepRatio = d->m_resizeObject->isKeepRatio();
      if ( _ev->state() & AltButton )
      {
        keepRatio = true;
      }
      docPoint  = KoPoint( doc()->unzoomPoint( _ev->pos() ) );
      resizeObject( d->modType, docPoint, keepRatio );
    }
    return;
  }


  /*if ( d->mousePressed && d->m_resizeObject && d->modType != MT_NONE )
  {
    if ( !d->m_isMoving )
    {
      d->m_isMoving = true;
      update();
    }
    else
      update( d->m_boundingRealRect );


    TQRect drawingRect;

    if ( d->modType == MT_MOVE )
    {
      drawingRect = TQRect( _ev->pos() - d->m_origPos, d->m_origSize );
      d->m_boundingRealRect = drawingRect;
    }
    else
    {
      drawingRect = doc()->zoomRect( calculateNewGeometry(d->modType,  _ev->pos().x(), _ev->pos().y() ) );
      drawingRect.moveBy( (int)( -xOffset() * doc()->zoomedResolutionX() ) , (int)( -yOffset() * doc()->zoomedResolutionY() ) );
    }

    // Autoscrolling
    if ( ( d->modType == MT_MOVE && drawingRect.top() < 0 ) ||  ( d->modType != MT_MOVE && _ev->pos().y() < 0 ) )
    {
      vertScrollBar()->setValue ((int) ( vertScrollBar()->value() -
          autoScrollAccelerationY( - drawingRect.top() ) ) );
    }
    else if ( ( d->modType == MT_MOVE && drawingRect.bottom() > height() ) ||  ( d->modType != MT_MOVE && _ev->pos().y() > height() ) )
    {
      vertScrollBar()->setValue ((int) ( vertScrollBar()->value() +
          autoScrollAccelerationY ( drawingRect.bottom() - height() ) ) );
    }
    if ( ( d->modType == MT_MOVE && drawingRect.left() < 0 ) ||  ( d->modType != MT_MOVE && _ev->pos().x() < 0 ) )
    {
      horzScrollBar()->setValue ((int) ( horzScrollBar()->value() -
          autoScrollAccelerationX( - drawingRect.left() ) ) );
    }
    else if ( ( d->modType == MT_MOVE && drawingRect.right() > width() ) ||  ( d->modType != MT_MOVE && _ev->pos().x() > width() )  )
    {
      horzScrollBar()->setValue ((int) (horzScrollBar()->value() +
          autoScrollAccelerationX( drawingRect.right() - width() ) ) );
    }

    if ( drawingRect.left() < 0 )
    {
        drawingRect.setRight( drawingRect.right() -drawingRect.left() );
        drawingRect.setLeft( 0 );
    }
    if ( drawingRect.top() < 0 )
    {
        drawingRect.setBottom( drawingRect.bottom() -drawingRect.top() );
        drawingRect.setTop( 0 );
    }

    d->m_boundingRealRect = drawingRect; //redraw this area next time the mouse has been moved

    //update( d->m_boundingRealRect );
    TQPainter p(this);
    p.setRasterOp( NotROP );
    p.setPen( TQPen( black, 0, DotLine ) );
    p.drawRect( drawingRect );
    p.end();
    return;
}*/

  if ( d->dragging )
  {
    return;
  }
  if ( d->dragStart.x() != -1 )
  {
    TQPoint p ( (int) _ev->pos().x() + (int) xOffset(),
               (int) _ev->pos().y() + (int) yOffset() );

    if ( ( d->dragStart - p ).manhattanLength() > 4 )
    {
      d->dragging = true;
      startTheDrag();
      d->dragStart.setX( -1 );
    }
    d->dragging = false;
    return;
  }

  // Get info about where the event occurred - this is duplicated
  // in ::mousePressEvent, needs to be separated into one function
  Sheet *sheet = activeSheet();
  if ( !sheet )
  {
    return;
  }

  if ( d->mouseSelectedObject )
  {
    EmbeddedObject *obj = 0;
    TQPoint p ( (int) _ev->x(),
              (int) _ev->y() );
    if ( ( obj = getObject( p, activeSheet() ) ) && obj->isSelected() )
    {
      KoRect const bound = obj->tqgeometry();
      TQRect zoomedBound = doc()->zoomRect( KoRect(bound.left(), bound.top(),
      bound.width(),
      bound.height() ) );
      zoomedBound.moveBy( (int)(-xOffset() * doc()->zoomedResolutionX() ), (int)(-yOffset() * doc()->zoomedResolutionY() ));
      setCursor( obj->getCursor( p, d->modType, zoomedBound ) );
      return;
    }
  }

  double dwidth = d->view->doc()->unzoomItX( width() );
  double ev_PosX;
  if ( sheet->layoutDirection()==Sheet::RightToLeft )
  {
    ev_PosX = dwidth - d->view->doc()->unzoomItX( _ev->pos().x() ) + xOffset();
  }
  else
  {
    ev_PosX = d->view->doc()->unzoomItX( _ev->pos().x() ) + xOffset();
  }
  double ev_PosY = d->view->doc()->unzoomItY( _ev->pos().y() ) + yOffset();

  // In which cell did the user click ?
  double xpos;
  double ypos;
  int col = sheet->leftColumn( ev_PosX, xpos );
  int row  = sheet->topRow( ev_PosY, ypos );

  // you cannot move marker when col > KS_colMax or row > KS_rowMax
  if ( col > KS_colMax || row > KS_rowMax )
  {
    kdDebug(36001) << "Canvas::mouseMoveEvent: col or row is out of range: "
                   << "col: " << col << " row: " << row << endl;
    return;
  }


  //*** Highlighted Range Resize Handling ***
  if (d->mouseAction == ResizeSelection)
  {
    choice()->update(TQPoint(col,row));
    return;
  }

  //Check to see if the mouse is over a highlight range size grip and if it is, change the cursor
  //tqshape to a resize arrow
  if (highlightRangeSizeGripAt(ev_PosX,ev_PosY))
  {
    if ( sheet->layoutDirection()==Sheet::RightToLeft )
      setCursor( sizeBDiagCursor );
    else
      setCursor( sizeFDiagCursor );
    return;
  }

  TQRect rct( (d->chooseCell ? choice() : selectionInfo())->lastRange() );

  TQRect r1;
  TQRect r2;

  double lx = sheet->dblColumnPos( rct.left() );
  double rx = sheet->dblColumnPos( rct.right() + 1 );
  double ty = sheet->dblRowPos( rct.top() );
  double by = sheet->dblRowPos( rct.bottom() + 1 );

  r1.setLeft( (int) (lx - 1) );
  r1.setTop( (int) (ty - 1) );
  r1.setRight( (int) (rx + 1) );
  r1.setBottom( (int) (by + 1) );

  r2.setLeft( (int) (lx + 1) );
  r2.setTop( (int) (ty + 1) );
  r2.setRight( (int) (rx - 1) );
  r2.setBottom( (int) (by - 1) );

  // Test whether the mouse is over some anchor
  {
    Cell *cell = sheet->visibleCellAt( col, row );
    TQString anchor;
    if ( sheet->layoutDirection()==Sheet::RightToLeft )
    {
      anchor = cell->testAnchor( d->view->doc()->zoomItX( cell->dblWidth() - ev_PosX + xpos ),
                                 d->view->doc()->zoomItY( ev_PosY - ypos ) );
    }
    else
    {
      anchor = cell->testAnchor( d->view->doc()->zoomItX( ev_PosX - xpos ),
                                 d->view->doc()->zoomItY( ev_PosY - ypos ) );
    }
    if ( !anchor.isEmpty() && anchor != d->anchor )
    {
      setCursor( KCursor::handCursor() );
    }

    d->anchor = anchor;
  }

  // Test wether mouse is over the selection handle
  TQRect selectionHandle = d->view->selectionInfo()->selectionHandleArea();
  if ( selectionHandle.contains( TQPoint( d->view->doc()->zoomItX( ev_PosX ),
                                         d->view->doc()->zoomItY( ev_PosY ) ) ) )
  {
    //If the cursor is over the handle, than it might be already on the next cell.
    //Recalculate the cell!
    col  = sheet->leftColumn( ev_PosX - d->view->doc()->unzoomItX( 2 ), xpos );
    row  = sheet->topRow( ev_PosY - d->view->doc()->unzoomItY( 2 ), ypos );

    if ( !sheet->isProtected() )
    {
      if ( sheet->layoutDirection()==Sheet::RightToLeft )
        setCursor( sizeBDiagCursor );
      else
        setCursor( sizeFDiagCursor );
    }
  }
  else if ( !d->anchor.isEmpty() )
  {
    if ( !sheet->isProtected() )
      setCursor( KCursor::handCursor() );
  }
  else if ( r1.contains( TQPoint( (int) ev_PosX, (int) ev_PosY ) )
            && !r2.contains( TQPoint( (int) ev_PosX, (int) ev_PosY ) ) )
  {
    setCursor( KCursor::handCursor() );
  }
  else if ( d->chooseCell )
  {
	//Visual cue to indicate that the user can drag-select the choice selection
	setCursor( KCursor::crossCursor() );
  }
  else
  {
	//Nothing special is happening, use a normal arrow cursor
    setCursor( arrowCursor );
  }

  // No marking, selecting etc. in progess? Then quit here.
  if ( d->mouseAction == NoAction )
    return;

  // Set the new extent of the selection
  (d->chooseCell ? choice() : selectionInfo())->update(TQPoint(col,row));
}

void Canvas::mouseReleaseEvent( TQMouseEvent* /*_ev*/)
{
  if ( d->scrollTimer->isActive() )
    d->scrollTimer->stop();

  d->mousePressed = false;
  d->view->disableAutoScroll();

  if ( d->modType != MT_NONE /*&& d->m_resizeObject && d->m_resizeObject->isSelected() */)
  {
    switch ( d->modType )
    {
      case MT_MOVE:
      {
        KoPoint move( objectRect( false ).topLeft() - d->m_moveStartPosMouse );
        if ( move != KoPoint( 0, 0 ) )
        {
          KCommand *cmd= activeSheet()->moveObject( view(), move.x(), move.y() );
          if(cmd)
            doc()->addCommand( cmd );
        } else
        {
          tqrepaint();
        }
        d->m_isMoving = false;
        break;
      }
      case MT_RESIZE_UP: case MT_RESIZE_LF: case MT_RESIZE_RT: case MT_RESIZE_LU: case MT_RESIZE_LD: case MT_RESIZE_RU: case MT_RESIZE_RD:
        finishResizeObject( i18n("Resize Object") );
        break;
      case MT_RESIZE_DN:
        finishResizeObject( i18n("Resize Object"), false );
        break;
      default:
        break;
    }
    return;
  }

  Sheet *sheet = activeSheet();
  if ( !sheet )
    return;

  Selection* selectionInfo = d->view->selectionInfo();
  TQRect s( selectionInfo->lastRange() );

  // The user started the drag in the lower right corner of the marker ?
  if ( d->mouseAction == ResizeCell && !sheet->isProtected() )
  {
    sheet->mergeCells(selectionInfo->lastRange());
    d->view->updateEditWidget();
  }
  else if ( d->mouseAction == AutoFill && !sheet->isProtected() )
  {
    TQRect dest = s;
    sheet->autofill( d->autoFillSource, dest );

    d->view->updateEditWidget();
  }
  // The user started the drag in the middle of a cell ?
  else if ( d->mouseAction == Mark && !d->chooseCell )
  {
    d->view->updateEditWidget();
  }

  d->mouseAction = NoAction;
  d->dragging = false;
  d->dragStart.setX( -1 );
}

void Canvas::processClickSelectionHandle( TQMouseEvent *event )
{
  // Auto fill ? That is done using the left mouse button.
  if ( event->button() == Qt::LeftButton )
  {
    d->mouseAction = AutoFill;
    d->autoFillSource = selectionInfo()->lastRange();
  }
  // Resize a cell (done with the right mouse button) ?
  // But for that to work there must not be a selection.
  else if ( event->button() == Qt::MidButton && selectionInfo()->isSingular())
  {
    d->mouseAction = ResizeCell;
  }

  return;
}

void Canvas::processLeftClickAnchor()
{
    bool isRefLink = localReferenceAnchor( d->anchor );
    bool isLocalLink = (d->anchor.find("file:") == 0);
    if ( !isRefLink )
    {
	TQString type=KMimeType::findByURL(d->anchor, 0, isLocalLink)->name();

	if ( KRun::isExecutableFile( d->anchor , type ) )
	{
        	//TQString question = i18n("Do you want to open this link to '%1'?\n").tqarg(d->anchor);

          	//question += i18n("Note that opening a link to a local file may "
                          //   "compromise your system's security.");

		TQString question = i18n("This link points to the program or script '%1'.\n"
					"Malicious programs can harm your computer.  Are you sure that you want to run this program?").tqarg(d->anchor);
        	// this will also start local programs, so adding a "don't warn again"
        	// checkbox will probably be too dangerous
        	int choice = KMessageBox::warningYesNo(this, question, i18n("Open Link?"));
        	if ( choice != KMessageBox::Yes )
        	{
			return;
            		//(void) new KRun( d->anchor );
        	}
	}

	new KRun(d->anchor);
    }
    else
    {
      selectionInfo()->initialize(Region(d->view, d->anchor));
    }
}

bool Canvas::highlightRangeSizeGripAt(double x, double y)
{
  if (!d->chooseCell)
		return 0;

  Region::ConstIterator end = choice()->constEnd();
  for (Region::ConstIterator it = choice()->constBegin(); it != end; ++it)
  {
    // TODO Stefan: adapt to Selection::selectionHandleArea
    KoRect visibleRect;
    sheetAreaToRect((*it)->rect().normalize(), visibleRect);

    TQPoint bottomRight((int) visibleRect.right(), (int) visibleRect.bottom());
    TQRect handle( ( (int) bottomRight.x() - 6 ),
                  ( (int) bottomRight.y() - 6 ),
                  ( 6 ),
                  ( 6 ) );

    if (handle.contains(TQPoint((int) x,(int) y)))
			{
				return true;
			}
	}

	return false;
}

void Canvas::mousePressEvent( TQMouseEvent * _ev )
{
  if ( _ev->button() == Qt::LeftButton )
  {
    d->mousePressed = true;
    d->view->enableAutoScroll();
  }

  if ( activeSheet() && _ev->button() == Qt::LeftButton)
  {
    d->m_moveStartPosMouse = objectRect( false ).topLeft();
    EmbeddedObject *obj = getObject( _ev->pos(), activeSheet() );

    if ( obj )
    {
       // use ctrl + Button to select / deselect object
      if ( _ev->state() & ControlButton && obj->isSelected() )
        deselectObject( obj );
      else if ( _ev->state() & ControlButton )
      {
        if ( d->modType == MT_NONE)
          return;

        selectObject( obj );
        raiseObject( obj );
        d->m_moveStartPosMouse = objectRect( false ).topLeft();
      }
      else
      {
        if ( d->modType != MT_MOVE || !obj->isSelected() )
            deselectAllObjects();

        selectObject( obj );

        raiseObject( obj );
        d->m_moveStartPosMouse = objectRect( false ).topLeft();
      }

      // start resizing
      if ( d->modType != MT_MOVE && d->modType != MT_NONE && !obj->isProtect() )
      {
        deselectAllObjects();
        selectObject( obj );
        raiseObject( obj );

        d->m_resizeObject = obj;

        d->m_ratio = static_cast<double>( obj->tqgeometry().width() ) /
            static_cast<double>( obj->tqgeometry().height() );
        d->m_rectBeforeResize = obj->tqgeometry();
      }

      KoPoint docPoint ( doc()->unzoomPoint( _ev->pos() ) );
      docPoint += KoPoint( xOffset(), yOffset() );
      d->m_origMousePos = docPoint;
      d->m_moveStartPosMouse = objectRect( false ).topLeft();
      return;
    }
    else
    {
      d->modType = MT_NONE;
      if ( !( _ev->state() & ShiftButton ) && !( _ev->state() & ControlButton ) )
        deselectAllObjects();
    }
  }

  // Get info about where the event occurred - this is duplicated
  // in ::mouseMoveEvent, needs to be separated into one function
  Sheet *sheet = activeSheet();
  if ( !sheet )
  {
    return;
  }

  double dwidth = d->view->doc()->unzoomItX( width() );
  double ev_PosX;
  if ( sheet->layoutDirection()==Sheet::RightToLeft )
  {
    ev_PosX = dwidth - d->view->doc()->unzoomItX( _ev->pos().x() ) + xOffset();
  }
  else
  {
    ev_PosX = d->view->doc()->unzoomItX( _ev->pos().x() ) + xOffset();
  }
  double ev_PosY = d->view->doc()->unzoomItY( _ev->pos().y() ) + yOffset();

  // In which cell did the user click ?
  double xpos;
  double ypos;
  int col  = sheet->leftColumn( ev_PosX, xpos );
  int row  = sheet->topRow( ev_PosY, ypos );
  // you cannot move marker when col > KS_colMax or row > KS_rowMax
  if ( col > KS_colMax || row > KS_rowMax )
  {
    kdDebug(36001) << "Canvas::mousePressEvent: col or row is out of range: "
                   << "col: " << col << " row: " << row << endl;
    return;
  }

  // you cannot move marker when col > KS_colMax or row > KS_rowMax
  if ( col > KS_colMax || row > KS_rowMax )
  {
    kdDebug(36001) << "Canvas::mousePressEvent: col or row is out of range: "
                   << "col: " << col << " row: " << row << endl;
    return;
  }

  if (d->chooseCell && highlightRangeSizeGripAt(ev_PosX,ev_PosY))
  {
    choice()->setActiveElement(TQPoint(col,row));
    d->mouseAction = ResizeSelection;
    return;
  }

  // We were editing a cell -> save value and get out of editing mode
  if ( d->cellEditor && !d->chooseCell )
  {
    deleteEditor( true ); // save changes
  }

  d->scrollTimer->start( 50 );

  // Did we click in the lower right corner of the marker/marked-area ?
  if ( selectionInfo()->selectionHandleArea().contains( TQPoint( d->view->doc()->zoomItX( ev_PosX ),
                                                                d->view->doc()->zoomItY( ev_PosY ) ) ) )
  {
    processClickSelectionHandle( _ev );
    return;
  }


  // TODO Stefan: adapt to non-cont. selection
  {
    // start drag ?
    TQRect rct( selectionInfo()->lastRange() );

    TQRect r1;
    TQRect r2;
    {
      double lx = sheet->dblColumnPos( rct.left() );
      double rx = sheet->dblColumnPos( rct.right() + 1 );
      double ty = sheet->dblRowPos( rct.top() );
      double by = sheet->dblRowPos( rct.bottom() + 1 );

      r1.setLeft( (int) (lx - 1) );
      r1.setTop( (int) (ty - 1) );
      r1.setRight( (int) (rx + 1) );
      r1.setBottom( (int) (by + 1) );

      r2.setLeft( (int) (lx + 1) );
      r2.setTop( (int) (ty + 1) );
      r2.setRight( (int) (rx - 1) );
      r2.setBottom( (int) (by - 1) );
    }

    d->dragStart.setX( -1 );

    if ( r1.contains( TQPoint( (int) ev_PosX, (int) ev_PosY ) )
         && !r2.contains( TQPoint( (int) ev_PosX, (int) ev_PosY ) ) )
    {
      d->dragStart.setX( (int) ev_PosX );
      d->dragStart.setY( (int) ev_PosY );

      return;
    }
  }

  //  kdDebug() << "Clicked in cell " << col << ", " << row << endl;

  // Extending an existing selection with the shift button ?
  if ((_ev->state() & ShiftButton) &&
      d->view->koDocument()->isReadWrite() &&
      !selectionInfo()->isColumnOrRowSelected())
  {
    (d->chooseCell ? choice() : selectionInfo())->update(TQPoint(col,row));
    return;
  }


  // Go to the upper left corner of the obscuring object if cells are merged
  Cell *cell = sheet->cellAt( col, row );
  if (cell->isPartOfMerged())
  {
    cell = cell->obscuringCells().first();
    col = cell->column();
    row = cell->row();
  }

  switch (_ev->button())
  {
    case Qt::LeftButton:
      if (!d->anchor.isEmpty())
      {
        // Hyperlink pressed
        processLeftClickAnchor();
      }
#ifdef NONCONTIGUOUSSELECTION
      else if ( _ev->state() & ControlButton )
      {
        if (d->chooseCell)
        {
#if 0 // TODO Stefan: remove for NCS of choices
          // Start a marking action
          d->mouseAction = Mark;
          // extend the existing selection
          choice()->extend(TQPoint(col,row), activeSheet());
#endif
        }
        else
        {
          // Start a marking action
          d->mouseAction = Mark;
          // extend the existing selection
          selectionInfo()->extend(TQPoint(col,row), activeSheet());
        }
// TODO Stefan: simplification, if NCS of choices is working
/*        (d->chooseCell ? choice() : selectionInfo())->extend(TQPoint(col,row), activeSheet());*/
      }
#endif
      else
      {
        // Start a marking action
        d->mouseAction = Mark;
        // reinitialize the selection
        (d->chooseCell ? choice() : selectionInfo())->initialize(TQPoint(col,row), activeSheet());
      }
      break;
    case Qt::MidButton:
      // Paste operation with the middle button?
      if ( d->view->koDocument()->isReadWrite() && !sheet->isProtected() )
      {
        (d->chooseCell ? choice() : selectionInfo())->initialize( TQPoint( col, row ), activeSheet() );
        sheet->paste(selectionInfo()->lastRange(), true, Paste::Normal,
                     Paste::OverWrite, false, 0, false, TQClipboard::Selection);
        sheet->setRegionPaintDirty(*selectionInfo());
      }
      break;
    case Qt::RightButton:
      if (!selectionInfo()->contains( TQPoint( col, row ) ))
      {
        // No selection or the mouse press was outside of an existing selection?
        (d->chooseCell ? choice() : selectionInfo())->initialize(TQPoint(col,row), activeSheet());
      }
      break;
    default:
      break;
  }

  scrollToCell(selectionInfo()->marker());
  if ( !d->chooseCell )
  {
    d->view->updateEditWidgetOnPress();
  }
  updatePosWidget();

  // Context menu?
  if ( _ev->button() == Qt::RightButton )
  {
    // TODO: Handle anchor // TODO Stefan: ???
    TQPoint p = mapToGlobal( _ev->pos() );
    d->view->openPopupMenu( p );
  }
}

void Canvas::startTheDrag()
{
  Sheet * sheet = activeSheet();
  if ( !sheet )
    return;

  // right area for start dragging
  TextDrag * d = new TextDrag( this );
  setCursor( KCursor::handCursor() );

  TQDomDocument doc = sheet->saveCellRegion(*selectionInfo());

  // Save to buffer
  TQBuffer buffer;
  buffer.open( IO_WriteOnly );
  TQTextStream str( &buffer );
  str.setEncoding( TQTextStream::UnicodeUTF8 );
  str << doc;
  buffer.close();

  d->setPlain( sheet->copyAsText( selectionInfo() ) );
  d->setKSpread( buffer.buffer() );

  d->dragCopy();
  setCursor( KCursor::arrowCursor() );
}

void Canvas::mouseDoubleClickEvent( TQMouseEvent*  _ev)
{

  EmbeddedObject *obj;
  if ( ( obj = getObject( _ev->pos(), activeSheet() ) ) )
  {
    switch ( obj->getType() )
    {
      case OBJECT_KOFFICE_PART: case OBJECT_CHART:
      {
        dynamic_cast<EmbeddedKOfficeObject*>(obj)->activate( view(), this );
        return;
        break;
      }
      default:
      {
        view()->extraProperties();
        return;
        break;
      }
    }
  }

  if ( d->view->koDocument()->isReadWrite() && activeSheet() )
    createEditor(true);
}

void Canvas::wheelEvent( TQWheelEvent* _ev )
{
  if ( _ev->orientation() == Qt::Vertical )
  {
    if ( vertScrollBar() )
      TQApplication::sendEvent( vertScrollBar(), _ev );
  }
  else if ( horzScrollBar() )
  {
    TQApplication::sendEvent( horzScrollBar(), _ev );
  }
}

void Canvas::paintEvent( TQPaintEvent* _ev )
{
  if ( d->view->doc()->isLoading() )
    return;

  Sheet* sheet = activeSheet();
  if ( !sheet )
    return;

  // ElapsedTime et( "Canvas::paintEvent" );

  double dwidth = d->view->doc()->unzoomItX( width() );
  KoRect rect = d->view->doc()->unzoomRect( _ev->rect() & TQWidget::rect() );
  if ( sheet->layoutDirection()==Sheet::RightToLeft )
    rect.moveBy( -xOffset(), yOffset() );
  else
    rect.moveBy( xOffset(), yOffset() );

  KoPoint tl = rect.topLeft();
  KoPoint br = rect.bottomRight();

  double tmp;
  int left_col;
  int right_col;
  //Philipp: I don't know why we need the +1, but otherwise we don't get it correctly
  //Testcase: Move a dialog slowly up left. Sometimes the top/left most points are not painted
  if ( sheet->layoutDirection()==Sheet::RightToLeft )
  {
    right_col = sheet->leftColumn( dwidth - tl.x(), tmp );
    left_col  = sheet->rightColumn( dwidth - br.x() + 1.0 );
  }
  else
  {
    left_col  = sheet->leftColumn( tl.x(), tmp );
    right_col = sheet->rightColumn( br.x() + 1.0 );
  }
  int top_row = sheet->topRow( tl.y(), tmp );
  int bottom_row = sheet->bottomRow( br.y() + 1.0 );

  TQRect vr( TQPoint(left_col, top_row),
            TQPoint(right_col, bottom_row) );
  d->view->doc()->emitBeginOperation( false );
  sheet->setRegionPaintDirty( vr );
  d->view->doc()->emitEndOperation( vr );
}

void Canvas::focusInEvent( TQFocusEvent* )
{
  if ( !d->cellEditor )
    return;

  //kdDebug(36001) << "d->chooseCell : " << ( d->chooseCell ? "true" : "false" ) << endl;
  // If we are in editing mode, we redirect the
  // focus to the CellEditor or EditWidget
  // And we know which, using lastEditorWithFocus.
  // This screws up <Tab> though (David)
  if ( lastEditorWithFocus() == EditWidget )
  {
    d->editWidget->setFocus();
    //kdDebug(36001) << "Focus to EditWidget" << endl;
    return;
  }

  //kdDebug(36001) << "Redirecting focus to editor" << endl;
  d->cellEditor->setFocus();
}

void Canvas::focusOutEvent( TQFocusEvent* )
{
    if ( d->scrollTimer->isActive() )
        d->scrollTimer->stop();
    d->mousePressed = false;
    d->view->disableAutoScroll();
}

void Canvas::dragMoveEvent( TQDragMoveEvent * _ev )
{
  Sheet * sheet = activeSheet();
  if ( !sheet )
  {
    _ev->ignore();
    return;
  }

  _ev->accept( TextDrag::canDecode( _ev ) );

  double dwidth = d->view->doc()->unzoomItX( width() );
  double xpos = sheet->dblColumnPos( selectionInfo()->lastRange().left() );
  double ypos = sheet->dblRowPos( selectionInfo()->lastRange().top() );
  double width  = sheet->columnFormat( selectionInfo()->lastRange().left() )->dblWidth( this );
  double height = sheet->rowFormat( selectionInfo()->lastRange().top() )->dblHeight( this );

  TQRect r1 ((int) xpos - 1, (int) ypos - 1, (int) width + 3, (int) height + 3);

  double ev_PosX;
  if (sheet->layoutDirection()==Sheet::RightToLeft)
    ev_PosX = dwidth - d->view->doc()->unzoomItX( _ev->pos().x() ) + xOffset();
  else
    ev_PosX = d->view->doc()->unzoomItX( _ev->pos().x() ) + xOffset();

  double ev_PosY = d->view->doc()->unzoomItY( _ev->pos().y() ) + yOffset();

  if ( r1.contains( TQPoint ((int) ev_PosX, (int) ev_PosY) ) )
    _ev->ignore( r1 );
}

void Canvas::dragLeaveEvent( TQDragLeaveEvent * )
{
  if ( d->scrollTimer->isActive() )
    d->scrollTimer->stop();
}

void Canvas::dropEvent( TQDropEvent * _ev )
{
  d->dragging = false;
  if ( d->scrollTimer->isActive() )
    d->scrollTimer->stop();
  Sheet * sheet = activeSheet();
  if ( !sheet || sheet->isProtected() )
  {
    _ev->ignore();
    return;
  }

  double dwidth = d->view->doc()->unzoomItX( width() );
  double xpos = sheet->dblColumnPos( selectionInfo()->lastRange().left() );
  double ypos = sheet->dblRowPos( selectionInfo()->lastRange().top() );
  double width  = sheet->columnFormat( selectionInfo()->lastRange().left() )->dblWidth( this );
  double height = sheet->rowFormat( selectionInfo()->lastRange().top() )->dblHeight( this );

  TQRect r1 ((int) xpos - 1, (int) ypos - 1, (int) width + 3, (int) height + 3);

  double ev_PosX;
  if (sheet->layoutDirection()==Sheet::RightToLeft)
    ev_PosX = dwidth - d->view->doc()->unzoomItX( _ev->pos().x() ) + xOffset();
  else
    ev_PosX = d->view->doc()->unzoomItX( _ev->pos().x() ) + xOffset();

  double ev_PosY = d->view->doc()->unzoomItY( _ev->pos().y() ) + yOffset();

  if ( r1.contains( TQPoint ((int) ev_PosX, (int) ev_PosY) ) )
  {
    _ev->ignore( );
    return;
  }
  else
    _ev->accept( );

  double tmp;
  int col = sheet->leftColumn( ev_PosX, tmp );
  int row = sheet->topRow( ev_PosY, tmp );

  if ( !TextDrag::canDecode( _ev ) )
  {
    _ev->ignore();
    return;
  }

  TQByteArray b;

  bool makeUndo = true;

  if ( _ev->provides( TextDrag::selectionMimeType() ) )
  {
    if ( TextDrag::target() == _ev->source() )
    {
      if ( !d->view->doc()->undoLocked() )
      {
        UndoDragDrop * undo
          = new UndoDragDrop(d->view->doc(), sheet, *selectionInfo(),
                             TQRect(col, row,
                                   selectionInfo()->boundingRect().width(),
                                   selectionInfo()->boundingRect().height()));
        d->view->doc()->addCommand( undo );
        makeUndo = false;
      }
      sheet->deleteSelection( selectionInfo(), false );
    }


    b = _ev->tqencodedData( TextDrag::selectionMimeType() );
    sheet->paste( b, TQRect( col, row, 1, 1 ), makeUndo );

    if ( _ev->source() == this )
      _ev->acceptAction();
    _ev->accept();
  }
  else
  {
    TQString text;
    if ( !TQTextDrag::decode( _ev, text ) )
    {
      _ev->ignore();
      return;
    }
    //    if ( TextDrag::target() == _ev->source() )
    //      sheet->deleteSelection( selectionInfo() );

    sheet->pasteTextPlain( text, TQRect( col, row, 1, 1 ) );
    _ev->accept();
    if ( _ev->source() == this )
      _ev->acceptAction();

    return;
  }
}

void Canvas::resizeEvent( TQResizeEvent* _ev )
{
    if (!activeSheet())
	    return;


    double ev_Width = d->view->doc()->unzoomItX( _ev->size().width() );
    double ev_Height = d->view->doc()->unzoomItY( _ev->size().height() );

    // workaround to allow horizontal resizing and zoom changing when sheet
    // direction and interface direction don't match (e.g. an RTL sheet on an
    // LTR interface)
    if ( activeSheet() && activeSheet()->layoutDirection()==Sheet::RightToLeft && !TQApplication::reverseLayout() )
    {
        int dx = _ev->size().width() - _ev->oldSize().width();
        scroll(dx, 0);
    }
    else if ( activeSheet() && activeSheet()->layoutDirection()==Sheet::LeftToRight && TQApplication::reverseLayout() )
    {
        int dx = _ev->size().width() - _ev->oldSize().width();
        scroll(-dx, 0);
    }

    // If we rise horizontally, then check if we are still within the valid area (KS_colMax)
    if ( _ev->size().width() > _ev->oldSize().width() )
    {
        int oldValue = horzScrollBar()->maxValue() - horzScrollBar()->value();

        if ( ( xOffset() + ev_Width ) >
               d->view->doc()->zoomItX( activeSheet()->sizeMaxX() ) )
        {
            horzScrollBar()->setRange( 0, d->view->doc()->zoomItX( activeSheet()->sizeMaxX() - ev_Width ) );
            if ( activeSheet()->layoutDirection()==Sheet::RightToLeft )
                horzScrollBar()->setValue( horzScrollBar()->maxValue() - oldValue );
        }
    }
    // If we lower vertically, then check if the range should represent the maximum range
    else if ( _ev->size().width() < _ev->oldSize().width() )
    {
        int oldValue = horzScrollBar()->maxValue() - horzScrollBar()->value();

        if ( horzScrollBar()->maxValue() ==
             int( d->view->doc()->zoomItX( activeSheet()->sizeMaxX() ) - ev_Width ) )
        {
            horzScrollBar()->setRange( 0, d->view->doc()->zoomItX( activeSheet()->sizeMaxX() - ev_Width ) );
            if ( activeSheet()->layoutDirection()==Sheet::RightToLeft )
                horzScrollBar()->setValue( horzScrollBar()->maxValue() - oldValue );
        }
    }

    // If we rise vertically, then check if we are still within the valid area (KS_rowMax)
    if ( _ev->size().height() > _ev->oldSize().height() )
    {
        if ( ( yOffset() + ev_Height ) >
             d->view->doc()->zoomItY( activeSheet()->sizeMaxY() ) )
        {
            vertScrollBar()->setRange( 0, d->view->doc()->zoomItY( activeSheet()->sizeMaxY() - ev_Height ) );
        }
    }
    // If we lower vertically, then check if the range should represent the maximum range
    else if ( _ev->size().height() < _ev->oldSize().height() )
    {
        if ( vertScrollBar()->maxValue() ==
             int( d->view->doc()->zoomItY( activeSheet()->sizeMaxY() ) - ev_Height ) )
        {
            vertScrollBar()->setRange( 0, d->view->doc()->zoomItY( activeSheet()->sizeMaxY() - ev_Height ) );
        }
    }
}

TQPoint Canvas::cursorPos()
{
  TQPoint cursor;
  if (d->chooseCell && !choice()->isEmpty())
    cursor = choice()->cursor();
  else
    cursor = selectionInfo()->cursor();

  return cursor;
}

TQRect Canvas::moveDirection( KSpread::MoveTo direction, bool extendSelection )
{
  kdDebug(36001) << "Canvas::moveDirection" << endl;

  TQPoint destination;
  TQPoint cursor = cursorPos();

  TQPoint cellCorner = cursor;
  Cell* cell = activeSheet()->cellAt(cursor.x(), cursor.y());

  /* cell is either the same as the marker, or the cell that is forced obscuring
     the marker cell
  */
  if (cell->isPartOfMerged())
  {
    cell = cell->obscuringCells().first();
    cellCorner = TQPoint(cell->column(), cell->row());
  }

  /* how many cells must we move to get to the next cell? */
  int offset = 0;
  RowFormat *rl = NULL;
  ColumnFormat *cl = NULL;
  switch (direction)
    /* for each case, figure out how far away the next cell is and then keep
       going one row/col at a time after that until a visible row/col is found

       NEVER use cell->column() or cell->row() -- it might be a default cell
    */
  {
    case KSpread::Bottom:
      offset = cell->mergedYCells() - (cursor.y() - cellCorner.y()) + 1;
      rl = activeSheet()->rowFormat( cursor.y() + offset );
      while ( ((cursor.y() + offset) <= KS_rowMax) && rl->isHide())
      {
        offset++;
        rl = activeSheet()->rowFormat( cursor.y() + offset );
      }

      destination = TQPoint(cursor.x(), TQMIN(cursor.y() + offset, KS_rowMax));
      break;
    case KSpread::Top:
      offset = (cellCorner.y() - cursor.y()) - 1;
      rl = activeSheet()->rowFormat( cursor.y() + offset );
      while ( ((cursor.y() + offset) >= 1) && rl->isHide())
      {
        offset--;
        rl = activeSheet()->rowFormat( cursor.y() + offset );
      }
      destination = TQPoint(cursor.x(), TQMAX(cursor.y() + offset, 1));
      break;
    case KSpread::Left:
      offset = (cellCorner.x() - cursor.x()) - 1;
      cl = activeSheet()->columnFormat( cursor.x() + offset );
      while ( ((cursor.x() + offset) >= 1) && cl->isHide())
      {
        offset--;
        cl = activeSheet()->columnFormat( cursor.x() + offset );
      }
      destination = TQPoint(TQMAX(cursor.x() + offset, 1), cursor.y());
      break;
    case KSpread::Right:
      offset = cell->mergedXCells() - (cursor.x() - cellCorner.x()) + 1;
      cl = activeSheet()->columnFormat( cursor.x() + offset );
      while ( ((cursor.x() + offset) <= KS_colMax) && cl->isHide())
      {
        offset++;
        cl = activeSheet()->columnFormat( cursor.x() + offset );
      }
      destination = TQPoint(TQMIN(cursor.x() + offset, KS_colMax), cursor.y());
      break;
    case KSpread::BottomFirst:
      offset = cell->mergedYCells() - (cursor.y() - cellCorner.y()) + 1;
      rl = activeSheet()->rowFormat( cursor.y() + offset );
      while ( ((cursor.y() + offset) <= KS_rowMax) && rl->isHide())
      {
        ++offset;
        rl = activeSheet()->rowFormat( cursor.y() + offset );
      }

      destination = TQPoint( 1, TQMIN( cursor.y() + offset, KS_rowMax ) );
      break;
  }

  if (extendSelection)
  {
    (d->chooseCell ? choice() : selectionInfo())->update(destination);
  }
  else
  {
    (d->chooseCell ? choice() : selectionInfo())->initialize(destination, activeSheet());
  }
  d->view->updateEditWidget();

  return TQRect( cursor, destination );
}

void Canvas::processEnterKey(TQKeyEvent* event)
{
  // array is true, if ctrl+alt are pressed
  bool array = (event->state() & TQt::AltButton) &&
      (event->state() & TQt::ControlButton);

  /* save changes to the current editor */
  if (!d->chooseCell)
  {
    deleteEditor(true, array);
  }

  /* use the configuration setting to see which direction we're supposed to move
     when enter is pressed.
  */
  KSpread::MoveTo direction = d->view->doc()->getMoveToValue();

  //if shift Button clicked inverse move direction
  if (event->state() & TQt::ShiftButton)
  {
    switch( direction )
    {
     case KSpread::Bottom:
      direction = KSpread::Top;
      break;
     case KSpread::Top:
      direction = KSpread::Bottom;
      break;
     case KSpread::Left:
      direction = KSpread::Right;
      break;
     case KSpread::Right:
      direction = KSpread::Left;
      break;
     case KSpread::BottomFirst:
      direction = KSpread::BottomFirst;
      break;
    }
  }

  /* never extend a selection with the enter key -- the shift key reverses
     direction, not extends the selection
  */
  TQRect r( moveDirection( direction, false ) );
  d->view->doc()->emitEndOperation( r );
}

void Canvas::processArrowKey( TQKeyEvent *event)
{
  /* NOTE:  hitting the tab key also calls this function.  Don't forget
     to account for it
  */

  /* save changes to the current editor */
  if (!d->chooseCell)
  {
    deleteEditor( true );
  }

  KSpread::MoveTo direction = KSpread::Bottom;
  bool makingSelection = event->state() & ShiftButton;

  switch (event->key())
  {
  case Key_Down:
    direction = KSpread::Bottom;
    break;
  case Key_Up:
    direction = KSpread::Top;
    break;
  case Key_Left:
    if (activeSheet()->layoutDirection()==Sheet::RightToLeft)
      direction = KSpread::Right;
    else
      direction = KSpread::Left;
    break;
  case Key_Right:
    if (activeSheet()->layoutDirection()==Sheet::RightToLeft)
      direction = KSpread::Left;
    else
      direction = KSpread::Right;
    break;
  case Key_Tab:
      direction = KSpread::Right;
      break;
  case Key_Backtab:
      //Shift+Tab moves to the left
      direction = KSpread::Left;
      makingSelection = false;
      break;
  default:
    Q_ASSERT(false);
    break;
  }

  TQRect r( moveDirection( direction, makingSelection ) );
  d->view->doc()->emitEndOperation( r );
}

void Canvas::processEscapeKey(TQKeyEvent * event)
{
  if ( d->cellEditor )
    deleteEditor( false );

  if ( view()->isInsertingObject() )
  {
    view()->resetInsertHandle();
    setCursor( arrowCursor );
    return;
  }

  event->accept(); // ?
  TQPoint cursor = cursorPos();

  d->view->doc()->emitEndOperation( TQRect( cursor, cursor ) );

  if ( d->mousePressed /*&& toolEditMode == TEM_MOUSE */)
  {
    switch (d->modType)
    {
      case MT_RESIZE_UP:
      case MT_RESIZE_DN:
      case MT_RESIZE_LF:
      case MT_RESIZE_RT:
      case MT_RESIZE_LU:
      case MT_RESIZE_LD:
      case MT_RESIZE_RU:
      case MT_RESIZE_RD:
      {
        TQRect oldBoundingRect = doc()->zoomRect( d->m_resizeObject->tqgeometry()/*getRepaintRect()*/);
        d->m_resizeObject->setGeometry( d->m_rectBeforeResize );
        oldBoundingRect.moveBy( (int)( -xOffset()*doc()->zoomedResolutionX() ) ,
                            (int)( -yOffset() * doc()->zoomedResolutionY()) );

        activeSheet()->setRegionPaintDirty( oldBoundingRect );
        tqrepaint( oldBoundingRect );
        repaintObject( d->m_resizeObject );
        d->m_ratio = 0.0;
        d->m_resizeObject = 0;
        d->m_isResizing = false;
        view()->disableAutoScroll();
        d->mousePressed = false;
        d->modType = MT_NONE;
        break;
      }
      case MT_MOVE:
      {
        if ( d->m_isMoving )
        {
          KoPoint move( d->m_moveStartPoint - objectRect( false ).topLeft() );
          activeSheet()->moveObject( view(), move, false );
          view()->disableAutoScroll();
          d->mousePressed = false;
          d->modType = MT_NONE;
          d->m_isMoving = false;
          update();
        }
        break;
      }
      default:
        break;
    }
  }
}

bool Canvas::processHomeKey(TQKeyEvent* event)
{
  bool makingSelection = event->state() & ShiftButton;
  Sheet* sheet = activeSheet();

  if ( d->cellEditor )
  // We are in edit mode -> go beginning of line
  {
    TQApplication::sendEvent( d->editWidget, event );
    return false;
  }
  else
  {
    TQPoint destination;
    /* start at the first used cell in the row and cycle through the right until
       we find a cell that has some output text.  But don't look past the current
       marker.
       The end result we want is to move to the left to the first cell with text,
       or just to the first column if there is no more text to the left.

       But why?  In excel, home key sends you to the first column always.
       We might want to change to that behavior.
    */

    if (event->state() & ControlButton)
    {
      /* ctrl + Home will always just send us to location (1,1) */
      destination = TQPoint( 1, 1 );
    }
    else
    {
      TQPoint marker = d->chooseCell ? choice()->marker() : selectionInfo()->marker();

      Cell * cell = sheet->getFirstCellRow(marker.y());
      while (cell != NULL && cell->column() < marker.x() && cell->isEmpty())
      {
        cell = sheet->getNextCellRight(cell->column(), cell->row());
      }

      int col = ( cell ? cell->column() : 1 );
      if ( col == marker.x())
        col = 1;
      destination = TQPoint(col, marker.y());
    }

    if ( selectionInfo()->marker() == destination )
    {
      d->view->doc()->emitEndOperation( TQRect( destination, destination ) );
      return false;
    }

    if (makingSelection)
    {
      (d->chooseCell ? choice() : selectionInfo())->update(destination);
    }
    else
    {
      (d->chooseCell ? choice() : selectionInfo())->initialize(destination, activeSheet());
    }
  }
  return true;
}

bool Canvas::processEndKey( TQKeyEvent *event )
{
  bool makingSelection = event->state() & ShiftButton;
  Sheet* sheet = activeSheet();
  Cell* cell = NULL;
  TQPoint marker = d->chooseCell ? choice()->marker() : selectionInfo()->marker();

  // move to the last used cell in the row
  // We are in edit mode -> go beginning of line
  if ( d->cellEditor )
  {
    TQApplication::sendEvent( d->editWidget, event );
    d->view->doc()->emitEndOperation( TQRect( marker, marker ) );
    return false;
  }
  else
  {
    int col = 1;

    cell = sheet->getLastCellRow(marker.y());
    while (cell != NULL && cell->column() > markerColumn() && cell->isEmpty())
    {
      cell = sheet->getNextCellLeft(cell->column(), cell->row());
    }

    col = (cell == NULL) ? KS_colMax : cell->column();

    TQPoint destination( col, marker.y() );
    if ( destination == marker )
    {
      d->view->doc()->emitEndOperation( TQRect( destination, destination ) );
      return false;
    }

    if (makingSelection)
    {
      (d->chooseCell ? choice() : selectionInfo())->update(destination);
    }
    else
    {
      (d->chooseCell ? choice() : selectionInfo())->initialize(destination, activeSheet());
    }
  }
  return true;
}

bool Canvas::processPriorKey(TQKeyEvent *event)
{
  bool makingSelection = event->state() & ShiftButton;
  if (!d->chooseCell)
  {
    deleteEditor( true );
  }

  TQPoint marker = d->chooseCell ? choice()->marker() : selectionInfo()->marker();

  TQPoint destination(marker.x(), TQMAX(1, marker.y() - 10));
  if ( destination == marker )
  {
    d->view->doc()->emitEndOperation( TQRect( destination, destination ) );
    return false;
  }

  if (makingSelection)
  {
    (d->chooseCell ? choice() : selectionInfo())->update(destination);
  }
  else
  {
    (d->chooseCell ? choice() : selectionInfo())->initialize(destination, activeSheet());
  }
  return true;
}

bool Canvas::processNextKey(TQKeyEvent *event)
{
  bool makingSelection = event->state() & ShiftButton;

  if (!d->chooseCell)
  {
    deleteEditor( true /*save changes*/ );
  }

  TQPoint marker = d->chooseCell ? choice()->marker() : selectionInfo()->marker();
  TQPoint destination(marker.x(), TQMAX(1, marker.y() + 10));

  if ( marker == destination )
  {
    d->view->doc()->emitEndOperation( TQRect( destination, destination ) );
    return false;
  }

  if (makingSelection)
  {
    (d->chooseCell ? choice() : selectionInfo())->update(destination);
  }
  else
  {
    (d->chooseCell ? choice() : selectionInfo())->initialize(destination, activeSheet());
  }
  return true;
}

void Canvas::processDeleteKey(TQKeyEvent* /* event */)
{
  if ( isObjectSelected() )
  {
    d->view->doc()->emitEndOperation( activeSheet()->visibleRect( this ) );
    d->view->deleteSelectedObjects();
    return;
  }

  activeSheet()->clearTextSelection( selectionInfo() );
  d->editWidget->setText( "" );

  TQPoint cursor = cursorPos();

  d->view->doc()->emitEndOperation( TQRect( cursor, cursor ) );
  return;
}

void Canvas::processF2Key(TQKeyEvent* /* event */)
{
  d->editWidget->setFocus();
  if ( d->cellEditor )
    d->editWidget->setCursorPosition( d->cellEditor->cursorPosition() - 1 );
  d->editWidget->cursorForward( false );


  TQPoint cursor = cursorPos();

  d->view->doc()->emitEndOperation( TQRect( cursor, cursor ) );
  return;
}

void Canvas::processF4Key(TQKeyEvent* event)
{
  /* passes F4 to the editor (if any), which will process it
   */
  if ( d->cellEditor )
  {
    d->cellEditor->handleKeyPressEvent( event );
//    d->editWidget->setFocus();
    d->editWidget->setCursorPosition( d->cellEditor->cursorPosition() );
  }
  TQPoint cursor = cursorPos();

  d->view->doc()->emitEndOperation( TQRect( cursor, cursor ) );
  return;
}

void Canvas::processOtherKey(TQKeyEvent *event)
{
  // No null character ...
  if ( event->text().isEmpty() || !d->view->koDocument()->isReadWrite()
       || !activeSheet() || activeSheet()->isProtected() )
  {
    event->accept();
  }
  else
  {
    if ( !d->cellEditor && !d->chooseCell )
    {
      // Switch to editing mode
      createEditor( CellEditor );
      d->cellEditor->handleKeyPressEvent( event );
    }
    else if ( d->cellEditor )
      d->cellEditor->handleKeyPressEvent( event );
  }

  TQPoint cursor = cursorPos();

  d->view->doc()->emitEndOperation( TQRect( cursor, cursor ) );

  return;
}

bool Canvas::processControlArrowKey( TQKeyEvent *event )
{
  bool makingSelection = event->state() & ShiftButton;

  Sheet* sheet = activeSheet();
  Cell* cell = NULL;
  Cell* lastCell;
  TQPoint destination;
  bool searchThroughEmpty = true;
  int row;
  int col;

  TQPoint marker = d->chooseCell ? choice()->marker() : selectionInfo()->marker();

  /* here, we want to move to the first or last cell in the given direction that is
     actually being used.  Ignore empty cells and cells on hidden rows/columns */
  switch ( event->key() )
  {
    //Ctrl+Key_Up
   case Key_Up:

    cell = sheet->cellAt( marker.x(), marker.y() );
    if ( (cell != NULL) && (!cell->isEmpty()) && (marker.y() != 1))
    {
      lastCell = cell;
      row = marker.y()-1;
      cell = sheet->cellAt(cell->column(), row);
      while ((cell != NULL) && (row > 0) && (!cell->isEmpty()) )
      {
        if (!(sheet->rowFormat(cell->row())->isHide()))
        {
          lastCell = cell;
          searchThroughEmpty = false;
        }
        row--;
        if ( row > 0 )
          cell = sheet->cellAt(cell->column(), row);
      }
      cell = lastCell;
    }
    if (searchThroughEmpty)
    {
      cell = sheet->getNextCellUp(marker.x(), marker.y());

      while ((cell != NULL) &&
            (cell->isEmpty() || (sheet->rowFormat(cell->row())->isHide())))
      {
        cell = sheet->getNextCellUp(cell->column(), cell->row());
      }
    }

    if (cell == NULL)
      row = 1;
    else
      row = cell->row();

    while ( sheet->rowFormat(row)->isHide() )
    {
      row++;
    }

    destination.setX(marker.x());
    destination.setY(row);
    break;

    //Ctrl+Key_Down
   case Key_Down:

    cell = sheet->cellAt( marker.x(), marker.y() );
    if ( (cell != NULL) && (!cell->isEmpty()) && (marker.y() != KS_rowMax))
    {
      lastCell = cell;
      row = marker.y()+1;
      cell = sheet->cellAt(cell->column(), row);
      while ((cell != NULL) && (row < KS_rowMax) && (!cell->isEmpty()) )
      {
        if (!(sheet->rowFormat(cell->row())->isHide()))
        {
          lastCell = cell;
          searchThroughEmpty = false;
        }
        row++;
        cell = sheet->cellAt(cell->column(), row);
      }
      cell = lastCell;
    }
    if (searchThroughEmpty)
    {
      cell = sheet->getNextCellDown(marker.x(), marker.y());

      while ((cell != NULL) &&
            (cell->isEmpty() || (sheet->rowFormat(cell->row())->isHide())))
      {
        cell = sheet->getNextCellDown(cell->column(), cell->row());
      }
    }

    if (cell == NULL)
      row = marker.y();
    else
      row = cell->row();

    while ( sheet->rowFormat(row)->isHide() )
    {
      row--;
    }

    destination.setX(marker.x());
    destination.setY(row);
    break;

  //Ctrl+Key_Left
  case Key_Left:

  if ( sheet->layoutDirection()==Sheet::RightToLeft )
  {
    cell = sheet->cellAt( marker.x(), marker.y() );
    if ( (cell != NULL) && (!cell->isEmpty()) && (marker.x() != KS_colMax))
    {
      lastCell = cell;
      col = marker.x()+1;
      cell = sheet->cellAt(col, cell->row());
      while ((cell != NULL) && (col < KS_colMax) && (!cell->isEmpty()) )
      {
        if (!(sheet->columnFormat(cell->column())->isHide()))
        {
          lastCell = cell;
          searchThroughEmpty = false;
        }
        col++;
        cell = sheet->cellAt(col, cell->row());
      }
      cell = lastCell;
    }
    if (searchThroughEmpty)
    {
      cell = sheet->getNextCellRight(marker.x(), marker.y());

      while ((cell != NULL) &&
            (cell->isEmpty() || (sheet->columnFormat(cell->column())->isHide())))
      {
        cell = sheet->getNextCellRight(cell->column(), cell->row());
      }
    }

    if (cell == NULL)
      col = marker.x();
    else
      col = cell->column();

    while ( sheet->columnFormat(col)->isHide() )
    {
      col--;
    }

    destination.setX(col);
    destination.setY(marker.y());
  }
  else
  {
    cell = sheet->cellAt( marker.x(), marker.y() );
    if ( (cell != NULL) && (!cell->isEmpty()) && (marker.x() != 1))
    {
      lastCell = cell;
      col = marker.x()-1;
      cell = sheet->cellAt(col, cell->row());
      while ((cell != NULL) && (col > 0) && (!cell->isEmpty()) )
      {
        if (!(sheet->columnFormat(cell->column())->isHide()))
        {
          lastCell = cell;
          searchThroughEmpty = false;
        }
        col--;
        if ( col > 0 )
            cell = sheet->cellAt(col, cell->row());
      }
      cell = lastCell;
    }
    if (searchThroughEmpty)
    {
      cell = sheet->getNextCellLeft(marker.x(), marker.y());

      while ((cell != NULL) &&
            (cell->isEmpty() || (sheet->columnFormat(cell->column())->isHide())))
      {
        cell = sheet->getNextCellLeft(cell->column(), cell->row());
      }
    }

    if (cell == NULL)
      col = 1;
    else
      col = cell->column();

    while ( sheet->columnFormat(col)->isHide() )
    {
      col++;
    }

    destination.setX(col);
    destination.setY(marker.y());
  }
    break;

  //Ctrl+Key_Right
  case Key_Right:

  if ( sheet->layoutDirection()==Sheet::RightToLeft )
  {
    cell = sheet->cellAt( marker.x(), marker.y() );
    if ( (cell != NULL) && (!cell->isEmpty()) && (marker.x() != 1))
    {
      lastCell = cell;
      col = marker.x()-1;
      cell = sheet->cellAt(col, cell->row());
      while ((cell != NULL) && (col > 0) && (!cell->isEmpty()) )
      {
        if (!(sheet->columnFormat(cell->column())->isHide()))
        {
          lastCell = cell;
          searchThroughEmpty = false;
        }
        col--;
        if ( col > 0 )
            cell = sheet->cellAt(col, cell->row());
      }
      cell = lastCell;
    }
    if (searchThroughEmpty)
    {
      cell = sheet->getNextCellLeft(marker.x(), marker.y());

      while ((cell != NULL) &&
            (cell->isEmpty() || (sheet->columnFormat(cell->column())->isHide())))
      {
        cell = sheet->getNextCellLeft(cell->column(), cell->row());
      }
    }

    if (cell == NULL)
      col = 1;
    else
      col = cell->column();

    while ( sheet->columnFormat(col)->isHide() )
    {
      col++;
    }

    destination.setX(col);
    destination.setY(marker.y());
  }
  else
  {
    cell = sheet->cellAt( marker.x(), marker.y() );
    if ( (cell != NULL) && (!cell->isEmpty()) && (marker.x() != KS_colMax))
    {
      lastCell = cell;
      col = marker.x()+1;
      cell = sheet->cellAt(col, cell->row());
      while ((cell != NULL) && (col < KS_colMax) && (!cell->isEmpty()) )
      {
        if (!(sheet->columnFormat(cell->column())->isHide()))
        {
          lastCell = cell;
          searchThroughEmpty = false;
        }
        col++;
        cell = sheet->cellAt(col, cell->row());
      }
      cell = lastCell;
    }
    if (searchThroughEmpty)
    {
      cell = sheet->getNextCellRight(marker.x(), marker.y());

      while ((cell != NULL) &&
            (cell->isEmpty() || (sheet->columnFormat(cell->column())->isHide())))
      {
        cell = sheet->getNextCellRight(cell->column(), cell->row());
      }
    }

    if (cell == NULL)
      col = marker.x();
    else
      col = cell->column();

    while ( sheet->columnFormat(col)->isHide() )
    {
      col--;
    }

    destination.setX(col);
    destination.setY(marker.y());
  }
    break;

  }

  if ( marker == destination )
  {
    d->view->doc()->emitEndOperation( TQRect( destination, destination ) );
    return false;
  }

  if (makingSelection)
  {
    (d->chooseCell ? choice() : selectionInfo())->update(destination);
  }
  else
  {
    (d->chooseCell ? choice() : selectionInfo())->initialize(destination, activeSheet());
  }
  return true;
}


void Canvas::keyPressEvent ( TQKeyEvent * _ev )
{
  Sheet * sheet = activeSheet();

  if ( !sheet || formatKeyPress( _ev ))
    return;

  // Dont handle the remaining special keys.
  if ( _ev->state() & ( TQt::AltButton | TQt::ControlButton ) &&
       (_ev->key() != Key_Down) &&
       (_ev->key() != Key_Up) &&
       (_ev->key() != Key_Right) &&
       (_ev->key() != Key_Left) &&
       (_ev->key() != Key_Home) &&
       (_ev->key() != Key_Enter) &&
       (_ev->key() != Key_Return) &&
       (_ev->key() != KGlobalSettings::contextMenuKey()))
  {
    TQWidget::keyPressEvent( _ev );
    return;
  }

  // Always accept so that events are not
  // passed to the parent.
  _ev->accept();

  d->view->doc()->emitBeginOperation(false);
  if ( _ev->key() == KGlobalSettings::contextMenuKey() ) {
    int row = markerRow();
    int col = markerColumn();
    KoPoint kop(sheet->columnPos(col, this), sheet->rowPos(row, this));
    TQPoint p = d->view->doc()->zoomPoint(kop);
    p = mapToGlobal(p);
    d->view->openPopupMenu( p );
  }
  switch( _ev->key() )
  {
   case Key_Return:
   case Key_Enter:
    processEnterKey( _ev );
    return;
    break;
   case Key_Down:
   case Key_Up:
   case Key_Left:
   case Key_Right:
   case Key_Tab: /* a tab behaves just like a right/left arrow */
   case Key_Backtab:  /* and so does Shift+Tab */
    if (_ev->state() & ControlButton)
    {
      if ( !processControlArrowKey( _ev ) )
        return;
    }
    else
    {
      processArrowKey( _ev );
      return;
    }
    break;

   case Key_Escape:
    processEscapeKey( _ev );
    return;
    break;

   case Key_Home:
    if ( !processHomeKey( _ev ) )
      return;
    break;

   case Key_End:
    if ( !processEndKey( _ev ) )
      return;
    break;

   case Key_Prior:  /* Page Up */
    if ( !processPriorKey( _ev ) )
      return;
    break;

   case Key_Next:   /* Page Down */
    if ( !processNextKey( _ev ) )
      return;
    break;

   case Key_Delete:
    processDeleteKey( _ev );
    return;
    break;

   case Key_F2:
    processF2Key( _ev );
    return;
    break;

   case Key_F4:
    processF4Key( _ev );
    return;
    break;

   default:
    processOtherKey( _ev );
    return;
    break;
  }

  //most process*Key methods call emitEndOperation, this only gets called in some situations
  // (after some move operations)
  d->view->doc()->emitEndOperation( sheet->visibleRect( this ) );
  return;
}

void Canvas::processIMEvent( TQIMEvent * event )
{
  d->view->doc()->emitBeginOperation( false );
  if ( !d->cellEditor && !d->chooseCell )
  {
    // Switch to editing mode
    createEditor( CellEditor );
    d->cellEditor->handleIMEvent( event );
  }

  TQPoint cursor;

  if ( d->chooseCell )
  {
    cursor = choice()->cursor();
    /* if the cursor is unset, pretend we're starting at the regular cursor */
    if (cursor.x() == 0 || cursor.y() == 0)
      cursor = choice()->cursor();
  }
  else
    cursor = selectionInfo()->cursor();

  d->view->doc()->emitEndOperation( TQRect( cursor, cursor ) );
}

bool Canvas::formatKeyPress( TQKeyEvent * _ev )
{
  if (!(_ev->state() & ControlButton ))
    return false;

  int key = _ev->key();
  if ( key != Key_Exclam && key != Key_At && key != Key_Ampersand
       && key != Key_Dollar && key != Key_Percent && key != Key_AsciiCircum
       && key != Key_NumberSign )
    return false;

  Cell  * cell = 0L;
  Sheet * sheet = activeSheet();

  d->view->doc()->emitBeginOperation(false);

  if ( !d->view->doc()->undoLocked() )
  {
    TQString dummy;
    UndoCellFormat * undo = new UndoCellFormat( d->view->doc(), sheet, *selectionInfo(), dummy );
    d->view->doc()->addCommand( undo );
  }

  Region::ConstIterator end(selectionInfo()->constEnd());
  for (Region::ConstIterator it = selectionInfo()->constBegin(); it != end; ++it)
  {
    TQRect rect = (*it)->rect().normalize();

  int right  = rect.right();
  int bottom = rect.bottom();

  if ( util_isRowSelected(rect) )
  {
    for ( int r = rect.top(); r <= bottom; ++r )
    {
      cell = sheet->getFirstCellRow( r );
      while ( cell )
      {
        if ( cell->isPartOfMerged() )
        {
          cell = sheet->getNextCellRight( cell->column(), r );
          continue;
        }

        formatCellByKey (cell, _ev->key(), rect);

        cell = sheet->getNextCellRight( cell->column(), r );
      } // while (cell)
      RowFormat * rw = sheet->nonDefaultRowFormat( r );
      TQPen pen;
      switch ( _ev->key() )
      {
       case Key_Exclam:
        rw->setFormatType (Number_format);
        rw->setPrecision( 2 );
        break;

       case Key_Dollar:
        rw->setFormatType (Money_format);
        rw->setPrecision( d->view->doc()->locale()->fracDigits() );
        break;

       case Key_Percent:
        rw->setFormatType (Percentage_format);
        break;

       case Key_At:
        rw->setFormatType( SecondeTime_format );
        break;

       case Key_NumberSign:
        rw->setFormatType( ShortDate_format );
        break;

       case Key_AsciiCircum:
        rw->setFormatType( Scientific_format );
        break;

       case Key_Ampersand:
        if ( r == rect.top() )
        {
          pen = TQPen( d->view->borderColor(), 1, SolidLine);
          rw->setTopBorderPen( pen );
        }
        if ( r == rect.bottom() )
        {
          pen = TQPen( d->view->borderColor(), 1, SolidLine);
          rw->setBottomBorderPen( pen );
        }
        break;

       default:
         d->view->doc()->emitEndOperation( rect );
        return false;
      }
      sheet->emit_updateRow( rw, r );
    }

    d->view->doc()->emitEndOperation( rect );
    return true;
  }

  if ( util_isColumnSelected(rect) )
  {
    for ( int c = rect.left(); c <= right; ++c )
    {
      cell = sheet->getFirstCellColumn( c );
      while ( cell )
      {
        if ( cell->isPartOfMerged() )
        {
          cell = sheet->getNextCellDown( c, cell->row() );
          continue;
        }

        formatCellByKey (cell, _ev->key(), rect);

        cell = sheet->getNextCellDown( c, cell->row() );
      }

      ColumnFormat * cw = sheet->nonDefaultColumnFormat( c );
      TQPen pen;
      switch ( _ev->key() )
      {
       case Key_Exclam:
        cw->setFormatType( Number_format );
        cw->setPrecision( 2 );
        break;

       case Key_Dollar:
        cw->setFormatType( Money_format );
        cw->setPrecision( d->view->doc()->locale()->fracDigits() );
        break;

       case Key_Percent:
        cw->setFormatType( Percentage_format );
        break;

       case Key_At:
        cw->setFormatType( SecondeTime_format );
        break;

       case Key_NumberSign:
        cw->setFormatType( ShortDate_format );
        break;

       case Key_AsciiCircum:
        cw->setFormatType( Scientific_format );
        break;

       case Key_Ampersand:
        if ( c == rect.left() )
        {
          pen = TQPen( d->view->borderColor(), 1, SolidLine);
          cw->setLeftBorderPen( pen );
        }
        if ( c == rect.right() )
        {
          pen = TQPen( d->view->borderColor(), 1, SolidLine);
          cw->setRightBorderPen( pen );
        }
        break;

       default:
         d->view->doc()->emitEndOperation( rect );
         return false;
      }
      sheet->emit_updateColumn( cw, c );
    }
    d->view->doc()->emitEndOperation( rect );
    return true;
  }

  for ( int row = rect.top(); row <= bottom; ++row )
  {
    for ( int col = rect.left(); col <= right; ++ col )
    {
      cell = sheet->nonDefaultCell( col, row );

      if ( cell->isPartOfMerged() )
        continue;

      formatCellByKey (cell, _ev->key(), rect);
    } // for left .. right
  } // for top .. bottom

  }
  _ev->accept();

  d->view->doc()->emitEndOperation( *selectionInfo() );
  return true;
}

bool Canvas::formatCellByKey (Cell *cell, int key, const TQRect &rect)
{
  TQPen pen;
  switch (key)
  {
    case Key_Exclam:
    cell->convertToDouble ();
    cell->format()->setFormatType (Number_format);
    cell->format()->setPrecision( 2 );
    break;

    case Key_Dollar:
    cell->convertToMoney ();
    break;

    case Key_Percent:
    cell->convertToPercent ();
    break;

    case Key_At:
    cell->convertToTime ();
    break;

    case Key_NumberSign:
    cell->convertToDate ();
    break;

    case Key_AsciiCircum:
    cell->format()->setFormatType (Scientific_format);
    cell->convertToDouble ();
    break;

    case Key_Ampersand:
    if ( cell->row() == rect.top() )
    {
      pen = TQPen( d->view->borderColor(), 1, SolidLine);
      cell->setTopBorderPen( pen );
    }
    if ( cell->row() == rect.bottom() )
    {
      pen = TQPen( d->view->borderColor(), 1, SolidLine);
      cell->setBottomBorderPen( pen );
    }
    if ( cell->column() == rect.left() )
    {
      pen = TQPen( d->view->borderColor(), 1, SolidLine);
      cell->setLeftBorderPen( pen );
    }
    if ( cell->column() == rect.right() )
    {
      pen = TQPen( d->view->borderColor(), 1, SolidLine);
      cell->setRightBorderPen( pen );
    }
    break;
  } // switch

  return true;
}


void Canvas::slotAutoScroll(const TQPoint &scrollDistance)
{
  TQPoint d = scrollDistance;
  horzScrollBar()->setValue( horzScrollBar()->value() + d.x() );
  vertScrollBar()->setValue( vertScrollBar()->value() + d.y() );
}

void Canvas::doAutoScroll()
{
    if ( !d->mousePressed )
    {
        d->scrollTimer->stop();
        return;
    }
    bool select = false;
    TQPoint pos = mapFromGlobal( TQCursor::pos() );

    //Provide progressive scrolling depending on the mouse position
    if ( pos.y() < 0 )
    {
        vertScrollBar()->setValue ((int) (vertScrollBar()->value() -
                                   autoScrollAccelerationY( - pos.y())));
        select = true;
    }
    else if ( pos.y() > height() )
    {
        vertScrollBar()->setValue ((int) (vertScrollBar()->value() +
                                   autoScrollAccelerationY (pos.y() - height())));
        select = true;
    }

    if ( pos.x() < 0 )
    {
        horzScrollBar()->setValue ((int) (horzScrollBar()->value() -
                                   autoScrollAccelerationX( - pos.x() )));
        select = true;
    }
    else if ( pos.x() > width() )
    {
        horzScrollBar()->setValue ((int) (horzScrollBar()->value() +
                                 autoScrollAccelerationX( pos.x() - width())));
        select = true;
    }

    if ( select )
    {
        TQMouseEvent * event = new TQMouseEvent(TQEvent::MouseMove, pos, 0, 0);
        mouseMoveEvent( event );
        delete event;
    }

    //Restart timer
    d->scrollTimer->start( 50 );
}

void Canvas::speakCell(TQWidget* w, const TQPoint& p, uint flags)
{
  Q_UNUSED(flags);
  if (w != this) return;
  Sheet* sheet = activeSheet();
  if (!sheet) return;
  int row = -1;
  int col = -1;
  if (p == TQPoint()) {
    row = markerRow();
    col = markerColumn();
    if (row == d->prevSpokenFocusRow && col == d->prevSpokenFocusCol) return;
    d->prevSpokenFocusRow = row;
    d->prevSpokenFocusCol = col;
  } else {
    TQPoint wp = w->mapFromGlobal(p);
    double tmp;
    double posX;
    if ( sheet->layoutDirection()==Sheet::RightToLeft )
    {
      double dwidth = d->view->doc()->unzoomItX( width() );
      posX = dwidth - d->view->doc()->unzoomItX( wp.x() );
    }
    else
      posX = d->view->doc()->unzoomItX( wp.x() );

    double posY = d->view->doc()->unzoomItY( wp.y() );
    col = sheet->leftColumn( (posX + xOffset()), tmp );
    row = sheet->topRow( (posY + yOffset()), tmp );
    if (row == d->prevSpokenPointerRow && col == d->prevSpokenPointerCol) return;
    d->prevSpokenPointerRow = row;
    d->prevSpokenPointerCol = col;
  }
  if (row == d->prevSpokenRow && col == d->prevSpokenCol) return;
  d->prevSpokenRow = row;
  d->prevSpokenCol = col;
  // kdDebug() << "Canvas::speakCell: row = " << row << " col = " << col << endl;
  if (row >=0 && col >= 0) {
    Cell* cell = sheet->cellAt( col, row );
    if (!cell) return;
    TQString text = cell->strOutText();
    if (!text.isEmpty()) {
      text.prepend(i18n("Spreadsheet cell", "Cell ") + cell->name() + " ");
      if (cell->isFormula()) {
        TQString f = cell->text();
        // Try to format the formula so synth can more clearly speak it.
        TQString f2;
        for (uint i = 0; i < f.length(); i++) f2 += f[i] + " ";
        f2.replace("(", i18n("character (", "left paren"));
        f2.replace(")", i18n("character )", "right paren"));
        f2.replace(":", i18n("character :", "colon"));
        f2.replace(";", i18n("character ;", "semicolon"));
        f2.replace("=", i18n("character =", "equals"));
        f2.replace(".", i18n("character .", "point"));
        f2.replace(",", i18n("character ,", "comma"));
        f2.replace(" . . ", i18n("characters ..", " dot dot "));
        text.append(i18n("Spreadsheet formula", " Formula ") + f2);
      }
      // kdDebug() << "Canvas::speakCell: text = " << text << endl;
      kospeaker->sayWidget(text);
    }
  }
}

double Canvas::autoScrollAccelerationX( int offset )
{
    switch( static_cast<int>( offset / 20 ) )
    {
        case 0: return 5.0;
        case 1: return 20.0;
        case 2: return d->view->doc()->unzoomItX( width() );
        case 3: return d->view->doc()->unzoomItX( width() );
        default: return d->view->doc()->unzoomItX( (int) (width() * 5.0) );
    }
}

double Canvas::autoScrollAccelerationY( int offset )
{
    switch( static_cast<int>( offset / 20 ) )
    {
        case 0: return 5.0;
        case 1: return 20.0;
        case 2: return d->view->doc()->unzoomItY( height() );
        case 3: return d->view->doc()->unzoomItY( height() );
        default: return d->view->doc()->unzoomItY( (int) (height() * 5.0) );
    }
}


KSpread::EmbeddedObject *Canvas::getObject( const TQPoint &pos, Sheet *_sheet )
{
  TQPoint const p ( (int) pos.x() ,
              (int) pos.y() );

  TQPtrListIterator<EmbeddedObject> itObject( doc()->embeddedObjects() );
  for( ; itObject.current(); ++itObject )
  {
    if ( itObject.current()->sheet() == _sheet )
    {
        KoRect const bound = ( itObject.current() )->tqgeometry();
        TQRect zoomedBound = doc()->zoomRect( KoRect(bound.left(), bound.top(),
                                bound.width(),
                                bound.height() ) );
        zoomedBound.moveBy( (int)( -xOffset() * doc()->zoomedResolutionX() ), (int)( -yOffset() * doc()->zoomedResolutionY() ) );
         if ( zoomedBound.contains( p ) )
              return itObject.current();
    }
  }
  return 0;
}

void Canvas::selectObject( EmbeddedObject *obj )
{
  if ( obj->sheet() != activeSheet() || obj->isSelected() )
    return;
  obj->setSelected( true );
  repaintObject( obj );

  d->mouseSelectedObject = true;
  emit objectSelectedChanged();
  deleteEditor( true );
}

void Canvas::deselectObject( EmbeddedObject *obj )
{
  if ( obj->sheet() != activeSheet() || !obj->isSelected() )
    return;
  obj->setSelected( false );
  repaintObject( obj );

  d->mouseSelectedObject = false;
  emit objectSelectedChanged();
}

void Canvas::selectAllObjects()
{
  TQPtrListIterator<EmbeddedObject> it( doc()->embeddedObjects() );
  for ( ; it.current() ; ++it )
  {
    if ( it.current()->sheet() == activeSheet() )
      it.current()->setSelected( true );
  }

   d->mouseSelectedObject = true;
//   emit objectSelectedChanged();
}

void Canvas::deselectAllObjects()
{
  if( activeSheet()->numSelected() == 0 )
    return;

  //lowerObject();

  TQPtrListIterator<EmbeddedObject> it( doc()->embeddedObjects() );
  for ( ; it.current() ; ++it )
      deselectObject( it.current() );

   d->mouseSelectedObject = false;
//   emit objectSelectedChanged();
}



void Canvas::setMouseSelectedObject(bool b)
{
  d->mouseSelectedObject = b;
  emit objectSelectedChanged();
}

bool Canvas::isObjectSelected()
{
  return d->mouseSelectedObject;
}


void Canvas::moveObjectsByMouse( KoPoint &pos, bool keepXorYunchanged )
{
  KoRect rect( objectRect( false ) );
  KoPoint move( 0, 0 );
  double diffx = pos.x() - d->m_origMousePos.x();
  double diffy = pos.y() - d->m_origMousePos.y();

  move = KoPoint( diffx, diffy );
  d->m_origMousePos = pos;

    // unwind last snapping
  KoRect movedRect( rect );
  movedRect.moveBy( diffx, diffy );

    // don't move object off canvas
  KoPoint diffDueToBorders(0,0);
//   KoRect pageRect( m_activePage->getPageRect() );
  if ( rect.left() + move.x() < 0/*pageRect.left()*/ )
    diffDueToBorders.setX( -rect.left() - move.x() );
//   else if ( rect.right() + move.x() > pageRect.right() )
//     diffDueToBorders.setX( pageRect.right() - (rect.right() + move.x()) );


  //kdDebug() << "rect.top() + move.y():" << rect.top() + move.y()<< endl;
  if ( rect.top() + move.y() < 0 )
    diffDueToBorders.setY( -rect.top() - move.y() );
//   else if ( rect.bottom() + move.y() > pageRect.bottom() )
//     diffDueToBorders.setY( pageRect.bottom() - (rect.bottom() + move.y()) );

//   m_moveSnapDiff += diffDueToBorders;
  move += diffDueToBorders;

//   movedRect.moveBy( m_moveSnapDiff.x(), m_moveSnapDiff.y() );
  if ( keepXorYunchanged )
  {
    KoPoint diff( d->m_moveStartPosMouse - movedRect.topLeft() );
    if ( fabs( diff.x() ) > fabs( diff.y() ) )
    {
//       m_moveSnapDiff.setY( /*m_moveSnapDiff.y() + */m_moveStartPosMouse.y() - movedRect.y() );
      movedRect.moveTopLeft( KoPoint( movedRect.x(), d->m_moveStartPosMouse.y() ) );
      move.setY( movedRect.y() - rect.y() );
    }
    else
    {
//       m_moveSnapDiff.setX( /*m_moveSnapDiff.x() + */m_moveStartPosMouse.x() - movedRect.x() );
      movedRect.moveTopLeft( KoPoint( d->m_moveStartPosMouse.x(), movedRect.y() ) );
      move.setX( movedRect.x() - rect.x() );
    }
  }

  if ( move != KoPoint( 0, 0 ) )
  {
        //kdDebug(33001) << "moveObjectsByMouse move = " << move << endl;
    activeSheet()->moveObject( view(), move, false );
  }
}


void Canvas::resizeObject( ModifyType _modType, const KoPoint & point, bool keepRatio )
{
    EmbeddedObject *obj = d->m_resizeObject;

    KoRect objRect = obj->tqgeometry();
    objRect.moveBy( -xOffset(), -yOffset() );
    TQRect oldBoundingRect( doc()->zoomRect( objRect ) );

    bool left = false;
    bool right = false;
    bool top = false;
    bool bottom = false;
    if ( _modType == MT_RESIZE_UP || _modType == MT_RESIZE_LU || _modType == MT_RESIZE_RU )
    {
        top = true;
//         snaptqStatus |= KoGuides::SNAP_HORIZ;
    }
    if ( _modType == MT_RESIZE_DN || _modType == MT_RESIZE_LD || _modType == MT_RESIZE_RD )
    {
        bottom = true;
//         snaptqStatus |= KoGuides::SNAP_HORIZ;
    }
    if ( _modType == MT_RESIZE_LF || _modType == MT_RESIZE_LU || _modType == MT_RESIZE_LD )
    {
        left = true;
//         snaptqStatus |= KoGuides::SNAP_VERT;
    }
    if ( _modType == MT_RESIZE_RT || _modType == MT_RESIZE_RU || _modType == MT_RESIZE_RD )
    {
        right = true;
//         snaptqStatus |= KoGuides::SNAP_VERT;
    }

    double newLeft = objRect.left();
    double newRight = objRect.right();
    double newTop = objRect.top();
    double newBottom = objRect.bottom();
    if ( top )
    {
        if ( point.y() < objRect.bottom() - MIN_SIZE )
        {
            newTop = point.y();
        }
        else
        {
            newTop = objRect.bottom() - MIN_SIZE;
        }
    }
    if ( bottom )
    {
        if ( point.y() > objRect.top() + MIN_SIZE )
        {
            newBottom = point.y();
        }
        else
        {
            newBottom = objRect.top() + MIN_SIZE;
        }
    }
    if ( left )
    {
        if ( point.x() < objRect.right() - MIN_SIZE )
        {
            newLeft = point.x();
        }
        else
        {
            newLeft = objRect.right() - MIN_SIZE;
        }
    }
    if ( right )
    {
        if ( point.x() > objRect.left() + MIN_SIZE )
        {
            newRight = point.x();
        }
        else
        {
            newRight = objRect.left() + MIN_SIZE;
        }
    }

  double width = newRight - newLeft;
  double height = newBottom - newTop;

  if ( keepRatio && d->m_ratio != 0 )
  {
    if ( ( top || bottom ) && ( right || left ) )
    {
      if ( height * height * d->m_ratio > width * width / d->m_ratio )
      {
        width = height * d->m_ratio;
      }
      else
      {
        height = width / d->m_ratio;
      }
    }
    else if ( top || bottom )
    {
      width = height * d->m_ratio;
    }
    else
    {
      height = width / d->m_ratio;
    }

    if ( top )
    {
      newTop = objRect.bottom() - height;
    }
    else
    {
      newBottom = objRect.top() + height;
    }
    if ( left )
    {
      newLeft = objRect.right() - width;
    }
    else
    {
      newRight = objRect.right() + width;
    }
  }

  if ( newLeft != objRect.left() || newRight != objRect.right() || newTop != objRect.top() || newBottom != objRect.bottom() )
  {
        // resizeBy and moveBy have to been used to make it work with rotated objects
        obj->resizeBy( width - objRect.width(), height - objRect.height() );

        if ( objRect.left() != newLeft || objRect.top() != newTop )
        {
            obj->moveBy( KoPoint( newLeft - objRect.left(), newTop - objRect.top() ) );
        }

//     if ( doc()->showGuideLines() && !m_disableSnapping )
//     {
//       KoRect rect( obj->getRealRect() );
//       KoPoint sp( rect.topLeft() );
//       if ( right )
//       {
//         sp.setX( rect.right() );
//       }
//       if ( bottom )
//       {
//         sp.setY( rect.bottom() );
//       }
//       m_gl.repaintSnapping( sp, snaptqStatus );
//     }

    tqrepaint( oldBoundingRect );
    repaintObject( obj );
    emit objectSizeChanged();
  }
}


void Canvas::finishResizeObject( const TQString &/*name*/, bool /*tqlayout*/ )
{
  if ( d->m_resizeObject )
  {
    KoPoint move = KoPoint( d->m_resizeObject->tqgeometry().x() - d->m_rectBeforeResize.x(),
                            d->m_resizeObject->tqgeometry().y() - d->m_rectBeforeResize.y() );
    KoSize size = KoSize( d->m_resizeObject->tqgeometry().width() - d->m_rectBeforeResize.width(),
                          d->m_resizeObject->tqgeometry().height() - d->m_rectBeforeResize.height() );

    if ( ( d->m_resizeObject->tqgeometry() ) != d->m_rectBeforeResize )
    {
        ChangeObjectGeometryCommand *resizeCmd = new ChangeObjectGeometryCommand( d->m_resizeObject, move, size );
        // the command is not executed as the object is allready resized.
        doc()->addCommand( resizeCmd );
    }

//     if ( tqlayout )
//       doc()->tqlayout( m_resizeObject );

    d->m_ratio = 0.0;
    d->m_isResizing = false;
    repaintObject( d->m_resizeObject );
    d->m_resizeObject = NULL;
  }
}

void Canvas::raiseObject( EmbeddedObject *object )
{
    if ( doc()->embeddedObjects().count() <= 1 )
        return;

    if ( d->m_objectDisplayAbove == 0 )
    {
        if ( activeSheet()->numSelected() == 1 )
        {
            d->m_objectDisplayAbove = object;
        }
    }
}

void Canvas::lowerObject()
{
    d->m_objectDisplayAbove = 0;
}

void Canvas::displayObjectList( TQPtrList<EmbeddedObject> &list )
{
  list = doc()->embeddedObjects();
  list.setAutoDelete( false );

    if ( d->m_objectDisplayAbove )
    {
        // it can happen that the object is no longer there e.g. when
        // the insert of the object is undone
        int pos = doc()->embeddedObjects().findRef( d->m_objectDisplayAbove );
        if ( pos != -1 && d->m_objectDisplayAbove->isSelected() )
        {
            list.take( pos );
            list.append( d->m_objectDisplayAbove );
        }
        else
        {
            //tz not possible due to const. should const be removed?
            //m_objectDisplayAbove = 0;
        }
    }
}


KoRect Canvas::objectRect( bool all ) const
{
  return activeSheet()->getRealRect( all );
}

void Canvas::deleteEditor (bool saveChanges, bool array)
{
  if ( !d->cellEditor )
    return;


	//There may be highlighted areas on the sheet which will need to be erased
	setSelectionChangePaintDirty( activeSheet() , *choice() );

  	d->editWidget->setEditMode( false );

  TQString t = d->cellEditor->text();
  // Delete the cell editor first and after that update the document.
  // That means we get a synchronous tqrepaint after the cell editor
  // widget is gone. Otherwise we may get painting errors.
  delete d->cellEditor;
  d->cellEditor = 0;

  if ( saveChanges )
  {
      if ( t.at(0)=='=' )
      {
          //a formula
          int openParenthese = t.contains('(' );
          int closeParenthese = t.contains(')' );
          int diff = TQABS( openParenthese - closeParenthese );
          if ( openParenthese > closeParenthese )
          {
              for (int i=0; i < diff;i++)
              {
                  t=t+')';
              }
          }
      }
    d->view->setText (t, array);
  }
  else
  {
    d->view->updateEditWidget();
  }

  setFocus();
}


void Canvas::createEditor(bool captureArrowKeys)
{
  if (!activeSheet())
    return;

  Cell * cell = activeSheet()->nonDefaultCell( markerColumn(), markerRow(), false );

  if ( !createEditor( CellEditor , true , captureArrowKeys ) )
      return;
  if ( cell )
      d->cellEditor->setText( cell->text() );
}

bool Canvas::createEditor( EditorType ed, bool addFocus, bool captureArrowKeys )
{
  Sheet * sheet = activeSheet();

  // Set the starting sheet of the choice.
  choice()->setSheet( activeSheet() );

  if ( !d->cellEditor )
  {
    Cell * cell = sheet->nonDefaultCell( marker().x(), marker().y(), false );

    if ( sheet->isProtected() && !cell->format()->notProtected( marker().x(), marker().y() ) )
      return false;

    if ( ed == CellEditor )
    {
      d->editWidget->setEditMode( true );
      d->cellEditor = new KSpread::CellEditor( cell, this, captureArrowKeys );
    }

    double w, h;
    double min_w = cell->dblWidth( markerColumn() );
    double min_h = cell->dblHeight( markerRow() );
    if ( cell->isDefault() )
    {
      w = min_w;
      h = min_h;
      //kdDebug(36001) << "DEFAULT" << endl;
    }
    else
    {
      w = cell->extraWidth();
      h = cell->extraHeight();
      //kdDebug(36001) << "HEIGHT=" << min_h << " EXTRA=" << h << endl;
    }

    double xpos = sheet->dblColumnPos( markerColumn() ) - xOffset();

    Sheet::LayoutDirection sheetDir = sheet->layoutDirection();
    bool rtlText = cell->strOutText().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 == Sheet::RightToLeft && !rtlText ) ||
                    ( sheetDir == Sheet::LeftToRight && rtlText  ) ) )
      xpos -= w - min_w;

    // paint editor above correct cell if sheet direction is RTL
    if ( sheetDir == Sheet::RightToLeft )
    {
      double dwidth = d->view->doc()->unzoomItX( width() );
      double w2 = TQMAX( w, min_w );
      xpos = dwidth - w2 - xpos;
    }

    double ypos = sheet->dblRowPos( markerRow() ) - yOffset();
    TQPalette p = d->cellEditor->palette();
    TQColorGroup g( p.active() );

    TQColor color = cell->format()->textColor( markerColumn(), markerRow() );
    if ( !color.isValid() )
        color = TQApplication::tqpalette().active().text();
    g.setColor( TQColorGroup::Text, color);

    color = cell->bgColor( markerColumn(), markerRow() );
    if ( !color.isValid() )
        color = g.base();
    g.setColor( TQColorGroup::Background, color );

    d->cellEditor->setPalette( TQPalette( g, p.disabled(), g ) );
    TQFont tmpFont = cell->format()->textFont( markerColumn(), markerRow() );
    tmpFont.setPointSizeFloat( 0.01 * d->view->doc()->zoom() * tmpFont.pointSizeFloat() );
    d->cellEditor->setFont( tmpFont );

    KoRect rect( xpos, ypos, w, h ); //needed to circumvent rounding issue with height/width


    TQRect zoomedRect=d->view->doc()->zoomRect( rect );
	/*zoomedRect.setLeft(zoomedRect.left()-2);
	zoomedRect.setRight(zoomedRect.right()+4);
	zoomedRect.setTop(zoomedRect.top()-1);
	zoomedRect.setBottom(zoomedRect.bottom()+2);*/

    d->cellEditor->setGeometry( zoomedRect );
    d->cellEditor->setMinimumSize( TQSize( d->view->doc()->zoomItX( min_w ), d->view->doc()->zoomItY( min_h ) ) );
    d->cellEditor->show();
    //kdDebug(36001) << "FOCUS1" << endl;
    //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.
  //  startChoose();

    if ( addFocus )
        d->cellEditor->setFocus();

	setSelectionChangePaintDirty(sheet, *selectionInfo());
	paintUpdates();
  }

  return true;
}

void Canvas::repaintObject( EmbeddedObject *obj )
{
	//Calculate where the object appears on the canvas widget and then tqrepaint that part of the widget
	TQRect canvasRelativeGeometry = doc()->zoomRect( obj->tqgeometry() );
	canvasRelativeGeometry.moveBy( (int)( -xOffset()*doc()->zoomedResolutionX() ) ,
			   			(int)( -yOffset() * doc()->zoomedResolutionY()) );

    update( canvasRelativeGeometry );

 /* if ( !obj->isSelected() )
  {
    KoRect g = obj->tqgeometry();
    g.moveBy( -xOffset(), -yOffset() );
    TQRect tqgeometry( doc()->zoomRect( g ) );

    update( tqgeometry );
  }
  else
  {
    TQPainter p(this);
    p.translate( -xOffset() * doc()->zoomedResolutionX() , -yOffset() * doc()->zoomedResolutionY() );
    obj->draw(&p); //this goes faster than calling tqrepaint
    p.end();
  }*/
}

void Canvas::copyOasisObjects()
{
    // We'll create a store (ZIP format) in memory
    TQBuffer buffer;
    TQCString mimeType = "application/vnd.oasis.opendocument.spreadsheet";
    KoStore* store = KoStore::createStore( TQT_TQIODEVICE(&buffer), KoStore::Write, mimeType );
    Q_ASSERT( store );
    Q_ASSERT( !store->bad() );
    KoOasisStore oasisStore( store );

    KoXmlWriter* manifestWriter = oasisStore.manifestWriter( mimeType );

    TQString plainText;
    KoPicture picture;
    if ( !doc()->saveOasisHelper( store, manifestWriter, Doc::SaveSelected, &plainText, &picture )
         || !oasisStore.closeManifestWriter() )
    {
        delete store;
        return;
    }
    delete store;

    KMultipleDrag* multiDrag = new KMultipleDrag();
    if ( !plainText.isEmpty() )
        multiDrag->addDragObject( new TQTextDrag( plainText, 0 ) );
    if ( !picture.isNull() )
        multiDrag->addDragObject( picture.dragObject( 0 ) );
    KoStoreDrag* storeDrag = new KoStoreDrag( mimeType, 0 );
    kdDebug() << k_funcinfo << "setting zip data: " << buffer.buffer().size() << " bytes." << endl;
    storeDrag->setEncodedData( buffer.buffer() );
    multiDrag->addDragObject( storeDrag );

    //save the objects as pictures too so that other programs can access them
    TQPtrListIterator<EmbeddedObject> itObject( doc()->embeddedObjects() );
    itObject.toFirst();
    if ( itObject.current() )
    {
      KoRect kr = objectRect(false);
      TQRect r( kr.toTQRect() );
      TQPixmap pixmap( r.width(), r.height() );
      pixmap.fill( "white" );
      TQPainter p(&pixmap);
      for( ; itObject.current(); ++itObject )
      {
        if ( itObject.current()->isSelected() )
          p.drawPixmap( itObject.current()->tqgeometry().toTQRect().left() - r.left(), itObject.current()->tqgeometry().toTQRect().top() - r.top(), itObject.current()->toPixmap( 1.0 , 1.0 ) );
      }
      p.end();
      if (!pixmap.isNull())
      {
        TQImageDrag *imagedrag = new TQImageDrag( pixmap.convertToImage() );
        multiDrag->addDragObject( imagedrag );
      }
    }

    TQDragObject *dragObject = multiDrag;
    TQApplication::tqclipboard()->setData( dragObject, TQClipboard::Clipboard );
}

void Canvas::closeEditor()
{
  if ( d->chooseCell )
    return;

  if ( d->cellEditor )
  {
    deleteEditor( true ); // save changes
  }
}

void Canvas::updateEditor()
{
  if (!d->chooseCell)
    return;

  Sheet* sheet = activeSheet();
  if (!sheet)
    return;

  if (d->cellEditor)
  {
    if (choice()->sheet() != sheet)
    {
      d->cellEditor->hide();
    }
    else
    {
      d->cellEditor->show();
    }
    d->cellEditor->updateChoice();
  }
}

void Canvas::setSelectionChangePaintDirty(Sheet* sheet, const Region& region)
{
  sheet->setRegionPaintDirty(region); // TODO should the paintDirtyList be in Canvas?
}


void Canvas::updatePosWidget()
{
    TQString buffer;
    // No selection, or only one cell merged selected
    if ( selectionInfo()->isSingular() )
    {
        if (activeSheet()->getLcMode())
        {
            buffer = "L" + TQString::number( markerRow() ) +
		"C" + TQString::number( markerColumn() );
        }
        else
        {
            buffer = Cell::columnName( markerColumn() ) +
		TQString::number( markerRow() );
        }
    }
    else
    {
        if (activeSheet()->getLcMode())
        {
          buffer = TQString::number( (selectionInfo()->lastRange().bottom()-selectionInfo()->lastRange().top()+1) )+"Lx";
          if ( util_isRowSelected( selectionInfo()->lastRange() ) )
            buffer+=TQString::number((KS_colMax-selectionInfo()->lastRange().left()+1))+"C";
            else
              buffer+=TQString::number((selectionInfo()->lastRange().right()-selectionInfo()->lastRange().left()+1))+"C";
        }
        else
        {
                //encodeColumnLabelText return @@@@ when column >KS_colMax
                //=> it's not a good display
                //=> for the moment I display pos of marker
          buffer=Cell::columnName( selectionInfo()->lastRange().left() ) +
                    TQString::number(selectionInfo()->lastRange().top()) + ":" +
                    Cell::columnName( TQMIN( KS_colMax, selectionInfo()->lastRange().right() ) ) +
                    TQString::number(selectionInfo()->lastRange().bottom());
                //buffer=activeSheet()->columnLabel( m_iMarkerColumn );
                //buffer+=tmp.setNum(m_iMarkerRow);
        }
  }

    if (buffer != d->posWidget->lineEdit()->text())
      d->posWidget->lineEdit()->setText(buffer);
}

void Canvas::equalizeRow()
{
  TQRect s( selection() );
  RowFormat *rl = d->view->activeSheet()->rowFormat(s.top());
  int size=rl->height(this);
  if ( s.top() == s.bottom() )
      return;
  for(int i=s.top()+1;i<=s.bottom();i++)
  {
      Sheet *sheet = activeSheet();
      if ( !sheet )
          return;
      size=TQMAX(d->view->activeSheet()->rowFormat(i)->height(this),size);
  }
  d->view->vBorderWidget()->equalizeRow(size);
}

void Canvas::equalizeColumn()
{
  TQRect s( selection() );
  ColumnFormat *cl = d->view->activeSheet()->columnFormat(s.left());
  int size=cl->width(this);
  if ( s.left() == s.right() )
      return;

  for(int i=s.left()+1;i<=s.right();i++)
  {
    size=TQMAX(d->view->activeSheet()->columnFormat(i)->width(this),size);
  }
  d->view->hBorderWidget()->equalizeColumn(size);
}

TQRect Canvas::cellsInArea( const TQRect area ) const
{
	KoRect unzoomedRect = d->view->doc()->unzoomRect( area );

       	unzoomedRect.moveBy( (int)xOffset(), (int)yOffset() );

  	double tmp;
  	int left_col = activeSheet()->leftColumn( unzoomedRect.left(), tmp );
  	int right_col = activeSheet()->rightColumn( unzoomedRect.right() );
  	int top_row = activeSheet()->topRow( unzoomedRect.top(), tmp );
  	int bottom_row = activeSheet()->bottomRow( unzoomedRect.bottom() );

  	return TQRect( left_col, top_row,
                right_col - left_col + 1, bottom_row - top_row + 1 );
}

TQRect Canvas::visibleCells() const
{
	return cellsInArea( TQRect(0,0,width(),height()) );

}


//---------------------------------------------
//
// Drawing Engine
//
//---------------------------------------------

void Canvas::paintUpdates()
{
  if (activeSheet() == NULL)
    return;

  TQPainter painter(this);

  //Save clip region
  TQRegion rgnComplete( painter.clipRegion() );
  TQWMatrix matrix;
  if ( d->view )
  {
    matrix = d->view->matrix();
  }
  else
  {
    matrix = painter.tqworldMatrix();
  }


  paintChildren( painter, matrix );

  painter.save();
  clipoutChildren( painter );

  KoRect unzoomedRect = d->view->doc()->unzoomRect( TQRect( 0, 0, width(), height() ) );
  // unzoomedRect.moveBy( xOffset(), yOffset() );


  /* paint any visible cell that has the paintDirty flag */
  TQRect range = visibleCells();
  Cell* cell = NULL;

  double topPos = activeSheet()->dblRowPos(range.top());
  double leftPos = activeSheet()->dblColumnPos(range.left());

  KoPoint dblCorner( leftPos - xOffset(), topPos - yOffset() );

  int x;
  int y;

  int right  = range.right();
  int bottom = range.bottom();
  Sheet * sheet = activeSheet();

#if 0
  kdDebug(36001)
    << "================================================================"
    << endl;
  kdDebug(36001) << "painting dirty cells " << endl;
#endif

  TQValueList<TQPoint>  mergedCellsPainted;
  for ( x = range.left(); x <= right; ++x )
  {
    for ( y = range.top(); y <= bottom; ++y )
    {
      if ( sheet->cellIsPaintDirty( TQPoint( x, y ) ) )
      {
        cell = sheet->cellAt( x, y );

        // recalc and retqlayout only for non default cells
        if (!cell->isDefault())
        {
          if (cell->calcDirtyFlag()) cell->calc();
          if (cell->layoutDirtyFlag()) cell->makeLayout( painter, x, y );
        }

       /* bool paintBordersBottom = false;
        bool paintBordersRight = false;
        bool paintBordersLeft = false;
	bool paintBordersTop = false; */

	int paintBorder=Cell::Border_None;

        TQPen bottomPen( cell->effBottomBorderPen( x, y ) );
        TQPen rightPen( cell->effRightBorderPen( x, y ) );
        TQPen leftPen( cell->effLeftBorderPen( x, y ) );
        TQPen topPen( cell->effTopBorderPen( x, y ) );

        // paint right border
        // - if rightmost cell
        // - if the pen is more "worth" than the left border pen of the cell
        //   on the left
        if ( x >= KS_colMax )
        {
          paintBorder |= Cell::Border_Right;
        }
        else
        {
          paintBorder |= Cell::Border_Right;
          if ( cell->effRightBorderValue( x, y ) <
               sheet->cellAt( x + 1, y )->effLeftBorderValue( x + 1, y ) )
            rightPen = sheet->cellAt( x + 1, y )->effLeftBorderPen( x + 1, y );
        }

        // similiar for other borders...
        // bottom border:
        if ( y >= KS_rowMax )
        {
          paintBorder |= Cell::Border_Bottom;
        }
        else
        {
          paintBorder |= Cell::Border_Bottom;
          if ( cell->effBottomBorderValue( x, y ) <
               sheet->cellAt( x, y + 1 )->effTopBorderValue( x, y + 1 ) )
            bottomPen = sheet->cellAt( x, y + 1 )->effTopBorderPen( x, y + 1 );
        }

        // left border:
        if ( x == 1 )
        {
          paintBorder |= Cell::Border_Left;
        }
        else
        {
          paintBorder |= Cell::Border_Left;
          if ( cell->effLeftBorderValue( x, y ) <
               sheet->cellAt( x - 1, y )->effRightBorderValue( x - 1, y ) )
            leftPen = sheet->cellAt( x - 1, y )->effRightBorderPen( x - 1, y );
        }

        // top border:
        if ( y == 1 )
        {
          paintBorder |= Cell::Border_Top;
        }
        else
        {
          paintBorder |= Cell::Border_Top;
          if ( cell->effTopBorderValue( x, y ) <
               sheet->cellAt( x, y - 1 )->effBottomBorderValue( x, y - 1 ) )
            topPen = sheet->cellAt( x, y - 1 )->effBottomBorderPen( x, y - 1 );
        }

	cell->paintCell( unzoomedRect, painter, d->view, dblCorner,
			 TQPoint( x, y), paintBorder,
			 rightPen,bottomPen,leftPen,topPen,
			 mergedCellsPainted);
      }
      dblCorner.setY( dblCorner.y() + sheet->rowFormat( y )->dblHeight( ) );
    }
    dblCorner.setY( topPos - yOffset() );
    dblCorner.setX( dblCorner.x() + sheet->columnFormat( x )->dblWidth( ) );
  }

  /* now paint the selection */
  //Nb.  No longer necessary to paint choose selection here as the cell reference highlight
  //stuff takes care of this anyway

  paintHighlightedRanges(painter, unzoomedRect);
  paintNormalMarker(painter, unzoomedRect);

  //restore clip region with tqchildren area
  painter.restore();
  //painter.setClipRegion( rgnComplete );
}



void Canvas::clipoutChildren( TQPainter& painter ) const
{
  TQRegion rgn = painter.clipRegion();
  if ( rgn.isEmpty() )
    rgn = TQRegion( TQRect( 0, 0, width(), height() ) );

  const double horizontalOffset = -xOffset() * doc()->zoomedResolutionX();
  const double verticalOffset = -yOffset() * doc()->zoomedResolutionY();

  TQPtrListIterator<EmbeddedObject> itObject( doc()->embeddedObjects() );
  for( ; itObject.current(); ++itObject )
  {
    if ( ( itObject.current() )->sheet() == activeSheet() )
    {
	TQRect childGeometry = doc()->zoomRect( itObject.current()->tqgeometry());

	//The clipping region is given in device coordinates
	//so subtract the current offset (scroll position) of the canvas
	childGeometry.moveBy( (int)horizontalOffset , (int)verticalOffset );

	if (painter.window().intersects(childGeometry))
		rgn -= childGeometry;

      //painter.fillRect( doc()->zoomRect( itObject.current()->tqgeometry() ), TQColor("red" ) );
    }
  }

  painter.setClipRegion( rgn );
}

TQRect Canvas::painterWindowGeometry( const TQPainter& painter ) const
{
  TQRect zoomedWindowGeometry = painter.window();

  zoomedWindowGeometry.moveBy( (int)( xOffset() * doc()->zoomedResolutionX() ) , (int)( yOffset() * doc()->zoomedResolutionY() ) );

	return zoomedWindowGeometry;
}

void Canvas::paintChildren( TQPainter& painter, TQWMatrix& /*matrix*/ )
{
  TQPtrListIterator<EmbeddedObject> itObject( doc()->embeddedObjects() );
  itObject.toFirst();
  if ( !itObject.current() )
    return;

  painter.save();
  painter.translate( -xOffset() * doc()->zoomedResolutionX() , -yOffset() * doc()->zoomedResolutionY() );

  const TQRect zoomedWindowGeometry = painterWindowGeometry( painter );
  const Sheet* sheet = activeSheet();

  for( ; itObject.current(); ++itObject )
  {
    TQRect const zoomedObjectGeometry = doc()->zoomRect( itObject.current()->tqgeometry() );
    if ( ( itObject.current() )->sheet() == activeSheet() &&
           zoomedWindowGeometry.intersects( zoomedObjectGeometry ) )
    {
	    //To prevent unnecessary redrawing of the embedded object, we only tqrepaint
	    //if one or more of the cells underneath the object has been marked as 'dirty'.

	   TQRect canvasRelativeGeometry = zoomedObjectGeometry;
	   canvasRelativeGeometry.moveBy( (int)( -xOffset()*doc()->zoomedResolutionX() ) ,
			   			(int)( -yOffset() * doc()->zoomedResolutionY()) );

	   const TQRect cellsUnderObject=cellsInArea( canvasRelativeGeometry );
	   bool redraw=false;

	   for (int x=cellsUnderObject.left();x<=cellsUnderObject.right();x++)
	   {
		for (int y=cellsUnderObject.top();y<=cellsUnderObject.bottom();y++)
	     		if ( sheet->cellIsPaintDirty( TQPoint(x,y) ) )
			{
				redraw=true;
				break;
			}
		if (redraw)
			break;
	   }

       	  if ( redraw )
      		itObject.current()->draw( &painter );
    }
  }
  painter.restore();
}

void Canvas::paintHighlightedRanges(TQPainter& painter, const KoRect& /*viewRect*/)
{
  TQValueList<TQColor> colors = choice()->colors();
  TQBrush nullBrush;
  int index = 0;
  Region::ConstIterator end(choice()->constEnd());
  for (Region::ConstIterator it = choice()->constBegin(); it != end; ++it)
  {
    //Only paint ranges or cells on the current sheet
    if ((*it)->sheet() != activeSheet())
    {
      index++;
      continue;
    }

    TQRect region = (*it)->rect().normalize();

		//double positions[4];
		//bool paintSides[4];
		KoRect unzoomedRect;

		sheetAreaToVisibleRect(region,unzoomedRect);
		//Convert region from sheet coordinates to canvas coordinates for use with the painter
		//retrieveMarkerInfo(region,viewRect,positions,paintSides);

    TQPen highlightPen( colors[(index) % colors.size()] ); // (*it)->color() );
		painter.setPen(highlightPen);

		//Adjust the canvas coordinate - rect to take account of zoom level

		TQRect zoomedRect;

		zoomedRect.setCoords (	d->view->doc()->zoomItX(unzoomedRect.left()),
					d->view->doc()->zoomItY(unzoomedRect.top()),
					d->view->doc()->zoomItX(unzoomedRect.right()),
					d->view->doc()->zoomItY(unzoomedRect.bottom()) );

		//Now adjust the highlight rectangle is slightly inside the cell borders (this means that multiple highlighted cells
		//look nicer together as the borders do not clash)

		zoomedRect.setLeft(zoomedRect.left()+1);
		zoomedRect.setTop(zoomedRect.top()+1);
		zoomedRect.setRight(zoomedRect.right()-1);
		zoomedRect.setBottom(zoomedRect.bottom()-1);

		painter.setBrush(nullBrush);
		painter.drawRect(zoomedRect);

		//Now draw the size grip (the little rectangle on the bottom right-hand corner of the range which the user can
		//click and drag to resize the region)


    TQBrush sizeGripBrush( colors[(index) % colors.size()] ); // (*it)->color());
		TQPen   sizeGripPen(TQt::white);

		painter.setPen(sizeGripPen);
		painter.setBrush(sizeGripBrush);

		painter.drawRect(zoomedRect.right()-3,zoomedRect.bottom()-3,6,6);
    index++;
  }
}

void Canvas::paintNormalMarker(TQPainter& painter, const KoRect &viewRect)
{
  //Only the active element (the one with the anchor) will be drawn with a border

  if( d->chooseCell )
	return;

  if (d->cellEditor)
	return;

  Region::ConstIterator end(selectionInfo()->constEnd());
  for (Region::ConstIterator it(selectionInfo()->constBegin()); it != end; ++it)
  {
    TQRect range = (*it)->rect().normalize();

  	double positions[4];
  	bool paintSides[4];

    bool current = TQRect(selectionInfo()->anchor(), selectionInfo()->marker()).normalize() == range;
    TQPen pen( TQt::black, 2 );
    painter.setPen( pen );

    retrieveMarkerInfo( selectionInfo()->extendToMergedAreas(range), viewRect, positions, paintSides );

    double left =   positions[0];
    double top =    positions[1];
    double right =  positions[2];
    double bottom = positions[3];

    bool paintLeft =   paintSides[0];
    bool paintTop =    paintSides[1];
    bool paintRight =  paintSides[2];
    bool paintBottom = paintSides[3];

    /* the extra '-1's thrown in here account for the thickness of the pen.
      want to look like this:                     not this:
                              * * * * * *                     * * * *
                              *         *                   *         *
                              *         *                   *         *
    */
    int l = 1;

    if ( paintTop )
    {
      painter.drawLine( d->view->doc()->zoomItX( left ) - l,      d->view->doc()->zoomItY( top ),
                        d->view->doc()->zoomItX( right ) + l, d->view->doc()->zoomItY( top ) );
    }
    if ( activeSheet()->layoutDirection()==Sheet::RightToLeft )
    {
      if ( paintRight )
      {
        painter.drawLine( d->view->doc()->zoomItX( right ), d->view->doc()->zoomItY( top ),
                          d->view->doc()->zoomItX( right ), d->view->doc()->zoomItY( bottom ) );
      }
      if ( paintLeft && paintBottom && current )
      {
        /* then the 'handle' in the bottom left corner is visible. */
        painter.drawLine( d->view->doc()->zoomItX( left ), d->view->doc()->zoomItY( top ),
                          d->view->doc()->zoomItX( left ), d->view->doc()->zoomItY( bottom ) - 3 );
        painter.drawLine( d->view->doc()->zoomItX( left ) + 4,  d->view->doc()->zoomItY( bottom ),
                          d->view->doc()->zoomItX( right ) + l + 1, d->view->doc()->zoomItY( bottom ) );
        painter.fillRect( d->view->doc()->zoomItX( left ) - 2, d->view->doc()->zoomItY( bottom ) -2, 5, 5,
                          painter.pen().color() );
      }
      else
      {
        if ( paintLeft )
        {
          painter.drawLine( d->view->doc()->zoomItX( left ), d->view->doc()->zoomItY( top ),
                            d->view->doc()->zoomItX( left ), d->view->doc()->zoomItY( bottom ) );
        }
        if ( paintBottom )
        {
          painter.drawLine( d->view->doc()->zoomItX( left ) - l,  d->view->doc()->zoomItY( bottom ),
                            d->view->doc()->zoomItX( right ) + l + 1, d->view->doc()->zoomItY( bottom ));
        }
      }
    }
    else // activeSheet()->layoutDirection()==Sheet::LeftToRight
    {
      if ( paintLeft )
      {
        painter.drawLine( d->view->doc()->zoomItX( left ), d->view->doc()->zoomItY( top ),
                          d->view->doc()->zoomItX( left ), d->view->doc()->zoomItY( bottom ) );
      }
      if ( paintRight && paintBottom && current )
      {
        /* then the 'handle' in the bottom right corner is visible. */
        painter.drawLine( d->view->doc()->zoomItX( right ), d->view->doc()->zoomItY( top ),
                          d->view->doc()->zoomItX( right ), d->view->doc()->zoomItY( bottom ) - 3 );
        painter.drawLine( d->view->doc()->zoomItX( left ) - l,  d->view->doc()->zoomItY( bottom ),
                          d->view->doc()->zoomItX( right ) - 3, d->view->doc()->zoomItY( bottom ) );
        painter.fillRect( d->view->doc()->zoomItX( right ) - 2, d->view->doc()->zoomItY( bottom ) - 2, 5, 5,
                          painter.pen().color() );
      }
      else
      {
        if ( paintRight )
        {
          painter.drawLine( d->view->doc()->zoomItX( right ), d->view->doc()->zoomItY( top ),
                            d->view->doc()->zoomItX( right ), d->view->doc()->zoomItY( bottom ) );
        }
        if ( paintBottom )
        {
          painter.drawLine( d->view->doc()->zoomItX( left ) - l,  d->view->doc()->zoomItY( bottom ),
                            d->view->doc()->zoomItX( right ) + l + 1, d->view->doc()->zoomItY( bottom ) );
        }
      }
    }
  }
}

void Canvas::sheetAreaToRect(const TQRect& sheetArea, KoRect& rect)
{
	Sheet* sheet=activeSheet();

	if ( sheet->layoutDirection()==Sheet::RightToLeft )
	{
		rect.setLeft(sheet->dblColumnPos( sheetArea.right()+1 ) );
		rect.setRight(sheet->dblColumnPos( sheetArea.left() ));
	}
	else
	{
		rect.setLeft(sheet->dblColumnPos( sheetArea.left() ));
		rect.setRight(sheet->dblColumnPos( sheetArea.right()+1 ));
	}

	rect.setTop(sheet->dblRowPos(sheetArea.top()));
	rect.setBottom(sheet->dblRowPos(sheetArea.bottom()+1));

}

void Canvas::sheetAreaToVisibleRect( const TQRect& sheetArea,
					    KoRect& visibleRect )
{
	Sheet* sheet=activeSheet();

	if (!sheet)
		return;

	double dwidth=d->view->doc()->unzoomItX(width());
	double xpos;
	double x;

	if ( sheet->layoutDirection()==Sheet::RightToLeft )
	{
		xpos = dwidth - sheet->dblColumnPos( sheetArea.right() ) + xOffset();
		x    = dwidth - sheet->dblColumnPos( sheetArea.left() ) + xOffset();
	}
	else
	{
		xpos = sheet->dblColumnPos( sheetArea.left() ) - xOffset();
		x    = sheet->dblColumnPos( sheetArea.right() ) - xOffset();
	}

	double ypos = sheet->dblRowPos(sheetArea.top())-yOffset();

	const ColumnFormat *columnFormat = sheet->columnFormat( sheetArea.right() );
	double tw = columnFormat->dblWidth( );
	double w = x - xpos + tw;

	double y = sheet->dblRowPos( sheetArea.bottom() ) - yOffset();
	const RowFormat* rowFormat = sheet->rowFormat( sheetArea.bottom() );
	double th = rowFormat->dblHeight( );
	double h = ( y - ypos ) + th;

	/* left, top, right, bottom */
	if ( sheet->layoutDirection()==Sheet::RightToLeft )
	{
		visibleRect.setLeft(xpos - tw );
		visibleRect.setRight(xpos - tw + w );
	}
	else
	{
		visibleRect.setLeft(xpos );
		visibleRect.setRight(xpos + w );
	}
	visibleRect.setTop(ypos);
	visibleRect.setBottom(ypos + h);
}

void Canvas::retrieveMarkerInfo( const TQRect &marker,
                                        const KoRect &viewRect,
                                        double positions[],
                                        bool paintSides[] )
{

	Sheet* sheet=activeSheet();

	if (!sheet) return;

	KoRect visibleRect;
	sheetAreaToVisibleRect(marker,visibleRect);


 /* Sheet * sheet = activeSheet();
  if ( !sheet )
    return;

  double dWidth = d->view->doc()->unzoomItX( width() );

  double xpos;
  double x;
  if ( sheet->layoutDirection()==Sheet::RightToLeft )
  {
    xpos = dWidth - sheet->dblColumnPos( marker.right() ) + xOffset();
    x    = dWidth - sheet->dblColumnPos( marker.left() ) + xOffset();
  }
  else
  {
    xpos = sheet->dblColumnPos( marker.left() ) - xOffset();
    x    = sheet->dblColumnPos( marker.right() ) - xOffset();
  }
  double ypos = sheet->dblRowPos( marker.top() ) - yOffset();

  const ColumnFormat *columnFormat = sheet->columnFormat( marker.right() );
  double tw = columnFormat->dblWidth( );
  double w = x - xpos + tw;

  double y = sheet->dblRowPos( marker.bottom() ) - yOffset();
  const RowFormat* rowFormat = sheet->rowFormat( marker.bottom() );
  double th = rowFormat->dblHeight( );
  double h = ( y - ypos ) + th;

	//left, top, right, bottom
  if ( sheet->layoutDirection()==Sheet::RightToLeft )
  {
    positions[0] = xpos - tw;
    positions[2] = xpos - tw + w;
  }
  else
  {
    positions[0] = xpos;
    positions[2] = xpos + w;
  }
  positions[1] = ypos;
	positions[3] = ypos + h;*/

  /* these vars are used for clarity, the array for simpler function arguments  */
	double left = visibleRect.left();
	double top = visibleRect.top();
	double right = visibleRect.right();
	double bottom = visibleRect.bottom();

  /* left, top, right, bottom */
  paintSides[0] = (viewRect.left() <= left) && (left <= viewRect.right()) &&
                (bottom >= viewRect.top()) && (top <= viewRect.bottom());
  paintSides[1] = (viewRect.top() <= top) && (top <= viewRect.bottom())
               && (right >= viewRect.left()) && (left <= viewRect.right());
  if ( sheet->layoutDirection()==Sheet::RightToLeft )
    paintSides[2] = (viewRect.left() <= right ) &&
                    (right - 1 <= viewRect.right()) &&
                    (bottom >= viewRect.top()) && (top <= viewRect.bottom());
  else
    paintSides[2] = (viewRect.left() <= right ) &&
                    (right <= viewRect.right()) &&
                    (bottom >= viewRect.top()) && (top <= viewRect.bottom());
  paintSides[3] = (viewRect.top() <= bottom) && (bottom <= viewRect.bottom())
               && (right >= viewRect.left()) && (left <= viewRect.right());

  positions[0] = TQMAX( left,   viewRect.left() );
  positions[1] = TQMAX( top,    viewRect.top() );
  positions[2] = TQMIN( right,  viewRect.right() );
  positions[3] = TQMIN( bottom, viewRect.bottom() );
}


/****************************************************************
 *
 * VBorder
 *
 ****************************************************************/

VBorder::VBorder( TQWidget *_parent, Canvas *_canvas, View *_view)
    : TQWidget( _parent, "", /*WNorthWestGravity*/WStaticContents | WResizeNoErase | WRepaintNoErase )
{
  m_pView = _view;
  m_pCanvas = _canvas;
  m_lSize = 0L;

  setBackgroundMode( PaletteButton );
  setMouseTracking( true );
  m_bResize = false;
  m_bSelection = false;
  m_iSelectionAnchor=1;
  m_bMousePressed = false;

  m_scrollTimer = new TQTimer( this );
  connect (m_scrollTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( doAutoScroll() ) );
}


VBorder::~VBorder()
{
    delete m_scrollTimer;
}

TQSize VBorder::tqsizeHint() const
{
  return TQSize( 40, 10 );
}


void VBorder::mousePressEvent( TQMouseEvent * _ev )
{
  if ( !m_pView->koDocument()->isReadWrite() )
    return;

  if ( _ev->button() == Qt::LeftButton )
    m_bMousePressed = true;

  const Sheet *sheet = m_pCanvas->activeSheet();
  if (!sheet)
	  return;

  double ev_PosY = m_pCanvas->d->view->doc()->unzoomItY( _ev->pos().y() ) + m_pCanvas->yOffset();
  double dHeight = m_pCanvas->d->view->doc()->unzoomItY( height() );
  m_bResize = false;
  m_bSelection = false;

  // We were editing a cell -> save value and get out of editing mode
  if ( m_pCanvas->editor() )
  {
    m_pCanvas->deleteEditor( true ); // save changes
  }

  m_scrollTimer->start( 50 );

  // Find the first visible row and the y position of this row.
  double y;
  int row = sheet->topRow( m_pCanvas->yOffset(), y );

  // Did the user click between two rows?
  while ( y < ( dHeight + m_pCanvas->yOffset() ) && ( !m_bResize ) )
  {
    double h = sheet->rowFormat( row )->dblHeight();
    row++;
    if ( row > KS_rowMax )
      row = KS_rowMax;
    if ( ( ev_PosY >= y + h - 2 ) &&
         ( ev_PosY <= y + h + 1 ) &&
         !( sheet->rowFormat( row )->isHide() && row == 1 ) )
      m_bResize = true;
    y += h;
  }

  //if row is hide and it's the first row
  //you mustn't resize it.
  double tmp2;
  int tmpRow = sheet->topRow( ev_PosY - 1, tmp2 );
  if ( sheet->rowFormat( tmpRow )->isHide() && tmpRow == 1 )
      m_bResize = false;

  // So he clicked between two rows ?
  if ( m_bResize )
  {
    // Determine row to resize
    double tmp;
    m_iResizedRow = sheet->topRow( ev_PosY - 1, tmp );
    if ( !sheet->isProtected() )
      paintSizeIndicator( _ev->pos().y(), true );
  }
  else
  {
    m_bSelection = true;

    double tmp;
    int hit_row = sheet->topRow( ev_PosY, tmp );
    if ( hit_row > KS_rowMax )
        return;

    m_iSelectionAnchor = hit_row;

    if ( !m_pView->selectionInfo()->contains( TQPoint(1, hit_row) ) ||
         !( _ev->button() == Qt::RightButton ) ||
         !m_pView->selectionInfo()->isRowSelected() )
    {
      TQPoint newMarker( 1, hit_row );
      TQPoint newAnchor( KS_colMax, hit_row );
#ifdef NONCONTIGUOUSSELECTION
      if (_ev->state() == ControlButton)
      {
        m_pView->selectionInfo()->extend(TQRect(newAnchor, newMarker));
      }
      else
#endif
      if (_ev->state() == ShiftButton)
      {
        m_pView->selectionInfo()->update(newMarker);
      }
      else
      {
        m_pView->selectionInfo()->initialize(TQRect(newAnchor, newMarker));
      }
    }

    if ( _ev->button() == Qt::RightButton )
    {
      TQPoint p = mapToGlobal( _ev->pos() );
      m_pView->popupRowMenu( p );
      m_bSelection = false;
    }
    m_pView->updateEditWidget();
  }
}

void VBorder::mouseReleaseEvent( TQMouseEvent * _ev )
{
    if ( m_scrollTimer->isActive() )
        m_scrollTimer->stop();

    m_bMousePressed = false;

    if ( !m_pView->koDocument()->isReadWrite() )
        return;

    Sheet *sheet = m_pCanvas->activeSheet();
    if (!sheet)
	    return;

    double ev_PosY = m_pCanvas->d->view->doc()->unzoomItY( _ev->pos().y() ) + m_pCanvas->yOffset();

    if ( m_bResize )
    {
        // Remove size indicator painted by paintSizeIndicator
        TQPainter painter;
        painter.begin( m_pCanvas );
        painter.setRasterOp( NotROP );
        painter.drawLine( 0, m_iResizePos, m_pCanvas->width(), m_iResizePos );
        painter.end();

        int start = m_iResizedRow;
        int end = m_iResizedRow;
        TQRect rect;
        rect.setCoords( 1, m_iResizedRow, KS_colMax, m_iResizedRow );
        if ( m_pView->selectionInfo()->isRowSelected() )
        {
          if ( m_pView->selectionInfo()->contains( TQPoint( 1, m_iResizedRow ) ) )
            {
                start = m_pView->selectionInfo()->lastRange().top();
                end = m_pView->selectionInfo()->lastRange().bottom();
                rect = m_pView->selectionInfo()->lastRange();
            }
        }

        double height = 0.0;
        double y = sheet->dblRowPos( m_iResizedRow );
        if ( ev_PosY - y <= 0.0 )
            height = 0.0;
        else
            height = ev_PosY - y;

        if ( !sheet->isProtected() )
        {
          if ( !m_pCanvas->d->view->doc()->undoLocked() )
          {
            //just resize
            if ( height != 0.0 )
            {
              // TODO Stefan: replace this
              UndoResizeColRow *undo = new UndoResizeColRow( m_pCanvas->d->view->doc(), m_pCanvas->activeSheet(), rect );
                m_pCanvas->d->view->doc()->addCommand( undo );
            }
          }

          for( int i = start; i <= end; i++ )
          {
            RowFormat *rl = sheet->nonDefaultRowFormat( i );
            if ( height != 0.0 )
            {
              if ( !rl->isHide() )
                rl->setDblHeight( height );
            }
            else
            {
              sheet->hideRow(*m_pView->selectionInfo());
            }
          }

          delete m_lSize;
          m_lSize = 0;
        }
    }
    else if ( m_bSelection )
    {
      TQRect rect = m_pView->selectionInfo()->lastRange();

        // TODO: please don't remove. Right now it's useless, but it's for a future feature
        // Norbert
        bool m_frozen = false;
        if ( m_frozen )
        {
            kdDebug(36001) << "selected: T " << rect.top() << " B " << rect.bottom() << endl;

            int i;
            RowFormat * row;
            TQValueList<int>hiddenRows;

            for ( i = rect.top(); i <= rect.bottom(); ++i )
            {
                row = m_pView->activeSheet()->rowFormat( i );
                if ( row->isHide() )
                {
                    hiddenRows.append(i);
                }
            }

            if ( hiddenRows.count() > 0 )
              m_pView->activeSheet()->showRow(*m_pView->selectionInfo());
        }
    }

    m_bSelection = false;
    m_bResize = false;
}

void VBorder::equalizeRow( double resize )
{
  Sheet *sheet = m_pCanvas->activeSheet();
  Q_ASSERT( sheet );

  TQRect selection( m_pView->selectionInfo()->selection() );
  if ( !m_pCanvas->d->view->doc()->undoLocked() )
  {
     UndoResizeColRow *undo = new UndoResizeColRow( m_pCanvas->d->view->doc(), m_pCanvas->activeSheet(), selection );
     m_pCanvas->d->view->doc()->addCommand( undo );
  }
  RowFormat *rl;
  for ( int i = selection.top(); i <= selection.bottom(); i++ )
  {
     rl = sheet->nonDefaultRowFormat( i );
     resize = TQMAX( 2.0, resize);
     rl->setDblHeight( resize );
  }
}

void VBorder::mouseDoubleClickEvent(TQMouseEvent*)
{
  Sheet *sheet = m_pCanvas->activeSheet();
  if (!sheet)
    return;

  if ( !m_pView->koDocument()->isReadWrite() || sheet->isProtected() )
    return;

  sheet->adjustRow(*m_pCanvas->selectionInfo());
}


void VBorder::mouseMoveEvent( TQMouseEvent * _ev )
{
  if ( !m_pView->koDocument()->isReadWrite() )
    return;

  Sheet *sheet = m_pCanvas->activeSheet();

  if (!sheet)
     return;

  double ev_PosY = m_pCanvas->d->view->doc()->unzoomItY( _ev->pos().y() ) + m_pCanvas->yOffset();
  double dHeight = m_pCanvas->d->view->doc()->unzoomItY( height() );

  // The button is pressed and we are resizing ?
  if ( m_bResize )
  {
    if ( !sheet->isProtected() )
      paintSizeIndicator( _ev->pos().y(), false );
  }
  // The button is pressed and we are selecting ?
  else if ( m_bSelection )
  {
    double y;
    int row = sheet->topRow( ev_PosY, y );
    if ( row > KS_rowMax )
      return;

    TQPoint newAnchor = m_pView->selectionInfo()->anchor();
    TQPoint newMarker = m_pView->selectionInfo()->marker();
    newMarker.setY( row );
    newAnchor.setY( m_iSelectionAnchor );
    m_pView->selectionInfo()->update(newMarker);

    if ( _ev->pos().y() < 0 )
      m_pCanvas->vertScrollBar()->setValue( m_pCanvas->d->view->doc()->zoomItY( ev_PosY ) );
    else if ( _ev->pos().y() > m_pCanvas->height() )
    {
      if ( row < KS_rowMax )
      {
        RowFormat *rl = sheet->rowFormat( row + 1 );
        y = sheet->dblRowPos( row + 1 );
        m_pCanvas->vertScrollBar()->setValue ((int) (m_pCanvas->d->view->doc()->zoomItY
              (ev_PosY + rl->dblHeight()) - dHeight));
      }
    }
  }
  // No button is pressed and the mouse is just moved
  else
  {

     //What is the internal size of 1 pixel
    const double unzoomedPixel = m_pCanvas->d->view->doc()->unzoomItY( 1 );
    double y;
    int tmpRow = sheet->topRow( m_pCanvas->yOffset(), y );

    while ( y < m_pCanvas->d->view->doc()->unzoomItY( height() ) + m_pCanvas->yOffset() )
    {
      double h = sheet->rowFormat( tmpRow )->dblHeight();
      //if col is hide and it's the first column
      //you mustn't resize it.
      if ( ev_PosY >= y + h - 2 * unzoomedPixel &&
           ev_PosY <= y + h + unzoomedPixel &&
           !( sheet->rowFormat( tmpRow )->isHide() && tmpRow == 1 ) )
      {
        setCursor( splitVCursor );
        return;
      }
      y += h;
      tmpRow++;
    }
    setCursor( arrowCursor );
  }
}

void VBorder::doAutoScroll()
{
    if ( !m_bMousePressed )
    {
        m_scrollTimer->stop();
        return;
    }

    TQPoint pos( mapFromGlobal( TQCursor::pos() ) );

    if ( pos.y() < 0 || pos.y() > height() )
    {
        TQMouseEvent * event = new TQMouseEvent( TQEvent::MouseMove, pos, 0, 0 );
        mouseMoveEvent( event );
        delete event;
    }

    //Restart timer
    m_scrollTimer->start( 50 );
}

void VBorder::wheelEvent( TQWheelEvent* _ev )
{
  if ( m_pCanvas->vertScrollBar() )
    TQApplication::sendEvent( m_pCanvas->vertScrollBar(), _ev );
}


void VBorder::paintSizeIndicator( int mouseY, bool firstTime )
{
    Sheet *sheet = m_pCanvas->activeSheet();
    if (!sheet)
	    return;

    TQPainter painter;
    painter.begin( m_pCanvas );
    painter.setRasterOp( NotROP );

    if ( !firstTime )
      painter.drawLine( 0, m_iResizePos, m_pCanvas->width(), m_iResizePos );

    m_iResizePos = mouseY;

    // Dont make the row have a height < 2 pixel.
    int y = m_pCanvas->d->view->doc()->zoomItY( sheet->dblRowPos( m_iResizedRow ) - m_pCanvas->yOffset() );
    if ( m_iResizePos < y + 2 )
        m_iResizePos = y;

    painter.drawLine( 0, m_iResizePos, m_pCanvas->width(), m_iResizePos );

    painter.end();

    TQString tmpSize;
    if ( m_iResizePos != y )
        tmpSize = i18n("Height: %1 %2").tqarg( KoUnit::toUserValue( m_pCanvas->doc()->unzoomItY( m_iResizePos - y ),
                                                               m_pView->doc()->unit() ) )
                                       .tqarg( m_pView->doc()->unitName() );
    else
        tmpSize = i18n( "Hide Row" );

    painter.begin( this );
    int len = painter.fontMetrics().width( tmpSize );
    int hei = painter.fontMetrics().height();
    painter.end();

    if ( !m_lSize )
    {
          m_lSize = new TQLabel( m_pCanvas );

          if ( sheet->layoutDirection()==Sheet::RightToLeft )
            m_lSize->setGeometry( m_pCanvas->width() - len - 5,
                                                  y + 3, len + 2, hei + 2 );
          else
            m_lSize->setGeometry( 3, y + 3, len + 2,hei + 2 );

          m_lSize->tqsetAlignment( TQt::AlignVCenter );
          m_lSize->setText( tmpSize );
          m_lSize->setPalette( TQToolTip::palette() );
          m_lSize->show();
    }
    else
    {
          if ( sheet->layoutDirection()==Sheet::RightToLeft )
            m_lSize->setGeometry( m_pCanvas->width() - len - 5,
                                                  y + 3, len + 2, hei + 2 );
          else
            m_lSize->setGeometry( 3, y + 3, len + 2,hei + 2 );

          m_lSize->setText( tmpSize );
    }
}

void VBorder::updateRows( int from, int to )
{
    Sheet *sheet = m_pCanvas->activeSheet();
    if ( !sheet )
        return;

    int y0 = sheet->rowPos( from, m_pCanvas );
    int y1 = sheet->rowPos( to+1, m_pCanvas );
    update( 0, y0, width(), y1-y0 );
}

void VBorder::paintEvent( TQPaintEvent* _ev )
{
  Sheet *sheet = m_pCanvas->activeSheet();
  if ( !sheet )
    return;

  TQPainter painter( this );
  TQColor highlightColor = View::highlightColor();
  TQPen pen( TQt::black, 1 );
  painter.setPen( pen );
  // painter.setBackgroundColor( tqcolorGroup().base() );

  // painter.eraseRect( _ev->rect() );

  //TQFontMetrics fm = painter.fontMetrics();
  // Matthias Elter: This causes a SEGFAULT in ~TQPainter!
  // Only god and the trolls know why ;-)
  // bah...took me quite some time to track this one down...

  painter.setClipRect( _ev->rect() );

  double yPos;
  //Get the top row and the current y-position
  int y = sheet->topRow( (m_pCanvas->d->view->doc()->unzoomItY( _ev->rect().y() ) + m_pCanvas->yOffset()), yPos );
  //Align to the offset
  yPos = yPos - m_pCanvas->yOffset();
  int width = m_pCanvas->d->view->doc()->zoomItX( YBORDER_WIDTH );

  TQFont normalFont = painter.font();
  if ( m_pCanvas->d->view->doc()->zoom() < 100 )
  {
    normalFont.setPointSizeFloat( 0.01 * m_pCanvas->d->view->doc()->zoom() *
                                  normalFont.pointSizeFloat() );
  }
  TQFont boldFont = normalFont;
  boldFont.setBold( true );

  //Loop through the rows, until we are out of range
  while ( yPos <= m_pCanvas->d->view->doc()->unzoomItY( _ev->rect().bottom() ) )
  {
    bool selected = (m_pView->selectionInfo()->isRowSelected(y));
    bool highlighted = (!selected && m_pView->selectionInfo()->isRowAffected(y));

    const RowFormat *row_lay = sheet->rowFormat( y );
    int zoomedYPos = m_pCanvas->d->view->doc()->zoomItY( yPos );
    int height = m_pCanvas->d->view->doc()->zoomItY( yPos + row_lay->dblHeight() ) - zoomedYPos;

    if ( selected )
    {
      TQBrush fillSelected( highlightColor );
      qDrawPlainRect ( &painter, 0, zoomedYPos, width, height+1, highlightColor.dark(150),
           1, &fillSelected );
    }
    else if ( highlighted )
    {
      TQBrush fillHighlighted( highlightColor );
      qDrawPlainRect ( &painter, 0, zoomedYPos, width, height+1, highlightColor.dark(150),
           1, &fillHighlighted );
    }
    else
    {
      TQColor c = tqcolorGroup().background();
      TQBrush fill( c );
      qDrawPlainRect ( &painter, 0, zoomedYPos, width, height+1, c.dark(150),
           1, &fill );
    }

    TQString rowText = TQString::number( y );

    // Reset painter
    painter.setFont( normalFont );
    painter.setPen( tqcolorGroup().text() );

    if ( selected )
      painter.setPen( tqcolorGroup().highlightedText() );
    else if ( highlighted )
      painter.setFont( boldFont );

    int len = painter.fontMetrics().width( rowText );
    if (!row_lay->isHide())
        painter.drawText( ( width-len )/2, zoomedYPos +
                          ( height + painter.fontMetrics().ascent() -
                            painter.fontMetrics().descent() ) / 2, rowText );

    yPos += row_lay->dblHeight();
    y++;
  }
}


void VBorder::focusOutEvent( TQFocusEvent* )
{
    if ( m_scrollTimer->isActive() )
        m_scrollTimer->stop();
    m_bMousePressed = false;
}


/****************************************************************
 *
 * HBorder
 *
 ****************************************************************/

HBorder::HBorder( TQWidget *_parent, Canvas *_canvas,View *_view )
    : TQWidget( _parent, "", /*WNorthWestGravity*/ WStaticContents| WResizeNoErase | WRepaintNoErase )
{
  m_pView = _view;
  m_pCanvas = _canvas;
  m_lSize = 0L;
  setBackgroundMode( PaletteButton );
  setMouseTracking( true );
  m_bResize = false;
  m_bSelection = false;
  m_iSelectionAnchor=1;
  m_bMousePressed = false;

  m_scrollTimer = new TQTimer( this );
  connect( m_scrollTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( doAutoScroll() ) );
}


HBorder::~HBorder()
{
    delete m_scrollTimer;
}

TQSize HBorder::tqsizeHint() const
{
  return TQSize( 40, 10 );
}

void HBorder::mousePressEvent( TQMouseEvent * _ev )
{
  if (!m_pView->koDocument()->isReadWrite())
    return;

  if ( _ev->button() == Qt::LeftButton )
    m_bMousePressed = true;

  const Sheet *sheet = m_pCanvas->activeSheet();
  if (!sheet)
	return;

  // We were editing a cell -> save value and get out of editing mode
  if ( m_pCanvas->editor() )
  {
      m_pCanvas->deleteEditor( true ); // save changes
  }

  m_scrollTimer->start( 50 );

  double ev_PosX;
  double dWidth = m_pCanvas->d->view->doc()->unzoomItX( width() );
  if ( sheet->layoutDirection()==Sheet::RightToLeft )
    ev_PosX = dWidth - m_pCanvas->d->view->doc()->unzoomItX( _ev->pos().x() ) + m_pCanvas->xOffset();
  else
    ev_PosX = m_pCanvas->d->view->doc()->unzoomItX( _ev->pos().x() ) + m_pCanvas->xOffset();
  m_bResize = false;
  m_bSelection = false;

  // Find the first visible column and the x position of this column.
  double x;

  const double unzoomedPixel = m_pCanvas->d->view->doc()->unzoomItX( 1 );
  if ( sheet->layoutDirection()==Sheet::RightToLeft )
  {
    int tmpCol = sheet->leftColumn( m_pCanvas->xOffset(), x );

    kdDebug() << "evPos: " << ev_PosX << ", x: " << x << ", COL: " << tmpCol << endl;
    while ( ev_PosX > x && ( !m_bResize ) )
    {
      double w = sheet->columnFormat( tmpCol )->dblWidth();

      kdDebug() << "evPos: " << ev_PosX << ", x: " << x << ", w: " << w << ", COL: " << tmpCol << endl;

      ++tmpCol;
      if ( tmpCol > KS_colMax )
        tmpCol = KS_colMax;
      //if col is hide and it's the first column
      //you mustn't resize it.

      if ( ev_PosX >= x + w - unzoomedPixel &&
           ev_PosX <= x + w + unzoomedPixel &&
           !( sheet->columnFormat( tmpCol )->isHide() && tmpCol == 1 ) )
      {
        m_bResize = true;
      }
      x += w;
    }

    //if col is hide and it's the first column
    //you mustn't resize it.
    double tmp2;
    tmpCol = sheet->leftColumn( dWidth - ev_PosX + 1, tmp2 );
    if ( sheet->columnFormat( tmpCol )->isHide() && tmpCol == 0 )
    {
      kdDebug() << "No resize: " << tmpCol << ", " << sheet->columnFormat( tmpCol )->isHide() << endl;
      m_bResize = false;
    }

    kdDebug() << "Resize: " << m_bResize << endl;
  }
  else
  {
    int col = sheet->leftColumn( m_pCanvas->xOffset(), x );

    // Did the user click between two columns?
    while ( x < ( dWidth + m_pCanvas->xOffset() ) && ( !m_bResize ) )
    {
      double w = sheet->columnFormat( col )->dblWidth();
      col++;
      if ( col > KS_colMax )
        col = KS_colMax;
      if ( ( ev_PosX >= x + w - unzoomedPixel ) &&
         ( ev_PosX <= x + w + unzoomedPixel ) &&
           !( sheet->columnFormat( col )->isHide() && col == 1 ) )
        m_bResize = true;
      x += w;
    }

    //if col is hide and it's the first column
    //you mustn't resize it.
    double tmp2;
    int tmpCol = sheet->leftColumn( ev_PosX - 1, tmp2 );
    if ( sheet->columnFormat( tmpCol )->isHide() && tmpCol == 1 )
      m_bResize = false;
  }

  // So he clicked between two rows ?
  if ( m_bResize )
  {
    // Determine the column to resize
    double tmp;
    if ( sheet->layoutDirection()==Sheet::RightToLeft )
    {
      m_iResizedColumn = sheet->leftColumn( ev_PosX - 1, tmp );
      // kdDebug() << "RColumn: " << m_iResizedColumn << ", PosX: " << ev_PosX << endl;

      if ( !sheet->isProtected() )
        paintSizeIndicator( _ev->pos().x(), true );
    }
    else
    {
      m_iResizedColumn = sheet->leftColumn( ev_PosX - 1, tmp );

      if ( !sheet->isProtected() )
        paintSizeIndicator( _ev->pos().x(), true );
    }

    // kdDebug() << "Column: " << m_iResizedColumn << endl;
  }
  else
  {
    m_bSelection = true;

    double tmp;
    int hit_col = sheet->leftColumn( ev_PosX, tmp );
    if ( hit_col > KS_colMax )
        return;

    m_iSelectionAnchor = hit_col;

    if ( !m_pView->selectionInfo()->contains( TQPoint( hit_col, 1 ) ) ||
         !( _ev->button() == Qt::RightButton ) ||
         !m_pView->selectionInfo()->isColumnSelected() )
    {
      TQPoint newMarker( hit_col, 1 );
      TQPoint newAnchor( hit_col, KS_rowMax );
#ifdef NONCONTIGUOUSSELECTION
      if (_ev->state() == ControlButton)
      {
        m_pView->selectionInfo()->extend(TQRect(newAnchor, newMarker));
      }
      else
#endif
      if (_ev->state() == ShiftButton)
      {
        m_pView->selectionInfo()->update(newMarker);
      }
      else
      {
        m_pView->selectionInfo()->initialize(TQRect(newAnchor, newMarker));
      }
    }

    if ( _ev->button() == Qt::RightButton )
    {
      TQPoint p = mapToGlobal( _ev->pos() );
      m_pView->popupColumnMenu( p );
      m_bSelection = false;
    }
    m_pView->updateEditWidget();
  }
}

void HBorder::mouseReleaseEvent( TQMouseEvent * _ev )
{
    if ( m_scrollTimer->isActive() )
        m_scrollTimer->stop();

    m_bMousePressed = false;

    if ( !m_pView->koDocument()->isReadWrite() )
      return;

    Sheet * sheet = m_pCanvas->activeSheet();
    if (!sheet)
	    return;

    if ( m_bResize )
    {
        double dWidth = m_pCanvas->d->view->doc()->unzoomItX( width() );
        double ev_PosX;

        // Remove size indicator painted by paintSizeIndicator
        TQPainter painter;
        painter.begin( m_pCanvas );
        painter.setRasterOp( NotROP );
        painter.drawLine( m_iResizePos, 0, m_iResizePos, m_pCanvas->height() );
        painter.end();

        int start = m_iResizedColumn;
        int end   = m_iResizedColumn;
        TQRect rect;
        rect.setCoords( m_iResizedColumn, 1, m_iResizedColumn, KS_rowMax );
        if ( m_pView->selectionInfo()->isColumnSelected() )
        {
            if ( m_pView->selectionInfo()->contains( TQPoint( m_iResizedColumn, 1 ) ) )
            {
                start = m_pView->selectionInfo()->lastRange().left();
                end   = m_pView->selectionInfo()->lastRange().right();
                rect  = m_pView->selectionInfo()->lastRange();
            }
        }

        double width = 0.0;
        double x;

        if ( sheet->layoutDirection()==Sheet::RightToLeft )
          ev_PosX = dWidth - m_pCanvas->d->view->doc()->unzoomItX( _ev->pos().x() ) + m_pCanvas->xOffset();
        else
          ev_PosX = m_pCanvas->d->view->doc()->unzoomItX( _ev->pos().x() ) + m_pCanvas->xOffset();

        x = sheet->dblColumnPos( m_iResizedColumn );

        if ( ev_PosX - x <= 0.0 )
          width = 0.0;
        else
          width = ev_PosX - x;

        if ( !sheet->isProtected() )
        {
          if ( !m_pCanvas->d->view->doc()->undoLocked() )
          {
            //just resize
            if ( width != 0.0 )
            {
              // TODO Stefan: replace this
                UndoResizeColRow *undo = new UndoResizeColRow( m_pCanvas->d->view->doc(), m_pCanvas->activeSheet(), rect );
                m_pCanvas->d->view->doc()->addCommand( undo );
            }
          }

          for( int i = start; i <= end; i++ )
          {
            ColumnFormat *cl = sheet->nonDefaultColumnFormat( i );
            if ( width != 0.0 )
            {
                if ( !cl->isHide() )
                    cl->setDblWidth( width );
            }
            else
            {
              sheet->hideColumn(*m_pView->selectionInfo());
            }
          }

          delete m_lSize;
          m_lSize = 0;
        }
    }
    else if ( m_bSelection )
    {
        TQRect rect = m_pView->selectionInfo()->lastRange();

        // TODO: please don't remove. Right now it's useless, but it's for a future feature
        // Norbert
        bool m_frozen = false;
        if ( m_frozen )
        {
            kdDebug(36001) << "selected: L " << rect.left() << " R " << rect.right() << endl;

            int i;
            ColumnFormat * col;
            TQValueList<int>hiddenCols;

            for ( i = rect.left(); i <= rect.right(); ++i )
            {
                col = m_pView->activeSheet()->columnFormat( i );
                if ( col->isHide() )
                {
                    hiddenCols.append(i);
                }
            }

            if ( hiddenCols.count() > 0 )
              m_pView->activeSheet()->showColumn(*m_pView->selectionInfo());
        }
    }

    m_bSelection = false;
    m_bResize = false;
}

void HBorder::equalizeColumn( double resize )
{
  Sheet *sheet = m_pCanvas->activeSheet();
  Q_ASSERT( sheet );

  TQRect selection( m_pView->selectionInfo()->selection() );
  if ( !m_pCanvas->d->view->doc()->undoLocked() )
  {
      UndoResizeColRow *undo = new UndoResizeColRow( m_pCanvas->d->view->doc(), m_pCanvas->activeSheet(), selection );
      m_pCanvas->d->view->doc()->addCommand( undo );
  }
  ColumnFormat *cl;
  for ( int i = selection.left(); i <= selection.right(); i++ )
  {
      cl = sheet->nonDefaultColumnFormat( i );
      resize = TQMAX( 2.0, resize );
      cl->setDblWidth( resize );
  }

}

void HBorder::mouseDoubleClickEvent(TQMouseEvent*)
{
  Sheet *sheet = m_pCanvas->activeSheet();
  if (!sheet)
    return;

  if ( !m_pView->koDocument()->isReadWrite() || sheet->isProtected() )
    return;

  sheet->adjustColumn(*m_pCanvas->selectionInfo());
}

void HBorder::mouseMoveEvent( TQMouseEvent * _ev )
{
  if ( !m_pView->koDocument()->isReadWrite() )
    return;

  Sheet *sheet = m_pCanvas->activeSheet();

  if (!sheet)
    return;

  double dWidth = m_pCanvas->d->view->doc()->unzoomItX( width() );
  double ev_PosX;
  if ( sheet->layoutDirection()==Sheet::RightToLeft )
    ev_PosX = dWidth - m_pCanvas->d->view->doc()->unzoomItX( _ev->pos().x() ) + m_pCanvas->xOffset();
  else
    ev_PosX = m_pCanvas->d->view->doc()->unzoomItX( _ev->pos().x() ) + m_pCanvas->xOffset();

  // The button is pressed and we are resizing ?
  if ( m_bResize )
  {
    if ( !sheet->isProtected() )
        paintSizeIndicator( _ev->pos().x(), false );
  }
  // The button is pressed and we are selecting ?
  else if ( m_bSelection )
  {
    double x;
    int col = sheet->leftColumn( ev_PosX, x );

    if ( col > KS_colMax )
      return;

    TQPoint newMarker = m_pView->selectionInfo()->marker();
    TQPoint newAnchor = m_pView->selectionInfo()->anchor();
    newMarker.setX( col );
    newAnchor.setX( m_iSelectionAnchor );
    m_pView->selectionInfo()->update(newMarker);

    if ( sheet->layoutDirection()==Sheet::RightToLeft )
    {
      if ( _ev->pos().x() < width() - m_pCanvas->width() )
      {
        ColumnFormat *cl = sheet->columnFormat( col + 1 );
        x = sheet->dblColumnPos( col + 1 );
        m_pCanvas->horzScrollBar()->setValue ( m_pCanvas->horzScrollBar()->maxValue() - (int)
            (m_pCanvas->d->view->doc()->zoomItX (ev_PosX + cl->dblWidth()) - m_pCanvas->d->view->doc()->unzoomItX( m_pCanvas->width() )));
      }
      else if ( _ev->pos().x() > width() )
        m_pCanvas->horzScrollBar()->setValue( m_pCanvas->horzScrollBar()->maxValue() - m_pCanvas->d->view->doc()->zoomItX( ev_PosX - dWidth + m_pCanvas->d->view->doc()->unzoomItX( m_pCanvas->width() ) ) );
    }
    else
    {
      if ( _ev->pos().x() < 0 )
        m_pCanvas->horzScrollBar()->setValue( m_pCanvas->d->view->doc()->zoomItX( ev_PosX ) );
      else if ( _ev->pos().x() > m_pCanvas->width() )
      {
        if ( col < KS_colMax )
        {
          ColumnFormat *cl = sheet->columnFormat( col + 1 );
          x = sheet->dblColumnPos( col + 1 );
          m_pCanvas->horzScrollBar()->setValue ((int)
              (m_pCanvas->d->view->doc()->zoomItX (ev_PosX + cl->dblWidth()) - dWidth));
        }
      }
    }

  }
  // No button is pressed and the mouse is just moved
  else
  {
     //What is the internal size of 1 pixel
    const double unzoomedPixel = m_pCanvas->d->view->doc()->unzoomItX( 1 );
    double x;

    if ( sheet->layoutDirection()==Sheet::RightToLeft )
    {
      int tmpCol = sheet->leftColumn( m_pCanvas->xOffset(), x );

      while ( ev_PosX > x )
      {
        double w = sheet->columnFormat( tmpCol )->dblWidth();
        ++tmpCol;

        //if col is hide and it's the first column
        //you mustn't resize it.
        if ( ev_PosX >= x + w - unzoomedPixel &&
             ev_PosX <= x + w + unzoomedPixel &&
             !( sheet->columnFormat( tmpCol )->isHide() && tmpCol == 0 ) )
        {
          setCursor( splitHCursor );
          return;
        }
        x += w;
      }
      setCursor( arrowCursor );
    }
    else
    {
      int tmpCol = sheet->leftColumn( m_pCanvas->xOffset(), x );

      while ( x < m_pCanvas->d->view->doc()->unzoomItY( width() ) + m_pCanvas->xOffset() )
      {
        double w = sheet->columnFormat( tmpCol )->dblWidth();
        //if col is hide and it's the first column
        //you mustn't resize it.
        if ( ev_PosX >= x + w - unzoomedPixel &&
             ev_PosX <= x + w + unzoomedPixel &&
             !( sheet->columnFormat( tmpCol )->isHide() && tmpCol == 1 ) )
        {
          setCursor( splitHCursor );
          return;
        }
        x += w;
        tmpCol++;
      }
      setCursor( arrowCursor );
    }
  }
}

void HBorder::doAutoScroll()
{
    if ( !m_bMousePressed )
    {
        m_scrollTimer->stop();
        return;
    }

    TQPoint pos( mapFromGlobal( TQCursor::pos() ) );

    if ( pos.x() < 0 || pos.x() > width() )
    {
        TQMouseEvent * event = new TQMouseEvent( TQEvent::MouseMove, pos, 0, 0 );
        mouseMoveEvent( event );
        delete event;
    }

    //Restart timer
    m_scrollTimer->start( 50 );
}

void HBorder::wheelEvent( TQWheelEvent* _ev )
{
  if ( m_pCanvas->horzScrollBar() )
    TQApplication::sendEvent( m_pCanvas->horzScrollBar(), _ev );
}

void HBorder::resizeEvent( TQResizeEvent* _ev )
{
  // workaround to allow horizontal resizing and zoom changing when sheet
  // direction and interface direction don't match (e.g. an RTL sheet on an
  // LTR interface)
  if ( m_pCanvas->activeSheet() && m_pCanvas->activeSheet()->layoutDirection()==Sheet::RightToLeft && !TQApplication::reverseLayout() )
  {
    int dx = _ev->size().width() - _ev->oldSize().width();
    scroll(dx, 0);
  }
  else if ( m_pCanvas->activeSheet() && m_pCanvas->activeSheet()->layoutDirection()==Sheet::LeftToRight && TQApplication::reverseLayout() )
  {
    int dx = _ev->size().width() - _ev->oldSize().width();
    scroll(-dx, 0);
  }
}

void HBorder::paintSizeIndicator( int mouseX, bool firstTime )
{
    Sheet *sheet = m_pCanvas->activeSheet();
    if (!sheet)
	    return;

    TQPainter painter;
    painter.begin( m_pCanvas );
    painter.setRasterOp( NotROP );

    if ( !firstTime )
      painter.drawLine( m_iResizePos, 0, m_iResizePos, m_pCanvas->height() );

    if ( sheet->layoutDirection()==Sheet::RightToLeft )
      m_iResizePos = mouseX + m_pCanvas->width() - width();
    else
      m_iResizePos = mouseX;

    // Dont make the column have a width < 2 pixels.
    int x = m_pCanvas->d->view->doc()->zoomItX( sheet->dblColumnPos( m_iResizedColumn ) - m_pCanvas->xOffset() );

    if ( sheet->layoutDirection()==Sheet::RightToLeft )
    {
      x = m_pCanvas->width() - x;

      if ( m_iResizePos > x - 2 )
          m_iResizePos = x;
    }
    else
    {
      if ( m_iResizePos < x + 2 )
          m_iResizePos = x;
    }

    painter.drawLine( m_iResizePos, 0, m_iResizePos, m_pCanvas->height() );

    painter.end();

    TQString tmpSize;
    if ( m_iResizePos != x )
        tmpSize = i18n("Width: %1 %2")
                  .tqarg( KGlobal::locale()->formatNumber( KoUnit::toUserValue( m_pCanvas->doc()->unzoomItX( (sheet->layoutDirection()==Sheet::RightToLeft) ? x - m_iResizePos : m_iResizePos - x ),
                                                                           m_pView->doc()->unit() )))
                  .tqarg( m_pView->doc()->unitName() );
    else
        tmpSize = i18n( "Hide Column" );

    painter.begin( this );
    int len = painter.fontMetrics().width( tmpSize );
    int hei = painter.fontMetrics().height();
    painter.end();

    if ( !m_lSize )
    {
        m_lSize = new TQLabel( m_pCanvas );

        if ( sheet->layoutDirection()==Sheet::RightToLeft )
          m_lSize->setGeometry( x - len - 5, 3, len + 2, hei + 2 );
        else
          m_lSize->setGeometry( x + 3, 3, len + 2, hei + 2 );

        m_lSize->tqsetAlignment( TQt::AlignVCenter );
        m_lSize->setText( tmpSize );
        m_lSize->setPalette( TQToolTip::palette() );
        m_lSize->show();
    }
    else
    {
        if ( sheet->layoutDirection()==Sheet::RightToLeft )
          m_lSize->setGeometry( x - len - 5, 3, len + 2, hei + 2 );
        else
          m_lSize->setGeometry( x + 3, 3, len + 2, hei + 2 );

        m_lSize->setText( tmpSize );
    }
}

void HBorder::updateColumns( int from, int to )
{
    Sheet *sheet = m_pCanvas->activeSheet();
    if ( !sheet )
        return;

    int x0 = sheet->columnPos( from, m_pCanvas );
    int x1 = sheet->columnPos( to+1, m_pCanvas );
    update( x0, 0, x1-x0, height() );
}

void HBorder::paintEvent( TQPaintEvent* _ev )
{
  Sheet * sheet = m_pCanvas->activeSheet();
  if ( !sheet )
    return;

  TQColor   highlightColor = View::highlightColor();
  TQPainter painter( this );
  TQPen pen( TQt::black, 1 );
  painter.setPen( pen );
  painter.setBackgroundColor( white );

  painter.setClipRect( _ev->rect() );

  // painter.eraseRect( _ev->rect() );

  //TQFontMetrics fm = painter.fontMetrics();
  // Matthias Elter: This causes a SEGFAULT in ~TQPainter!
  // Only god and the trolls know why ;-)
  // bah...took me quite some time to track this one down...

  double xPos;
  int x;

  if ( sheet->layoutDirection()==Sheet::RightToLeft )
  {
    //Get the left column and the current x-position
    x = sheet->leftColumn( int( m_pCanvas->d->view->doc()->unzoomItX( width() ) - m_pCanvas->d->view->doc()->unzoomItX( _ev->rect().x() ) + m_pCanvas->xOffset() ), xPos );
    //Align to the offset
    xPos = m_pCanvas->d->view->doc()->unzoomItX( width() ) - xPos + m_pCanvas->xOffset();
  }
  else
  {
    //Get the left column and the current x-position
    x = sheet->leftColumn( int( m_pCanvas->d->view->doc()->unzoomItX( _ev->rect().x() ) + m_pCanvas->xOffset() ), xPos );
    //Align to the offset
    xPos = xPos - m_pCanvas->xOffset();
  }

  int height = m_pCanvas->d->view->doc()->zoomItY( TQFont(painter.font()).pointSizeFloat() + 5 );

  TQFont normalFont = painter.font();
  if ( m_pCanvas->d->view->doc()->zoom() < 100 )
  {
    normalFont.setPointSizeFloat( 0.01 * m_pCanvas->d->view->doc()->zoom() *
                                  normalFont.pointSizeFloat() );
  }
  TQFont boldFont = normalFont;
  boldFont.setBold( true );

  if ( sheet->layoutDirection()==Sheet::RightToLeft )
  {
    if ( x > KS_colMax )
      x = KS_colMax;

    xPos -= sheet->columnFormat( x )->dblWidth();

    //Loop through the columns, until we are out of range
    while ( xPos <= m_pCanvas->d->view->doc()->unzoomItX( _ev->rect().right() ) )
    {
      bool selected = (m_pView->selectionInfo()->isColumnSelected(x));
      bool highlighted = (!selected && m_pView->selectionInfo()->isColumnAffected(x));

      const ColumnFormat * col_lay = sheet->columnFormat( x );
      int zoomedXPos = m_pCanvas->d->view->doc()->zoomItX( xPos );
      int width = m_pCanvas->d->view->doc()->zoomItX( xPos + col_lay->dblWidth() ) - zoomedXPos;

      if ( selected )
      {
        TQBrush fillSelected( highlightColor );
        qDrawPlainRect ( &painter, zoomedXPos, 0, width+1, height, highlightColor.dark(150),
           1, &fillSelected );
      }
      else if ( highlighted )
      {
        TQBrush fillHighlighted( highlightColor );
        qDrawPlainRect ( &painter, zoomedXPos, 0, width+1, height, highlightColor.dark(150),
           1, &fillHighlighted );
      }
      else
      {
        TQColor c = tqcolorGroup().background();
        TQBrush fill( c );
        qDrawPlainRect ( &painter, zoomedXPos, 0, width+1, height, c.dark(150),
           1, &fill );
      }

      // Reset painter
      painter.setFont( normalFont );
      painter.setPen( tqcolorGroup().text() );

      if ( selected )
        painter.setPen( tqcolorGroup().highlightedText() );
      else if ( highlighted )
        painter.setFont( boldFont );
      if ( !m_pView->activeSheet()->getShowColumnNumber() )
      {
        TQString colText = Cell::columnName( x );
        int len = painter.fontMetrics().width( colText );
        if ( !col_lay->isHide() )
          painter.drawText( zoomedXPos + ( width - len ) / 2,
                            ( height + painter.fontMetrics().ascent() -
                              painter.fontMetrics().descent() ) / 2, colText );
      }
      else
      {
        TQString tmp;
        int len = painter.fontMetrics().width( tmp.setNum(x) );
        if (!col_lay->isHide())
          painter.drawText( zoomedXPos + ( width - len ) / 2,
                            ( height + painter.fontMetrics().ascent() -
                              painter.fontMetrics().descent() ) / 2,
                            tmp.setNum(x) );
      }
      xPos += col_lay->dblWidth();
      --x;
    }
  }
  else
  {
    //Loop through the columns, until we are out of range
    while ( xPos <= m_pCanvas->d->view->doc()->unzoomItX( _ev->rect().right() ) )
    {
      bool selected = (m_pView->selectionInfo()->isColumnSelected(x));
      bool highlighted = (!selected && m_pView->selectionInfo()->isColumnAffected(x));

      const ColumnFormat *col_lay = sheet->columnFormat( x );
      int zoomedXPos = m_pCanvas->d->view->doc()->zoomItX( xPos );
      int width = m_pCanvas->d->view->doc()->zoomItX( xPos + col_lay->dblWidth() ) - zoomedXPos;

      if ( selected )
      {
        TQBrush fillSelected( highlightColor );
        qDrawPlainRect ( &painter, zoomedXPos, 0, width+1, height, highlightColor.dark(),
           1, &fillSelected );
      }
      else if ( highlighted )
      {
        TQBrush fillHighlighted( highlightColor );
        qDrawPlainRect ( &painter, zoomedXPos, 0, width+1, height, highlightColor.dark(),
           1, &fillHighlighted );
      }
      else
      {
        TQColor c = tqcolorGroup().background();
        TQBrush fill( c );
        qDrawPlainRect ( &painter, zoomedXPos, 0, width+1, height, c.dark(150),
           1, &fill );
      }

      // Reset painter
      painter.setFont( normalFont );
      painter.setPen( tqcolorGroup().text() );

      if ( selected )
        painter.setPen( tqcolorGroup().highlightedText() );
      else if ( highlighted )
        painter.setFont( boldFont );
      if ( !m_pView->activeSheet()->getShowColumnNumber() )
      {
        TQString colText = Cell::columnName( x );
        int len = painter.fontMetrics().width( colText );
        if (!col_lay->isHide())
          painter.drawText( zoomedXPos + ( width - len ) / 2,
                            ( height + painter.fontMetrics().ascent() -
                              painter.fontMetrics().descent() ) / 2, colText );
      }
      else
      {
        TQString tmp;
        int len = painter.fontMetrics().width( tmp.setNum(x) );
        if (!col_lay->isHide())
          painter.drawText( zoomedXPos + ( width - len ) / 2,
                            ( height + painter.fontMetrics().ascent() -
                              painter.fontMetrics().descent() ) / 2,
                            tmp.setNum(x) );
      }
      xPos += col_lay->dblWidth();
      ++x;
    }
  }
}


void HBorder::focusOutEvent( TQFocusEvent* )
{
    if ( m_scrollTimer->isActive() )
        m_scrollTimer->stop();
    m_bMousePressed = false;
}

/****************************************************************
 *
 * ToolTip
 *
 ****************************************************************/

ToolTip::ToolTip( Canvas* canvas )
    : TQToolTip( canvas ), m_canvas( canvas )
{
}

// find the label for the tip
// this is a hack of course, because it's not available from TQToolTip
TQLabel *tip_findLabel()
{
    TQWidgetList  *list = TQApplication::tqallWidgets();
    TQWidgetListIt it( *list );
    TQWidget * w;
    while ( (w=it.current()) != 0 )
    {
        if(w->isA("TQTipLabel"))
            return static_cast<TQLabel*>(w);
        ++it;
    }
    delete list;
    return 0;
}

void ToolTip::maybeTip( const TQPoint& p )
{
    Sheet *sheet = m_canvas->activeSheet();
    if ( !sheet )
        return;

    // Over which cell is the mouse ?
    double ypos, xpos;
    double dwidth = m_canvas->doc()->unzoomItX( m_canvas->width() );
    int col;
    if ( sheet->layoutDirection()==Sheet::RightToLeft )
      col = sheet->leftColumn( (dwidth - m_canvas->doc()->unzoomItX( p.x() ) +
                                              m_canvas->xOffset()), xpos );
    else
      col = sheet->leftColumn( (m_canvas->doc()->unzoomItX( p.x() ) +
                                     m_canvas->xOffset()), xpos );


    int row = sheet->topRow( (m_canvas->doc()->unzoomItY( p.y() ) +
                                   m_canvas->yOffset()), ypos );

    const Cell* cell = sheet->visibleCellAt( col, row );
    if ( !cell )
        return;

#if 0
    // Quick cut
    if( cell->strOutText().isEmpty() )
        return;
#endif
    // displayed tool tip, which has the following priorities:
    //  - cell content if the cell dimension is too small
    //  - cell comment
    //  - hyperlink
    TQString tipText;
    TQString comment = cell->format()->comment( col, row );

    // If cell is too small, show the content
    if ( cell->testFlag( Cell::Flag_CellTooShortX ) ||
         cell->testFlag( Cell::Flag_CellTooShortY ) )
    {
        tipText = cell->strOutText();
    }

    // Show hyperlink, if any
    if ( tipText.isEmpty() )
    {
      tipText = cell->link();
    }

    // Nothing to display, bail out
    if ( tipText.isEmpty() && comment.isEmpty() )
      return;

    // Cut if the tip is ridiculously long
    const unsigned maxLen = 256;
    if ( tipText.length() > maxLen )
        tipText = tipText.left(maxLen).append("...");

    // Determine position and width of the current cell.
    double u = cell->dblWidth( col );
    double v = cell->dblHeight( row );

    // Special treatment for obscured cells.
    if ( cell->isObscured() && cell->isPartOfMerged() )
    {
      cell = cell->obscuringCells().first();
      const int moveX = cell->column();
      const int moveY = cell->row();

      // Use the obscuring cells dimensions
      u = cell->dblWidth( moveX );
      v = cell->dblHeight( moveY );
      xpos = sheet->dblColumnPos( moveX );
      ypos = sheet->dblRowPos( moveY );
    }

    // Get the cell dimensions
    TQRect marker;
    bool insideMarker = false;

    if ( sheet->layoutDirection()==Sheet::RightToLeft )
    {
      KoRect unzoomedMarker( dwidth - u - xpos + m_canvas->xOffset(),
                             ypos - m_canvas->yOffset(),
                             u,
                             v );

      marker = m_canvas->doc()->zoomRect( unzoomedMarker );
      insideMarker = marker.contains( p );
    }
    else
    {
      KoRect unzoomedMarker( xpos - m_canvas->xOffset(),
                             ypos - m_canvas->yOffset(),
                             u,
                             v );

      marker = m_canvas->doc()->zoomRect( unzoomedMarker );
      insideMarker = marker.contains( p );
    }

    // No use if mouse is somewhere else
    if ( !insideMarker )
        return;

    // Find the tipLabel
    // NOTE: if we failed, check again when the tip is shown already
    TQLabel* tipLabel = tip_findLabel();

    // Ensure that it is plain text
    // Not funny if (intentional or not) <a> appears as hyperlink
    if ( tipLabel )
         tipLabel->setTextFormat( TQt::PlainText );

    TQFontMetrics fm = tipLabel ? tipLabel->fontMetrics() : m_canvas->fontMetrics();
    const TQRect r( 0, 0, 200, -1 );
    // Wrap the text if too long
    if ( tipText.length() > 16 )
    {
        KWordWrap* wrap = KWordWrap::formatText( fm, r, 0, tipText );
        tipText = wrap->wrappedString();
        delete wrap;
    }
    // Wrap the comment if too long
    if ( comment.length() > 16 )
    {
      KWordWrap* wrap = KWordWrap::formatText( fm, r, 0, comment );
      comment = wrap->wrappedString();
      delete wrap;
    }

    // Show comment, if any
    if ( tipText.isEmpty() )
    {
      tipText = comment;
    }
    else if ( !comment.isEmpty() )
    {
      //Add 2 extra lines and a text, when both should be in the tooltip
      if ( !comment.isEmpty() )
        comment = "\n\n" + i18n("Comment:") + "\n" + comment;

      tipText += comment;
    }

    // Now we shows the tip
    tip( marker, tipText );

    // Here we try to find the tip label again
    // Reason: the previous tip_findLabel might fail if no tip has ever shown yet
    if ( !tipLabel )
    {
      tipLabel = tip_findLabel();
      if( tipLabel )
            tipLabel->setTextFormat( TQt::PlainText );
    }

}

#include "kspread_canvas.moc"