summaryrefslogtreecommitdiff
path: root/dbaccess/source/ui/tabledesign/TEditControl.cxx
blob: 6ee67535d414b208e0ead5fd28fd0f6dbc3b0c6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "TEditControl.hxx"
#include <com/sun/star/sdbc/SQLException.hpp>
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#include <com/sun/star/sdbcx/XAlterTable.hpp>
#include <com/sun/star/sdbcx/XDrop.hpp>
#include <com/sun/star/sdbcx/XAppend.hpp>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/util/XNumberFormatTypes.hpp>
#include <core_resource.hxx>
#include <strings.hrc>
#include <strings.hxx>
#include <stringconstants.hxx>
#include <browserids.hxx>
#include <helpids.h>
#include <comphelper/types.hxx>
#include <FieldDescControl.hxx>
#include <FieldDescriptions.hxx>
#include "TableUndo.hxx"
#include <TableController.hxx>
#include <connectivity/dbmetadata.hxx>
#include <connectivity/dbtools.hxx>
#include <SqlNameEdit.hxx>
#include <TableRowExchange.hxx>
#include <sot/storage.hxx>
#include <UITools.hxx>
#include "TableFieldControl.hxx"
#include <dsntypes.hxx>
#include <vcl/commandevent.hxx>
#include <vcl/svapp.hxx>

#include <dbaccess_slotid.hrc>

using namespace ::dbaui;
using namespace ::comphelper;
using namespace ::svt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdb;


#define HANDLE_ID       0

// default field widths
#define FIELDNAME_WIDTH     100
#define FIELDTYPE_WIDTH     150
#define FIELDDESCR_WIDTH    300

// Maximum length in description field
#define MAX_DESCR_LEN       256

OTableEditorCtrl::ClipboardInvalidator::ClipboardInvalidator(OTableEditorCtrl* _pOwner)
: m_pOwner(_pOwner)
{

    m_aInvalidateTimer.SetTimeout(500);
    m_aInvalidateTimer.SetInvokeHandler(LINK(this, OTableEditorCtrl::ClipboardInvalidator, OnInvalidate));
    m_aInvalidateTimer.Start();
}

OTableEditorCtrl::ClipboardInvalidator::~ClipboardInvalidator()
{
    m_aInvalidateTimer.Stop();
}

void OTableEditorCtrl::ClipboardInvalidator::Stop()
{
    m_aInvalidateTimer.Stop();
}

IMPL_LINK_NOARG(OTableEditorCtrl::ClipboardInvalidator, OnInvalidate, Timer *, void)
{
    m_pOwner->GetView()->getController().InvalidateFeature(SID_CUT);
    m_pOwner->GetView()->getController().InvalidateFeature(SID_COPY);
    m_pOwner->GetView()->getController().InvalidateFeature(SID_PASTE);
}

void OTableEditorCtrl::Init()
{
    OTableRowView::Init();

    // Should it be opened ReadOnly?
    bool bRead(GetView()->getController().isReadOnly());

    SetReadOnly( bRead );

    // Insert the columns
    InsertDataColumn( FIELD_NAME, DBA_RES(STR_TAB_FIELD_COLUMN_NAME), FIELDNAME_WIDTH );

    InsertDataColumn( FIELD_TYPE, DBA_RES(STR_TAB_FIELD_COLUMN_DATATYPE), FIELDTYPE_WIDTH );

    ::dbaccess::ODsnTypeCollection aDsnTypes(GetView()->getController().getORB());
    bool bShowColumnDescription = aDsnTypes.supportsColumnDescription(::comphelper::getString(GetView()->getController().getDataSource()->getPropertyValue(PROPERTY_URL)));
    InsertDataColumn( HELP_TEXT, DBA_RES(STR_TAB_HELP_TEXT), bShowColumnDescription ? FIELDTYPE_WIDTH : FIELDDESCR_WIDTH );

    if ( bShowColumnDescription )
    {
        InsertDataColumn( COLUMN_DESCRIPTION, DBA_RES(STR_COLUMN_DESCRIPTION), FIELDTYPE_WIDTH );
    }

    InitCellController();

    // Insert the rows
    RowInserted(0, m_pRowList->size());
}

OTableEditorCtrl::OTableEditorCtrl(vcl::Window* pWindow)
    :OTableRowView(pWindow)
    ,pNameCell(nullptr)
    ,pTypeCell(nullptr)
    ,pHelpTextCell(nullptr)
    ,pDescrCell(nullptr)
    ,pDescrWin(nullptr)
    ,nCutEvent(nullptr)
    ,nPasteEvent(nullptr)
    ,nDeleteEvent(nullptr)
    ,nInsNewRowsEvent(nullptr)
    ,nInvalidateTypeEvent(nullptr)
    ,m_eChildFocus(NONE)
    ,nOldDataPos(-1)
    ,bReadOnly(true)
    ,m_aInvalidate(this)
{

    SetHelpId(HID_TABDESIGN_BACKGROUND);
    GetDataWindow().SetHelpId(HID_CTL_TABLEEDIT);

    m_pRowList = &GetView()->getController().getRows();
    m_nDataPos = 0;
}

SfxUndoManager& OTableEditorCtrl::GetUndoManager() const
{
    return GetView()->getController().GetUndoManager();
}


void OTableEditorCtrl::SetReadOnly( bool bRead )
{
    // nothing to do?
    if (bRead == IsReadOnly())
        // This check is important, as the underlying Def may be unnecessarily locked or unlocked
        // or worse, this action may not be reversed afterwards
        return;

    bReadOnly = bRead;

    // Disable active cells
    long nRow(GetCurRow());
    sal_uInt16 nCol(GetCurColumnId());
    DeactivateCell();

    // Select the correct Browsers cursor
    BrowserMode nMode(BrowserMode::COLUMNSELECTION | BrowserMode::MULTISELECTION | BrowserMode::KEEPHIGHLIGHT |
                      BrowserMode::HLINES      | BrowserMode::VLINES|BrowserMode::AUTOSIZE_LASTCOL);
    if( !bReadOnly )
        nMode |= BrowserMode::HIDECURSOR;
    SetMode(nMode);

    if( !bReadOnly )
        ActivateCell( nRow, nCol );
}

void OTableEditorCtrl::InitCellController()
{
    // Cell Field name
    sal_Int32 nMaxTextLen = EDIT_NOLIMIT;
    OUString sExtraNameChars;
    Reference<XConnection> xCon;
    try
    {
        xCon = GetView()->getController().getConnection();
        Reference< XDatabaseMetaData> xMetaData = xCon.is() ? xCon->getMetaData() : Reference< XDatabaseMetaData>();

        nMaxTextLen = xMetaData.is() ? xMetaData->getMaxColumnNameLength() : 0;

        if( nMaxTextLen == 0 )
            nMaxTextLen = EDIT_NOLIMIT;
        sExtraNameChars = xMetaData.is() ? xMetaData->getExtraNameCharacters() : OUString();

    }
    catch(SQLException&)
    {
        OSL_FAIL("getMaxColumnNameLength");
    }

    pNameCell = VclPtr<OSQLNameEdit>::Create(&GetDataWindow(), WB_LEFT, sExtraNameChars);
    pNameCell->SetMaxTextLen( nMaxTextLen );
    pNameCell->setCheck( isSQL92CheckEnabled(xCon) );

    // Cell type
    pTypeCell = VclPtr<ListBoxControl>::Create( &GetDataWindow() );
    pTypeCell->SetDropDownLineCount( 15 );

    // Cell description
    pDescrCell = VclPtr<Edit>::Create( &GetDataWindow(), WB_LEFT );
    pDescrCell->SetMaxTextLen( MAX_DESCR_LEN );

    pHelpTextCell = VclPtr<Edit>::Create( &GetDataWindow(), WB_LEFT );
    pHelpTextCell->SetMaxTextLen( MAX_DESCR_LEN );

    pNameCell->SetHelpId(HID_TABDESIGN_NAMECELL);
    pTypeCell->SetHelpId(HID_TABDESIGN_TYPECELL);
    pDescrCell->SetHelpId(HID_TABDESIGN_COMMENTCELL);
    pHelpTextCell->SetHelpId(HID_TABDESIGN_HELPTEXT);

    Size aHeight;
    const Control* pControls[] = { pTypeCell,pDescrCell,pNameCell,pHelpTextCell};
    for(const Control* pControl : pControls)
    {
        const Size aTemp(pControl->GetOptimalSize());
        if ( aTemp.Height() > aHeight.Height() )
            aHeight.setHeight( aTemp.Height() );
    }
    SetDataRowHeight(aHeight.Height());

    ClearModified();
}

