File: CellToolBase_p.cpp

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

// KSpread
#include "ApplicationSettings.h"
#include "CalculationSettings.h"
#include "CellStorage.h"
#include "Map.h"
#include "RowColumnFormat.h"
#include "RowFormatStorage.h"
#include "Selection.h"
#include "Sheet.h"

// commands
#include "commands/DataManipulators.h"
#include "commands/StyleCommand.h"

// ui
#include "ui/CellEditor.h"
#include "ui/CellToolOptionWidget.h"
#include "ui/ExternalEditor.h"
#include "ui/SheetView.h"

// Calligra
#include <KoCanvasBase.h>
#include <KoCanvasController.h>
#include <KoCanvasResourceManager.h>
#include <KoViewConverter.h>

// KDE
#include <KFontAction>
#include <KFontChooser>
#include <KFontSizeAction>

// Qt
#include <QApplication>
#include <QGridLayout>
#include <QPainter>
#include <QToolButton>

using namespace Calligra::Sheets;

void CellToolBase::Private::updateEditor(const Cell& cell)
{
    const Cell& theCell = cell.isPartOfMerged() ? cell.masterCell() : cell;
    const Style style = theCell.style();
    if (q->selection()->activeSheet()->isProtected() && style.hideFormula()) {
        optionWidget->editor()->setPlainText(theCell.displayText());
    } else if (q->selection()->activeSheet()->isProtected() && style.hideAll()) {
        optionWidget->editor()->clear();
    } else {
        optionWidget->editor()->setPlainText(theCell.userInput());
    }
}

#define ACTION_EXEC( name, command ) { \
        QAction *a = q->action(name); \
        const bool blocked = a->blockSignals(true); \
        a->command; \
        a->blockSignals(blocked); \
    }

void CellToolBase::Private::updateActions(const Cell& cell)
{
    const Style style = cell.style();

    // -- font actions --
    ACTION_EXEC("bold", setChecked(style.bold()));
    ACTION_EXEC("italic", setChecked(style.italic()));
    ACTION_EXEC("underline", setChecked(style.underline()));
    ACTION_EXEC("strikeOut", setChecked(style.strikeOut()));

    static_cast<KFontAction*>(q->action("font"))->setFont(style.fontFamily());
    static_cast<KFontSizeAction*>(q->action("fontSize"))->setFontSize(style.fontSize());
    // -- horizontal alignment actions --
    ACTION_EXEC("alignLeft", setChecked(style.halign() == Style::Left));
    ACTION_EXEC("alignCenter", setChecked(style.halign() == Style::Center));
    ACTION_EXEC("alignRight", setChecked(style.halign() == Style::Right));
    // -- vertical alignment actions --
    ACTION_EXEC("alignTop", setChecked(style.valign() == Style::Top));
    ACTION_EXEC("alignMiddle", setChecked(style.valign() == Style::Middle));
    ACTION_EXEC("alignBottom", setChecked(style.valign() == Style::Bottom));

    ACTION_EXEC("verticalText", setChecked(style.verticalText()));
    ACTION_EXEC("wrapText", setChecked(style.wrapText()));

    Format::Type ft = style.formatType();
    ACTION_EXEC("percent", setChecked(ft == Format::Percentage));
    ACTION_EXEC("currency", setChecked(ft == Format::Money));

    const bool showFormulas = q->selection()->activeSheet()->getShowFormula();
    q->action("alignLeft")->setEnabled(!showFormulas);
    q->action("alignCenter")->setEnabled(!showFormulas);
    q->action("alignRight")->setEnabled(!showFormulas);

    if (!q->selection()->activeSheet()->isProtected() || style.notProtected()) {
        q->action("clearComment")->setEnabled(!cell.comment().isEmpty());
        q->action("decreaseIndentation")->setEnabled(style.indentation() > 0.0);
    }

    // Now, activate/deactivate some actions depending on what is selected.
    if (!q->selection()->activeSheet()->isProtected()) {
        const bool colSelected = q->selection()->isColumnSelected();
        const bool rowSelected = q->selection()->isRowSelected();
        // -- column & row actions --
        q->action("resizeCol")->setEnabled(!rowSelected);
        q->action("insertColumn")->setEnabled(!rowSelected);
        q->action("deleteColumn")->setEnabled(!rowSelected);
        q->action("hideColumn")->setEnabled(!rowSelected);
        q->action("equalizeCol")->setEnabled(!rowSelected);
        q->action("resizeRow")->setEnabled(!colSelected);
        q->action("deleteRow")->setEnabled(!colSelected);
        q->action("insertRow")->setEnabled(!colSelected);
        q->action("hideRow")->setEnabled(!colSelected);
        q->action("equalizeRow")->setEnabled(!colSelected);
        // -- data insert actions --
        q->action("textToColumns")->setEnabled(!rowSelected);

        const bool simpleSelection = q->selection()->isSingular() || colSelected || rowSelected;
        q->action("sheetFormat")->setEnabled(!simpleSelection);
        q->action("sort")->setEnabled(!simpleSelection);
        q->action("sortDec")->setEnabled(!simpleSelection);
        q->action("sortInc")->setEnabled(!simpleSelection);
        q->action("mergeCells")->setEnabled(!simpleSelection);
        q->action("mergeCellsHorizontal")->setEnabled(!simpleSelection);
        q->action("mergeCellsVertical")->setEnabled(!simpleSelection);
        q->action("fillRight")->setEnabled(!simpleSelection);
        q->action("fillUp")->setEnabled(!simpleSelection);
        q->action("fillDown")->setEnabled(!simpleSelection);
        q->action("fillLeft")->setEnabled(!simpleSelection);
        q->action("createStyleFromCell")->setEnabled(simpleSelection); // just from one cell

        const bool contiguousSelection = q->selection()->isContiguous();
        q->action("subtotals")->setEnabled(contiguousSelection);
    }
}

