summaryrefslogtreecommitdiff
path: root/sc/source/ui/dbgui/fieldwnd.cxx
blob: 37010813e65843b251d8b1f83eed08688f94cd16 (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 ************************************************************************/

#include <config_lgpl.h>

#include "fieldwnd.hxx"

#include <comphelper/string.hxx>
#include <vcl/decoview.hxx>
#include <vcl/help.hxx>
#include <vcl/svapp.hxx>
#include <vcl/virdev.hxx>
#include <vcl/mnemonic.hxx>

#include "pvlaydlg.hxx"
#include "dpuiglobal.hxx"
#include "dpmacros.hxx"
#include "AccessibleDataPilotControl.hxx"
#include "scresid.hxx"
#include "pivot.hrc"

using namespace com::sun::star;
using ::std::vector;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::WeakReference;
using ::com::sun::star::accessibility::XAccessible;

const size_t PIVOTFIELD_INVALID = static_cast< size_t >(-1);
const size_t INVALID_INDEX = static_cast<size_t>(-1);

#if DEBUG_PIVOT_TABLE
using std::cout;
using std::endl;
#endif

namespace {

#if DEBUG_PIVOT_TABLE
void DumpAllFuncData(const ScDPFieldControlBase::FuncDataType& rData)
{
    cout << "---" << endl;
    ScDPFieldControlBase::FuncDataType::const_iterator it = rData.begin(), itEnd = rData.end();
    for (; it != itEnd; ++it)
        it->Dump();
}
#endif

}

ScDPFieldControlBase::FieldName::FieldName(const OUString& rText, bool bFits, sal_uInt8 nDupCount) :
    maText(rText), mbFits(bFits), mnDupCount(nDupCount) {}

ScDPFieldControlBase::FieldName::FieldName(const FieldName& r) :
    maText(r.maText), mbFits(r.mbFits), mnDupCount(r.mnDupCount) {}

OUString ScDPFieldControlBase::FieldName::getDisplayedText() const
{
    OUStringBuffer aBuf(maText);
    if (mnDupCount > 0)
        aBuf.append(static_cast<sal_Int32>(mnDupCount+1));
    return aBuf.makeStringAndClear();
}

ScDPFieldControlBase::ScrollBar::ScrollBar(Window* pParent, WinBits nStyle) :
    ::ScrollBar(pParent, nStyle),
    mpParent(pParent)
{
}

void ScDPFieldControlBase::ScrollBar::Command( const CommandEvent& rCEvt )
{
    mpParent->Command(rCEvt);
}

ScDPFieldControlBase::AccessRef::AccessRef( const com::sun::star::uno::WeakReference< ::com::sun::star::accessibility::XAccessible > & rAccessible ) : mxRef( rAccessible ) {}

// easy, safe access to the backing accessible for the lifetime of AccessRef
ScAccessibleDataPilotControl *ScDPFieldControlBase::AccessRef::operator -> () const
{
    if (!mxRef.is())
        return NULL;
    return static_cast< ScAccessibleDataPilotControl * >( mxRef.get() );
}

ScDPFieldControlBase::ScDPFieldControlBase(
    ScPivotLayoutDlg* pParent, const ResId& rResId, FixedText* pCaption, const char* pcHelpId) :
    Control(pParent, rResId),
    mpDlg(pParent),
    mpCaption(pCaption),
    mnFieldSelected(0)
{
    SetHelpId( pcHelpId );

    if (pCaption)
        maName = MnemonicGenerator::EraseAllMnemonicChars( pCaption->GetText() );
}

ScDPFieldControlBase::~ScDPFieldControlBase()
{
    AccessRef aRef( mxAccessible );
    if( aRef.is() )
        aRef->dispose();
}

OUString ScDPFieldControlBase::GetName() const
{
    return maName;
}

void ScDPFieldControlBase::SetName(const OUString& rName)
{
    maName = rName;
}

bool ScDPFieldControlBase::IsExistingIndex( size_t nIndex ) const
{
    return nIndex < maFieldNames.size();
}

void ScDPFieldControlBase::AppendField( const OUString& rText, const ScPivotFuncData& rFunc )
{
    size_t nNewIndex = maFieldNames.size();

    sal_uInt8 nDupCount = GetNextDupCount(rText);
    maFieldNames.push_back(FieldName(rText, true, nDupCount));
    maFuncData.push_back(new ScPivotFuncData(rFunc));

    AccessRef xRef(mxAccessible);
    if ( xRef.is() )
        xRef->AddField(nNewIndex);
}

size_t ScDPFieldControlBase::AddField(
    const OUString& rText, const Point& rPos, const ScPivotFuncData& rFunc)
{
    size_t nNewIndex = GetFieldIndex(rPos);
    if (nNewIndex == PIVOTFIELD_INVALID)
        return PIVOTFIELD_INVALID;

    if (nNewIndex > maFieldNames.size())
        nNewIndex = maFieldNames.size();

    sal_uInt8 nDupCount = GetNextDupCount(rText);
    maFieldNames.insert(maFieldNames.begin() + nNewIndex, FieldName(rText, true, nDupCount));

    maFuncData.insert(maFuncData.begin() + nNewIndex, new ScPivotFuncData(rFunc));
    maFuncData.back().mnDupCount = nDupCount;

    mnFieldSelected = nNewIndex;
    ResetScrollBar();
    Invalidate();

    AccessRef xRef( mxAccessible );
    if ( xRef.is() )
        xRef->AddField(nNewIndex);

    return nNewIndex;
}

bool ScDPFieldControlBase::MoveField(size_t nCurPos, const Point& rPos, size_t& rnIndex)
{
    if (nCurPos >= maFieldNames.size())
        // out-of-bound
        return false;

    size_t nNewIndex = GetFieldIndex(rPos);
    if (nNewIndex == PIVOTFIELD_INVALID)
        return false;

    if (nNewIndex == nCurPos)
        // Nothing to do.
        return true;

    FieldName aName = maFieldNames[nCurPos];
    ScPivotFuncData aFunc = maFuncData[nCurPos];
    if (nNewIndex >= maFieldNames.size())
    {
        // Move to the back.
        maFieldNames.erase(maFieldNames.begin()+nCurPos);
        maFieldNames.push_back(aName);
        maFuncData.erase(maFuncData.begin()+nCurPos);
        maFuncData.push_back(new ScPivotFuncData(aFunc));
        rnIndex = maFieldNames.size()-1;
    }
    else
    {
        maFieldNames.erase(maFieldNames.begin()+nCurPos);
        maFuncData.erase(maFuncData.begin()+nCurPos);
        size_t nTmp = nNewIndex; // we need to keep the original index for accessible.
        if (nNewIndex > nCurPos)
            --nTmp;

        maFieldNames.insert(maFieldNames.begin()+nTmp, aName);
        maFuncData.insert(maFuncData.begin()+nTmp, new ScPivotFuncData(aFunc));
        rnIndex = nTmp;
    }

    ResetScrollBar();
    Invalidate();

    AccessRef xRef( mxAccessible );
    if ( xRef.is() )
        xRef->MoveField(nCurPos, nNewIndex);

    return true;
}

void ScDPFieldControlBase::DeleteFieldByIndex( size_t nIndex )
{
    if (!IsExistingIndex(nIndex))
        // Nothing to delete.
        return;

    AccessRef xRef(mxAccessible);
    if (xRef.is())
        xRef->RemoveField(nIndex);


    maFieldNames.erase(maFieldNames.begin() + nIndex);
    if (mnFieldSelected >= maFieldNames.size())
        mnFieldSelected = maFieldNames.size() - 1;

    maFuncData.erase(maFuncData.begin() + nIndex);

    ResetScrollBar();
    Invalidate();
}

size_t ScDPFieldControlBase::GetFieldCount() const
{
    return maFieldNames.size();
}

bool ScDPFieldControlBase::IsEmpty() const
{
    return maFieldNames.empty();
}

void ScDPFieldControlBase::ClearFields()
{
    AccessRef xRef( mxAccessible );
    if ( xRef.is() )
        for( size_t nIdx = maFieldNames.size(); nIdx > 0; --nIdx )
            xRef->RemoveField( nIdx - 1 );

    maFieldNames.clear();
    maFuncData.clear();
}

void ScDPFieldControlBase::SetFieldText(const OUString& rText, size_t nIndex, sal_uInt8 nDupCount)
{
    if( IsExistingIndex( nIndex ) )
    {
        maFieldNames[nIndex] = FieldName(rText, true, nDupCount);
        Invalidate();

        AccessRef xRef( mxAccessible );
        if ( xRef.is() )
            xRef->FieldNameChange(nIndex);
    }
}

OUString ScDPFieldControlBase::GetFieldText( size_t nIndex ) const
{
    if( IsExistingIndex( nIndex ) )
        return maFieldNames[nIndex].maText;
    return OUString();
}

void ScDPFieldControlBase::GetExistingIndex( const Point& rPos, size_t& rnIndex )
{
    if (maFieldNames.empty() || GetFieldType() == PIVOTFIELDTYPE_SELECT)
    {
        rnIndex = 0;
        return;
    }

    rnIndex = GetFieldIndex(rPos);
    if (rnIndex == PIVOTFIELD_INVALID)
        rnIndex = 0;
}

size_t ScDPFieldControlBase::GetSelectedField() const
{
    return mnFieldSelected;
}

vector<ScDPFieldControlBase::FieldName>& ScDPFieldControlBase::GetFieldNames()
{
    return maFieldNames;
}

const vector<ScDPFieldControlBase::FieldName>& ScDPFieldControlBase::GetFieldNames() const
{
    return maFieldNames;
}

void ScDPFieldControlBase::Paint( const Rectangle& /* rRect */ )
{
    // hiding the caption is now done from StateChanged
    Redraw();
}

void ScDPFieldControlBase::StateChanged( StateChangedType nStateChange )
{
    Control::StateChanged( nStateChange );

    if( nStateChange == STATE_CHANGE_INITSHOW )
    {
        /*  After the fixed text associated to this control has received its
            unique mnemonic from VCL dialog initialization code, put this text
            into the field windows.
            #124828# Hiding the FixedTexts and clearing the tab stop style bits
            has to be done after assigning the mnemonics, but Paint() is too
            late, because the test tool may send key events to the dialog when
            it isn't visible. Mnemonics are assigned in Dialog::StateChanged()
            for STATE_CHANGE_INITSHOW, so this can be done immediately
            afterwards. */

        if ( mpCaption )
        {
            SetText( mpCaption->GetText() );
            mpCaption->Hide();
        }
    }
}

void ScDPFieldControlBase::DataChanged( const DataChangedEvent& rDCEvt )
{
    Control::DataChanged( rDCEvt );
    if( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )
        Invalidate();
}

void ScDPFieldControlBase::Command( const CommandEvent& rCEvt )
{
    if (rCEvt.GetCommand() == COMMAND_WHEEL)
    {
        const CommandWheelData* pData = rCEvt.GetWheelData();
        if (pData->GetMode() == COMMAND_WHEEL_SCROLL && !pData->IsHorz())
        {
            // Handle vertical mouse wheel scrolls.
            long nNotch = pData->GetNotchDelta(); // positive => up; negative => down
            HandleWheelScroll(nNotch);
        }
    }
}

void ScDPFieldControlBase::MouseButtonDown( const MouseEvent& rMEvt )
{
    if( rMEvt.IsLeft() )
    {
        size_t nNewSelectIndex = GetFieldIndex( rMEvt.GetPosPixel() );
        if (nNewSelectIndex != PIVOTFIELD_INVALID && IsExistingIndex(nNewSelectIndex))
        {
            // grabbing after GetFieldIndex() will prevent to focus empty window
            GrabFocusAndSelect( nNewSelectIndex );

            if( rMEvt.GetClicks() == 1 )
            {
                PointerStyle ePtr = mpDlg->NotifyMouseButtonDown( GetFieldType(), nNewSelectIndex );
                CaptureMouse();
                SetPointer( Pointer( ePtr ) );
            }
            else
                mpDlg->NotifyDoubleClick( GetFieldType(), nNewSelectIndex );
        }
    }
}

void ScDPFieldControlBase::MouseButtonUp( const MouseEvent& rMEvt )
{
    if( rMEvt.IsLeft() )
    {
        if( rMEvt.GetClicks() == 1 )
        {
            Point aScrPos = OutputToScreenPixel(rMEvt.GetPosPixel());
            ScPivotFieldType eToType = mpDlg->GetFieldTypeAtPoint(aScrPos);

            mpDlg->DropFieldItem(aScrPos, eToType);
            SetPointer( Pointer( POINTER_ARROW ) );
        }

        if( IsMouseCaptured() )
            ReleaseMouse();
    }
}

void ScDPFieldControlBase::MouseMove( const MouseEvent& rMEvt )
{
    if( IsMouseCaptured() )
    {
        Point aScrPos = OutputToScreenPixel(rMEvt.GetPosPixel());
        ScPivotFieldType eFieldType = mpDlg->GetFieldTypeAtPoint(aScrPos);
        PointerStyle ePtr = mpDlg->GetPointerStyleAtPoint(aScrPos, eFieldType);
        SetPointer( Pointer( ePtr ) );
    }
    const FieldNames& rFields = GetFieldNames();
    size_t nIndex = GetFieldIndex(rMEvt.GetPosPixel());
    // does the string not fit on the screen ? show a helpful helptext instead
    if (nIndex != PIVOTFIELD_INVALID && (nIndex < rFields.size()) && !rFields[nIndex].mbFits)
    {
        Point aPos = OutputToScreenPixel( rMEvt.GetPosPixel() );
        Rectangle   aRect( aPos, GetSizePixel() );
        String aHelpText = GetFieldText(nIndex);
        Help::ShowQuickHelp( this, aRect, aHelpText );
    }
}

void ScDPFieldControlBase::KeyInput( const KeyEvent& rKEvt )
{
    const KeyCode& rKeyCode = rKEvt.GetKeyCode();
    sal_uInt16 nCode = rKeyCode.GetCode();


    const FieldNames& rFields = GetFieldNames();
    bool bFieldMove = ( rKeyCode.IsMod1() && (GetFieldType() != PIVOTFIELDTYPE_SELECT) );
    bool bKeyEvaluated = true;
    void (ScDPFieldControlBase::*pMoveXY) (SCsCOL nDX, SCsROW nDY);
    if (bFieldMove)
        pMoveXY = &ScDPFieldControlBase::MoveFieldRel;
    else
        pMoveXY = &ScDPFieldControlBase::MoveSelection;
    switch( nCode )
    {
    case KEY_UP:    (this->*pMoveXY)(  0, -1 ); break;
    case KEY_DOWN:  (this->*pMoveXY)(  0,  1 ); break;
    case KEY_LEFT:  (this->*pMoveXY)( -1,  0 ); break;
    case KEY_RIGHT: (this->*pMoveXY)(  1,  0 ); break;
    case KEY_HOME:
        if (bFieldMove)
            MoveField( 0 );
        else
        {
            if( !rFields.empty() )
                MoveSelection( 0 );
        }
        break;
    case KEY_END:
        if (bFieldMove)
            MoveField( rFields.size() - 1 );
        else
        {
            if( !rFields.empty() )
                MoveSelection( rFields.size() - 1 );
        }
        break;
    default:
        if ( !bFieldMove && nCode == KEY_DELETE )
            mpDlg->NotifyRemoveField( GetFieldType(), mnFieldSelected );
        else
            bKeyEvaluated = false;
        break;
    }

    if (bKeyEvaluated)
    {
        ScrollToShowSelection();
        Invalidate();
    }
    else
        Control::KeyInput( rKEvt );
}

void ScDPFieldControlBase::GetFocus()
{
    Control::GetFocus();
    Invalidate();
    if( GetGetFocusFlags() & GETFOCUS_MNEMONIC )
    {
        size_t nOldCount = GetFieldCount();
        mpDlg->NotifyMoveFieldToEnd( GetFieldType() );
        if (GetFieldCount() > nOldCount)
            // Scroll to the end only when a new field is inserted.
            ScrollToEnd();
    }
    else // notify change focus
        mpDlg->NotifyFieldFocus( GetFieldType(), true );

    AccessRef xRef( mxAccessible );
    if( xRef.is() )
        xRef->GotFocus();
}

void ScDPFieldControlBase::LoseFocus()
{
    Control::LoseFocus();
    Invalidate();
    mpDlg->NotifyFieldFocus( GetFieldType(), false );

    AccessRef xRef( mxAccessible );
    if( xRef.is() )
        xRef->LostFocus();
}

Reference<XAccessible> ScDPFieldControlBase::CreateAccessible()
{
    com::sun::star::uno::Reference < ::com::sun::star::accessibility::XAccessible > xReturn(new ScAccessibleDataPilotControl(GetAccessibleParentWindow()->GetAccessible(), this));

    mxAccessible = xReturn;
    AccessRef xRef( mxAccessible );
    xRef->Init();

    return xReturn;
}

void ScDPFieldControlBase::FieldFocusChanged(size_t nOldSelected, size_t nFieldSelected)
{
    AccessRef xRef( mxAccessible );
    if ( xRef.is() )
        xRef->FieldFocusChange(nOldSelected, nFieldSelected);
}

void ScDPFieldControlBase::UpdateStyle()
{
    WinBits nMask = ~(WB_TABSTOP | WB_NOTABSTOP);
    SetStyle( (GetStyle() & nMask) | (IsEmpty() ? WB_NOTABSTOP : WB_TABSTOP) );
}

void ScDPFieldControlBase::DrawBackground( OutputDevice& rDev )
{
    const StyleSettings& rStyleSet = GetSettings().GetStyleSettings();
    Color aFaceColor = rStyleSet.GetFaceColor();
    Color aWinColor = rStyleSet.GetWindowColor();
    Color aWinTextColor = rStyleSet.GetWindowTextColor();

    Point aPos0;
    Size aSize( GetSizePixel() );

    if (mpCaption)
    {
        rDev.SetLineColor( aWinTextColor );
        rDev.SetFillColor( aWinColor );
    }
    else
    {
        rDev.SetLineColor( aFaceColor );
        rDev.SetFillColor( aFaceColor );
    }
    rDev.DrawRect( Rectangle( aPos0, aSize ) );

    rDev.SetTextColor( aWinTextColor );

    /*  Draw the caption text. This needs some special handling, because we
        support hard line breaks here. This part will draw each line of the
        text for itself. */

    xub_StrLen nTokenCnt = comphelper::string::getTokenCount(GetText(), '\n');
    long nY = (aSize.Height() - nTokenCnt * rDev.GetTextHeight()) / 2;
    sal_Int32 nStringIx = 0;
    for( xub_StrLen nToken = 0; nToken < nTokenCnt; ++nToken )
    {
        String aLine( GetText().getToken( 0, '\n', nStringIx ) );
        Point aLinePos( (aSize.Width() - rDev.GetCtrlTextWidth( aLine )) / 2, nY );
        rDev.DrawCtrlText( aLinePos, aLine );
        nY += rDev.GetTextHeight();
    }
}

void ScDPFieldControlBase::DrawField(
        OutputDevice& rDev, const Rectangle& rRect, FieldName& rText, bool bFocus )
{
    const StyleSettings& rStyleSet = GetSettings().GetStyleSettings();
    Color aTextColor = rStyleSet.GetButtonTextColor();

    VirtualDevice aVirDev( rDev );
    // #i97623# VirtualDevice is always LTR while other windows derive direction from parent
    aVirDev.EnableRTL( IsRTLEnabled() );

    OUString aText = rText.getDisplayedText();

    Size aDevSize( rRect.GetSize() );
    long    nWidth       = aDevSize.Width();
    long    nHeight      = aDevSize.Height();
    long    nLabelWidth  = rDev.GetTextWidth( aText );
    long    nLabelHeight = rDev.GetTextHeight();

    // #i31600# if text is too long, cut and add ellipsis
    rText.mbFits = nLabelWidth + 6 <= nWidth;
    if (!rText.mbFits)
    {
        sal_Int32 nMinLen = 0;
        sal_Int32 nMaxLen = aText.getLength();
        bool bFits = false;
        do
        {
            sal_Int32 nCurrLen = (nMinLen + nMaxLen) / 2;
            OUStringBuffer aBuf(rText.maText.copy(0, nCurrLen));
            aBuf.appendAscii("...");
            aText = aBuf.makeStringAndClear();
            nLabelWidth = rDev.GetTextWidth( aText );
            bFits = nLabelWidth + 6 <= nWidth;
            (bFits ? nMinLen : nMaxLen) = nCurrLen;
        }
        while( !bFits || (nMinLen + 1 < nMaxLen) );
    }
    Point aLabelPos( (nWidth - nLabelWidth) / 2, ::std::max< long >( (nHeight - nLabelHeight) / 2, 3 ) );

    aVirDev.SetOutputSizePixel( aDevSize );
    aVirDev.SetFont( rDev.GetFont() );
    DecorationView aDecoView( &aVirDev );
    aDecoView.DrawButton( Rectangle( Point( 0, 0 ), aDevSize ), bFocus ? BUTTON_DRAW_DEFAULT : 0 );
    aVirDev.SetTextColor( aTextColor );
    aVirDev.DrawText( aLabelPos, aText );
    rDev.DrawBitmap( rRect.TopLeft(), aVirDev.GetBitmap( Point( 0, 0 ), aDevSize ) );
}

void ScDPFieldControlBase::AppendPaintable(Window* p)
{
    maPaintables.push_back(p);
}

void ScDPFieldControlBase::DrawPaintables()
{
    Rectangle aRect(GetPosPixel(), GetSizePixel());
    Paintables::iterator itr = maPaintables.begin(), itrEnd = maPaintables.end();
    for (; itr != itrEnd; ++itr)
    {
        Window* p = *itr;
        if (!p->IsVisible())
            continue;

        p->Paint(aRect);
    }
}

void ScDPFieldControlBase::DrawInvertSelection()
{
    if (!HasFocus())
        return;

    if (mnFieldSelected >= maFieldNames.size())
        return;

    size_t nPos = GetDisplayPosition(mnFieldSelected);
    if (nPos == INVALID_INDEX)
        return;

    Size aFldSize = GetFieldSize();
    long nFldWidth = aFldSize.Width();
    long nSelWidth = std::min<long>(
        GetTextWidth(maFieldNames[mnFieldSelected].getDisplayedText()) + 4, nFldWidth - 6);

    Point aPos = GetFieldPosition(nPos);
    aPos += Point((nFldWidth - nSelWidth) / 2, 3);
    Size aSize(nSelWidth, aFldSize.Height() - 6);

    Rectangle aSel(aPos, aSize);
    InvertTracking(aSel, SHOWTRACK_SMALL | SHOWTRACK_WINDOW);
}

Size ScDPFieldControlBase::GetStdFieldBtnSize() const
{
    return mpDlg->GetStdFieldBtnSize();
}

void ScDPFieldControlBase::MoveField( size_t nDestIndex )
{
    if (nDestIndex != mnFieldSelected)
    {
        std::swap(maFieldNames[nDestIndex], maFieldNames[mnFieldSelected]);
        std::swap(maFuncData[nDestIndex], maFuncData[mnFieldSelected]);
        mnFieldSelected = nDestIndex;
    }
}

void ScDPFieldControlBase::MoveFieldRel( SCsCOL nDX, SCsROW nDY )
{
    MoveField( CalcNewFieldIndex( nDX, nDY ) );
}

void ScDPFieldControlBase::MoveSelection(size_t nIndex)
{
    FieldNames& rFields = GetFieldNames();
    if (rFields.empty())
        return;

    if (nIndex >= rFields.size())
        // Prevent it from going out-of-bound.
        nIndex = rFields.size() - 1;

    if( mnFieldSelected != nIndex )
    {
        size_t nOldSelected = mnFieldSelected;
        mnFieldSelected = nIndex;
        Invalidate();

        if (HasFocus())
            FieldFocusChanged(nOldSelected, mnFieldSelected);
    }

    ScrollToShowSelection();
}

void ScDPFieldControlBase::MoveSelection(SCsCOL nDX, SCsROW nDY)
{
    size_t nNewIndex = CalcNewFieldIndex( nDX, nDY );
    MoveSelection( nNewIndex );
}

sal_uInt8 ScDPFieldControlBase::GetNextDupCount(const OUString& rFieldText) const
{
    sal_uInt8 nMax = 0;
    FieldNames::const_iterator it = maFieldNames.begin(), itEnd = maFieldNames.end();
    for (; it != itEnd; ++it)
    {
        if (it->maText != rFieldText)
            continue;

        sal_uInt8 nNextUp = it->mnDupCount + 1;
        if (nMax < nNextUp)
            nMax = nNextUp;
    }
    return nMax;
}

sal_uInt8 ScDPFieldControlBase::GetNextDupCount(const ScPivotFuncData& rData, size_t nSelfIndex) const
{
    sal_uInt8 nDupCount = 0;
    bool bFound = false;
    for (size_t i = 0, n = maFuncData.size(); i < n; ++i)
    {
        if (i == nSelfIndex)
            // Skip itself.
            continue;

        const ScPivotFuncData& r = maFuncData[i];

        if (r.mnCol != rData.mnCol || r.mnFuncMask != rData.mnFuncMask)
            continue;

        bFound = true;
        if (r.mnDupCount > nDupCount)
            nDupCount = r.mnDupCount;
    }

    return bFound ? nDupCount + 1 : 0;
}

void ScDPFieldControlBase::SelectNext()
{
    MoveSelection(mnFieldSelected + 1);
}

void ScDPFieldControlBase::GrabFocusAndSelect( size_t nIndex )
{
    MoveSelection( nIndex );
    if( !HasFocus() )
        GrabFocus();
}

const ScPivotFuncData& ScDPFieldControlBase::GetFuncData(size_t nIndex) const
{
    return maFuncData.at(nIndex);
}

ScPivotFuncData& ScDPFieldControlBase::GetFuncData(size_t nIndex)
{
    return maFuncData.at(nIndex);
}

namespace {

class PushFuncItem : std::unary_function<ScPivotFuncData, void>
{
    std::vector<ScDPFieldControlBase::FuncItem>& mrItems;
public:
    PushFuncItem(std::vector<ScDPFieldControlBase::FuncItem>& rItems) : mrItems(rItems) {}

    void operator() (const ScPivotFuncData& r)
    {
        ScDPFieldControlBase::FuncItem aItem;
        aItem.mnCol = r.mnCol;
        aItem.mnFuncMask = r.mnFuncMask;
        mrItems.push_back(aItem);
    }
};

}

void ScDPFieldControlBase::GetAllFuncItems(std::vector<FuncItem>& rItems) const
{
    std::for_each(maFuncData.begin(), maFuncData.end(), PushFuncItem(rItems));
}

namespace {

class PivotFieldInserter : public ::std::unary_function<ScPivotFuncData, void>
{
    vector<ScPivotField>& mrFields;
public:
    explicit PivotFieldInserter(vector<ScPivotField>& r, size_t nSize) : mrFields(r)
    {
        mrFields.reserve(nSize);
    }

    PivotFieldInserter(const PivotFieldInserter& r) : mrFields(r.mrFields) {}

    void operator() (const ScPivotFuncData& r)
    {
        ScPivotField aField;
        aField.nCol = r.mnCol;
        aField.mnOriginalDim = r.mnOriginalDim;
        aField.mnDupCount = r.mnDupCount;
        aField.nFuncMask = r.mnFuncMask;
        aField.maFieldRef = r.maFieldRef;
        mrFields.push_back(aField);
    }
};

}

void ScDPFieldControlBase::ConvertToPivotArray(std::vector<ScPivotField>& rArray) const
{
    for_each(maFuncData.begin(), maFuncData.end(), PivotFieldInserter(rArray, maFuncData.size()));
}

namespace {

class EqualByDimOnly : std::unary_function<ScPivotFuncData, bool>
{
    const ScPivotFuncData& mrData;
    long mnDim;

public:
    EqualByDimOnly(const ScPivotFuncData& rData) : mrData(rData)
    {
        mnDim = rData.mnCol;
        if (rData.mnOriginalDim >= 0)
            mnDim = rData.mnOriginalDim;
    }
    bool operator() (const ScPivotFuncData& rData) const
    {
        long nDim = rData.mnCol;
        if (rData.mnOriginalDim >= 0)
            nDim = rData.mnOriginalDim;

        return nDim == mnDim;
    }
};

}

size_t ScDPFieldControlBase::GetFieldIndexByData( const ScPivotFuncData& rData ) const
{
    FuncDataType::const_iterator it = std::find_if(maFuncData.begin(), maFuncData.end(), EqualByDimOnly(rData));
    return it == maFuncData.end() ? PIVOTFIELD_INVALID : std::distance(maFuncData.begin(), it);
}

//=============================================================================

ScDPHorFieldControl::ScDPHorFieldControl(
    ScPivotLayoutDlg* pDialog, const ResId& rResId, FixedText* pCaption, const char* pcHelpId) :
    ScDPFieldControlBase(pDialog, rResId, pCaption, pcHelpId),
    maScroll(this, WB_HORZ | WB_DRAG),
    mnFieldBtnRowCount(0),
    mnFieldBtnColCount(0)
{
    maScroll.SetScrollHdl( LINK(this, ScDPHorFieldControl, ScrollHdl) );
    maScroll.SetEndScrollHdl( LINK(this, ScDPHorFieldControl, EndScrollHdl) );
    maScroll.Hide();

    AppendPaintable(&maScroll);
}

ScDPHorFieldControl::~ScDPHorFieldControl()
{
}

Point ScDPHorFieldControl::GetFieldPosition( size_t nIndex )
{
    Point aPos;
    Size aSize;
    GetFieldBtnPosSize(nIndex, aPos, aSize);
    return aPos;
}

Size ScDPHorFieldControl::GetFieldSize() const
{
    return GetStdFieldBtnSize();
}

size_t ScDPHorFieldControl::GetFieldIndex( const Point& rPos )
{
    if (rPos.X() < 0 || rPos.Y() < 0)
        return PIVOTFIELD_INVALID;

    Size aWndSize = GetSizePixel();
    if (rPos.X() > aWndSize.Width() || rPos.Y() > aWndSize.Height())
        return PIVOTFIELD_INVALID;

    size_t nX = rPos.X();
    size_t nY = rPos.Y();
    size_t nW = aWndSize.Width();
    size_t nH = aWndSize.Height();

    Size aFldSize = GetFieldSize();
    size_t nCurX = OUTER_MARGIN_HOR + aFldSize.Width() + ROW_FIELD_BTN_GAP/2;
    size_t nCurY = OUTER_MARGIN_VER + aFldSize.Height() + ROW_FIELD_BTN_GAP/2;
    size_t nCol = 0;
    size_t nRow = 0;
    while (nX > nCurX && nCurX <= nW)
    {
        nCurX += aFldSize.Width() + ROW_FIELD_BTN_GAP;
        ++nCol;
    }
    while (nY > nCurY && nCurY <= nH)
    {
        nCurY += aFldSize.Height() + ROW_FIELD_BTN_GAP;
        ++nRow;
    }

    size_t nOffset = maScroll.GetThumbPos();
    nCol += nOffset; // convert to logical column ID.
    size_t nIndex = nCol * mnFieldBtnRowCount + nRow;
    size_t nFldCount = GetFieldCount();
    if (nIndex > nFldCount)
        nIndex = nFldCount;
    return IsValidIndex(nIndex) ? nIndex : PIVOTFIELD_INVALID;
}

void ScDPHorFieldControl::Redraw()
{
    VirtualDevice   aVirDev;
    // #i97623# VirtualDevice is always LTR while other windows derive direction from parent
    aVirDev.EnableRTL( IsRTLEnabled() );
    aVirDev.SetMapMode( MAP_PIXEL );

    Point           aPos0;
    Size            aSize( GetSizePixel() );
    Font            aFont( GetFont() );         // Font vom Window
    aFont.SetTransparent( true );
    aVirDev.SetFont( aFont );
    aVirDev.SetOutputSizePixel( aSize );

    DrawBackground( aVirDev );

    FieldNames& rFields = GetFieldNames();
    {
        long nScrollOffset = maScroll.GetThumbPos();
        FieldNames::iterator itr = rFields.begin(), itrEnd = rFields.end();
        if (nScrollOffset)
            ::std::advance(itr, nScrollOffset*mnFieldBtnRowCount);

        for (size_t i = 0; itr != itrEnd; ++itr, ++i)
        {
            Point aFldPt;
            Size aFldSize;
            if (!GetFieldBtnPosSize(i, aFldPt, aFldSize))
                break;

            size_t nField = i + nScrollOffset*mnFieldBtnRowCount;
            bool bFocus = HasFocus() && (nField == GetSelectedField());
            DrawField(aVirDev, Rectangle(aFldPt, aFldSize), *itr, bFocus);
        }
    }

    DrawBitmap( aPos0, aVirDev.GetBitmap( aPos0, aSize ) );
    DrawPaintables();
    DrawInvertSelection();
    UpdateStyle();
}

void ScDPHorFieldControl::CalcSize()
{
    Size aWndSize = GetSizePixel();

    long nScrollSize = GetSettings().GetStyleSettings().GetScrollBarSize();
    maScroll.SetSizePixel(Size(aWndSize.Width() - OUTER_MARGIN_HOR*2, nScrollSize));
    maScroll.SetPosPixel(Point(OUTER_MARGIN_HOR, aWndSize.Height() - OUTER_MARGIN_VER - nScrollSize));

    long nTotalH = aWndSize.Height() - nScrollSize - OUTER_MARGIN_VER*2;
    long nTotalW = aWndSize.Width() - OUTER_MARGIN_HOR*2;
    mnFieldBtnRowCount = nTotalH / (GetFieldSize().Height() + ROW_FIELD_BTN_GAP);
    mnFieldBtnColCount = (nTotalW + ROW_FIELD_BTN_GAP) / (GetFieldSize().Width() + ROW_FIELD_BTN_GAP);

    maScroll.SetLineSize(1);
    maScroll.SetVisibleSize(mnFieldBtnColCount);
    maScroll.SetPageSize(mnFieldBtnColCount);
    maScroll.SetRange(Range(0, mnFieldBtnColCount));
}

bool ScDPHorFieldControl::IsValidIndex(size_t /*nIndex*/) const
{
    return true;
}

size_t ScDPHorFieldControl::CalcNewFieldIndex(SCsCOL nDX, SCsROW nDY) const
{
    size_t nSel = GetSelectedField();
    size_t nFldCount = GetFieldCount();
    SCsROW nRow = nSel % mnFieldBtnRowCount;
    SCsCOL nCol = nSel / mnFieldBtnRowCount;
    SCsCOL nColUpper = static_cast<SCsCOL>(ceil(
        static_cast<double>(nFldCount) / static_cast<double>(mnFieldBtnRowCount)) - 1);
    SCsROW nRowUpper = mnFieldBtnRowCount - 1;

    nCol += nDX;
    if (nCol < 0)
        nCol = 0;
    else if (nColUpper < nCol)
        nCol = nColUpper;
    nRow += nDY;
    if (nRow < 0)
        nRow = 0;
    else if (nRowUpper < nRow)
        nRow = nRowUpper;

    nSel = nCol*mnFieldBtnRowCount + nRow;
    if (nSel >= nFldCount)
        nSel = nFldCount - 1;

    return nSel;
}

size_t ScDPHorFieldControl::GetDisplayPosition(size_t nIndex) const
{
    size_t nColFirst = maScroll.GetThumbPos();
    size_t nColLast = nColFirst + mnFieldBtnColCount - 1;
    size_t nCol = nIndex / mnFieldBtnRowCount;
    size_t nRow = nIndex % mnFieldBtnRowCount;
    if (nCol < nColFirst || nColLast < nCol)
        // index is outside the visible area.
        return INVALID_INDEX;

    size_t nPos = (nCol - nColFirst)*mnFieldBtnRowCount + nRow;
    return nPos;
}

String ScDPHorFieldControl::GetDescription() const
{
    return ScResId(STR_ACC_DATAPILOT_COL_DESCR);
}

void ScDPHorFieldControl::ScrollToEnd()
{
    maScroll.DoScroll(maScroll.GetRangeMax());
}

void ScDPHorFieldControl::ScrollToShowSelection()
{
    size_t nLower = maScroll.GetThumbPos();
    size_t nUpper = nLower + mnFieldBtnColCount - 1;
    size_t nCol = GetSelectedField() / mnFieldBtnRowCount;
    if (nCol < nLower)
    {
        // scroll to left.
        maScroll.DoScroll(nCol);
    }
    else if (nUpper < nCol)
    {
        // scroll to right.
        maScroll.DoScroll(nCol - mnFieldBtnColCount + 1);
    }
}

void ScDPHorFieldControl::ResetScrollBar()
{
    long nOldMax = maScroll.GetRangeMax();
    long nNewMax = static_cast<long>(ceil(
        static_cast<double>(GetFieldCount()) / static_cast<double>(mnFieldBtnRowCount)));

    if (nOldMax != nNewMax)
    {
        maScroll.SetRangeMax(nNewMax);
        bool bShow = mnFieldBtnColCount*mnFieldBtnRowCount < GetFieldCount();
        maScroll.Show(bShow);
    }
}

void ScDPHorFieldControl::HandleWheelScroll(long /*nNotch*/)
{
    // not handled for horizontal field controls.
}

bool ScDPHorFieldControl::GetFieldBtnPosSize(size_t nPos, Point& rPos, Size& rSize)
{
    if (nPos >= mnFieldBtnColCount*mnFieldBtnRowCount)
        return false;

    Point aPos = Point(OUTER_MARGIN_HOR, OUTER_MARGIN_VER);
    size_t nRow = nPos % mnFieldBtnRowCount;
    size_t nCol = nPos / mnFieldBtnRowCount;

    aPos.X() += nCol*(GetFieldSize().Width() + ROW_FIELD_BTN_GAP);
    aPos.Y() += nRow*(GetFieldSize().Height() + ROW_FIELD_BTN_GAP);

    rPos = aPos;
    rSize = GetFieldSize();
    return true;
}

void ScDPHorFieldControl::HandleScroll()
{
    Redraw();
}

IMPL_LINK_NOARG(ScDPHorFieldControl, ScrollHdl)
{
    HandleScroll();
    return 0;
}

IMPL_LINK_NOARG(ScDPHorFieldControl, EndScrollHdl)
{
    HandleScroll();
    return 0;
}

//=============================================================================

ScDPPageFieldControl::ScDPPageFieldControl(
    ScPivotLayoutDlg* pDialog, const ResId& rResId, FixedText* pCaption, const char* pcHelpId) :
    ScDPHorFieldControl(pDialog, rResId, pCaption, pcHelpId)
{
}

ScDPPageFieldControl::~ScDPPageFieldControl()
{
}

ScPivotFieldType ScDPPageFieldControl::GetFieldType() const
{
    return PIVOTFIELDTYPE_PAGE;
}

String ScDPPageFieldControl::GetDescription() const
{
    return ScResId(STR_ACC_DATAPILOT_PAGE_DESCR);
}

//=============================================================================

ScDPColFieldControl::ScDPColFieldControl(
    ScPivotLayoutDlg* pDialog, const ResId& rResId, FixedText* pCaption, const char* pcHelpId) :
    ScDPHorFieldControl(pDialog, rResId, pCaption, pcHelpId)
{
}

ScDPColFieldControl::~ScDPColFieldControl()
{
}

ScPivotFieldType ScDPColFieldControl::GetFieldType() const
{
    return PIVOTFIELDTYPE_COL;
}

String ScDPColFieldControl::GetDescription() const
{
    return ScResId(STR_ACC_DATAPILOT_COL_DESCR);
}

//=============================================================================

ScDPRowFieldControl::ScDPRowFieldControl(
    ScPivotLayoutDlg* pDialog, const ResId& rResId, FixedText* pCaption, const char* pcHelpId) :
    ScDPFieldControlBase(pDialog, rResId, pCaption, pcHelpId),
    maScroll(this, WB_VERT | WB_DRAG),
    mnColumnBtnCount(0)
{
    maScroll.SetScrollHdl( LINK(this, ScDPRowFieldControl, ScrollHdl) );
    maScroll.SetEndScrollHdl( LINK(this, ScDPRowFieldControl, EndScrollHdl) );
    maScroll.Show(false);

    AppendPaintable(&maScroll);
}

ScDPRowFieldControl::~ScDPRowFieldControl()
{
}

//-------------------------------------------------------------------

Point ScDPRowFieldControl::GetFieldPosition(size_t nIndex)
{
    Point aPos;
    Size aSize;
    GetFieldBtnPosSize(nIndex, aPos, aSize);
    return aPos;
}

Size ScDPRowFieldControl::GetFieldSize() const
{
    return GetStdFieldBtnSize();
}

size_t ScDPRowFieldControl::GetFieldIndex( const Point& rPos )
{
    if (rPos.X() < 0 || rPos.Y() < 0)
        return PIVOTFIELD_INVALID;

    long nFldH = GetFieldSize().Height();
    long nThreshold = OUTER_MARGIN_VER + nFldH + ROW_FIELD_BTN_GAP / 2;

    size_t nIndex = 0;
    for (; nIndex < mnColumnBtnCount; ++nIndex)
    {
        if (rPos.Y() < nThreshold)
            break;

        nThreshold += nFldH + ROW_FIELD_BTN_GAP;
    }

    if (nIndex >= mnColumnBtnCount)
        nIndex = mnColumnBtnCount - 1;

    nIndex += maScroll.GetThumbPos();
    return IsValidIndex(nIndex) ? nIndex : PIVOTFIELD_INVALID;
}

void ScDPRowFieldControl::Redraw()
{
    VirtualDevice   aVirDev;
    // #i97623# VirtualDevice is always LTR while other windows derive direction from parent
    aVirDev.EnableRTL( IsRTLEnabled() );
    aVirDev.SetMapMode( MAP_PIXEL );

    Point aPos0;
    Size aWndSize = GetSizePixel();
    Font aFont = GetFont();
    aFont.SetTransparent(true);
    aVirDev.SetFont(aFont);
    aVirDev.SetOutputSizePixel(aWndSize);

    DrawBackground(aVirDev);

    FieldNames& rFields = GetFieldNames();
    {
        long nScrollOffset = maScroll.GetThumbPos();
        FieldNames::iterator itr = rFields.begin(), itrEnd = rFields.end();
        if (nScrollOffset)
            ::std::advance(itr, nScrollOffset);

        for (size_t i = 0; itr != itrEnd; ++itr, ++i)
        {
            Point aFldPt;
            Size aFldSize;
            if (!GetFieldBtnPosSize(i, aFldPt, aFldSize))
                break;

            size_t nField = i + nScrollOffset;
            bool bFocus = HasFocus() && (nField == GetSelectedField());
            DrawField(aVirDev, Rectangle(aFldPt, aFldSize), *itr, bFocus);
        }
    }

    // Create a bitmap from the virtual device, and place that bitmap onto
    // this control.
    DrawBitmap(aPos0, aVirDev.GetBitmap(aPos0, aWndSize));

    DrawPaintables();
    DrawInvertSelection();
    UpdateStyle();
}

void ScDPRowFieldControl::CalcSize()
{
    Size aWndSize = GetSizePixel();

    long nTotal = aWndSize.Height() - OUTER_MARGIN_VER;
    mnColumnBtnCount = nTotal / (GetFieldSize().Height() + ROW_FIELD_BTN_GAP);

    long nScrollSize = GetSettings().GetStyleSettings().GetScrollBarSize();

    maScroll.SetSizePixel(Size(nScrollSize, aWndSize.Height() - OUTER_MARGIN_VER*2));
    maScroll.SetPosPixel(Point(aWndSize.Width() - nScrollSize - OUTER_MARGIN_HOR, OUTER_MARGIN_VER));
    maScroll.SetLineSize(1);
    maScroll.SetVisibleSize(mnColumnBtnCount);
    maScroll.SetPageSize(mnColumnBtnCount);
    maScroll.SetRange(Range(0, mnColumnBtnCount));
    maScroll.DoScroll(0);

}

bool ScDPRowFieldControl::IsValidIndex(size_t /*nIndex*/) const
{
    // This method is here in case we decide to impose an arbitrary upper
    // boundary on the number of fields.
    return true;
}

size_t ScDPRowFieldControl::CalcNewFieldIndex(SCsCOL /*nDX*/, SCsROW nDY) const
{
    size_t nNewField = GetSelectedField();
    nNewField += nDY;
    return IsExistingIndex(nNewField) ? nNewField : GetSelectedField();
}

size_t ScDPRowFieldControl::GetDisplayPosition(size_t nIndex) const
{
    size_t nLower = maScroll.GetThumbPos();
    size_t nUpper = nLower + mnColumnBtnCount;
    if (nLower <= nIndex && nIndex <= nUpper)
        return nIndex - nLower;

    return INVALID_INDEX;
}

//-------------------------------------------------------------------

String ScDPRowFieldControl::GetDescription() const
{
    return ScResId(STR_ACC_DATAPILOT_ROW_DESCR);
}

ScPivotFieldType ScDPRowFieldControl::GetFieldType() const
{
    return PIVOTFIELDTYPE_ROW;
}

void ScDPRowFieldControl::ScrollToEnd()
{
    maScroll.DoScroll(maScroll.GetRangeMax());
}

void ScDPRowFieldControl::ScrollToShowSelection()
{
    size_t nLower = maScroll.GetThumbPos();
    size_t nUpper = nLower + mnColumnBtnCount - 1;
    size_t nSel = GetSelectedField();
    if (nSel < nLower)
    {
        // scroll up
        maScroll.DoScroll(nSel);
    }
    else if (nUpper < nSel)
    {
        // scroll down
        size_t nD = nSel - nUpper;
        maScroll.DoScroll(nLower + nD);
    }
}

void ScDPRowFieldControl::ResetScrollBar()
{
    long nOldMax = maScroll.GetRangeMax();
    long nNewMax = std::max<long>(mnColumnBtnCount, GetFieldCount());

    if (nOldMax != nNewMax)
    {
        maScroll.SetRangeMax(nNewMax);
        maScroll.Show(GetFieldCount() > mnColumnBtnCount);
    }
}

void ScDPRowFieldControl::HandleWheelScroll(long nNotch)
{
    maScroll.DoScroll(maScroll.GetThumbPos() - nNotch);
}

bool ScDPRowFieldControl::GetFieldBtnPosSize(size_t nPos, Point& rPos, Size& rSize)
{
    if (nPos >= mnColumnBtnCount)
        return false;

    size_t nOffset = maScroll.GetThumbPos();
    if (nPos + nOffset >= GetFieldCount())
        return false;

    rSize = GetFieldSize();
    rPos = Point(OUTER_MARGIN_HOR, OUTER_MARGIN_VER);
    rPos.Y() += nPos * (rSize.Height() + ROW_FIELD_BTN_GAP);
    return true;
}

void ScDPRowFieldControl::HandleScroll()
{
    Redraw();
}

IMPL_LINK_NOARG(ScDPRowFieldControl, ScrollHdl)
{
    HandleScroll();
    return 0;
}

IMPL_LINK_NOARG(ScDPRowFieldControl, EndScrollHdl)
{
    HandleScroll();
    return 0;
}

//=============================================================================

ScDPSelectFieldControl::ScDPSelectFieldControl(
        ScPivotLayoutDlg* pDialog, const ResId& rResId, FixedText* pCaption, const char* pcHelpId) :
    ScDPHorFieldControl(pDialog, rResId, pCaption, pcHelpId)
{
    SetName(String(ScResId(STR_SELECT)));
}

ScDPSelectFieldControl::~ScDPSelectFieldControl()
{
}

ScPivotFieldType ScDPSelectFieldControl::GetFieldType() const
{
    return PIVOTFIELDTYPE_SELECT;
}

String ScDPSelectFieldControl::GetDescription() const
{
    return ScResId(STR_ACC_DATAPILOT_SEL_DESCR);
}

//=============================================================================

ScDPDataFieldControl::ScDPDataFieldControl(
    ScPivotLayoutDlg* pDialog, const ResId& rResId, FixedText* pCaption, const char* pcHelpId) :
    ScDPHorFieldControl(pDialog, rResId, pCaption, pcHelpId)
{
}

ScDPDataFieldControl::~ScDPDataFieldControl()
{
}

ScPivotFieldType ScDPDataFieldControl::GetFieldType() const
{
    return PIVOTFIELDTYPE_DATA;
}

Size ScDPDataFieldControl::GetFieldSize() const
{
    Size aWndSize = GetSizePixel();
    long nFieldObjWidth = static_cast<long>(aWndSize.Width() / 2.0 - OUTER_MARGIN_HOR - DATA_FIELD_BTN_GAP/2);
    Size aFieldSize(nFieldObjWidth, FIELD_BTN_HEIGHT);
    return aFieldSize;
}

String ScDPDataFieldControl::GetDescription() const
{
    return ScResId(STR_ACC_DATAPILOT_DATA_DESCR);
}

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