void OTableEditorCtrl::ClearModified()
{
    pNameCell->ClearModifyFlag();
    pDescrCell->ClearModifyFlag();
    pHelpTextCell->ClearModifyFlag();
    pTypeCell->SaveValue();
}

OTableEditorCtrl::~OTableEditorCtrl()
{
    disposeOnce();
}

void OTableEditorCtrl::dispose()
{
    // Reset the Undo-Manager
    GetUndoManager().Clear();

    m_aInvalidate.Stop();

    // Take possible Events from the queue
    if( nCutEvent )
        Application::RemoveUserEvent( nCutEvent );
    if( nPasteEvent )
        Application::RemoveUserEvent( nPasteEvent );
    if( nDeleteEvent )
        Application::RemoveUserEvent( nDeleteEvent );
    if( nInsNewRowsEvent )
        Application::RemoveUserEvent( nInsNewRowsEvent );
    if( nInvalidateTypeEvent )
        Application::RemoveUserEvent( nInvalidateTypeEvent );

    // Delete the control types
    pNameCell.disposeAndClear();
    pTypeCell.disposeAndClear();
    pDescrCell.disposeAndClear();
    pHelpTextCell.disposeAndClear();
    pDescrWin.clear();
    OTableRowView::dispose();
}

bool OTableEditorCtrl::SetDataPtr( long nRow )
{
    if(nRow == -1)
        return false;

    OSL_ENSURE(nRow < static_cast<long>(m_pRowList->size()),"Row is greater than size!");
    if(nRow >= static_cast<long>(m_pRowList->size()))
        return false;
    pActRow = (*m_pRowList)[nRow];
    return pActRow != nullptr;
}

bool OTableEditorCtrl::SeekRow(long _nRow)
{
    // Call the Base class to remember which row must be repainted
    EditBrowseBox::SeekRow(_nRow);

    m_nCurrentPos = _nRow;
    return SetDataPtr(_nRow);
}

void OTableEditorCtrl::PaintCell(OutputDevice& rDev, const tools::Rectangle& rRect,
                                   sal_uInt16 nColumnId ) const
{
    const OUString aText( GetCellText( m_nCurrentPos, nColumnId ));

    rDev.Push( PushFlags::CLIPREGION );
    rDev.SetClipRegion(vcl::Region(rRect));
    rDev.DrawText( rRect, aText, DrawTextFlags::Left | DrawTextFlags::VCenter );
    rDev.Pop();
}

CellController* OTableEditorCtrl::GetController(long nRow, sal_uInt16 nColumnId)
{
    // If EditorCtrl is ReadOnly, editing is forbidden
    Reference<XPropertySet> xTable = GetView()->getController().getTable();
    if (IsReadOnly() || (   xTable.is() &&
                            xTable->getPropertySetInfo()->hasPropertyByName(PROPERTY_TYPE) &&
                            ::comphelper::getString(xTable->getPropertyValue(PROPERTY_TYPE)) == "VIEW"))
        return nullptr;

    // If the row is ReadOnly, editing is forbidden
    SetDataPtr( nRow );
    if( pActRow->IsReadOnly() )
        return nullptr;

    OFieldDescription* pActFieldDescr = pActRow->GetActFieldDescr();
    switch (nColumnId)
    {
        case FIELD_NAME:
            return new EditCellController( pNameCell );
        case FIELD_TYPE:
            if (pActFieldDescr && !pActFieldDescr->GetName().isEmpty())
                return new ListBoxCellController( pTypeCell );
            else return nullptr;
        case HELP_TEXT:
            if (pActFieldDescr && !pActFieldDescr->GetName().isEmpty())
                return new EditCellController( pHelpTextCell );
            else
                return nullptr;
        case COLUMN_DESCRIPTION:
            if (pActFieldDescr && !pActFieldDescr->GetName().isEmpty())
                return new EditCellController( pDescrCell );
            else
                return nullptr;
        default:
            return nullptr;
    }
}

void OTableEditorCtrl::InitController(CellControllerRef&, long nRow, sal_uInt16 nColumnId)
{
    SeekRow( nRow == -1 ? GetCurRow() : nRow);
    OFieldDescription* pActFieldDescr = pActRow->GetActFieldDescr();
    OUString aInitString;

    switch (nColumnId)
    {
        case FIELD_NAME:
            if( pActFieldDescr )
                aInitString = pActFieldDescr->GetName();
            pNameCell->SetText( aInitString );
            pNameCell->SaveValue();
            break;
        case FIELD_TYPE:
            {
                if ( pActFieldDescr && pActFieldDescr->getTypeInfo() )
                    aInitString = pActFieldDescr->getTypeInfo()->aUIName;

                // Set the ComboBox contents
                pTypeCell->Clear();
                if( !pActFieldDescr )
                    break;

                const OTypeInfoMap& rTypeInfo = GetView()->getController().getTypeInfo();
                for (auto const& elem : rTypeInfo)
                    pTypeCell->InsertEntry( elem.second->aUIName );
                pTypeCell->SelectEntry( aInitString );
            }

            break;
        case HELP_TEXT:
            if( pActFieldDescr )
                aInitString = pActFieldDescr->GetHelpText();
            pHelpTextCell->SetText( aInitString );
            pHelpTextCell->SaveValue();
            break;
        case COLUMN_DESCRIPTION:
            if( pActFieldDescr )
                aInitString = pActFieldDescr->GetDescription();
            pDescrCell->SetText( aInitString );
            pDescrCell->SaveValue();
            break;

    }
}

EditBrowseBox::RowStatus OTableEditorCtrl::GetRowStatus(long nRow) const
{
    const_cast<OTableEditorCtrl*>(this)->SetDataPtr( nRow );
    if( !pActRow )
        return EditBrowseBox::CLEAN;
    if (nRow >= 0 && nRow == m_nDataPos)
    {
        if( pActRow->IsPrimaryKey() )
            return EditBrowseBox::CURRENT_PRIMARYKEY;
        return EditBrowseBox::CURRENT;
    }
    else
    {
        if( pActRow->IsPrimaryKey() )
            return EditBrowseBox::PRIMARYKEY;
        return EditBrowseBox::CLEAN;
    }
}