void CellToolBase::Private::setProtectedActionsEnabled(bool enable)
{
    // Enable/disable actions.
    const QList<KAction*> actions = q->actions().values();
    for (int i = 0; i < actions.count(); ++i)
        actions[i]->setEnabled(enable);
    optionWidget->formulaButton()->setEnabled(enable);
    optionWidget->editor()->setEnabled(enable);

    // These actions are always enabled.
    q->action("copy")->setEnabled(true);
    q->action("gotoCell")->setEnabled(true);
    q->action("edit_find")->setEnabled(true);
    q->action("edit_find_next")->setEnabled(true);
    q->action("edit_find_last")->setEnabled(true);
}

void CellToolBase::Private::processEnterKey(QKeyEvent* event)
{
// array is true, if ctrl+alt are pressed
    bool array = (event->modifiers() & Qt::AltModifier) &&
                 (event->modifiers() & Qt::ControlModifier);

    /* save changes to the current editor */
    q->deleteEditor(true, array);

    /* use the configuration setting to see which direction we're supposed to move
        when enter is pressed.
    */
    Calligra::Sheets::MoveTo direction = q->selection()->activeSheet()->map()->settings()->moveToValue();

//if shift Button clicked inverse move direction
    if (event->modifiers() & Qt::ShiftModifier) {
        switch (direction) {
        case Bottom:
            direction = Top;
            break;
        case Top:
            direction = Bottom;
            break;
        case Left:
            direction = Right;
            break;
        case Right:
            direction = Left;
            break;
        case BottomFirst:
            direction = BottomFirst;
            break;
        case NoMovement:
            direction = NoMovement;
            break;
        }
    }

    /* never extend a selection with the enter key -- the shift key reverses
        direction, not extends the selection
    */
    QRect r(moveDirection(direction, false));
    event->accept(); // QKeyEvent
}

void CellToolBase::Private::processArrowKey(QKeyEvent *event)
{
    /* NOTE:  hitting the tab key also calls this function.  Don't forget
        to account for it
    */
    register Sheet * const sheet = q->selection()->activeSheet();
    if (!sheet)
        return;

    /* save changes to the current editor */
    q->selection()->emitCloseEditor(true);

    Calligra::Sheets::MoveTo direction = Bottom;
    bool makingSelection = event->modifiers() & Qt::ShiftModifier;

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

    QRect r(moveDirection(direction, makingSelection));
    event->accept(); // QKeyEvent
}

void CellToolBase::Private::processEscapeKey(QKeyEvent * event)
{
    q->selection()->emitCloseEditor(false); // discard changes
    event->accept(); // QKeyEvent
}

bool CellToolBase::Private::processHomeKey(QKeyEvent* event)
{
    register Sheet * const sheet = q->selection()->activeSheet();
    if (!sheet)
        return false;

    bool makingSelection = event->modifiers() & Qt::ShiftModifier;

    if (q->editor()) {
        // We are in edit mode -> go beginning of line
        QApplication::sendEvent(q->editor()->widget(), event);
        return false;
    } else {
        QPoint 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->modifiers() & Qt::ControlModifier) {
            /* ctrl + Home will always just send us to location (1,1) */
            destination = QPoint(1, 1);
        } else {
            QPoint marker = q->selection()->marker();

            Cell cell = sheet->cellStorage()->firstInRow(marker.y(), CellStorage::VisitContent);
            while (!cell.isNull() && cell.column() < marker.x() && cell.isEmpty()) {
                cell = sheet->cellStorage()->nextInRow(cell.column(), cell.row(), CellStorage::VisitContent);
            }

            int col = (!cell.isNull() ? cell.column() : 1);
            if (col == marker.x())
                col = 1;
            destination = QPoint(col, marker.y());
        }

        if (q->selection()->marker() == destination)
            return false;

        if (makingSelection) {
            q->selection()->update(destination);
        } else {
            q->selection()->initialize(destination, sheet);
        }
        q->scrollToCell(destination);
        event->accept(); // QKeyEvent
    }
    return true;
}

bool CellToolBase::Private::processEndKey(QKeyEvent *event)
{
    register Sheet * const sheet = q->selection()->activeSheet();
    if (!sheet)
        return false;

    bool makingSelection = event->modifiers() & Qt::ShiftModifier;
    Cell cell;
    QPoint marker = q->selection()->marker();

    if (q->editor()) {
        // We are in edit mode -> go end of line
        QApplication::sendEvent(q->editor()->widget(), event);
        return false;
    } else {
        // move to the last used cell in the row
        int col = 1;

        cell = sheet->cellStorage()->lastInRow(marker.y(), CellStorage::VisitContent);
        while (!cell.isNull() && cell.column() > q->selection()->marker().x() && cell.isEmpty()) {
            cell = sheet->cellStorage()->prevInRow(cell.column(), cell.row(), CellStorage::VisitContent);
        }

        col = (cell.isNull()) ? q->maxCol() : cell.column();

        QPoint destination(col, marker.y());
        if (destination == marker)
            return false;

        if (makingSelection) {
            q->selection()->update(destination);
        } else {
            q->selection()->initialize(destination, sheet);
        }
        q->scrollToCell(destination);
        event->accept(); // QKeyEvent
    }
    return true;
}

