1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
/* -*- 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 <memory>
#include <filtnav.hxx>
#include <fmexch.hxx>
#include <helpids.h>
#include <fmprop.hxx>
#include <svx/strings.hrc>

#include <com/sun/star/awt/XControl.hpp>
#include <com/sun/star/form/runtime/XFormController.hpp>
#include <com/sun/star/util/NumberFormatter.hpp>
#include <com/sun/star/sdb/SQLContext.hpp>

#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>
#include <connectivity/dbtools.hxx>
#include <connectivity/sqlnode.hxx>
#include <cppuhelper/implbase.hxx>
#include <i18nlangtag/languagetag.hxx>
#include <fmshimp.hxx>
#include <o3tl/safeint.hxx>
#include <sfx2/objitem.hxx>
#include <sfx2/request.hxx>
#include <svx/dialmgr.hxx>
#include <svx/fmshell.hxx>
#include <svx/fmtools.hxx>
#include <svx/svxids.hrc>
#include <vcl/settings.hxx>
#include <tools/diagnose_ex.h>
#include <vcl/commandevent.hxx>
#include <vcl/event.hxx>
#include <vcl/svlbitm.hxx>
#include <vcl/treelistentry.hxx>
#include <vcl/viewdataentry.hxx>
#include <vcl/svapp.hxx>

#include <bitmaps.hlst>

#include <functional>

#define DROP_ACTION_TIMER_INITIAL_TICKS     10
    // it takes this long for the scrolling to begin
#define DROP_ACTION_TIMER_SCROLL_TICKS      3
    // a line is scrolled in these intervals
#define DROP_ACTION_TIMER_TICK_BASE         10
    // this is the basis for multiplying both figures (in ms)

using namespace ::svxform;
using namespace ::connectivity;
using namespace ::dbtools;


namespace svxform
{


    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::container::XIndexAccess;
    using ::com::sun::star::uno::UNO_QUERY;
    using ::com::sun::star::beans::XPropertySet;
    using ::com::sun::star::form::runtime::XFormController;
    using ::com::sun::star::form::runtime::XFilterController;
    using ::com::sun::star::form::runtime::XFilterControllerListener;
    using ::com::sun::star::form::runtime::FilterEvent;
    using ::com::sun::star::lang::EventObject;
    using ::com::sun::star::form::XForm;
    using ::com::sun::star::container::XChild;
    using ::com::sun::star::awt::XControl;
    using ::com::sun::star::sdbc::XConnection;
    using ::com::sun::star::util::XNumberFormatsSupplier;
    using ::com::sun::star::util::XNumberFormatter;
    using ::com::sun::star::util::NumberFormatter;
    using ::com::sun::star::sdbc::XRowSet;
    using ::com::sun::star::lang::Locale;
    using ::com::sun::star::sdb::SQLContext;
    using ::com::sun::star::uno::XInterface;
    using ::com::sun::star::uno::UNO_QUERY_THROW;
    using ::com::sun::star::uno::UNO_SET_THROW;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::Sequence;


OFilterItemExchange::OFilterItemExchange()
    : m_pFormItem(nullptr)
{
}

void OFilterItemExchange::AddSupportedFormats()
{
    AddFormat(getFormatId());
}


SotClipboardFormatId OFilterItemExchange::getFormatId()
{
    static SotClipboardFormatId s_nFormat =
         SotExchange::RegisterFormatName("application/x-openoffice;windows_formatname=\"form.FilterControlExchange\"");
    DBG_ASSERT(static_cast<SotClipboardFormatId>(-1) != s_nFormat, "OFilterExchangeHelper::getFormatId: bad exchange id!");
    return s_nFormat;
}


OLocalExchange* OFilterExchangeHelper::createExchange() const
{
    return new OFilterItemExchange;
}


Image FmFilterData::GetImage() const
{
    return Image();
}

FmParentData::~FmParentData()
{
}

Image FmFormItem::GetImage() const
{
    return Image(StockImage::Yes, RID_SVXBMP_FORM);
}

FmFilterItem* FmFilterItems::Find( const ::sal_Int32 _nFilterComponentIndex ) const
{
    for ( auto & pData : m_aChildren )
    {
        FmFilterItem& rCondition = dynamic_cast<FmFilterItem&>(*pData);
        if ( _nFilterComponentIndex == rCondition.GetComponentIndex() )
            return &rCondition;
    }
    return nullptr;
}

Image FmFilterItems::GetImage() const
{
    return Image(StockImage::Yes, RID_SVXBMP_FILTER);
}

FmFilterItem::FmFilterItem( FmFilterItems* pParent,
                            const OUString& aFieldName,
                            const OUString& aText,
                            const sal_Int32 _nComponentIndex )
          :FmFilterData(pParent, aText)
          ,m_aFieldName(aFieldName)
          ,m_nComponentIndex( _nComponentIndex )
{
}

Image FmFilterItem::GetImage() const
{
    return Image(StockImage::Yes, RID_SVXBMP_FIELD);
}

// Hints for communication between model and view

namespace {

class FmFilterHint : public SfxHint
{
    FmFilterData*   m_pData;

public:
    explicit FmFilterHint(FmFilterData* pData):m_pData(pData){}
    FmFilterData* GetData() const { return m_pData; }
};

class FmFilterInsertedHint : public FmFilterHint
{
    size_t m_nPos;   // Position relative to the parent of the data

public:
    FmFilterInsertedHint(FmFilterData* pData, size_t nRelPos)
        :FmFilterHint(pData)
        ,m_nPos(nRelPos){}

    size_t GetPos() const { return m_nPos; }
};

class FmFilterRemovedHint : public FmFilterHint
{
public:
    explicit FmFilterRemovedHint(FmFilterData* pData)
        :FmFilterHint(pData){}
};


class FmFilterTextChangedHint : public FmFilterHint
{
public:
    explicit FmFilterTextChangedHint(FmFilterData* pData)
        :FmFilterHint(pData){}
};

class FilterClearingHint : public SfxHint
{
public:
    FilterClearingHint(){}
};

class FmFilterCurrentChangedHint : public SfxHint
{
public:
    FmFilterCurrentChangedHint(){}
};

}

// class FmFilterAdapter, listener at the FilterControls
class FmFilterAdapter : public ::cppu::WeakImplHelper< XFilterControllerListener >
{
    FmFilterModel*              m_pModel;
    Reference< XIndexAccess >   m_xControllers;

public:
    FmFilterAdapter(FmFilterModel* pModel, const Reference< XIndexAccess >& xControllers);

// XEventListener
    virtual void SAL_CALL disposing(const EventObject& Source) override;

// XFilterControllerListener
    virtual void SAL_CALL predicateExpressionChanged( const FilterEvent& Event ) override;
    virtual void SAL_CALL disjunctiveTermRemoved( const FilterEvent& Event ) override;
    virtual void SAL_CALL disjunctiveTermAdded( const FilterEvent& Event ) override;

// helpers
    /// @throws RuntimeException
    void dispose();

    void AddOrRemoveListener( const Reference< XIndexAccess >& _rxControllers, const bool _bAdd );

    static void setText(sal_Int32 nPos,
        const FmFilterItem* pFilterItem,
        const OUString& rText);
};


FmFilterAdapter::FmFilterAdapter(FmFilterModel* pModel, const Reference< XIndexAccess >& xControllers)
    :m_pModel( pModel )
    ,m_xControllers( xControllers )
{
    AddOrRemoveListener( m_xControllers, true );
}


void FmFilterAdapter::dispose()
{
    AddOrRemoveListener( m_xControllers, false );
}


void FmFilterAdapter::AddOrRemoveListener( const Reference< XIndexAccess >& _rxControllers, const bool _bAdd )
{
    for (sal_Int32 i = 0, nLen = _rxControllers->getCount(); i < nLen; ++i)
    {
        Reference< XIndexAccess > xElement( _rxControllers->getByIndex(i), UNO_QUERY );

        // step down
        AddOrRemoveListener( xElement, _bAdd );

        // handle this particular controller
        Reference< XFilterController > xController( xElement, UNO_QUERY );
        OSL_ENSURE( xController.is(), "FmFilterAdapter::InsertElements: no XFilterController, cannot sync data!" );
        if ( xController.is() )
        {
            if ( _bAdd )
                xController->addFilterControllerListener( this );
            else
                xController->removeFilterControllerListener( this );
        }
    }
}


void FmFilterAdapter::setText(sal_Int32 nRowPos,
                              const FmFilterItem* pFilterItem,
                              const OUString& rText)
{
    FmFormItem* pFormItem = dynamic_cast<FmFormItem*>( pFilterItem->GetParent()->GetParent()  );
    assert(pFormItem);
    try
    {
        Reference< XFilterController > xController( pFormItem->GetController(), UNO_QUERY_THROW );
        xController->setPredicateExpression( pFilterItem->GetComponentIndex(), nRowPos, rText );
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("svx");
    }
}


// XEventListener

void SAL_CALL FmFilterAdapter::disposing(const EventObject& /*e*/)
{
}