void OTableEditorCtrl::SaveCurRow()
{
    if (GetFieldDescr(GetCurRow()) == nullptr)
        // there is no data in the current row
        return;
    if (!SaveModified())
        return;

    SetDataPtr(GetCurRow());
    pDescrWin->SaveData( pActRow->GetActFieldDescr() );
}

void OTableEditorCtrl::DisplayData(long nRow)
{
    // go to the correct cell
    SetDataPtr(nRow);

    // Disable Edit-Mode temporarily
    bool bWasEditing = IsEditing();
    if (bWasEditing)
        DeactivateCell();

    CellControllerRef aTemp;
    InitController(aTemp, nRow, FIELD_NAME);
    InitController(aTemp, nRow, FIELD_TYPE);
    InitController(aTemp, nRow, COLUMN_DESCRIPTION);
    InitController(aTemp, nRow, HELP_TEXT);

    GoToRow(nRow);
    // Update the Description-Window
    GetView()->GetDescWin()->DisplayData(GetFieldDescr(nRow));
    // redraw the row
    RowModified(nRow);

    // and re-enable edit mode
    ActivateCell(nRow, GetCurColumnId());
}

void OTableEditorCtrl::CursorMoved()
{
    // New line?
    m_nDataPos = GetCurRow();
    if( m_nDataPos != nOldDataPos && m_nDataPos != -1)
    {
        CellControllerRef aTemp;
        InitController(aTemp,m_nDataPos,FIELD_NAME);
        InitController(aTemp,m_nDataPos,FIELD_TYPE);
        InitController(aTemp,m_nDataPos,COLUMN_DESCRIPTION);
        InitController(aTemp,m_nDataPos,HELP_TEXT);
    }

    OTableRowView::CursorMoved();
}

sal_Int32 OTableEditorCtrl::HasFieldName( const OUString& rFieldName )
{

    Reference<XConnection> xCon = GetView()->getController().getConnection();
    Reference< XDatabaseMetaData> xMetaData = xCon.is() ? xCon->getMetaData() : Reference< XDatabaseMetaData>();

    ::comphelper::UStringMixEqual bCase(!xMetaData.is() || xMetaData->supportsMixedCaseQuotedIdentifiers());

    sal_Int32 nCount(0);
    for (auto const& row : *m_pRowList)
    {
        OFieldDescription* pFieldDescr = row->GetActFieldDescr();
        if( pFieldDescr && bCase(rFieldName,pFieldDescr->GetName()))
            nCount++;
    }
    return nCount;
}

void OTableEditorCtrl::SaveData(long nRow, sal_uInt16 nColId)
{
    // Store the cell content
    SetDataPtr( nRow == -1 ? GetCurRow() : nRow);
    OFieldDescription* pActFieldDescr = pActRow->GetActFieldDescr();

    switch( nColId)
    {
        // Store NameCell
        case FIELD_NAME:
        {
            // If there is no name, do nothing
            const OUString aName(pNameCell->GetText());

            if( aName.isEmpty() )
            {
                // If FieldDescr exists, the field is deleted and the old content restored
                if (pActFieldDescr)
                {
                    GetUndoManager().AddUndoAction(std::make_unique<OTableEditorTypeSelUndoAct>(this, nRow, FIELD_TYPE, pActFieldDescr->getTypeInfo()));
                    SwitchType(TOTypeInfoSP());
                    pActFieldDescr = pActRow->GetActFieldDescr();
                }
                else
                    return;
            }
            if(pActFieldDescr)
                pActFieldDescr->SetName( aName );
            pNameCell->ClearModifyFlag();

            break;
        }

        // Store the field type
        case FIELD_TYPE:
            break;

        // Store DescrCell
        case HELP_TEXT:
        {
            // if the current field description is NULL, set Default
            if( !pActFieldDescr )
            {
                pHelpTextCell->SetText(OUString());
                pHelpTextCell->ClearModifyFlag();
            }
            else
                pActFieldDescr->SetHelpText( pHelpTextCell->GetText() );
            break;
        }
        case COLUMN_DESCRIPTION:
        {
            // Set the default if the field description is null
            if( !pActFieldDescr )
            {
                pDescrCell->SetText(OUString());
                pDescrCell->ClearModifyFlag();
            }
            else
                pActFieldDescr->SetDescription( pDescrCell->GetText() );
            break;
        }
        case FIELD_PROPERTY_DEFAULT:
        case FIELD_PROPERTY_REQUIRED:
        case FIELD_PROPERTY_TEXTLEN:
        case FIELD_PROPERTY_NUMTYPE:
        case FIELD_PROPERTY_AUTOINC:
        case FIELD_PROPERTY_LENGTH:
        case FIELD_PROPERTY_SCALE:
        case FIELD_PROPERTY_BOOL_DEFAULT:
            pDescrWin->SaveData(pActFieldDescr);

            if ( FIELD_PROPERTY_AUTOINC == nColId && pActFieldDescr->IsAutoIncrement() )
            {
                OTableController& rController = GetView()->getController();
                if ( rController.isAutoIncrementPrimaryKey() )
                {
                    pActFieldDescr->SetPrimaryKey( true );
                    InvalidateHandleColumn();
                    Invalidate();
                }
            }
            break;
    }
}

bool OTableEditorCtrl::SaveModified()
{
    sal_uInt16 nColId = GetCurColumnId();

    switch( nColId )
    {
        // Field type
        case FIELD_TYPE:
        {
            // Reset the type
            resetType();
        } break;
    }

    return true;
}

bool OTableEditorCtrl::CursorMoving(long nNewRow, sal_uInt16 nNewCol)
{

    if (!EditBrowseBox::CursorMoving(nNewRow, nNewCol))
        return false;

    // Called after SaveModified(), current row is still the old one
    m_nDataPos = nNewRow;
    nOldDataPos = GetCurRow();

    // Reset the markers
    InvalidateStatusCell( nOldDataPos );
    InvalidateStatusCell( m_nDataPos );

    // Store the data from the Property window
    if( SetDataPtr(nOldDataPos) && pDescrWin)
        pDescrWin->SaveData( pActRow->GetActFieldDescr() );

    // Show new data in the Property window
    if( SetDataPtr(m_nDataPos) && pDescrWin)
        pDescrWin->DisplayData( pActRow->GetActFieldDescr() );

    return true;
}

IMPL_LINK_NOARG( OTableEditorCtrl, InvalidateFieldType, void*, void )
{
    nInvalidateTypeEvent = nullptr;
    Invalidate( GetFieldRectPixel(nOldDataPos, FIELD_TYPE) );
}