bool CellToolBase::Private::processPriorKey(QKeyEvent *event)
{
    bool makingSelection = event->modifiers() & Qt::ShiftModifier;
    q->selection()->emitCloseEditor(true); // save changes

    QPoint marker = q->selection()->marker();

    QPoint destination(marker.x(), qMax(1, marker.y() - 10));
    if (destination == marker)
        return false;

    if (makingSelection) {
        q->selection()->update(destination);
    } else {
        q->selection()->initialize(destination, q->selection()->activeSheet());
    }
    q->scrollToCell(destination);
    event->accept(); // QKeyEvent
    return true;
}

bool CellToolBase::Private::processNextKey(QKeyEvent *event)
{
    bool makingSelection = event->modifiers() & Qt::ShiftModifier;

    q->selection()->emitCloseEditor(true); // save changes

    QPoint marker = q->selection()->marker();
    QPoint destination(marker.x(), qMax(1, marker.y() + 10));

    if (marker == destination)
        return false;

    if (makingSelection) {
        q->selection()->update(destination);
    } else {
        q->selection()->initialize(destination, q->selection()->activeSheet());
    }
    q->scrollToCell(destination);
    event->accept(); // QKeyEvent
    return true;
}

void CellToolBase::Private::processOtherKey(QKeyEvent *event)
{
    register Sheet * const sheet = q->selection()->activeSheet();

    // No null character ...
    if (event->text().isEmpty() || !q->selection()->activeSheet()->map()->isReadWrite() ||
            !sheet || sheet->isProtected()) {
        event->accept(); // QKeyEvent
    } else {
        if (!q->editor()) {
            // Switch to editing mode
            q->createEditor();
        }
        // Send it to the embedded editor.
        QApplication::sendEvent(q->editor()->widget(), event);
    }
}