namespace
{
    OUString lcl_getLabelName_nothrow( const Reference< XControl >& _rxControl )
    {
        OUString sLabelName;
        try
        {
            Reference< XPropertySet > xModel( _rxControl->getModel(), UNO_QUERY_THROW );
            sLabelName = getLabelName( xModel );
        }
        catch( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION("svx");
        }
        return sLabelName;
    }

    Reference< XPropertySet > lcl_getBoundField_nothrow( const Reference< XControl >& _rxControl )
    {
        Reference< XPropertySet > xField;
        try
        {
            Reference< XPropertySet > xModelProps( _rxControl->getModel(), UNO_QUERY_THROW );
            xField.set( xModelProps->getPropertyValue( FM_PROP_BOUNDFIELD ), UNO_QUERY_THROW );
        }
        catch( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION("svx");
        }
        return xField;
    }
}

// XFilterControllerListener

void FmFilterAdapter::predicateExpressionChanged( const FilterEvent& Event )
{
    SolarMutexGuard aGuard;

    if ( !m_pModel )
        return;

    // the controller which sent the event
    Reference< XFormController > xController( Event.Source, UNO_QUERY_THROW );
    Reference< XFilterController > xFilterController( Event.Source, UNO_QUERY_THROW );
    Reference< XForm > xForm( xController->getModel(), UNO_QUERY_THROW );

    FmFormItem* pFormItem = m_pModel->Find( m_pModel->m_aChildren, xForm );
    OSL_ENSURE( pFormItem, "FmFilterAdapter::predicateExpressionChanged: don't know this form!" );
    if ( !pFormItem )
        return;

    const sal_Int32 nActiveTerm( xFilterController->getActiveTerm() );

    FmFilterData* pData = pFormItem->GetChildren()[nActiveTerm].get();
    FmFilterItems& rFilter = dynamic_cast<FmFilterItems&>(*pData);
    FmFilterItem* pFilterItem = rFilter.Find( Event.FilterComponent );
    if ( pFilterItem )
    {
        if ( !Event.PredicateExpression.isEmpty())
        {
            pFilterItem->SetText( Event.PredicateExpression );
            // notify the UI
            FmFilterTextChangedHint aChangeHint(pFilterItem);
            m_pModel->Broadcast( aChangeHint );
        }
        else
        {
            // no text anymore so remove the condition
            m_pModel->Remove(pFilterItem);
        }
    }
    else
    {
        // searching the component by field name
        OUString aFieldName( lcl_getLabelName_nothrow( xFilterController->getFilterComponent( Event.FilterComponent ) ) );

        std::unique_ptr<FmFilterItem> pNewFilterItem(new FmFilterItem(&rFilter, aFieldName, Event.PredicateExpression, Event.FilterComponent));
        m_pModel->Insert(rFilter.GetChildren().end(), std::move(pNewFilterItem));
    }

    // ensure there's one empty term in the filter, just in case the active term was previously empty
    m_pModel->EnsureEmptyFilterRows( *pFormItem );
}


void SAL_CALL FmFilterAdapter::disjunctiveTermRemoved( const FilterEvent& Event )
{
    SolarMutexGuard aGuard;

    Reference< XFormController > xController( Event.Source, UNO_QUERY_THROW );
    Reference< XFilterController > xFilterController( Event.Source, UNO_QUERY_THROW );
    Reference< XForm > xForm( xController->getModel(), UNO_QUERY_THROW );

    FmFormItem* pFormItem = m_pModel->Find( m_pModel->m_aChildren, xForm );
    OSL_ENSURE( pFormItem, "FmFilterAdapter::disjunctiveTermRemoved: don't know this form!" );
    if ( !pFormItem )
        return;

    auto& rTermItems = pFormItem->GetChildren();
    const bool bValidIndex = ( Event.DisjunctiveTerm >= 0 ) && ( o3tl::make_unsigned(Event.DisjunctiveTerm) < rTermItems.size() );
    OSL_ENSURE( bValidIndex, "FmFilterAdapter::disjunctiveTermRemoved: invalid term index!" );
    if ( !bValidIndex )
        return;

    // if the first term was removed, then the to-be first term needs its text updated
    if ( Event.DisjunctiveTerm == 0 )
    {
        rTermItems[1]->SetText( SvxResId(RID_STR_FILTER_FILTER_FOR));
        FmFilterTextChangedHint aChangeHint( rTermItems[1].get() );
        m_pModel->Broadcast( aChangeHint );
    }

    // finally remove the entry from the model
    m_pModel->Remove( rTermItems.begin() + Event.DisjunctiveTerm );

    // ensure there's one empty term in the filter, just in case the currently removed one was the last empty one
    m_pModel->EnsureEmptyFilterRows( *pFormItem );
}


void SAL_CALL FmFilterAdapter::disjunctiveTermAdded( const FilterEvent& Event )
{
    SolarMutexGuard aGuard;

    Reference< XFormController > xController( Event.Source, UNO_QUERY_THROW );
    Reference< XFilterController > xFilterController( Event.Source, UNO_QUERY_THROW );
    Reference< XForm > xForm( xController->getModel(), UNO_QUERY_THROW );

    FmFormItem* pFormItem = m_pModel->Find( m_pModel->m_aChildren, xForm );
    OSL_ENSURE( pFormItem, "FmFilterAdapter::disjunctiveTermAdded: don't know this form!" );
    if ( !pFormItem )
        return;

    const sal_Int32 nInsertPos = Event.DisjunctiveTerm;
    bool bValidIndex = ( nInsertPos >= 0 ) && ( o3tl::make_unsigned(nInsertPos) <= pFormItem->GetChildren().size() );
    if ( !bValidIndex )
    {
        OSL_FAIL( "FmFilterAdapter::disjunctiveTermAdded: invalid index!" );
        return;
    }

    auto insertPos = pFormItem->GetChildren().begin() + nInsertPos;

    // "Filter for" for first position, "Or" for the other positions
    std::unique_ptr<FmFilterItems> pFilterItems(new FmFilterItems(pFormItem, (nInsertPos?SvxResId(RID_STR_FILTER_FILTER_OR):SvxResId(RID_STR_FILTER_FILTER_FOR))));
    m_pModel->Insert( insertPos, std::move(pFilterItems) );
}


FmFilterModel::FmFilterModel()
              :FmParentData(nullptr, OUString())
              ,OSQLParserClient(comphelper::getProcessComponentContext())
              ,m_pCurrentItems(nullptr)
{
}


FmFilterModel::~FmFilterModel()
{
    Clear();
}


void FmFilterModel::Clear()
{
    // notify
    FilterClearingHint aClearedHint;
    Broadcast( aClearedHint );

    // lose endings
    if (m_pAdapter.is())
    {
        m_pAdapter->dispose();
        m_pAdapter.clear();
    }

    m_pCurrentItems  = nullptr;
    m_xController    = nullptr;
    m_xControllers   = nullptr;

    m_aChildren.clear();
}


void FmFilterModel::Update(const Reference< XIndexAccess > & xControllers, const Reference< XFormController > & xCurrent)
{
    if ( xCurrent == m_xController )
        return;

    if (!xControllers.is())
    {
        Clear();
        return;
    }

    // there is only a new current controller
    if ( m_xControllers != xControllers )
    {
        Clear();

        m_xControllers = xControllers;
        Update(m_xControllers, this);

        DBG_ASSERT(xCurrent.is(), "FmFilterModel::Update(...) no current controller");

        // Listening for TextChanges
        m_pAdapter = new FmFilterAdapter(this, xControllers);

        SetCurrentController(xCurrent);
        EnsureEmptyFilterRows( *this );
    }
    else
        SetCurrentController(xCurrent);
}