void OTableEditorCtrl::CellModified( long nRow, sal_uInt16 nColId )
{

    // If the description is null, use the default
    if(nRow == -1)
        nRow = GetCurRow();
    SetDataPtr( nRow );
    OFieldDescription* pActFieldDescr = pActRow->GetActFieldDescr();

    OUString sActionDescription;
    switch ( nColId )
    {
    case FIELD_NAME:    sActionDescription = DBA_RES( STR_CHANGE_COLUMN_NAME ); break;
    case FIELD_TYPE:    sActionDescription = DBA_RES( STR_CHANGE_COLUMN_TYPE ); break;
    case HELP_TEXT:
    case COLUMN_DESCRIPTION:   sActionDescription = DBA_RES( STR_CHANGE_COLUMN_DESCRIPTION ); break;
    default:            sActionDescription = DBA_RES( STR_CHANGE_COLUMN_ATTRIBUTE ); break;
    }

    GetUndoManager().EnterListAction( sActionDescription, OUString(), 0, ViewShellId(-1) );
    if (!pActFieldDescr)
    {
        const OTypeInfoMap& rTypeInfoMap = GetView()->getController().getTypeInfo();
        if ( !rTypeInfoMap.empty() )
        {
            OTypeInfoMap::const_iterator aTypeIter = rTypeInfoMap.find(DataType::VARCHAR);
            if ( aTypeIter == rTypeInfoMap.end() )
                aTypeIter = rTypeInfoMap.begin();
            pActRow->SetFieldType( aTypeIter->second );
        }
        else
            pActRow->SetFieldType( GetView()->getController().getTypeInfoFallBack() );

        nInvalidateTypeEvent = Application::PostUserEvent( LINK(this, OTableEditorCtrl, InvalidateFieldType), nullptr, true );
        pActFieldDescr = pActRow->GetActFieldDescr();
        pDescrWin->DisplayData( pActFieldDescr );
        GetUndoManager().AddUndoAction( std::make_unique<OTableEditorTypeSelUndoAct>(this, nRow, nColId+1, TOTypeInfoSP()) );
    }

    if( nColId != FIELD_TYPE )
        GetUndoManager().AddUndoAction( std::make_unique<OTableDesignCellUndoAct>(this, nRow, nColId) );
    else
    {
        GetUndoManager().AddUndoAction(std::make_unique<OTableEditorTypeSelUndoAct>(this, GetCurRow(), nColId, GetFieldDescr(GetCurRow())->getTypeInfo()));
        resetType();
    }

    SaveData(nRow,nColId);
    // SaveData could create an undo action as well
    GetUndoManager().LeaveListAction();
    RowModified(nRow);
    CellControllerRef xController(Controller());
    if(xController.is())
        xController->SetModified();

    // Set the Modify flag
    GetView()->getController().setModified( true );
    InvalidateFeatures();
}

void OTableEditorCtrl::resetType()
{
    sal_Int32 nPos = pTypeCell->GetSelectedEntryPos();
    if(nPos != LISTBOX_ENTRY_NOTFOUND)
        SwitchType( GetView()->getController().getTypeInfo(nPos) );
    else
        SwitchType(TOTypeInfoSP());
}

void OTableEditorCtrl::CellModified()
{
    CellModified( GetCurRow(), GetCurColumnId() );
}

void OTableEditorCtrl::InvalidateFeatures()
{
    GetView()->getController().InvalidateFeature(SID_UNDO);
    GetView()->getController().InvalidateFeature(SID_REDO);
    GetView()->getController().InvalidateFeature(SID_SAVEDOC);
}

void OTableEditorCtrl::CopyRows()
{
    // set to the right row and save it
    if( SetDataPtr(m_nDataPos) )
        pDescrWin->SaveData( pActRow->GetActFieldDescr() );

    // Copy selected rows to the ClipboardList
    std::shared_ptr<OTableRow>  pClipboardRow;
    std::shared_ptr<OTableRow>  pRow;
    std::vector< std::shared_ptr<OTableRow> > vClipboardList;
    vClipboardList.reserve(GetSelectRowCount());

    for( long nIndex=FirstSelectedRow(); nIndex != SFX_ENDOFSELECTION; nIndex=NextSelectedRow() )
    {
        pRow = (*m_pRowList)[nIndex];
        OSL_ENSURE(pRow,"OTableEditorCtrl::CopyRows: Row is NULL!");
        if ( pRow && pRow->GetActFieldDescr() )
        {
            pClipboardRow.reset(new OTableRow( *pRow ));
            vClipboardList.push_back( pClipboardRow);
        }
    }
    if(!vClipboardList.empty())
    {
        rtl::Reference<OTableRowExchange> pData = new OTableRowExchange(vClipboardList);
        pData->CopyToClipboard(GetParent());
    }
}

OUString OTableEditorCtrl::GenerateName( const OUString& rName )
{
    // Create a base name for appending numbers to
    OUString aBaseName;
    Reference<XConnection> xCon = GetView()->getController().getConnection();
    Reference< XDatabaseMetaData> xMetaData = xCon.is() ? xCon->getMetaData() : Reference< XDatabaseMetaData>();

    sal_Int32 nMaxTextLen(xMetaData.is() ? xMetaData->getMaxColumnNameLength() : 0);

    if( (rName.getLength()+2) >nMaxTextLen )
        aBaseName = rName.copy( 0, nMaxTextLen-2 );
    else
        aBaseName = rName;

    // append a sequential number to the base name (up to 99)
    OUString aFieldName( rName);
    sal_Int32 i=1;
    while( HasFieldName(aFieldName) )
    {
        aFieldName = aBaseName + OUString::number(i);
        i++;
    }

    return aFieldName;
}

void OTableEditorCtrl::InsertRows( long nRow )
{

    std::vector<  std::shared_ptr<OTableRow> > vInsertedUndoRedoRows; // need for undo/redo handling
    // get rows from clipboard
    TransferableDataHelper aTransferData(TransferableDataHelper::CreateFromSystemClipboard(GetParent()));
    if(aTransferData.HasFormat(SotClipboardFormatId::SBA_TABED))
    {
        ::tools::SvRef<SotStorageStream> aStreamRef;
        bool bOk = aTransferData.GetSotStorageStream(SotClipboardFormatId::SBA_TABED,aStreamRef);
        if (bOk && aStreamRef.is())
        {
            aStreamRef->Seek(STREAM_SEEK_TO_BEGIN);
            aStreamRef->ResetError();
            long nInsertRow = nRow;
            std::shared_ptr<OTableRow>  pRow;
            sal_Int32 nSize = 0;
            (*aStreamRef).ReadInt32( nSize );
            vInsertedUndoRedoRows.reserve(nSize);
            for(sal_Int32 i=0;i < nSize;++i)
            {
                pRow.reset(new OTableRow());
                ReadOTableRow( *aStreamRef, *pRow );
                pRow->SetReadOnly( false );
                sal_Int32 nType = pRow->GetActFieldDescr()->GetType();
                if ( pRow->GetActFieldDescr() )
                    pRow->GetActFieldDescr()->SetType(GetView()->getController().getTypeInfoByType(nType));
                // Adjust the field names
                pRow->GetActFieldDescr()->SetName( GenerateName( pRow->GetActFieldDescr()->GetName() ) );
                pRow->SetPos(nInsertRow);
                m_pRowList->insert( m_pRowList->begin()+nInsertRow,pRow );
                vInsertedUndoRedoRows.push_back(std::make_shared<OTableRow>(*pRow));
                nInsertRow++;
            }
        }
    }
    // RowInserted calls CursorMoved.
    // The UI data should not be stored here.
    RowInserted( nRow,vInsertedUndoRedoRows.size() );

    // Create the Undo-Action
    GetUndoManager().AddUndoAction( std::make_unique<OTableEditorInsUndoAct>(this, nRow,vInsertedUndoRedoRows) );
    GetView()->getController().setModified( true );
    InvalidateFeatures();
}