bool CellToolBase::Private::processControlArrowKey(QKeyEvent *event)
{
    register Sheet * const sheet = q->selection()->activeSheet();
    if (!sheet)
        return false;

    bool makingSelection = event->modifiers() & Qt::ShiftModifier;

    Cell cell;
    Cell lastCell;
    QPoint destination;
    bool searchThroughEmpty = true;
    int row;
    int col;

    QPoint marker = q->selection()->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+Qt::Key_Up
    case Qt::Key_Up:

        cell = Cell(sheet, marker.x(), marker.y());
        if ((!cell.isNull()) && (!cell.isEmpty()) && (marker.y() != 1)) {
            lastCell = cell;
            row = marker.y() - 1;
            cell = Cell(sheet, cell.column(), row);
            while ((!cell.isNull()) && (row > 0) && (!cell.isEmpty())) {
                if (!sheet->rowFormats()->isHiddenOrFiltered(cell.row())) {
                    lastCell = cell;
                    searchThroughEmpty = false;
                }
                row--;
                if (row > 0)
                    cell = Cell(sheet, cell.column(), row);
            }
            cell = lastCell;
        }
        if (searchThroughEmpty) {
            cell = sheet->cellStorage()->prevInColumn(marker.x(), marker.y(), CellStorage::VisitContent);

            while ((!cell.isNull()) &&
                    (cell.isEmpty() || (sheet->rowFormats()->isHiddenOrFiltered(cell.row())))) {
                cell = sheet->cellStorage()->prevInColumn(cell.column(), cell.row(), CellStorage::VisitContent);
            }
        }

        if (cell.isNull())
            row = 1;
        else
            row = cell.row();

        int lastHiddenOrFiltered;
        while (sheet->rowFormats()->isHiddenOrFiltered(row, &lastHiddenOrFiltered)) {
            row = lastHiddenOrFiltered + 1;
        }

        destination.setX(qBound(1, marker.x(), q->maxCol()));
        destination.setY(qBound(1, row, q->maxRow()));
        break;

        //Ctrl+Qt::Key_Down
    case Qt::Key_Down:

        cell = Cell(sheet, marker.x(), marker.y());
        if ((!cell.isNull()) && (!cell.isEmpty()) && (marker.y() != q->maxRow())) {
            lastCell = cell;
            row = marker.y() + 1;
            cell = Cell(sheet, cell.column(), row);
            while ((!cell.isNull()) && (row < q->maxRow()) && (!cell.isEmpty())) {
                if (!(sheet->rowFormats()->isHiddenOrFiltered(cell.row()))) {
                    lastCell = cell;
                    searchThroughEmpty = false;
                }
                row++;
                cell = Cell(sheet, cell.column(), row);
            }
            cell = lastCell;
        }
        if (searchThroughEmpty) {
            cell = sheet->cellStorage()->nextInColumn(marker.x(), marker.y(), CellStorage::VisitContent);

            while ((!cell.isNull()) &&
                    (cell.isEmpty() || (sheet->rowFormats()->isHiddenOrFiltered(cell.row())))) {
                cell = sheet->cellStorage()->nextInColumn(cell.column(), cell.row(), CellStorage::VisitContent);
            }
        }

        if (cell.isNull())
            row = marker.y();
        else
            row = cell.row();

        int firstHiddenOrFiltered;
        while (row >= 1 && sheet->rowFormats()->isHiddenOrFiltered(row, 0, &firstHiddenOrFiltered)) {
            row = firstHiddenOrFiltered - 1;
        }

        destination.setX(qBound(1, marker.x(), q->maxCol()));
        destination.setY(qBound(1, row, q->maxRow()));
        break;

//Ctrl+Qt::Key_Left
    case Qt::Key_Left:

        if (sheet->layoutDirection() == Qt::RightToLeft) {
            cell = Cell(sheet, marker.x(), marker.y());
            if ((!cell.isNull()) && (!cell.isEmpty()) && (marker.x() != q->maxCol())) {
                lastCell = cell;
                col = marker.x() + 1;
                cell = Cell(sheet, col, cell.row());
                while ((!cell.isNull()) && (col < q->maxCol()) && (!cell.isEmpty())) {
                    if (!(sheet->columnFormat(cell.column())->isHiddenOrFiltered())) {
                        lastCell = cell;
                        searchThroughEmpty = false;
                    }
                    col++;
                    cell = Cell(sheet, col, cell.row());
                }
                cell = lastCell;
            }
            if (searchThroughEmpty) {
                cell = sheet->cellStorage()->nextInRow(marker.x(), marker.y(), CellStorage::VisitContent);

                while ((!cell.isNull()) &&
                        (cell.isEmpty() || (sheet->columnFormat(cell.column())->isHiddenOrFiltered()))) {
                    cell = sheet->cellStorage()->nextInRow(cell.column(), cell.row(), CellStorage::VisitContent);
                }
            }

            if (cell.isNull())
                col = marker.x();
            else
                col = cell.column();

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

            destination.setX(qBound(1, col, q->maxCol()));
            destination.setY(qBound(1, marker.y(), q->maxRow()));
        } else {
            cell = Cell(sheet, marker.x(), marker.y());
            if ((!cell.isNull()) && (!cell.isEmpty()) && (marker.x() != 1)) {
                lastCell = cell;
                col = marker.x() - 1;
                cell = Cell(sheet, col, cell.row());
                while ((!cell.isNull()) && (col > 0) && (!cell.isEmpty())) {
                    if (!(sheet->columnFormat(cell.column())->isHiddenOrFiltered())) {
                        lastCell = cell;
                        searchThroughEmpty = false;
                    }
                    col--;
                    if (col > 0)
                        cell = Cell(sheet, col, cell.row());
                }
                cell = lastCell;
            }
            if (searchThroughEmpty) {
                cell = sheet->cellStorage()->prevInRow(marker.x(), marker.y(), CellStorage::VisitContent);

                while ((!cell.isNull()) &&
                        (cell.isEmpty() || (sheet->columnFormat(cell.column())->isHiddenOrFiltered()))) {
                    cell = sheet->cellStorage()->prevInRow(cell.column(), cell.row(), CellStorage::VisitContent);
                }
            }

            if (cell.isNull())
                col = 1;
            else
                col = cell.column();

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

            destination.setX(qBound(1, col, q->maxCol()));
            destination.setY(qBound(1, marker.y(), q->maxRow()));
        }
        break;

//Ctrl+Qt::Key_Right
    case Qt::Key_Right:

        if (sheet->layoutDirection() == Qt::RightToLeft) {
            cell = Cell(sheet, marker.x(), marker.y());
            if ((!cell.isNull()) && (!cell.isEmpty()) && (marker.x() != 1)) {
                lastCell = cell;
                col = marker.x() - 1;
                cell = Cell(sheet, col, cell.row());
                while ((!cell.isNull()) && (col > 0) && (!cell.isEmpty())) {
                    if (!(sheet->columnFormat(cell.column())->isHiddenOrFiltered())) {
                        lastCell = cell;
                        searchThroughEmpty = false;
                    }
                    col--;
                    if (col > 0)
                        cell = Cell(sheet, col, cell.row());
                }
                cell = lastCell;
            }
            if (searchThroughEmpty) {
                cell = sheet->cellStorage()->prevInRow(marker.x(), marker.y(), CellStorage::VisitContent);

                while ((!cell.isNull()) &&
                        (cell.isEmpty() || (sheet->columnFormat(cell.column())->isHiddenOrFiltered()))) {
                    cell = sheet->cellStorage()->prevInRow(cell.column(), cell.row(), CellStorage::VisitContent);
                }
            }

            if (cell.isNull())
                col = 1;
            else
                col = cell.column();

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

            destination.setX(qBound(1, col, q->maxCol()));
            destination.setY(qBound(1, marker.y(), q->maxRow()));
        } else {
            cell = Cell(sheet, marker.x(), marker.y());
            if ((!cell.isNull()) && (!cell.isEmpty()) && (marker.x() != q->maxCol())) {
                lastCell = cell;
                col = marker.x() + 1;
                cell = Cell(sheet, col, cell.row());
                while ((!cell.isNull()) && (col < q->maxCol()) && (!cell.isEmpty())) {
                    if (!(sheet->columnFormat(cell.column())->isHiddenOrFiltered())) {
                        lastCell = cell;
                        searchThroughEmpty = false;
                    }
                    col++;
                    cell = Cell(sheet, col, cell.row());
                }
                cell = lastCell;
            }
            if (searchThroughEmpty) {
                cell = sheet->cellStorage()->nextInRow(marker.x(), marker.y(), CellStorage::VisitContent);

                while ((!cell.isNull()) &&
                        (cell.isEmpty() || (sheet->columnFormat(cell.column())->isHiddenOrFiltered()))) {
                    cell = sheet->cellStorage()->nextInRow(cell.column(), cell.row(), CellStorage::VisitContent);
                }
            }

            if (cell.isNull())
                col = marker.x();
            else
                col = cell.column();

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

            destination.setX(qBound(1, col, q->maxCol()));
            destination.setY(qBound(1, marker.y(), q->maxRow()));
        }
        break;

    }

    if (marker == destination)
        return false;

    if (makingSelection) {
        q->selection()->update(destination);
    } else {
        q->selection()->initialize(destination, sheet);
    }
    q->scrollToCell(destination);
    return true;
}