void FmFilterModel::Update(const Reference< XIndexAccess > & xControllers, FmParentData* pParent)
{
    try
    {
        sal_Int32 nCount = xControllers->getCount();
        for ( sal_Int32 i = 0; i < nCount; ++i )
        {
            Reference< XFormController > xController( xControllers->getByIndex(i), UNO_QUERY_THROW );

            Reference< XPropertySet > xFormProperties( xController->getModel(), UNO_QUERY_THROW );
            OUString aName;
            OSL_VERIFY( xFormProperties->getPropertyValue( FM_PROP_NAME ) >>= aName );

            // Insert a new item for the form
            FmFormItem* pFormItem = new FmFormItem( pParent, xController, aName );
            Insert( pParent->GetChildren().end(), std::unique_ptr<FmFilterData>(pFormItem) );

            Reference< XFilterController > xFilterController( pFormItem->GetFilterController(), UNO_SET_THROW );

            // insert the existing filters for the form
            OUString aTitle(SvxResId(RID_STR_FILTER_FILTER_FOR));

            const Sequence< Sequence< OUString > > aExpressions = xFilterController->getPredicateExpressions();
            for ( auto const & conjunctionTerm : aExpressions )
            {
                // we always display one row, even if there's no term to be displayed
                FmFilterItems* pFilterItems = new FmFilterItems( pFormItem, aTitle );
                Insert( pFormItem->GetChildren().end(), std::unique_ptr<FmFilterData>(pFilterItems) );

                const Sequence< OUString >& rDisjunction( conjunctionTerm );
                sal_Int32 nComponentIndex = -1;
                for ( const OUString& rDisjunctiveTerm : rDisjunction )
                {
                    ++nComponentIndex;

                    if ( rDisjunctiveTerm.isEmpty() )
                        // no condition for this particular component in this particular conjunction term
                        continue;

                    // determine the display name of the control
                    const Reference< XControl > xFilterControl( xFilterController->getFilterComponent( nComponentIndex ) );
                    const OUString sDisplayName( lcl_getLabelName_nothrow( xFilterControl ) );

                    // insert a new entry
                    std::unique_ptr<FmFilterItem> pANDCondition(new FmFilterItem( pFilterItems, sDisplayName, rDisjunctiveTerm, nComponentIndex ));
                    Insert( pFilterItems->GetChildren().end(), std::move(pANDCondition) );
                }

                // title for the next conditions
                aTitle = SvxResId( RID_STR_FILTER_FILTER_OR );
            }

            // now add dependent controllers
            Update( xController, pFormItem );
        }
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("svx");
    }
}


FmFormItem* FmFilterModel::Find(const ::std::vector<std::unique_ptr<FmFilterData>>& rItems, const Reference< XFormController > & xController) const
{
    for (const auto& rItem : rItems)
    {
        FmFormItem* pForm = dynamic_cast<FmFormItem*>( rItem.get() );
        if (pForm)
        {
            if ( xController == pForm->GetController() )
                return pForm;
            else
            {
                pForm = Find(pForm->GetChildren(), xController);
                if (pForm)
                    return pForm;
            }
        }
    }
    return nullptr;
}


FmFormItem* FmFilterModel::Find(const ::std::vector<std::unique_ptr<FmFilterData>>& rItems, const Reference< XForm >& xForm) const
{
    for (const auto& rItem : rItems)
    {
        FmFormItem* pForm = dynamic_cast<FmFormItem*>( rItem.get() );
        if (pForm)
        {
            if (xForm == pForm->GetController()->getModel())
                return pForm;
            else
            {
                pForm = Find(pForm->GetChildren(), xForm);
                if (pForm)
                    return pForm;
            }
        }
    }
    return nullptr;
}


void FmFilterModel::SetCurrentController(const Reference< XFormController > & xCurrent)
{
    if ( xCurrent == m_xController )
        return;

    m_xController = xCurrent;

    FmFormItem* pItem = Find( m_aChildren, xCurrent );
    if ( !pItem )
        return;

    try
    {
        Reference< XFilterController > xFilterController( m_xController, UNO_QUERY_THROW );
        const sal_Int32 nActiveTerm( xFilterController->getActiveTerm() );
        if ( pItem->GetChildren().size() > o3tl::make_unsigned(nActiveTerm) )
        {
            SetCurrentItems( static_cast< FmFilterItems* >( pItem->GetChildren()[ nActiveTerm ].get() ) );
        }
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("svx");
    }
}


void FmFilterModel::AppendFilterItems( FmFormItem& _rFormItem )
{
    // insert the condition behind the last filter items
    auto iter = std::find_if(_rFormItem.GetChildren().rbegin(), _rFormItem.GetChildren().rend(),
        [](const std::unique_ptr<FmFilterData>& rChild) { return dynamic_cast<const FmFilterItems*>(rChild.get()) != nullptr; });

    sal_Int32 nInsertPos = iter.base() - _rFormItem.GetChildren().begin();
    // delegate this to the FilterController, it will notify us, which will let us update our model
    try
    {
        Reference< XFilterController > xFilterController( _rFormItem.GetFilterController(), UNO_SET_THROW );
        if ( nInsertPos >= xFilterController->getDisjunctiveTerms() )
            xFilterController->appendEmptyDisjunctiveTerm();
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("svx");
    }
}

void FmFilterModel::Insert(const ::std::vector<std::unique_ptr<FmFilterData>>::iterator& rPos, std::unique_ptr<FmFilterData> pData)
{
    auto pTemp = pData.get();
    size_t nPos;
    ::std::vector<std::unique_ptr<FmFilterData>>& rItems = pData->GetParent()->GetChildren();
    if (rPos == rItems.end())
    {
        nPos = rItems.size();
        rItems.push_back(std::move(pData));
    }
    else
    {
        nPos = rPos - rItems.begin();
        rItems.insert(rPos, std::move(pData));
    }

    // notify the UI
    FmFilterInsertedHint aInsertedHint(pTemp, nPos);
    Broadcast( aInsertedHint );
}

void FmFilterModel::Remove(FmFilterData* pData)
{
    FmParentData* pParent = pData->GetParent();
    ::std::vector<std::unique_ptr<FmFilterData>>& rItems = pParent->GetChildren();

    // erase the item from the model
    auto i = ::std::find_if(rItems.begin(), rItems.end(),
            [&](const std::unique_ptr<FmFilterData>& p) { return p.get() == pData; } );
    DBG_ASSERT(i != rItems.end(), "FmFilterModel::Remove(): unknown Item");
    // position within the parent
    sal_Int32 nPos = i - rItems.begin();
    if (dynamic_cast<const FmFilterItems*>( pData) !=  nullptr)
    {
        FmFormItem* pFormItem = static_cast<FmFormItem*>(pParent);

        try
        {
            Reference< XFilterController > xFilterController( pFormItem->GetFilterController(), UNO_SET_THROW );

            bool bEmptyLastTerm = ( ( nPos == 0 ) && xFilterController->getDisjunctiveTerms() == 1 );
            if ( bEmptyLastTerm )
            {
                // remove all children (by setting an empty predicate expression)
                ::std::vector< std::unique_ptr<FmFilterData> >& rChildren = static_cast<FmFilterItems*>(pData)->GetChildren();
                while ( !rChildren.empty() )
                {
                    auto removePos = rChildren.end() - 1;
                    if (FmFilterItem* pFilterItem = dynamic_cast<FmFilterItem*>( removePos->get() ))
                    {
                        FmFilterAdapter::setText( nPos, pFilterItem, OUString() );
                    }
                    Remove( removePos );
                }
            }
            else
            {
                xFilterController->removeDisjunctiveTerm( nPos );
            }
        }
        catch( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION("svx");
        }
    }
    else // FormItems can not be deleted
    {
        FmFilterItem& rFilterItem = dynamic_cast<FmFilterItem&>(*pData);

        // if it's the last condition remove the parent
        if (rItems.size() == 1)
            Remove(rFilterItem.GetParent());
        else
        {
            // find the position of the father within his father
            ::std::vector<std::unique_ptr<FmFilterData>>& rParentParentItems = pData->GetParent()->GetParent()->GetChildren();
            auto j = ::std::find_if(rParentParentItems.begin(), rParentParentItems.end(),
                [&](const std::unique_ptr<FmFilterData>& p) { return p.get() == rFilterItem.GetParent(); });
            DBG_ASSERT(j != rParentParentItems.end(), "FmFilterModel::Remove(): unknown Item");
            sal_Int32 nParentPos = j - rParentParentItems.begin();

            // EmptyText removes the filter
            FmFilterAdapter::setText(nParentPos, &rFilterItem, OUString());
            Remove( i );
        }
    }
}