void OTableEditorCtrl::DeleteRows()
{
    OSL_ENSURE(GetView()->getController().isDropAllowed(),"Call of DeleteRows not valid here. Please check isDropAllowed!");
    // Create the Undo-Action
    GetUndoManager().AddUndoAction( std::make_unique<OTableEditorDelUndoAct>(this) );

    // Delete all marked rows
    long nIndex = FirstSelectedRow();
    nOldDataPos = nIndex;

    while( nIndex != SFX_ENDOFSELECTION )
    {
        // Remove rows
        m_pRowList->erase( m_pRowList->begin()+nIndex );
        RowRemoved( nIndex );

        // Insert the empty row at the end
        m_pRowList->push_back( std::make_shared<OTableRow>());
        RowInserted( GetRowCount()-1 );

        nIndex = FirstSelectedRow();
    }

    // Force the current record to be displayed
    m_nDataPos = GetCurRow();
    InvalidateStatusCell( nOldDataPos );
    InvalidateStatusCell( m_nDataPos );
    SetDataPtr( m_nDataPos );
    ActivateCell();
    pDescrWin->DisplayData( pActRow->GetActFieldDescr() );
    GetView()->getController().setModified( true );
    InvalidateFeatures();
}

void OTableEditorCtrl::InsertNewRows( long nRow )
{
    OSL_ENSURE(GetView()->getController().isAddAllowed(),"Call of InsertNewRows not valid here. Please check isAppendAllowed!");
    // Create Undo-Action
    long nInsertRows = GetSelectRowCount();
    if( !nInsertRows )
        nInsertRows = 1;
    GetUndoManager().AddUndoAction( std::make_unique<OTableEditorInsNewUndoAct>(this, nRow, nInsertRows) );
    // Insert the number of selected rows
    for( long i=nRow; i<(nRow+nInsertRows); i++ )
        m_pRowList->insert( m_pRowList->begin()+i ,std::make_shared<OTableRow>());
    RowInserted( nRow, nInsertRows );

    GetView()->getController().setModified( true );
    InvalidateFeatures();
}

void OTableEditorCtrl::SetControlText( long nRow, sal_uInt16 nColId, const OUString& rText )
{
    // Set the Browser Controls
    if( nColId < FIELD_FIRST_VIRTUAL_COLUMN )
    {
        GoToRow( nRow );
        GoToColumnId( nColId );
        CellControllerRef xController = Controller();
        if(xController.is())
            xController->GetWindow().SetText( rText );
        else
            RowModified(nRow,nColId);
    }

    // Set the Tabpage controls
    else
    {
        pDescrWin->SetControlText( nColId, rText );
    }
}

void OTableEditorCtrl::SetCellData( long nRow, sal_uInt16 nColId, const TOTypeInfoSP& _pTypeInfo )
{
    // Relocate the current pointer
    if( nRow == -1 )
        nRow = GetCurRow();
    OFieldDescription* pFieldDescr = GetFieldDescr( nRow );
    if( !pFieldDescr && nColId != FIELD_TYPE)
        return;

    // Set individual fields
    switch( nColId )
    {
        case FIELD_TYPE:
            SwitchType( _pTypeInfo );
            break;
        default:
            OSL_FAIL("OTableEditorCtrl::SetCellData: invalid column!");
    }
    SetControlText(nRow,nColId,_pTypeInfo.get() ? _pTypeInfo->aUIName : OUString());
}

void OTableEditorCtrl::SetCellData( long nRow, sal_uInt16 nColId, const css::uno::Any& _rNewData )
{
    // Relocate the current pointer
    if( nRow == -1 )
        nRow = GetCurRow();
    OFieldDescription* pFieldDescr = GetFieldDescr( nRow );
    if( !pFieldDescr && nColId != FIELD_TYPE)
        return;

    OUString sValue;
    // Set individual fields
    switch( nColId )
    {
        case FIELD_NAME:
            sValue = ::comphelper::getString(_rNewData);
            pFieldDescr->SetName( sValue );
            break;

        case FIELD_TYPE:
            OSL_FAIL("OTableEditorCtrl::SetCellData: invalid column!");
            break;

        case COLUMN_DESCRIPTION:
            pFieldDescr->SetDescription( sValue = ::comphelper::getString(_rNewData) );
            break;

        case FIELD_PROPERTY_DEFAULT:
            pFieldDescr->SetControlDefault( _rNewData );
            sValue = GetView()->GetDescWin()->getGenPage()->getFieldControl()->getControlDefault(pFieldDescr);
            break;

        case FIELD_PROPERTY_REQUIRED:
            {
                sValue = ::comphelper::getString(_rNewData);
                pFieldDescr->SetIsNullable( sValue.toInt32() );
            }
            break;

        case FIELD_PROPERTY_TEXTLEN:
        case FIELD_PROPERTY_LENGTH:
            {
                sValue = ::comphelper::getString(_rNewData);
                pFieldDescr->SetPrecision( sValue.toInt32() );
            }
            break;

        case FIELD_PROPERTY_NUMTYPE:
            OSL_FAIL("OTableEditorCtrl::SetCellData: invalid column!");
            break;

        case FIELD_PROPERTY_AUTOINC:
            {
                sValue = ::comphelper::getString(_rNewData);
                pFieldDescr->SetAutoIncrement(sValue == DBA_RES(STR_VALUE_YES));
            }
            break;
        case FIELD_PROPERTY_SCALE:
            {
                sValue = ::comphelper::getString(_rNewData);
                pFieldDescr->SetScale(sValue.toInt32());
            }
            break;

        case FIELD_PROPERTY_BOOL_DEFAULT:
            sValue = GetView()->GetDescWin()->BoolStringPersistent(::comphelper::getString(_rNewData));
            pFieldDescr->SetControlDefault(makeAny(sValue));
            break;

        case FIELD_PROPERTY_FORMAT:
            {
                sValue = ::comphelper::getString(_rNewData);
                pFieldDescr->SetFormatKey(sValue.toInt32());
            }
            break;
    }

    SetControlText(nRow,nColId,sValue);
}

Any OTableEditorCtrl::GetCellData( long nRow, sal_uInt16 nColId )
{
    OFieldDescription* pFieldDescr = GetFieldDescr( nRow );
    if( !pFieldDescr )
        return Any();

    // Relocate the current pointer
    if( nRow==-1 )
        nRow = GetCurRow();
    SetDataPtr( nRow );

    static const OUString strYes(DBA_RES(STR_VALUE_YES));
    static const OUString strNo(DBA_RES(STR_VALUE_NO));
    OUString sValue;
    // Read out the fields
    switch( nColId )
    {
        case FIELD_NAME:
            sValue = pFieldDescr->GetName();
            break;

        case FIELD_TYPE:
            if ( pFieldDescr->getTypeInfo() )
                sValue = pFieldDescr->getTypeInfo()->aUIName;
            break;

        case COLUMN_DESCRIPTION:
            sValue = pFieldDescr->GetDescription();
            break;
        case HELP_TEXT:
            sValue = pFieldDescr->GetHelpText();
            break;

        case FIELD_PROPERTY_DEFAULT:
            return pFieldDescr->GetControlDefault();

        case FIELD_PROPERTY_REQUIRED:
            sValue = pFieldDescr->GetIsNullable() == ColumnValue::NULLABLE ? strYes : strNo;
            break;

        case FIELD_PROPERTY_TEXTLEN:
        case FIELD_PROPERTY_LENGTH:
            sValue = OUString::number(pFieldDescr->GetPrecision());
            break;

        case FIELD_PROPERTY_NUMTYPE:
            OSL_FAIL("OTableEditorCtrl::GetCellData: invalid column!");
            break;

        case FIELD_PROPERTY_AUTOINC:
            sValue = pFieldDescr->IsAutoIncrement() ? strYes : strNo;
            break;

        case FIELD_PROPERTY_SCALE:
            sValue = OUString::number(pFieldDescr->GetScale());
            break;

        case FIELD_PROPERTY_BOOL_DEFAULT:
            sValue = GetView()->GetDescWin()->BoolStringUI(::comphelper::getString(pFieldDescr->GetControlDefault()));
            break;

        case FIELD_PROPERTY_FORMAT:
            sValue = OUString::number(pFieldDescr->GetFormatKey());
            break;
    }

    return makeAny(sValue);
}