bool CellToolBase::Private::formatKeyPress(QKeyEvent * _ev)
{
    if (!(_ev->modifiers() & Qt::ControlModifier))
        return false;

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

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

    switch (_ev->key()) {
    case Qt::Key_Exclam:
        command->setText(i18nc("(qtundo-format)", "Number Format"));
        command->setFormatType(Format::Number);
        command->setPrecision(2);
        break;

    case Qt::Key_Dollar:
        command->setText(i18nc("(qtundo-format)", "Currency Format"));
        command->setFormatType(Format::Money);
        command->setPrecision(q->selection()->activeSheet()->map()->calculationSettings()->locale()->fracDigits());
        break;

    case Qt::Key_Percent:
        command->setText(i18nc("(qtundo-format)", "Percentage Format"));
        command->setFormatType(Format::Percentage);
        break;

    case Qt::Key_At:
        command->setText(i18nc("(qtundo-format)", "Time Format"));
        command->setFormatType(Format::SecondeTime);
        break;

    case Qt::Key_NumberSign:
        command->setText(i18nc("(qtundo-format)", "Date Format"));
        command->setFormatType(Format::ShortDate);
        break;

    case Qt::Key_AsciiCircum:
        command->setText(i18nc("(qtundo-format)", "Scientific Format"));
        command->setFormatType(Format::Scientific);
        break;

    case Qt::Key_Ampersand:
        command->setText(i18nc("(qtundo-format)", "Change Border"));
        command->setTopBorderPen(QPen(q->canvas()->resourceManager()->foregroundColor().toQColor(), 1, Qt::SolidLine));
        command->setBottomBorderPen(QPen(q->canvas()->resourceManager()->foregroundColor().toQColor(), 1, Qt::SolidLine));
        command->setLeftBorderPen(QPen(q->canvas()->resourceManager()->foregroundColor().toQColor(), 1, Qt::SolidLine));
        command->setRightBorderPen(QPen(q->canvas()->resourceManager()->foregroundColor().toQColor(), 1, Qt::SolidLine));
        break;

    default:
        delete command;
        return false;
    }

    command->add(*q->selection());
    command->execute();
    _ev->accept(); // QKeyEvent

    return true;
}

QRect CellToolBase::Private::moveDirection(Calligra::Sheets::MoveTo direction, bool extendSelection)
{
    kDebug(36005) << "Canvas::moveDirection";

    register Sheet * const sheet = q->selection()->activeSheet();
    if (!sheet)
        return QRect();

    QPoint destination;
    QPoint cursor = q->selection()->cursor();

    QPoint cellCorner = cursor;
    Cell cell(sheet, 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.masterCell();
        cellCorner = QPoint(cell.column(), cell.row());
    }

    /* how many cells must we move to get to the next cell? */
    int offset = 0;
    const ColumnFormat *cl = 0;
    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 Bottom:
        offset = cell.mergedYCells() - (cursor.y() - cellCorner.y()) + 1;
        while (((cursor.y() + offset) <= q->maxRow()) && sheet->rowFormats()->isHiddenOrFiltered(cursor.y() + offset)) {
            offset++;
        }

        destination = QPoint(cursor.x(), qMin(cursor.y() + offset, q->maxRow()));
        break;
    case Top:
        offset = (cellCorner.y() - cursor.y()) - 1;
        while (((cursor.y() + offset) >= 1) && sheet->rowFormats()->isHiddenOrFiltered(cursor.y() + offset)) {
            offset--;
        }
        destination = QPoint(cursor.x(), qMax(cursor.y() + offset, 1));
        break;
    case Left:
        offset = (cellCorner.x() - cursor.x()) - 1;
        cl = sheet->columnFormat(cursor.x() + offset);
        while (((cursor.x() + offset) >= 1) && cl->isHiddenOrFiltered()) {
            offset--;
            cl = sheet->columnFormat(cursor.x() + offset);
        }
        destination = QPoint(qMax(cursor.x() + offset, 1), cursor.y());
        break;
    case Right:
        offset = cell.mergedXCells() - (cursor.x() - cellCorner.x()) + 1;
        cl = sheet->columnFormat(cursor.x() + offset);
        while (((cursor.x() + offset) <= q->maxCol()) && cl->isHiddenOrFiltered()) {
            offset++;
            cl = sheet->columnFormat(cursor.x() + offset);
        }
        destination = QPoint(qMin(cursor.x() + offset, q->maxCol()), cursor.y());
        break;
    case BottomFirst:
        offset = cell.mergedYCells() - (cursor.y() - cellCorner.y()) + 1;
        while (((cursor.y() + offset) <= q->maxRow()) && sheet->rowFormats()->isHiddenOrFiltered(cursor.y() + offset)) {
            ++offset;
        }

        destination = QPoint(1, qMin(cursor.y() + offset, q->maxRow()));
        break;
    case NoMovement:
        destination = cursor;
        break;
    }

    if (extendSelection) {
        q->selection()->update(destination);
    } else {
        q->selection()->initialize(destination, sheet);
    }
    q->scrollToCell(destination);
    updateEditor(Cell(q->selection()->activeSheet(), q->selection()->cursor()));

    return QRect(cursor, destination);
}