void FmFilterModel::Remove( const ::std::vector<std::unique_ptr<FmFilterData>>::iterator& rPos )
{
    // remove from parent's child list
    std::unique_ptr<FmFilterData> pData = std::move(*rPos);
    pData->GetParent()->GetChildren().erase( rPos );

    // notify the view, this will remove the actual SvTreeListEntry
    FmFilterRemovedHint aRemoveHint( pData.get() );
    Broadcast( aRemoveHint );
}


bool FmFilterModel::ValidateText(FmFilterItem const * pItem, OUString& rText, OUString& rErrorMsg) const
{
    FmFormItem* pFormItem = dynamic_cast<FmFormItem*>( pItem->GetParent()->GetParent()  );
    assert(pFormItem);
    try
    {
        Reference< XFormController > xFormController( pFormItem->GetController() );
        // obtain the connection of the form belonging to the controller
        Reference< XRowSet > xRowSet( xFormController->getModel(), UNO_QUERY_THROW );
        Reference< XConnection > xConnection( getConnection( xRowSet ) );

        // obtain a number formatter for this connection
        // TODO: shouldn't this be cached?
        Reference< XNumberFormatsSupplier > xFormatSupplier = getNumberFormats( xConnection, true );
        Reference< XNumberFormatter > xFormatter( NumberFormatter::create( comphelper::getProcessComponentContext() ), UNO_QUERY_THROW );
        xFormatter->attachNumberFormatsSupplier( xFormatSupplier );

        // get the field (database column) which the item is responsible for
        Reference< XFilterController > xFilterController( xFormController, UNO_QUERY_THROW );
        Reference< XPropertySet > xField( lcl_getBoundField_nothrow( xFilterController->getFilterComponent( pItem->GetComponentIndex() ) ), UNO_SET_THROW );

        // parse the given text as filter predicate
        OUString aErr, aTxt( rText );
        std::unique_ptr< OSQLParseNode > pParseNode = predicateTree( aErr, aTxt, xFormatter, xField );
        rErrorMsg = aErr;
        rText = aTxt;
        if ( pParseNode != nullptr )
        {
            OUString aPreparedText;
            Locale aAppLocale = Application::GetSettings().GetUILanguageTag().getLocale();
            pParseNode->parseNodeToPredicateStr(
                aPreparedText, xConnection, xFormatter, xField, OUString(), aAppLocale, OUString("."), getParseContext() );
            rText = aPreparedText;
            return true;
        }
    }
    catch( const Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("svx");
    }

    return false;
}


void FmFilterModel::Append(FmFilterItems* pItems, std::unique_ptr<FmFilterItem> pFilterItem)
{
    Insert(pItems->GetChildren().end(), std::move(pFilterItem));
}


void FmFilterModel::SetTextForItem(FmFilterItem* pItem, const OUString& rText)
{
    ::std::vector<std::unique_ptr<FmFilterData>>& rItems = pItem->GetParent()->GetParent()->GetChildren();
    auto i = ::std::find_if(rItems.begin(), rItems.end(),
                [&](const std::unique_ptr<FmFilterData>& p) { return p.get() == pItem->GetParent(); });
    sal_Int32 nParentPos = i - rItems.begin();

    FmFilterAdapter::setText(nParentPos, pItem, rText);

    if (rText.isEmpty())
        Remove(pItem);
    else
    {
        // Change the text
        pItem->SetText(rText);
        FmFilterTextChangedHint aChangeHint(pItem);
        Broadcast( aChangeHint );
    }
}


void FmFilterModel::SetCurrentItems(FmFilterItems* pCurrent)
{
    if (m_pCurrentItems == pCurrent)
        return;

    // search for the condition
    if (pCurrent)
    {
        FmFormItem* pFormItem = static_cast<FmFormItem*>(pCurrent->GetParent());
        ::std::vector<std::unique_ptr<FmFilterData>>& rItems = pFormItem->GetChildren();
        auto i = ::std::find_if(rItems.begin(), rItems.end(),
                    [&](const std::unique_ptr<FmFilterData>& p) { return p.get() == pCurrent; });

        if (i != rItems.end())
        {
            // determine the filter position
            sal_Int32 nPos = i - rItems.begin();
            try
            {
                Reference< XFilterController > xFilterController( pFormItem->GetFilterController(), UNO_SET_THROW );
                xFilterController->setActiveTerm( nPos );
            }
            catch( const Exception& )
            {
                DBG_UNHANDLED_EXCEPTION("svx");
            }

            if ( m_xController != pFormItem->GetController() )
                // calls SetCurrentItems again
                SetCurrentController( pFormItem->GetController() );
            else
                m_pCurrentItems = pCurrent;
        }
        else
            m_pCurrentItems = nullptr;
    }
    else
        m_pCurrentItems = nullptr;


    // notify the UI
    FmFilterCurrentChangedHint aHint;
    Broadcast( aHint );
}


void FmFilterModel::EnsureEmptyFilterRows( FmParentData& _rItem )
{
    // checks whether for each form there's one free level for input
    ::std::vector< std::unique_ptr<FmFilterData> >& rChildren = _rItem.GetChildren();
    bool bAppendLevel = dynamic_cast<const FmFormItem*>(&_rItem) !=  nullptr;

    for ( const auto& rpChild : rChildren )
    {
        FmFilterItems* pItems = dynamic_cast<FmFilterItems*>( rpChild.get() );
        if ( pItems && pItems->GetChildren().empty() )
        {
            bAppendLevel = false;
            break;
        }

        FmFormItem* pFormItem = dynamic_cast<FmFormItem*>( rpChild.get() );
        if (pFormItem)
        {
            EnsureEmptyFilterRows( *pFormItem );
            continue;
        }
    }

    if ( bAppendLevel )
    {
        FmFormItem* pFormItem = dynamic_cast<FmFormItem*>( &_rItem  );
        OSL_ENSURE( pFormItem, "FmFilterModel::EnsureEmptyFilterRows: no FmFormItem, but a FmFilterItems child?" );
        if ( pFormItem )
            AppendFilterItems( *pFormItem );
    }
}

namespace {

class FmFilterItemsString : public SvLBoxString
{
public:
    explicit FmFilterItemsString(const OUString& rStr)
        : SvLBoxString(rStr)
    {
    }

    virtual void Paint(const Point& rPos, SvTreeListBox& rDev, vcl::RenderContext& rRenderContext,
                       const SvViewDataEntry* pView, const SvTreeListEntry& rEntry) override;
    virtual void InitViewData( SvTreeListBox* pView,SvTreeListEntry* pEntry, SvViewDataItem* pViewData = nullptr) override;
};

}

const int nxDBmp = 12;

void FmFilterItemsString::Paint(const Point& rPos, SvTreeListBox& rDev, vcl::RenderContext& rRenderContext,
                                const SvViewDataEntry* /*pView*/, const SvTreeListEntry& rEntry)
{
    FmFilterItems* pRow = static_cast<FmFilterItems*>(rEntry.GetUserData());
    FmFormItem* pForm = static_cast<FmFormItem*>(pRow->GetParent());

    // current filter is significant painted
    const bool bIsCurrentFilter = pForm->GetChildren()[ pForm->GetFilterController()->getActiveTerm() ].get() == pRow;
    if (bIsCurrentFilter)
    {
        rRenderContext.Push(PushFlags::LINECOLOR);
        rRenderContext.SetLineColor(rRenderContext.GetTextColor());

        Size aSize(GetWidth(&rDev, &rEntry), GetHeight(&rDev, &rEntry));
        tools::Rectangle aRect(rPos, aSize);
        Point aFirst(rPos.X(), aRect.Bottom() - 6);
        Point aSecond(aFirst .X() + 2, aFirst.Y() + 3);

        rRenderContext.DrawLine(aFirst, aSecond);

        aFirst = aSecond;
        aFirst.AdjustX(1 );
        aSecond.AdjustX(6 );
        aSecond.AdjustY( -5 );

        rRenderContext.DrawLine(aFirst, aSecond);
        rRenderContext.Pop();
    }

    rRenderContext.DrawText(Point(rPos.X() + nxDBmp, rPos.Y()), GetText());
}


void FmFilterItemsString::InitViewData( SvTreeListBox* pView,SvTreeListEntry* pEntry, SvViewDataItem* pViewData)
{
    if( !pViewData )
        pViewData = pView->GetViewDataItem( pEntry, this );

    Size aSize(pView->GetTextWidth(GetText()), pView->GetTextHeight());
    aSize.AdjustWidth(nxDBmp );
    pViewData->mnWidth = aSize.Width();
    pViewData->mnHeight = aSize.Height();
}