OUString OTableEditorCtrl::GetCellText( long nRow, sal_uInt16 nColId ) const
{
    OUString sCellText;
    const_cast< OTableEditorCtrl* >( this )->GetCellData( nRow, nColId ) >>= sCellText;
    return sCellText;
}

sal_uInt32 OTableEditorCtrl::GetTotalCellWidth(long nRow, sal_uInt16 nColId)
{
    return GetTextWidth(GetCellText(nRow, nColId)) + 2 * GetTextWidth("0");
}

OFieldDescription* OTableEditorCtrl::GetFieldDescr( long nRow )
{
    std::vector< std::shared_ptr<OTableRow> >::size_type nListCount(
        m_pRowList->size());
    if( (nRow<0) || (sal::static_int_cast< unsigned long >(nRow)>=nListCount) )
    {
        OSL_FAIL("(nRow<0) || (nRow>=nListCount)");
        return nullptr;
    }
    std::shared_ptr<OTableRow>  pRow = (*m_pRowList)[ nRow ];
    if( !pRow )
        return nullptr;
    return pRow->GetActFieldDescr();
}

bool OTableEditorCtrl::IsCutAllowed()
{
    bool bIsCutAllowed = (GetView()->getController().isAddAllowed() && GetView()->getController().isDropAllowed()) ||
                            GetView()->getController().isAlterAllowed();

    if(bIsCutAllowed)
    {
        switch(m_eChildFocus)
        {
            case DESCRIPTION:
                bIsCutAllowed = !pDescrCell->GetSelected().isEmpty();
                break;
            case HELPTEXT:
                bIsCutAllowed = !pHelpTextCell->GetSelected().isEmpty();
                break;
            case NAME:
                bIsCutAllowed = !pNameCell->GetSelected().isEmpty();
                break;
            case ROW:
                bIsCutAllowed = IsCopyAllowed();
                break;
            default:
                bIsCutAllowed = false;
                break;
        }
    }

    return bIsCutAllowed;
}

bool OTableEditorCtrl::IsCopyAllowed()
{
    bool bIsCopyAllowed = false;
    if(m_eChildFocus == DESCRIPTION )
        bIsCopyAllowed = !pDescrCell->GetSelected().isEmpty();
    else if(HELPTEXT == m_eChildFocus )
        bIsCopyAllowed = !pHelpTextCell->GetSelected().isEmpty();
    else if(m_eChildFocus == NAME)
        bIsCopyAllowed = !pNameCell->GetSelected().isEmpty();
    else if(m_eChildFocus == ROW)
    {
        Reference<XPropertySet> xTable = GetView()->getController().getTable();
        if( !GetSelectRowCount() || (xTable.is() && ::comphelper::getString(xTable->getPropertyValue(PROPERTY_TYPE)) == "VIEW"))
            return false;

        // If one of the selected rows is empty, Copy is not possible
        std::shared_ptr<OTableRow>  pRow;
        long nIndex = FirstSelectedRow();
        while( nIndex != SFX_ENDOFSELECTION )
        {
            pRow = (*m_pRowList)[nIndex];
            if( !pRow->GetActFieldDescr() )
                return false;

            nIndex = NextSelectedRow();
        }

        bIsCopyAllowed = true;
    }

    return bIsCopyAllowed;
}

bool OTableEditorCtrl::IsPasteAllowed() const
{
    bool bAllowed = GetView()->getController().isAddAllowed();
    if ( bAllowed )
    {
        TransferableDataHelper aTransferData(TransferableDataHelper::CreateFromSystemClipboard(GetParent()));
        bool bRowFormat = aTransferData.HasFormat(SotClipboardFormatId::SBA_TABED);
        if ( m_eChildFocus == ROW )
            bAllowed = bRowFormat;
        else
            bAllowed = !bRowFormat && aTransferData.HasFormat(SotClipboardFormatId::STRING);
    }

    return bAllowed;
}

void OTableEditorCtrl::cut()
{
    if(m_eChildFocus == NAME)
    {
        if(GetView()->getController().isAlterAllowed())
        {
            SaveData(-1,FIELD_NAME);
            pNameCell->Cut();
            CellModified(-1,FIELD_NAME);
        }
    }
    else if(m_eChildFocus == DESCRIPTION)
    {
        if(GetView()->getController().isAlterAllowed())
        {
            SaveData(-1,COLUMN_DESCRIPTION);
            pDescrCell->Cut();
            CellModified(-1,COLUMN_DESCRIPTION);
        }
    }
    else if(HELPTEXT == m_eChildFocus )
    {
        if(GetView()->getController().isAlterAllowed())
        {
            SaveData(-1,HELP_TEXT);
            pHelpTextCell->Cut();
            CellModified(-1,HELP_TEXT);
        }
    }
    else if(m_eChildFocus == ROW)
    {
        if (nCutEvent)
            Application::RemoveUserEvent(nCutEvent);
        nCutEvent = Application::PostUserEvent(LINK(this, OTableEditorCtrl, DelayedCut), nullptr, true);
    }
}

void OTableEditorCtrl::copy()
{
    if(GetSelectRowCount())
        OTableRowView::copy();
    else if(m_eChildFocus == NAME)
        pNameCell->Copy();
    else if(HELPTEXT == m_eChildFocus )
        pHelpTextCell->Copy();
    else if(m_eChildFocus == DESCRIPTION )
        pDescrCell->Copy();
}

void OTableEditorCtrl::paste()
{
    TransferableDataHelper aTransferData(TransferableDataHelper::CreateFromSystemClipboard(GetParent()));
    if(aTransferData.HasFormat(SotClipboardFormatId::SBA_TABED))
    {
        if( nPasteEvent )
            Application::RemoveUserEvent( nPasteEvent );
        nPasteEvent = Application::PostUserEvent( LINK(this, OTableEditorCtrl, DelayedPaste), nullptr, true );
    }
    else if(m_eChildFocus == NAME)
    {
        if(GetView()->getController().isAlterAllowed())
        {
            pNameCell->Paste();
            CellModified();
        }
    }
    else if(HELPTEXT == m_eChildFocus )
    {
        if(GetView()->getController().isAlterAllowed())
        {
            pHelpTextCell->Paste();
            CellModified();
        }
    }
    else if(m_eChildFocus == DESCRIPTION)
    {
        if(GetView()->getController().isAlterAllowed())
        {
            pDescrCell->Paste();
            CellModified();
        }
    }
}

bool OTableEditorCtrl::IsDeleteAllowed()
{

    return GetSelectRowCount() != 0 && GetView()->getController().isDropAllowed();
}

bool OTableEditorCtrl::IsInsertNewAllowed( long nRow )
{

    bool bInsertNewAllowed = GetView()->getController().isAddAllowed();
    // If fields can be added, Paste in the new fields
    if (bInsertNewAllowed && !GetView()->getController().isDropAllowed())
    {
        SetDataPtr(nRow);
        if( GetActRow()->IsReadOnly() )
            return false;
    }

    return bInsertNewAllowed;
}