void CellToolBase::Private::paintSelection(QPainter &painter, const QRectF &viewRect)
{
    if (q->selection()->referenceSelection() || q->editor()) {
        return;
    }
    Sheet *const sheet = q->selection()->activeSheet();

    // save the painter state
    painter.save();
    // disable antialiasing
    painter.setRenderHint(QPainter::Antialiasing, false);
    // Extend the clip rect by one in each direction to avoid artefacts caused by rounding errors.
    // TODO Stefan: This unites the region's rects. May be bad. Check!
    painter.setClipRegion(painter.clipRegion().boundingRect().adjusted(-1, -1, 1, 1));

    QLineF line;
    QPen pen(QApplication::palette().text().color(), q->canvas()->viewConverter()->viewToDocumentX(2.0));
    painter.setPen(pen);

    const Calligra::Sheets::Selection* selection = q->selection();
    const QRect currentRange = selection->extendToMergedAreas(QRect(selection->anchor(), selection->marker()));
    Region::ConstIterator end(selection->constEnd());
    for (Region::ConstIterator it(selection->constBegin()); it != end; ++it) {
        const QRect range = (*it)->isAll() ? (*it)->rect() : selection->extendToMergedAreas((*it)->rect());

        // Only the active element (the one with the anchor) will be drawn with a border
        const bool current = (currentRange == range);

        double positions[4];
        bool paintSides[4];
        retrieveMarkerInfo(range, viewRect, positions, paintSides);

        double left =   positions[0];
        double top =    positions[1];
        double right =  positions[2];
        double bottom = positions[3];
        if (sheet->layoutDirection() == Qt::RightToLeft) {
            // The painter's origin is translated by the negative canvas offset.
            // viewRect.left() is the canvas offset. Add it once to the
            // coordinates. Then, the upper left corner of the canvas has to
            // match the correct document position, which is the scrolling
            // offset (viewRect.left()) plus the width of the visible area
            // (viewRect.width()); that's the right border (left+width).
            const qreal offset = /*2 * viewRect.left() +*/ viewRect.width();
            left = offset - positions[2];
            right = offset - positions[0];
        }

        bool paintLeft =   paintSides[0];
        bool paintTop =    paintSides[1];
        bool paintRight =  paintSides[2];
        bool paintBottom = paintSides[3];
        if (sheet->layoutDirection() == Qt::RightToLeft) {
            paintLeft  = paintSides[2];
            paintRight = paintSides[0];
        }

        const double unzoomedPixelX = q->canvas()->viewConverter()->viewToDocumentX(1.0);
        const double unzoomedPixelY = q->canvas()->viewConverter()->viewToDocumentY(1.0);
        // get the transparent selection color
        QColor selectionColor(QApplication::palette().highlight().color());
        selectionColor.setAlpha(127);
        if (current) {
            // save old clip region
            const QRegion clipRegion = painter.clipRegion();
            // clip out the cursor region
            const QRect cursor = QRect(selection->cursor(), selection->cursor());
            const QRect extCursor = selection->extendToMergedAreas(cursor);
            QRectF cursorRect = sheet->cellCoordinatesToDocument(extCursor);
            if (sheet->layoutDirection() == Qt::RightToLeft) {
                // See comment above.
                const qreal offset = /*2 * viewRect.left() +*/ viewRect.width();
                const qreal left = offset - cursorRect.right();
                const qreal right = offset - cursorRect.left();
                cursorRect.setLeft(left);
                cursorRect.setRight(right);
            }
            cursorRect.adjust(unzoomedPixelX, unzoomedPixelY, unzoomedPixelX, unzoomedPixelY);
            painter.setClipRegion(clipRegion.subtracted(cursorRect.toRect()));
            // draw the transparent selection background
            painter.fillRect(QRectF(left, top, right - left, bottom - top), selectionColor);
            // restore clip region
            painter.setClipRegion(clipRegion);
        } else {
            // draw the transparent selection background
            painter.fillRect(QRectF(left, top, right - left, bottom - top), selectionColor);
        }

        if (paintTop) {
            line = QLineF(left, top, right, top);
            painter.drawLine(line);
        }
        if (selection->activeSheet()->layoutDirection() == Qt::RightToLeft) {
            if (paintRight) {
                line = QLineF(right, top, right, bottom);
                painter.drawLine(line);
            }
            if (paintLeft && paintBottom && current) {
                /* then the 'handle' in the bottom left corner is visible. */
                line = QLineF(left, top, left, bottom - 3 * unzoomedPixelY);
                painter.drawLine(line);
                line = QLineF(left + 4 * unzoomedPixelX,  bottom, right + unzoomedPixelY, bottom);
                painter.drawLine(line);
                painter.fillRect(QRectF(left - 2 * unzoomedPixelX, bottom - 2 * unzoomedPixelY,
                                        5 * unzoomedPixelX, 5 * unzoomedPixelY), painter.pen().color());
            } else {
                if (paintLeft) {
                    line = QLineF(left, top, left, bottom);
                    painter.drawLine(line);
                }
                if (paintBottom) {
                    line = QLineF(left, bottom, right, bottom);
                    painter.drawLine(line);
                }
            }
        } else { // activeSheet()->layoutDirection() == Qt::LeftToRight
            if (paintLeft) {
                line = QLineF(left, top, left, bottom);
                painter.drawLine(line);
            }
            if (paintRight && paintBottom && current) {
                /* then the 'handle' in the bottom right corner is visible. */
                line = QLineF(right, top, right, bottom - 3 * unzoomedPixelY);
                painter.drawLine(line);
                line = QLineF(left, bottom, right - 3 * unzoomedPixelX, bottom);
                painter.drawLine(line);
                painter.fillRect(QRectF(right - 2 * unzoomedPixelX, bottom - 2 * unzoomedPixelX,
                                        5 * unzoomedPixelX, 5 * unzoomedPixelY), painter.pen().color());
            } else {
                if (paintRight) {
                    line = QLineF(right, top, right, bottom);
                    painter.drawLine(line);
                }
                if (paintBottom) {
                    line = QLineF(left, bottom, right, bottom);
                    painter.drawLine(line);
                }
            }
        }
    }
    // restore painter state
    painter.restore();
}