namespace {

class FmFilterString : public SvLBoxString
{
    OUString m_aName;

public:
    FmFilterString( const OUString& rStr, const OUString& aName)
        : SvLBoxString(rStr)
        , m_aName(aName)
    {
        m_aName += ": ";
    }

    virtual void Paint(const Point& rPos, SvTreeListBox& rDev, vcl::RenderContext& rRenderContext,
                       const SvViewDataEntry* pView, const SvTreeListEntry& rEntry) override;
    virtual void InitViewData( SvTreeListBox* pView,SvTreeListEntry* pEntry, SvViewDataItem* pViewData = nullptr) override;
};

}

const int nxD = 4;

void FmFilterString::InitViewData( SvTreeListBox* pView,SvTreeListEntry* pEntry, SvViewDataItem* pViewData)
{
    if( !pViewData )
        pViewData = pView->GetViewDataItem( pEntry, this );

    vcl::Font aOldFont( pView->GetFont());
    vcl::Font aFont( aOldFont );
    aFont.SetWeight(WEIGHT_BOLD);
    pView->Control::SetFont( aFont );

    Size aSize(pView->GetTextWidth(m_aName), pView->GetTextHeight());
    pView->Control::SetFont( aOldFont );
    aSize.AdjustWidth(pView->GetTextWidth(GetText()) + nxD );
    pViewData->mnWidth = aSize.Width();
    pViewData->mnHeight = aSize.Height();
}

void FmFilterString::Paint(const Point& rPos, SvTreeListBox& rDev, vcl::RenderContext& rRenderContext,
                           const SvViewDataEntry* /*pView*/, const SvTreeListEntry& /*rEntry*/)
{
    rRenderContext.Push(PushFlags::FONT);
    vcl::Font aFont(rRenderContext.GetFont());
    aFont.SetWeight(WEIGHT_BOLD);
    rRenderContext.SetFont(aFont);

    Point aPos(rPos);
    rRenderContext.DrawText(aPos, m_aName);

    // position for the second text
    aPos.AdjustX(rDev.GetTextWidth(m_aName) + nxD );
    rRenderContext.Pop();
    rDev.DrawText(aPos, GetText());
}

FmFilterNavigator::FmFilterNavigator( vcl::Window* pParent )
                  :SvTreeListBox( pParent, WB_HASBUTTONS|WB_HASLINES|WB_BORDER|WB_HASBUTTONSATROOT )
                  ,m_pEditingCurrently( nullptr )
                  ,m_aControlExchange( this )
                  ,m_aTimerCounter( 0 )
                  ,m_aDropActionType( DA_SCROLLUP )
{
    SetHelpId( HID_FILTER_NAVIGATOR );

    SetNodeBitmaps(
        Image(StockImage::Yes, RID_SVXBMP_COLLAPSEDNODE),
        Image(StockImage::Yes, RID_SVXBMP_EXPANDEDNODE)
    );

    m_pModel.reset( new FmFilterModel() );
    StartListening( *m_pModel );

    EnableInplaceEditing( true );
    SetSelectionMode(SelectionMode::Multiple);

    SetDragDropMode(DragDropMode::ALL);

    m_aDropActionTimer.SetInvokeHandler(LINK(this, FmFilterNavigator, OnDropActionTimer));
}


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

void FmFilterNavigator::dispose()
{
    EndListening( *m_pModel );
    m_pModel.reset();
    SvTreeListBox::dispose();
}


void FmFilterNavigator::UpdateContent(const Reference< XIndexAccess > & xControllers, const Reference< XFormController > & xCurrent)
{
    if (xCurrent == m_pModel->GetCurrentController())
        return;

    m_pModel->Update(xControllers, xCurrent);

    // expand the filters for the current controller
    SvTreeListEntry* pEntry = FindEntry(m_pModel->GetCurrentForm());
    if (pEntry && !IsExpanded(pEntry))
    {
        SelectAll(false);

        if (!IsExpanded(pEntry))
            Expand(pEntry);

        pEntry = FindEntry(m_pModel->GetCurrentItems());
        if (pEntry)
        {
            if (!IsExpanded(pEntry))
                Expand(pEntry);
            Select(pEntry);
        }
    }
}


bool FmFilterNavigator::EditingEntry( SvTreeListEntry* pEntry, Selection& rSelection )
{
    m_pEditingCurrently = pEntry;
    if (!SvTreeListBox::EditingEntry( pEntry, rSelection ))
        return false;

    return pEntry && dynamic_cast<const FmFilterItem*>(static_cast<FmFilterData*>(pEntry->GetUserData())) != nullptr;
}


bool FmFilterNavigator::EditedEntry( SvTreeListEntry* pEntry, const OUString& rNewText )
{
    DBG_ASSERT(pEntry == m_pEditingCurrently, "FmFilterNavigator::EditedEntry: suspicious entry!");
    m_pEditingCurrently = nullptr;

    if (EditingCanceled())
        return true;

    DBG_ASSERT(dynamic_cast<const FmFilterItem*>(static_cast<FmFilterData*>(pEntry->GetUserData())) != nullptr,
                    "FmFilterNavigator::EditedEntry() wrong entry");

    OUString aText(comphelper::string::strip(rNewText, ' '));
    if (aText.isEmpty())
    {
        // deleting the entry asynchron
        PostUserEvent(LINK(this, FmFilterNavigator, OnRemove), pEntry, true);
    }
    else
    {
        OUString aErrorMsg;

        if (m_pModel->ValidateText(static_cast<FmFilterItem*>(pEntry->GetUserData()), aText, aErrorMsg))
        {
            GrabFocus();
            // this will set the text at the FmFilterItem, as well as update any filter controls
            // which are connected to this particular entry
            m_pModel->SetTextForItem( static_cast< FmFilterItem* >( pEntry->GetUserData() ), aText );

            SetCursor( pEntry, true );
            SetEntryText( pEntry, aText );
        }
        else
        {
            // display the error and return sal_False
            SQLContext aError;
            aError.Message = SvxResId(RID_STR_SYNTAXERROR);
            aError.Details = aErrorMsg;
            displayException(aError, this);

            return false;
        }
    }
    return true;
}


IMPL_LINK( FmFilterNavigator, OnRemove, void*, p, void )
{
    SvTreeListEntry* pEntry = static_cast<SvTreeListEntry*>(p);
    // now remove the entry
    m_pModel->Remove(static_cast<FmFilterData*>(pEntry->GetUserData()));
}


IMPL_LINK_NOARG(FmFilterNavigator, OnDropActionTimer, Timer *, void)
{
    if (--m_aTimerCounter > 0)
        return;

    switch (m_aDropActionType)
    {
        case DA_SCROLLUP :
            ScrollOutputArea(1);
            m_aTimerCounter = DROP_ACTION_TIMER_SCROLL_TICKS;
            break;
        case DA_SCROLLDOWN :
            ScrollOutputArea(-1);
            m_aTimerCounter = DROP_ACTION_TIMER_SCROLL_TICKS;
            break;
        case DA_EXPANDNODE:
        {
            SvTreeListEntry* pToExpand = GetEntry(m_aTimerTriggered);
            if (pToExpand && (GetChildCount(pToExpand) > 0) &&  !IsExpanded(pToExpand))
                Expand(pToExpand);
            m_aDropActionTimer.Stop();
        }
        break;
    }
}