bool OTableEditorCtrl::IsPrimaryKeyAllowed()
{
    if( !GetSelectRowCount() )
        return false;

    OTableController& rController = GetView()->getController();
    if ( !rController.getSdbMetaData().supportsPrimaryKeys() )
        return false;

    Reference<XPropertySet> xTable = rController.getTable();
    // Key must not be changed
    // This applies only if the table is not new and not a  css::sdbcx::View. Otherwise no DROP is executed

    if(xTable.is() && ::comphelper::getString(xTable->getPropertyValue(PROPERTY_TYPE)) == "VIEW")
        return false;
    // If there is an empty field, no primary key
    // The entry is only permitted if
    // - there are no empty entries in the selection
    // - No Memo or Image entries
    // - DROP is not permitted (see above) and the column is not Required (not null flag is not set).
    long nIndex = FirstSelectedRow();
    std::shared_ptr<OTableRow>  pRow;
    while( nIndex != SFX_ENDOFSELECTION )
    {
        pRow = (*m_pRowList)[nIndex];
        OFieldDescription* pFieldDescr = pRow->GetActFieldDescr();
        if(!pFieldDescr)
            return false;
        else
        {
            // Memo and Image fields cannot be primary keys
            // or if the column cannot be dropped and the Required flag is not set
            // or if a css::sdbcx::View is available and the Required flag is not set
            const TOTypeInfoSP& pTypeInfo = pFieldDescr->getTypeInfo();
            if(     pTypeInfo->nSearchType == ColumnSearch::NONE
                || (pFieldDescr->IsNullable() && pRow->IsReadOnly())
              )
                return false;
        }

        nIndex = NextSelectedRow();
    }

    return true;
}

void OTableEditorCtrl::Command(const CommandEvent& rEvt)
{
    switch (rEvt.GetCommand())
    {
        case CommandEventId::ContextMenu:
        {
            Point aMenuPos( rEvt.GetMousePosPixel() );
            if (!rEvt.IsMouseEvent())
            {
                if  ( 1 == GetSelectColumnCount() )
                {
                    sal_uInt16 nSelId = GetColumnId(
                        sal::static_int_cast< sal_uInt16 >(
                            FirstSelectedColumn() ) );
                    ::tools::Rectangle aColRect( GetFieldRectPixel( 0, nSelId, false ) );

                    aMenuPos = aColRect.TopCenter();
                }
                else if ( GetSelectRowCount() > 0 )
                {
                    ::tools::Rectangle aColRect( GetFieldRectPixel( FirstSelectedRow(), HANDLE_ID ) );

                    aMenuPos = aColRect.TopCenter();
                }
                else
                {
                    OTableRowView::Command(rEvt);
                    return;
                }
            }

            // Show the Context menu
            if( !IsReadOnly() )
            {
                sal_uInt16 nColId = GetColumnId(GetColumnAtXPosPixel(aMenuPos.X()));
                long   nRow = GetRowAtYPosPixel(aMenuPos.Y());

                if ( HANDLE_ID != nColId )
                {
                    if ( nRow < 0 && nColId != BROWSER_INVALIDID )
                    {   // hit the header
                        if ( 3 != nColId )
                        {   // 3 would mean the last column, and this last column is auto-sized
                            if ( !IsColumnSelected( nColId ) )
                                SelectColumnId( nColId );

                            VclBuilder aBuilder(nullptr, VclBuilderContainer::getUIRootDir(), "dbaccess/ui/querycolmenu.ui", "");
                            VclPtr<PopupMenu> aContextMenu(aBuilder.get_menu("menu"));
                            aContextMenu->EnableItem(aContextMenu->GetItemId("delete"), false);
                            aContextMenu->RemoveDisabledEntries(true, true);
                            if (aContextMenu->Execute(this, aMenuPos) == aContextMenu->GetItemId("width"))
                                adjustBrowseBoxColumnWidth( this, nColId );
                        }
                    }
                }
                else
                {
                    VclBuilder aBuilder(nullptr, VclBuilderContainer::getUIRootDir(), "dbaccess/ui/tabledesignrowmenu.ui", "");
                    VclPtr<PopupMenu> aContextMenu(aBuilder.get_menu("menu"));

                    aContextMenu->EnableItem(aContextMenu->GetItemId("cut"), IsCutAllowed());
                    aContextMenu->EnableItem(aContextMenu->GetItemId("copy"), IsCopyAllowed());
                    aContextMenu->EnableItem(aContextMenu->GetItemId("paste"), IsPasteAllowed());
                    aContextMenu->EnableItem(aContextMenu->GetItemId("delete"), IsDeleteAllowed());
                    aContextMenu->EnableItem(aContextMenu->GetItemId("primarykey"), IsPrimaryKeyAllowed());
                    aContextMenu->EnableItem(aContextMenu->GetItemId("insert"), IsInsertNewAllowed(nRow));
                    aContextMenu->CheckItem("primarykey", IsRowSelected(GetCurRow()) && IsPrimaryKey());

                    // remove all the disable entries
                    aContextMenu->RemoveDisabledEntries(true, true);

                    if( SetDataPtr(m_nDataPos) )
                        pDescrWin->SaveData( pActRow->GetActFieldDescr() );

                    // All actions which change the number of rows must be run asynchronously
                    // otherwise there may be problems between the Context menu and the Browser
                    m_nDataPos = GetCurRow();
                    aContextMenu->Execute(this, aMenuPos);
                    OString sIdent = aContextMenu->GetCurItemIdent();
                    if (sIdent == "cut")
                        cut();
                    else if (sIdent == "copy")
                        copy();
                    else if (sIdent == "paste")
                        paste();
                    else if (sIdent == "delete")
                    {
                        if( nDeleteEvent )
                            Application::RemoveUserEvent( nDeleteEvent );
                        nDeleteEvent = Application::PostUserEvent( LINK(this, OTableEditorCtrl, DelayedDelete), nullptr, true );
                    }
                    else if (sIdent == "insert")
                    {
                        if( nInsNewRowsEvent )
                            Application::RemoveUserEvent( nInsNewRowsEvent );
                        nInsNewRowsEvent = Application::PostUserEvent( LINK(this, OTableEditorCtrl, DelayedInsNewRows), nullptr, true );
                    }
                    else if (sIdent == "primarykey")
                    {
                        SetPrimaryKey( !IsPrimaryKey() );
                    }
                }
            }
        }
        break;
        default:
            OTableRowView::Command(rEvt);
    }

}

IMPL_LINK_NOARG( OTableEditorCtrl, DelayedCut, void*, void )
{
    nCutEvent = nullptr;
    OTableRowView::cut();
}

IMPL_LINK_NOARG( OTableEditorCtrl, DelayedPaste, void*, void )
{
    nPasteEvent = nullptr;

    sal_Int32 nPastePosition = GetView()->getController().getFirstEmptyRowPosition();
    if ( !GetView()->getController().getTable().is() )
        nPastePosition = GetSelectRowCount() ? FirstSelectedRow() : GetCurRow();

    if (!IsInsertNewAllowed(nPastePosition))
    {   // Insertion is not allowed, only appending, so test if there are full cells after the PastePosition

        auto aIter = std::find_if(m_pRowList->rbegin(), m_pRowList->rend(), [](const std::shared_ptr<OTableRow>& rxRow) {
            return rxRow && rxRow->GetActFieldDescr() && !rxRow->GetActFieldDescr()->GetName().isEmpty(); });
        auto nFreeFromPos = static_cast<sal_Int32>(std::distance(aIter, m_pRowList->rend())); // from here on there are only empty rows
        if (nPastePosition < nFreeFromPos)  // if at least one PastePosition is full, go right to the end
            nPastePosition = nFreeFromPos;
    }

    OTableRowView::Paste( nPastePosition );
    SetNoSelection();
    GoToRow( nPastePosition );
}