void CellToolBase::Private::paintReferenceSelection(QPainter &painter, const QRectF &viewRect)
{
    Q_UNUSED(viewRect);
    if (!q->selection()->referenceSelection()) {
        return;
    }
    // save painter state
    painter.save();

    // Define the reference selection handle.
    const qreal pixelX = q->canvas()->viewConverter()->viewToDocumentX(1);
    const qreal pixelY = q->canvas()->viewConverter()->viewToDocumentY(1);
    const QRectF handleArea(-3 * pixelX, -3 * pixelY, 6 * pixelX, 6 * pixelY);

    // A list of already found regions to color the same region with the same color.
    QSet<QString> alreadyFoundRegions;
    // The colors for the referenced ranges and the color index.
    const QList<QColor> colors = q->selection()->colors();
    int index = 0;

    // Iterate over the referenced ranges.
    const Region::ConstIterator end(q->selection()->constEnd());
    for (Region::ConstIterator it(q->selection()->constBegin()); it != end; ++it) {
        Sheet *const sheet = (*it)->sheet();
        // Only paint ranges or cells on the current sheet
        if (sheet != q->selection()->activeSheet()) {
            index++;
            continue;
        }
        // Only paint a reference once.
        if (alreadyFoundRegions.contains((*it)->name())) {
            continue;
        }
        alreadyFoundRegions.insert((*it)->name());

        const QRect range = q->selection()->extendToMergedAreas((*it)->rect());
        QRectF area = sheet->cellCoordinatesToDocument(range);

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

        // 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)
        area.adjust(pixelX, pixelY, -pixelX, -pixelY);

        // The current color.
        const QColor color = colors[index++ % colors.size()];

        // Paint the reference range's outline.
        if ((*it)->sheet()->layoutDirection() == Qt::RightToLeft) {
            // See comment in paintSelection().
            const qreal offset = /*2 * viewRect.left() +*/ viewRect.width();
            const qreal left = offset - area.right();
            const qreal right = offset - area.left();
            area.setLeft(left);
            area.setRight(right);
        }

        painter.setBrush(QBrush());
        painter.setPen(color);
        painter.drawRect(area);

        // 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)
        painter.setPen(Qt::white);
        painter.setBrush(color);
        const bool rtl = sheet->layoutDirection() == Qt::RightToLeft;
        const QPointF corner(rtl ? area.bottomLeft() : area.bottomRight());
        painter.drawRect(handleArea.translated(corner));
    }

    // restore painter state
    painter.restore();
}

void CellToolBase::Private::retrieveMarkerInfo(const QRect &cellRange, const QRectF &viewRect,
        double positions[], bool paintSides[])
{
    // Everything is in document coordinates here.
    // The layout direction, which is view dependent, is applied afterwards.

    const Sheet* sheet = q->selection()->activeSheet();
    const QRectF visibleRect = sheet->cellCoordinatesToDocument(cellRange);

    /* these vars are used for clarity, the array for simpler function arguments  */
    qreal left = visibleRect.left();
    qreal top = visibleRect.top();
    qreal right = visibleRect.right();
    qreal 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());
    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] = qMax(left,   viewRect.left());
    positions[1] = qMax(top,    viewRect.top());
    positions[2] = qMin(right,  viewRect.right());
    positions[3] = qMin(bottom, viewRect.bottom());
}

QList<QAction*> CellToolBase::Private::popupActionList() const
{
    QList<QAction*> actions;
    const Cell cell = Cell(q->selection()->activeSheet(), q->selection()->marker());
    const bool isProtected = !q->selection()->activeSheet()->map()->isReadWrite() ||
                             (q->selection()->activeSheet()->isProtected() &&
                              !(cell.style().notProtected() && q->selection()->isSingular()));
    if (!isProtected) {
        actions.append(q->action("cellStyle"));
        actions.append(popupMenuActions["separator1"]);
        actions.append(q->action("cut"));
    }
    actions.append(q->action("copy"));
    if (!isProtected) {
        actions.append(q->action("paste"));
        actions.append(q->action("specialPaste"));
        actions.append(q->action("pasteWithInsertion"));
        actions.append(popupMenuActions["separator2"]);
        actions.append(q->action("clearAll"));
        actions.append(q->action("adjust"));
        actions.append(q->action("setDefaultStyle"));
        actions.append(q->action("setAreaName"));

        if (!q->selection()->isColumnOrRowSelected()) {
            actions.append(popupMenuActions["separator3"]);
            actions.append(popupMenuActions["insertCell"]);
            actions.append(popupMenuActions["deleteCell"]);
        } else if (q->selection()->isColumnSelected()) {
            actions.append(q->action("resizeCol"));
            actions.append(popupMenuActions["adjustColumn"]);
            actions.append(popupMenuActions["separator4"]);
            actions.append(popupMenuActions["insertColumn"]);
            actions.append(popupMenuActions["deleteColumn"]);
            actions.append(q->action("hideColumn"));

            q->action("showSelColumns")->setEnabled(false);
            const ColumnFormat* columnFormat;
            Region::ConstIterator endOfList = q->selection()->constEnd();
            for (Region::ConstIterator it = q->selection()->constBegin(); it != endOfList; ++it) {
                QRect range = (*it)->rect();
                int col;
                for (col = range.left(); col < range.right(); ++col) {
                    columnFormat = q->selection()->activeSheet()->columnFormat(col);
                    if (columnFormat->isHidden()) {
                        q->action("showSelColumns")->setEnabled(true);
                        actions.append(q->action("showSelColumns"));
                        break;
                    }
                }
                if (range.left() > 1 && col == range.right()) {
                    bool allHidden = true;
                    for (col = 1; col < range.left(); ++col) {
                        columnFormat = q->selection()->activeSheet()->columnFormat(col);
                        allHidden &= columnFormat->isHidden();
                    }
                    if (allHidden) {
                        q->action("showSelColumns")->setEnabled(true);
                        actions.append(q->action("showSelColumns"));
                        break;
                    }
                } else {
                    break;
                }
            }
        } else if (q->selection()->isRowSelected()) {
            actions.append(q->action("resizeRow"));
            actions.append(popupMenuActions["adjustRow"]);
            actions.append(popupMenuActions["separator5"]);
            actions.append(popupMenuActions["insertRow"]);
            actions.append(popupMenuActions["deleteRow"]);
            actions.append(q->action("hideRow"));

            q->action("showSelRows")->setEnabled(false);
            Region::ConstIterator endOfList = q->selection()->constEnd();
            for (Region::ConstIterator it = q->selection()->constBegin(); it != endOfList; ++it) {
                QRect range = (*it)->rect();
                int row;
                for (row = range.top(); row < range.bottom(); ++row) {
                    if (q->selection()->activeSheet()->rowFormats()->isHidden(row)) {
                        q->action("showSelRows")->setEnabled(true);
                        actions.append(q->action("showSelRows"));
                        break;
                    }
                }
                if (range.top() > 1 && row == range.bottom()) {
                    bool allHidden = true;
                    for (row = 1; row < range.top(); ++row) {
                        allHidden &= q->selection()->activeSheet()->rowFormats()->isHidden(row);
                    }
                    if (allHidden) {
                        q->action("showSelRows")->setEnabled(true);
                        actions.append(q->action("showSelRows"));
                        break;
                    }
                } else {
                    break;
                }
            }
        }
        actions.append(popupMenuActions["separator6"]);
        actions.append(q->action("comment"));
        if (!cell.comment().isEmpty()) {
            actions.append(q->action("clearComment"));
        }

        if (testListChoose(q->selection())) {
            actions.append(popupMenuActions["separator7"]);
            actions.append(popupMenuActions["listChoose"]);
        }
    }
    return actions;
}