sal_Int8 FmFilterNavigator::AcceptDrop( const AcceptDropEvent& rEvt )
{
    Point aDropPos = rEvt.maPosPixel;

    // possible DropActions scroll and expand
    if (rEvt.mbLeaving)
    {
        if (m_aDropActionTimer.IsActive())
            m_aDropActionTimer.Stop();
    }
    else
    {
        bool bNeedTrigger = false;
        // first entry ?
        if ((aDropPos.Y() >= 0) && (aDropPos.Y() < GetEntryHeight()))
        {
            m_aDropActionType = DA_SCROLLUP;
            bNeedTrigger = true;
        }
        else
        {
            if ((aDropPos.Y() < GetSizePixel().Height()) && (aDropPos.Y() >= GetSizePixel().Height() - GetEntryHeight()))
            {
                m_aDropActionType = DA_SCROLLDOWN;
                bNeedTrigger = true;
            }
            else
            {   // is it an entry with children, and not yet expanded?
                SvTreeListEntry* pDroppedOn = GetEntry(aDropPos);
                if (pDroppedOn && (GetChildCount(pDroppedOn) > 0) && !IsExpanded(pDroppedOn))
                {
                    // -> expand
                    m_aDropActionType = DA_EXPANDNODE;
                    bNeedTrigger = true;
                }
            }
        }
        if (bNeedTrigger && (m_aTimerTriggered != aDropPos))
        {
            m_aTimerCounter = DROP_ACTION_TIMER_INITIAL_TICKS;
            // remember DropPos because there are QueryDrops even though the mouse was not moved
            m_aTimerTriggered = aDropPos;
            if (!m_aDropActionTimer.IsActive())
            {
                m_aDropActionTimer.SetTimeout(DROP_ACTION_TIMER_TICK_BASE);
                m_aDropActionTimer.Start();
            }
        }
        else if (!bNeedTrigger)
            m_aDropActionTimer.Stop();
    }

    if (!m_aControlExchange.isDragSource())
        return DND_ACTION_NONE;

    if (!OFilterItemExchange::hasFormat(GetDataFlavorExVector()))
        return DND_ACTION_NONE;

    // do we contain the formitem?
    if (!FindEntry(m_aControlExchange->getFormItem()))
        return DND_ACTION_NONE;

    SvTreeListEntry* pDropTarget = GetEntry(aDropPos);
    if (!pDropTarget)
        return DND_ACTION_NONE;

    FmFilterData* pData = static_cast<FmFilterData*>(pDropTarget->GetUserData());
    FmFormItem* pForm = nullptr;
    if (dynamic_cast<const FmFilterItem*>(pData) !=  nullptr)
    {
        pForm = dynamic_cast<FmFormItem*>( pData->GetParent()->GetParent() );
        if (pForm != m_aControlExchange->getFormItem())
            return DND_ACTION_NONE;
    }
    else if (dynamic_cast<const FmFilterItems*>( pData) !=  nullptr)
    {
        pForm = dynamic_cast<FmFormItem*>( pData->GetParent() );
        if (pForm != m_aControlExchange->getFormItem())
            return DND_ACTION_NONE;
    }
    else
        return DND_ACTION_NONE;

    return rEvt.mnAction;
}

namespace
{
    FmFilterItems* getTargetItems(SvTreeListEntry const * _pTarget)
    {
        FmFilterData*   pData = static_cast<FmFilterData*>(_pTarget->GetUserData());
        FmFilterItems*  pTargetItems = dynamic_cast<FmFilterItems*>(pData);
        if (!pTargetItems)
            pTargetItems = dynamic_cast<FmFilterItems*>(pData->GetParent());
        return pTargetItems;
    }
}

sal_Int8 FmFilterNavigator::ExecuteDrop( const ExecuteDropEvent& rEvt )
{
    // you can't scroll after dropping...
    if (m_aDropActionTimer.IsActive())
        m_aDropActionTimer.Stop();

    if (!m_aControlExchange.isDragSource())
        return DND_ACTION_NONE;

    Point aDropPos = rEvt.maPosPixel;
    SvTreeListEntry* pDropTarget = GetEntry( aDropPos );
    if (!pDropTarget)
        return DND_ACTION_NONE;

    // search the container where to add the items
    FmFilterItems*  pTargetItems = getTargetItems(pDropTarget);
    SelectAll(false);
    SvTreeListEntry* pEntry = FindEntry(pTargetItems);
    Select(pEntry);
    SetCurEntry(pEntry);

    insertFilterItem(m_aControlExchange->getDraggedEntries(),pTargetItems,DND_ACTION_COPY == rEvt.mnAction);

    return DND_ACTION_COPY;
}


void FmFilterNavigator::InitEntry(SvTreeListEntry* pEntry,
                                  const OUString& rStr,
                                  const Image& rImg1,
                                  const Image& rImg2)
{
    SvTreeListBox::InitEntry( pEntry, rStr, rImg1, rImg2 );
    std::unique_ptr<SvLBoxString> pString;

    if (dynamic_cast<const FmFilterItem*>(static_cast<FmFilterData*>(pEntry->GetUserData())) != nullptr)
        pString.reset(new FmFilterString(rStr,
            static_cast<FmFilterItem*>(pEntry->GetUserData())->GetFieldName()));
    else if (dynamic_cast<const FmFilterItems*>(static_cast<FmFilterData*>(pEntry->GetUserData())) != nullptr)
        pString.reset(new FmFilterItemsString(rStr));

    if (pString)
        pEntry->ReplaceItem(std::move(pString), 1 );
}


bool FmFilterNavigator::Select( SvTreeListEntry* pEntry, bool bSelect )
{
    if (bSelect == IsSelected(pEntry))  // This happens sometimes. I think the basic class errs too much on the side of caution. ;)
        return true;

    if (SvTreeListBox::Select(pEntry, bSelect))
    {
        if (bSelect)
        {
            FmFormItem* pFormItem = nullptr;
            if ( dynamic_cast<const FmFilterItem*>(static_cast<FmFilterData*>(pEntry->GetUserData())) != nullptr)
                pFormItem = static_cast<FmFormItem*>(static_cast<FmFilterItem*>(pEntry->GetUserData())->GetParent()->GetParent());
            else if (dynamic_cast<const FmFilterItems*>(static_cast<FmFilterData*>(pEntry->GetUserData())) != nullptr)
                pFormItem = static_cast<FmFormItem*>(static_cast<FmFilterItem*>(pEntry->GetUserData())->GetParent()->GetParent());
            else if (dynamic_cast<const FmFormItem*>(static_cast<FmFilterData*>(pEntry->GetUserData())) != nullptr)
                pFormItem = static_cast<FmFormItem*>(pEntry->GetUserData());

            if (pFormItem)
            {
                // will the controller be exchanged?
                if (dynamic_cast<const FmFilterItem*>(static_cast<FmFilterData*>(pEntry->GetUserData())) != nullptr)
                    m_pModel->SetCurrentItems(static_cast<FmFilterItems*>(static_cast<FmFilterItem*>(pEntry->GetUserData())->GetParent()));
                else if (dynamic_cast<const FmFilterItems*>(static_cast<FmFilterData*>(pEntry->GetUserData())) != nullptr)
                    m_pModel->SetCurrentItems(static_cast<FmFilterItems*>(pEntry->GetUserData()));
                else if (dynamic_cast<const FmFormItem*>(static_cast<FmFilterData*>(pEntry->GetUserData())) != nullptr)
                    m_pModel->SetCurrentController(static_cast<FmFormItem*>(pEntry->GetUserData())->GetController());
            }
        }
        return true;
    }
    else
        return false;
}

void FmFilterNavigator::Notify( SfxBroadcaster& /*rBC*/, const SfxHint& rHint )
{
    if (const FmFilterInsertedHint* pInsertHint = dynamic_cast<const FmFilterInsertedHint*>(&rHint))
    {
        Insert(pInsertHint->GetData(), pInsertHint->GetPos());
    }
    else if( dynamic_cast<const FilterClearingHint*>(&rHint) )
    {
        SvTreeListBox::Clear();
    }
    else if (const FmFilterRemovedHint* pRemoveHint = dynamic_cast<const FmFilterRemovedHint*>(&rHint))
    {
        Remove(pRemoveHint->GetData());
    }
    else if (const FmFilterTextChangedHint *pChangeHint = dynamic_cast<const FmFilterTextChangedHint*>(&rHint))
    {
        SvTreeListEntry* pEntry = FindEntry(pChangeHint->GetData());
        if (pEntry)
            SetEntryText( pEntry, pChangeHint->GetData()->GetText());
    }
    else if( dynamic_cast<const FmFilterCurrentChangedHint*>(&rHint) )
    {
        // invalidate the entries
        for (SvTreeListEntry* pEntry = First(); pEntry != nullptr;
             pEntry = Next(pEntry))
            GetModel()->InvalidateEntry( pEntry );
    }
}

SvTreeListEntry* FmFilterNavigator::FindEntry(const FmFilterData* pItem) const
{
    SvTreeListEntry* pEntry = nullptr;
    if (pItem)
    {
        for (pEntry = First(); pEntry != nullptr; pEntry = Next( pEntry ))
        {
            FmFilterData* pEntryItem = static_cast<FmFilterData*>(pEntry->GetUserData());
            if (pEntryItem == pItem)
                break;
        }
    }
    return pEntry;
}


void FmFilterNavigator::Insert(FmFilterData* pItem, sal_uLong nPos)
{
    const FmParentData* pParent = pItem->GetParent() ? pItem->GetParent() : m_pModel.get();

    // insert the item
    SvTreeListEntry* pParentEntry = FindEntry( pParent );
    InsertEntry( pItem->GetText(), pItem->GetImage(), pItem->GetImage(), pParentEntry, false, nPos, pItem );
    if ( pParentEntry )
        Expand( pParentEntry );
}