IMPL_LINK_NOARG( OTableEditorCtrl, DelayedDelete, void*, void )
{
    nDeleteEvent = nullptr;
    DeleteRows();
}

IMPL_LINK_NOARG( OTableEditorCtrl, DelayedInsNewRows, void*, void )
{
    nInsNewRowsEvent = nullptr;
    sal_Int32 nPastePosition = GetView()->getController().getFirstEmptyRowPosition();
    if ( !GetView()->getController().getTable().is() )
        nPastePosition = GetSelectRowCount() ? FirstSelectedRow() : m_nDataPos;

    InsertNewRows( nPastePosition );
    SetNoSelection();
    GoToRow( nPastePosition );
}

void OTableEditorCtrl::AdjustFieldDescription(OFieldDescription* _pFieldDesc,
                                         MultiSelection& _rMultiSel,
                                         sal_Int32 _nPos,
                                         bool _bSet,
                                         bool _bPrimaryKey)
{
    _pFieldDesc->SetPrimaryKey( _bPrimaryKey );
    if(!_bSet && _pFieldDesc->getTypeInfo()->bNullable)
    {
        _pFieldDesc->SetIsNullable(ColumnValue::NO_NULLS);
        _pFieldDesc->SetControlDefault(Any());
    }
    if ( _pFieldDesc->IsAutoIncrement() && !_bPrimaryKey )
    {
        OTableController& rController = GetView()->getController();
        if ( rController.isAutoIncrementPrimaryKey() )
        {
            _pFieldDesc->SetAutoIncrement(false);
        }
    }
    // update field description
    pDescrWin->DisplayData(_pFieldDesc);

    _rMultiSel.Insert( _nPos );
    _rMultiSel.Select( _nPos );
}

void OTableEditorCtrl::SetPrimaryKey( bool bSet )
{
    // Delete any existing Primary Keys
    MultiSelection aDeletedPrimKeys;
    aDeletedPrimKeys.SetTotalRange( Range(0,GetRowCount()) );

    sal_Int32 nRow = 0;
    for (auto const& row : *m_pRowList)
    {
        OFieldDescription* pFieldDescr = row->GetActFieldDescr();
        if( pFieldDescr && row->IsPrimaryKey() && (!bSet || !IsRowSelected(nRow)) )
        {
            AdjustFieldDescription(pFieldDescr,aDeletedPrimKeys,nRow,bSet,false);
        }
        ++nRow;
    }

    // Set the primary keys of the marked rows
    MultiSelection aInsertedPrimKeys;
    aInsertedPrimKeys.SetTotalRange( Range(0,GetRowCount()) );
    if( bSet )
    {
        long nIndex = FirstSelectedRow();
        while( nIndex != SFX_ENDOFSELECTION )
        {
            // Set the key
            std::shared_ptr<OTableRow>  pRow = (*m_pRowList)[nIndex];
            OFieldDescription* pFieldDescr = pRow->GetActFieldDescr();
            if(pFieldDescr)
                AdjustFieldDescription(pFieldDescr,aInsertedPrimKeys,nIndex,false,true);

            nIndex = NextSelectedRow();
        }
    }

    GetUndoManager().AddUndoAction( std::make_unique<OPrimKeyUndoAct>(this, aDeletedPrimKeys, aInsertedPrimKeys) );

    // Invalidate the handle-columns
    InvalidateHandleColumn();

    // Set the TableDocSh's ModifyFlag
    GetView()->getController().setModified( true );
    InvalidateFeatures();
}

bool OTableEditorCtrl::IsPrimaryKey()
{
    // Are all marked fields part of the Primary Key ?
    long nPrimaryKeys = 0;
    sal_Int32 nRow=0;
    for (auto const& row : *m_pRowList)
    {
        if( IsRowSelected(nRow) && !row->IsPrimaryKey() )
            return false;
        if( row->IsPrimaryKey() )
            ++nPrimaryKeys;
        ++nRow;
    }

    // Are there any unselected fields that are part of the Key ?
    return GetSelectRowCount() == nPrimaryKeys;
}

void OTableEditorCtrl::SwitchType( const TOTypeInfoSP& _pType )
{
    // if there is no assigned field name
    long nRow(GetCurRow());
    OFieldDescription* pActFieldDescr = GetFieldDescr( nRow );
    if( pActFieldDescr )
        // Store the old description
        pDescrWin->SaveData( pActFieldDescr );

    if ( nRow < 0 || nRow > static_cast<long>(m_pRowList->size()) )
        return;
    // Show the new description
    std::shared_ptr<OTableRow>  pRow = (*m_pRowList)[nRow];
    pRow->SetFieldType( _pType, true );
    if ( _pType.get() )
    {
        const sal_Int32 nCurrentlySelected = pTypeCell->GetSelectedEntryPos();

        if  (   ( LISTBOX_ENTRY_NOTFOUND == nCurrentlySelected )
            ||  ( GetView()->getController().getTypeInfo( nCurrentlySelected ) != _pType )
            )
        {
            sal_Int32 nEntryPos = 0;
            const OTypeInfoMap& rTypeInfo = GetView()->getController().getTypeInfo();
            for (auto const& elem : rTypeInfo)
            {
                if(elem.second == _pType)
                    break;
                ++nEntryPos;
            }
            if (nEntryPos < pTypeCell->GetEntryCount())
                pTypeCell->SelectEntryPos( nEntryPos );
        }
    }

    pActFieldDescr = pRow->GetActFieldDescr();
    if (pActFieldDescr != nullptr && !pActFieldDescr->GetFormatKey())
    {
        sal_Int32 nFormatKey = ::dbtools::getDefaultNumberFormat( pActFieldDescr->GetType(),
            pActFieldDescr->GetScale(),
            pActFieldDescr->IsCurrency(),
            Reference< XNumberFormatTypes>(GetView()->getController().getNumberFormatter()->getNumberFormatsSupplier()->getNumberFormats(),UNO_QUERY),
            GetView()->getLocale());

        pActFieldDescr->SetFormatKey(nFormatKey);
    }

    pDescrWin->DisplayData( pActFieldDescr );
}

OTableDesignView* OTableEditorCtrl::GetView() const
{
    return static_cast<OTableDesignView*>(GetParent()->GetParent());
}

void OTableEditorCtrl::DeactivateCell(bool bUpdate)
{
    OTableRowView::DeactivateCell(bUpdate);
    // now we have to deactivate the field description
    long nRow(GetCurRow());
    if (pDescrWin)
        pDescrWin->SetReadOnly(bReadOnly || !SetDataPtr(nRow) || GetActRow()->IsReadOnly());
}

bool OTableEditorCtrl::PreNotify( NotifyEvent& rNEvt )
{
    if (rNEvt.GetType() == MouseNotifyEvent::GETFOCUS)
    {
        if( pHelpTextCell && pHelpTextCell->HasChildPathFocus() )
            m_eChildFocus = HELPTEXT;
        else if( pDescrCell && pDescrCell->HasChildPathFocus() )
            m_eChildFocus = DESCRIPTION;
        else if(pNameCell && pNameCell->HasChildPathFocus() )
            m_eChildFocus = NAME;
        else
            m_eChildFocus = ROW;
    }

    return OTableRowView::PreNotify(rNEvt);
}

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