void CellToolBase::Private::createPopupMenuActions()
{
    QAction* action = 0;

    for (int i = 1; i <= 7; ++i) {
        action = new QAction(q);
        action->setSeparator(true);
        popupMenuActions.insert(QString("separator%1").arg(i), action);
    }

    action = new KAction(KIcon("insertcell"), i18n("Insert Cells..."), q);
    connect(action, SIGNAL(triggered(bool)), q, SLOT(insertCells()));
    popupMenuActions.insert("insertCell", action);

    action = new KAction(KIcon("removecell"), i18n("Delete Cells..."), q);
    connect(action, SIGNAL(triggered(bool)), q, SLOT(deleteCells()));
    popupMenuActions.insert("deleteCell", action);

    action = new KAction(KIcon("adjustcol"), i18n("Adjust Column"), q);
    connect(action, SIGNAL(triggered(bool)), q, SLOT(adjustColumn()));
    popupMenuActions.insert("adjustColumn", action);

    action = new KAction(KIcon("insert_table_col"), i18n("Insert Columns"), q);
    connect(action, SIGNAL(triggered(bool)), q, SLOT(insertColumn()));
    popupMenuActions.insert("insertColumn", action);

    action = new KAction(KIcon("delete_table_col"), i18n("Delete Columns"), q);
    connect(action, SIGNAL(triggered(bool)), q, SLOT(deleteColumn()));
    popupMenuActions.insert("deleteColumn", action);

    action = new KAction(KIcon("adjustrow"), i18n("Adjust Row"), q);
    connect(action, SIGNAL(triggered(bool)), q, SLOT(adjustRow()));
    popupMenuActions.insert("adjustRow", action);

    action = new KAction(KIcon("insert_table_row"), i18n("Insert Rows"), q);
    connect(action, SIGNAL(triggered(bool)), q, SLOT(insertRow()));
    popupMenuActions.insert("insertRow", action);

    action = new KAction(KIcon("delete_table_row"), i18n("Delete Rows"), q);
    connect(action, SIGNAL(triggered(bool)), q, SLOT(deleteRow()));
    popupMenuActions.insert("deleteRow", action);

    action = new KAction(i18n("Selection List..."), q);
    connect(action, SIGNAL(triggered(bool)), q, SLOT(listChoosePopupMenu()));
    popupMenuActions.insert("listChoose", action);
}

bool CellToolBase::Private::testListChoose(Selection *selection) const
{
    const Sheet *const sheet = selection->activeSheet();
    const Cell cursorCell(sheet, selection->cursor());
    const CellStorage *const storage = sheet->cellStorage();

    const Region::ConstIterator end(selection->constEnd());
    for (Region::ConstIterator it(selection->constBegin()); it != end; ++it) {
        const QRect range = (*it)->rect();
        if (cursorCell.column() < range.left() || cursorCell.column() > range.right()) {
            continue; // next range
        }
        Cell cell;
        if (range.top() == 1) {
            cell = storage->firstInColumn(cursorCell.column(), CellStorage::Values);
        } else {
            cell = storage->nextInColumn(cursorCell.column(), range.top() - 1, CellStorage::Values);
        }
        while (!cell.isNull() && cell.row() <= range.bottom()) {
            if (cell.isDefault() || cell.isPartOfMerged()
                    || cell.isFormula() || cell.isTime() || cell.isDate()
                    || cell.value().isNumber() || cell.value().asString().isEmpty()
                    || (cell == cursorCell)) {
                cell = storage->nextInColumn(cell.column(), cell.row(), CellStorage::Values);
                continue;
            }
            if (cell.userInput() != cursorCell.userInput()) {
                return true;
            }
            cell = storage->nextInColumn(cell.column(), cell.row(), CellStorage::Values);
        }
    }
    return false;
}