void FmFilterNavigator::Remove(FmFilterData const * pItem)
{
    // the entry for the data
    SvTreeListEntry* pEntry = FindEntry(pItem);

    if (pEntry == m_pEditingCurrently)
        // cancel editing
        EndEditing(true);

    if (pEntry)
        GetModel()->Remove( pEntry );
}

FmFormItem* FmFilterNavigator::getSelectedFilterItems(::std::vector<FmFilterItem*>& _rItemList)
{
    // be sure that the data is only used within only one form!
    FmFormItem* pFirstItem = nullptr;

    bool bHandled = true;
    bool bFoundSomething = false;
    for (SvTreeListEntry* pEntry = FirstSelected();
         bHandled && pEntry != nullptr;
         pEntry = NextSelected(pEntry))
    {
        FmFilterItem* pFilter = dynamic_cast<FmFilterItem*>( static_cast<FmFilterData*>(pEntry->GetUserData()) );
        if (pFilter)
        {
            FmFormItem* pForm = dynamic_cast<FmFormItem*>( pFilter->GetParent()->GetParent() );
            if (!pForm)
                bHandled = false;
            else if (!pFirstItem)
                pFirstItem = pForm;
            else if (pFirstItem != pForm)
                bHandled = false;

            if (bHandled)
            {
                _rItemList.push_back(pFilter);
                bFoundSomething = true;
            }
        }
    }
    if ( !bHandled || !bFoundSomething )
        pFirstItem = nullptr;
    return pFirstItem;
}

void FmFilterNavigator::insertFilterItem(const ::std::vector<FmFilterItem*>& _rFilterList,FmFilterItems* _pTargetItems,bool _bCopy)
{
    for (FmFilterItem* pLookupItem : _rFilterList)
    {
        if ( pLookupItem->GetParent() == _pTargetItems )
            continue;

        FmFilterItem* pFilterItem = _pTargetItems->Find( pLookupItem->GetComponentIndex() );
        OUString aText = pLookupItem->GetText();
        if ( !pFilterItem )
        {
            pFilterItem = new FmFilterItem( _pTargetItems, pLookupItem->GetFieldName(), aText, pLookupItem->GetComponentIndex() );
            m_pModel->Append( _pTargetItems, std::unique_ptr<FmFilterItem>(pFilterItem) );
        }

        if ( !_bCopy )
            m_pModel->Remove( pLookupItem );

        // now set the text for the new dragged item
        m_pModel->SetTextForItem( pFilterItem, aText );
    }

    m_pModel->EnsureEmptyFilterRows( *_pTargetItems->GetParent() );
}


void FmFilterNavigator::StartDrag( sal_Int8 /*_nAction*/, const Point& /*_rPosPixel*/ )
{
    EndSelection();

    // be sure that the data is only used within an only one form!
    m_aControlExchange.prepareDrag();

    ::std::vector<FmFilterItem*> aItemList;
    if ( FmFormItem* pFirstItem = getSelectedFilterItems(aItemList) )
    {
        m_aControlExchange->setDraggedEntries(aItemList);
        m_aControlExchange->setFormItem(pFirstItem);
        m_aControlExchange.startDrag( DND_ACTION_COPYMOVE );
    }
}


void FmFilterNavigator::Command( const CommandEvent& rEvt )
{
    bool bHandled = false;
    switch (rEvt.GetCommand())
    {
        case CommandEventId::ContextMenu:
        {
            // the place where it was clicked
            Point aWhere;
            SvTreeListEntry* pClicked = nullptr;
            if (rEvt.IsMouseEvent())
            {
                aWhere = rEvt.GetMousePosPixel();
                pClicked = GetEntry(aWhere);
                if (pClicked == nullptr)
                    break;

                if (!IsSelected(pClicked))
                {
                    SelectAll(false);
                    Select(pClicked);
                    SetCurEntry(pClicked);
                }
            }
            else
            {
                pClicked = GetCurEntry();
                if (!pClicked)
                    break;
                aWhere = GetEntryPosition( pClicked );
            }

            ::std::vector<FmFilterData*> aSelectList;
            for (SvTreeListEntry* pEntry = FirstSelected();
                 pEntry != nullptr;
                 pEntry = NextSelected(pEntry))
            {
                // don't delete forms
                FmFormItem* pForm = dynamic_cast<FmFormItem*>( static_cast<FmFilterData*>(pEntry->GetUserData()) );
                if (!pForm)
                    aSelectList.push_back(static_cast<FmFilterData*>(pEntry->GetUserData()));
            }
            if (aSelectList.size() == 1)
            {
                // don't delete the only empty row of a form
                FmFilterItems* pFilterItems = dynamic_cast<FmFilterItems*>( aSelectList[0] );
                if (pFilterItems && pFilterItems->GetChildren().empty()
                    && pFilterItems->GetParent()->GetChildren().size() == 1)
                    aSelectList.clear();
            }

            VclBuilder aBuilder(nullptr, VclBuilderContainer::getUIRootDir(), "svx/ui/filtermenu.ui", "");
            VclPtr<PopupMenu> aContextMenu(aBuilder.get_menu("menu"));

            // every condition could be deleted except the first one if it's the only one
            aContextMenu->EnableItem(aContextMenu->GetItemId("delete"), !aSelectList.empty());


            bool bEdit = dynamic_cast<FmFilterItem*>( static_cast<FmFilterData*>(pClicked->GetUserData()) ) != nullptr &&
                IsSelected(pClicked) && GetSelectionCount() == 1;

            aContextMenu->EnableItem(aContextMenu->GetItemId("edit"), bEdit);
            aContextMenu->EnableItem(aContextMenu->GetItemId("isnull"), bEdit);
            aContextMenu->EnableItem(aContextMenu->GetItemId("isnotnull"), bEdit);

            aContextMenu->RemoveDisabledEntries(true, true);
            aContextMenu->Execute(this, aWhere);
            OString sIdent = aContextMenu->GetCurItemIdent();
            if (sIdent == "edit")
                EditEntry( pClicked );
            else if (sIdent == "isnull")
            {
                OUString aErrorMsg;
                OUString aText = "IS NULL";
                m_pModel->ValidateText(static_cast<FmFilterItem*>(pClicked->GetUserData()),
                                        aText, aErrorMsg);
                m_pModel->SetTextForItem(static_cast<FmFilterItem*>(pClicked->GetUserData()), aText);
            }
            else if (sIdent == "isnotnull")
            {
                OUString aErrorMsg;
                OUString aText = "IS NOT NULL";

                m_pModel->ValidateText(static_cast<FmFilterItem*>(pClicked->GetUserData()),
                                        aText, aErrorMsg);
                m_pModel->SetTextForItem(static_cast<FmFilterItem*>(pClicked->GetUserData()), aText);
            }
            else if (sIdent == "delete")
            {
                DeleteSelection();
            }
            bHandled = true;
        }
        break;
        default: break;
    }

    if (!bHandled)
        SvTreeListBox::Command( rEvt );
}

SvTreeListEntry* FmFilterNavigator::getNextEntry(SvTreeListEntry* _pStartWith)
{
    SvTreeListEntry* pEntry = _pStartWith ? _pStartWith : LastSelected();
    pEntry = Next(pEntry);
    // we need the next filter entry
    while( pEntry && GetChildCount( pEntry ) == 0 && pEntry != Last() )
        pEntry = Next(pEntry);
    return pEntry;
}

SvTreeListEntry* FmFilterNavigator::getPrevEntry(SvTreeListEntry* _pStartWith)
{
    SvTreeListEntry* pEntry = _pStartWith ? _pStartWith : FirstSelected();
    pEntry = Prev(pEntry);
    // check if the previous entry is a filter, if so get the next prev
    if ( pEntry && GetChildCount( pEntry ) != 0 )
    {
        pEntry = Prev(pEntry);
        // if the entry is still no leaf return
        if ( pEntry && GetChildCount( pEntry ) != 0 )
            pEntry = nullptr;
    }
    return pEntry;
}

void FmFilterNavigator::KeyInput(const KeyEvent& rKEvt)
{
    const vcl::KeyCode& rKeyCode = rKEvt.GetKeyCode();

    switch ( rKeyCode.GetCode() )
    {
    case KEY_UP:
    case KEY_DOWN:
    {
        if ( !rKeyCode.IsMod1() || !rKeyCode.IsMod2() || rKeyCode.IsShift() )
            break;

        ::std::vector<FmFilterItem*> aItemList;
        if ( !getSelectedFilterItems( aItemList ) )
            break;

        ::std::function<SvTreeListEntry*(FmFilterNavigator *, SvTreeListEntry*)> getter = ::std::mem_fn(&FmFilterNavigator::getNextEntry);
        if ( rKeyCode.GetCode() == KEY_UP )
            getter = ::std::mem_fn(&FmFilterNavigator::getPrevEntry);

        SvTreeListEntry* pTarget = getter( this, nullptr );
        if ( !pTarget )
            break;

        FmFilterItems* pTargetItems = getTargetItems( pTarget );
        if ( !pTargetItems )
            break;

        ::std::vector<FmFilterItem*>::const_iterator aEnd = aItemList.end();
        bool bNextTargetItem = true;
        while ( bNextTargetItem )
        {
            ::std::vector<FmFilterItem*>::const_iterator i = aItemList.begin();
            for (; i != aEnd; ++i)
            {
                if ( (*i)->GetParent() == pTargetItems )
                {
                    pTarget = getter(this,pTarget);
                    if ( !pTarget )
                        return;
                    pTargetItems = getTargetItems( pTarget );
                    break;
                }
                else
                {
                    FmFilterItem* pFilterItem = pTargetItems->Find( (*i)->GetComponentIndex() );
                    // we found the text component so jump above
                    if ( pFilterItem )
                    {
                        pTarget = getter( this, pTarget );
                        if ( !pTarget )
                            return;

                        pTargetItems = getTargetItems( pTarget );
                        break;
                    }
                }
            }
            bNextTargetItem = i != aEnd && pTargetItems;
        }

        if ( pTargetItems )
        {
            insertFilterItem( aItemList, pTargetItems, false );
            return;
        }
    }
    break;

    case KEY_DELETE:
    {
        if ( rKeyCode.GetModifier() )
            break;

        if ( !IsSelected( First() ) || GetEntryCount() > 1 )
            DeleteSelection();
        return;
    }
    }

    SvTreeListBox::KeyInput(rKEvt);
}


void FmFilterNavigator::DeleteSelection()
{
    // to avoid the deletion of an entry twice (e.g. deletion of a parent and afterward
    // the deletion of its child, I have to shrink the selection list
    ::std::vector<SvTreeListEntry*> aEntryList;
    for (SvTreeListEntry* pEntry = FirstSelected();
         pEntry != nullptr;
         pEntry = NextSelected(pEntry))
    {
        FmFilterItem* pFilterItem = dynamic_cast<FmFilterItem*>( static_cast<FmFilterData*>(pEntry->GetUserData()) );
        if (pFilterItem && IsSelected(GetParent(pEntry)))
            continue;

        FmFormItem* pForm = dynamic_cast<FmFormItem*>( static_cast<FmFilterData*>(pEntry->GetUserData()) );
        if (!pForm)
            aEntryList.push_back(pEntry);
    }

    // Remove the selection
    SelectAll(false);

    for (::std::vector<SvTreeListEntry*>::reverse_iterator i = aEntryList.rbegin();
        // link problems with operator ==
        i.base() != aEntryList.rend().base(); ++i)
    {
        m_pModel->Remove(static_cast<FmFilterData*>((*i)->GetUserData()));
    }
}

FmFilterNavigatorWin::FmFilterNavigatorWin( SfxBindings* _pBindings, SfxChildWindow* _pMgr,
                              vcl::Window* _pParent )
                     :SfxDockingWindow( _pBindings, _pMgr, _pParent, WinBits(WB_STDMODELESS|WB_SIZEABLE|WB_ROLLABLE|WB_3DLOOK|WB_DOCKABLE) )
                     ,SfxControllerItem( SID_FM_FILTER_NAVIGATOR_CONTROL, *_pBindings )
{
    SetHelpId( HID_FILTER_NAVIGATOR_WIN );

    m_pNavigator = VclPtr<FmFilterNavigator>::Create( this );
    m_pNavigator->Show();
    SetText( SvxResId(RID_STR_FILTER_NAVIGATOR) );
    SfxDockingWindow::SetFloatingSize( Size(200,200) );
}


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

void FmFilterNavigatorWin::dispose()
{
    m_pNavigator.disposeAndClear();
    ::SfxControllerItem::dispose();
    SfxDockingWindow::dispose();
}


void FmFilterNavigatorWin::UpdateContent(FmFormShell const * pFormShell)
{
    if (!m_pNavigator)
        return;

    if (!pFormShell)
        m_pNavigator->UpdateContent( nullptr, nullptr );
    else
    {
        Reference<XFormController> const xController(pFormShell->GetImpl()->getActiveInternalController_Lock());
        Reference< XIndexAccess >   xContainer;
        if (xController.is())
        {
            Reference< XChild >  xChild = xController;
            for (Reference< XInterface >  xParent(xChild->getParent());
                 xParent.is();
                 xParent = xChild.is() ? xChild->getParent() : Reference< XInterface > ())
            {
                xContainer.set(xParent, UNO_QUERY);
                xChild.set(xParent, UNO_QUERY);
            }
        }
        m_pNavigator->UpdateContent(xContainer, xController);
    }
}


void FmFilterNavigatorWin::StateChanged( sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    if( !pState  || SID_FM_FILTER_NAVIGATOR_CONTROL != nSID )
        return;

    if( eState >= SfxItemState::DEFAULT )
    {
        FmFormShell* pShell = dynamic_cast<FmFormShell*>( static_cast<const SfxObjectItem*>(pState)->GetShell()  );
        UpdateContent( pShell );
    }
    else
        UpdateContent( nullptr );
}


bool FmFilterNavigatorWin::Close()
{
    if ( m_pNavigator && m_pNavigator->IsEditingActive() )
        m_pNavigator->EndEditing();

    if ( m_pNavigator && m_pNavigator->IsEditingActive() )
        // the EndEditing was vetoed (perhaps of an syntax error or such)
        return false;

    UpdateContent( nullptr );
    return SfxDockingWindow::Close();
}


void FmFilterNavigatorWin::FillInfo( SfxChildWinInfo& rInfo ) const
{
    SfxDockingWindow::FillInfo( rInfo );
    rInfo.bVisible = false;
}


Size FmFilterNavigatorWin::CalcDockingSize( SfxChildAlignment eAlign )
{
    if ( ( eAlign == SfxChildAlignment::TOP ) || ( eAlign == SfxChildAlignment::BOTTOM ) )
        return Size();

    return SfxDockingWindow::CalcDockingSize( eAlign );
}


SfxChildAlignment FmFilterNavigatorWin::CheckAlignment( SfxChildAlignment eActAlign, SfxChildAlignment eAlign )
{
    switch (eAlign)
    {
        case SfxChildAlignment::LEFT:
        case SfxChildAlignment::RIGHT:
        case SfxChildAlignment::NOALIGNMENT:
            return eAlign;
        default:
            break;
    }

    return eActAlign;
}


void FmFilterNavigatorWin::Resize()
{
    SfxDockingWindow::Resize();

    Size aLogOutputSize = PixelToLogic(GetOutputSizePixel(), MapMode(MapUnit::MapAppFont));
    Size aLogExplSize = aLogOutputSize;
    aLogExplSize.AdjustWidth( -6 );
    aLogExplSize.AdjustHeight( -6 );

    Point aExplPos = LogicToPixel(Point(3,3), MapMode(MapUnit::MapAppFont));
    Size aExplSize = LogicToPixel(aLogExplSize, MapMode(MapUnit::MapAppFont));

    m_pNavigator->SetPosSizePixel( aExplPos, aExplSize );
}

void FmFilterNavigatorWin::GetFocus()
{
    // oj #97405#
    if ( m_pNavigator )
        m_pNavigator->GrabFocus();
}

SFX_IMPL_DOCKINGWINDOW( FmFilterNavigatorWinMgr, SID_FM_FILTER_NAVIGATOR )<--- There is an unknown macro here somewhere. Configuration is required. If SFX_IMPL_DOCKINGWINDOW is a macro then please configure it.


FmFilterNavigatorWinMgr::FmFilterNavigatorWinMgr( vcl::Window *_pParent, sal_uInt16 _nId,
                                    SfxBindings *_pBindings, SfxChildWinInfo* _pInfo )
                 :SfxChildWindow( _pParent, _nId )
{
    SetWindow( VclPtr<FmFilterNavigatorWin>::Create( _pBindings, this, _pParent ) );
    static_cast<SfxDockingWindow*>(GetWindow())->Initialize( _pInfo );
}


}

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