1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
/* -*- 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 "SelectionBrowseBox.hxx"
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#include <com/sun/star/sdbc/DataType.hpp>
#include <JoinExchange.hxx>
#include <QueryDesignView.hxx>
#include <querycontroller.hxx>
#include <sqlbison.hxx>
#include <QueryTableView.hxx>
#include <browserids.hxx>
#include <comphelper/stl_types.hxx>
#include <comphelper/string.hxx>
#include "TableFieldInfo.hxx"
#include <core_resource.hxx>
#include <strings.hrc>
#include <strings.hxx>
#include <helpids.h>
#include "QTableWindow.hxx"
#include <vcl/button.hxx>
#include <vcl/weld.hxx>
#include <vcl/settings.hxx>
#include "QueryDesignFieldUndoAct.hxx"
#include <sqlmessage.hxx>
#include <UITools.hxx>
#include <o3tl/safeint.hxx>
#include <osl/diagnose.h>
#include <i18nlangtag/languagetag.hxx>
#include <vcl/treelistentry.hxx>
#include <vcl/commandevent.hxx>
#include <vcl/svapp.hxx>

using namespace ::svt;
using namespace ::dbaui;
using namespace ::connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::accessibility;

#define DEFAULT_QUERY_COLS  20
#define DEFAULT_SIZE        GetTextWidth("0") * 30
#define HANDLE_ID            0
#define HANDLE_COLUMN_WIDTH 70
#define SORT_COLUMN_NONE    0xFFFFFFFF

namespace
{
    bool isFieldNameAsterisk(const OUString& _sFieldName )
    {
        bool bAsterisk = _sFieldName.isEmpty() || _sFieldName.toChar() == '*';
        if ( !bAsterisk )
        {
            sal_Int32 nTokenCount = comphelper::string::getTokenCount(_sFieldName, '.');
            if (    (nTokenCount == 2 && _sFieldName.getToken(1,'.')[0] == '*' )
                ||  (nTokenCount == 3 && _sFieldName.getToken(2,'.')[0] == '*' ) )
            {
                bAsterisk = true;
            }
        }
        return bAsterisk;
    }
    bool lcl_SupportsCoreSQLGrammar(const Reference< XConnection>& _xConnection)
    {
        bool bSupportsCoreGrammar = false;
        if ( _xConnection.is() )
        {
            try
            {
                Reference< XDatabaseMetaData >  xMetaData = _xConnection->getMetaData();
                bSupportsCoreGrammar = xMetaData.is() && xMetaData->supportsCoreSQLGrammar();
            }
            catch(Exception&)
            {
            }
        }
        return bSupportsCoreGrammar;
    }
}

OSelectionBrowseBox::OSelectionBrowseBox( vcl::Window* pParent )
                   :EditBrowseBox( pParent,EditBrowseBoxFlags::NO_HANDLE_COLUMN_CONTENT, WB_3DLOOK, BrowserMode::COLUMNSELECTION | BrowserMode::KEEPHIGHLIGHT |  BrowserMode::HIDESELECT |
                                  BrowserMode::HIDECURSOR | BrowserMode::HLINES | BrowserMode::VLINES )
                   ,m_nSeekRow(0)
                   ,m_nMaxColumns(0)
                   ,m_aFunctionStrings(DBA_RES(STR_QUERY_FUNCTIONS))
                   ,m_nVisibleCount(0)
                   ,m_nLastSortColumn(SORT_COLUMN_NONE)
                   ,m_bOrderByUnRelated(true)
                   ,m_bGroupByUnRelated(true)
                   ,m_bStopTimer(false)
                   ,m_bWasEditing(false)
                   ,m_bDisableErrorBox(false)
                   ,m_bInUndoMode(false)
{
    SetHelpId(HID_CTL_QRYDGNCRIT);

    m_nMode =       BrowserMode::COLUMNSELECTION | BrowserMode::HIDESELECT
                |   BrowserMode::KEEPHIGHLIGHT   | BrowserMode::HIDECURSOR
                |   BrowserMode::HLINES      | BrowserMode::VLINES
                |   BrowserMode::HEADERBAR_NEW   ;

    m_pTextCell     = VclPtr<Edit>::Create(&GetDataWindow(), 0);
    m_pVisibleCell  = VclPtr<CheckBoxControl>::Create(&GetDataWindow());
    m_pTableCell    = VclPtr<ListBoxControl>::Create(&GetDataWindow());
    m_pFieldCell    = VclPtr<ComboBoxControl>::Create(&GetDataWindow());
    m_pOrderCell    = VclPtr<ListBoxControl>::Create(&GetDataWindow());
    m_pFunctionCell = VclPtr<ListBoxControl>::Create(&GetDataWindow());

    m_pVisibleCell->SetHelpId(HID_QRYDGN_ROW_VISIBLE);
    m_pTableCell->SetHelpId(HID_QRYDGN_ROW_TABLE);
    m_pFieldCell->SetHelpId(HID_QRYDGN_ROW_FIELD);
    weld::ComboBox& rOrderBox = m_pOrderCell->get_widget();
    m_pOrderCell->SetHelpId(HID_QRYDGN_ROW_ORDER);
    m_pFunctionCell->SetHelpId(HID_QRYDGN_ROW_FUNCTION);

    // switch off triState of css::form::CheckBox
    m_pVisibleCell->GetBox().EnableTriState( false );

    vcl::Font aTitleFont = OutputDevice::GetDefaultFont( DefaultFontType::SANS_UNICODE,Window::GetSettings().GetLanguageTag().getLanguageType(),GetDefaultFontFlags::OnlyOne);
    aTitleFont.SetFontSize(Size(0, 6));
    SetTitleFont(aTitleFont);

    const OUString aTxt(DBA_RES(STR_QUERY_SORTTEXT));
    for (sal_Int32 nIdx {0}; nIdx>=0;)
        rOrderBox.append_text(aTxt.getToken(0, ';', nIdx));

    m_bVisibleRow.insert(m_bVisibleRow.end(), BROW_ROW_CNT, true);

    m_bVisibleRow[BROW_FUNCTION_ROW] = false;   // first hide

    m_timerInvalidate.SetTimeout(200);
    m_timerInvalidate.SetInvokeHandler(LINK(this, OSelectionBrowseBox, OnInvalidateTimer));
    m_timerInvalidate.Start();
}

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

void OSelectionBrowseBox::dispose()
{
    m_pTextCell.disposeAndClear();
    m_pVisibleCell.disposeAndClear();
    m_pFieldCell.disposeAndClear();
    m_pTableCell.disposeAndClear();
    m_pOrderCell.disposeAndClear();
    m_pFunctionCell.disposeAndClear();
    ::svt::EditBrowseBox::dispose();
}

void OSelectionBrowseBox::initialize()
{
    Reference< XConnection> xConnection = static_cast<OQueryController&>(getDesignView()->getController()).getConnection();
    if(xConnection.is())
    {
        const IParseContext& rContext = static_cast<OQueryController&>(getDesignView()->getController()).getParser().getContext();
        const IParseContext::InternationalKeyCode eFunctions[] = {
            IParseContext::InternationalKeyCode::Avg,IParseContext::InternationalKeyCode::Count,IParseContext::InternationalKeyCode::Max
            ,IParseContext::InternationalKeyCode::Min,IParseContext::InternationalKeyCode::Sum
            ,IParseContext::InternationalKeyCode::Every
            ,IParseContext::InternationalKeyCode::Any
            ,IParseContext::InternationalKeyCode::Some
            ,IParseContext::InternationalKeyCode::StdDevPop
            ,IParseContext::InternationalKeyCode::StdDevSamp
            ,IParseContext::InternationalKeyCode::VarSamp
            ,IParseContext::InternationalKeyCode::VarPop
            ,IParseContext::InternationalKeyCode::Collect
            ,IParseContext::InternationalKeyCode::Fusion
            ,IParseContext::InternationalKeyCode::Intersection
        };

        OUString sGroup = m_aFunctionStrings.copy(m_aFunctionStrings.lastIndexOf(';')+1);
        m_aFunctionStrings = m_aFunctionStrings.getToken(0, ';');

        for (IParseContext::InternationalKeyCode eFunction : eFunctions)
        {
            m_aFunctionStrings += ";" + OStringToOUString(rContext.getIntlKeywordAscii(eFunction), RTL_TEXTENCODING_UTF8);
        }
        m_aFunctionStrings += ";" + sGroup;

        // Aggregate functions in general available only with Core SQL
        // We slip in a few optionals one, too.
        if ( lcl_SupportsCoreSQLGrammar(xConnection) )
        {
            weld::ComboBox& rComboBox = m_pFunctionCell->get_widget();
            for (sal_Int32 nIdx {0}; nIdx>=0;)
                rComboBox.append_text(m_aFunctionStrings.getToken(0, ';', nIdx));
        }
        else // else only COUNT(*) and COUNT("table".*)
        {
            weld::ComboBox& rComboBox = m_pFunctionCell->get_widget();
            rComboBox.append_text(m_aFunctionStrings.getToken(0, ';'));
            rComboBox.append_text(m_aFunctionStrings.getToken(2, ';')); // 2 -> COUNT
        }
        try
        {
            Reference< XDatabaseMetaData >  xMetaData = xConnection->getMetaData();
            if ( xMetaData.is() )
            {
                m_bOrderByUnRelated = xMetaData->supportsOrderByUnrelated();
                m_bGroupByUnRelated = xMetaData->supportsGroupByUnrelated();
            }
        }
        catch(Exception&)
        {
        }
    }

    Init();
}

OQueryDesignView* OSelectionBrowseBox::getDesignView()
{
    OSL_ENSURE(static_cast<const OQueryDesignView*>(GetParent()),"Parent isn't an OQueryDesignView!");
    return static_cast<OQueryDesignView*>(GetParent());
}

OQueryDesignView* OSelectionBrowseBox::getDesignView() const
{
    OSL_ENSURE(static_cast<const OQueryDesignView*>(GetParent()),"Parent isn't an OQueryDesignView!");
    return static_cast<OQueryDesignView*>(GetParent());
}

namespace
{
    class OSelectionBrwBoxHeader : public ::svt::EditBrowserHeader
    {
        VclPtr<OSelectionBrowseBox> m_pBrowseBox;
    protected:
        virtual void Select() override;
    public:
        explicit OSelectionBrwBoxHeader(OSelectionBrowseBox* pParent);
        virtual ~OSelectionBrwBoxHeader() override { disposeOnce(); }
        virtual void dispose() override { m_pBrowseBox.clear(); ::svt::EditBrowserHeader::dispose(); }
    };
    OSelectionBrwBoxHeader::OSelectionBrwBoxHeader(OSelectionBrowseBox* pParent)
        : ::svt::EditBrowserHeader(pParent,WB_BUTTONSTYLE|WB_DRAG)
        ,m_pBrowseBox(pParent)
    {
    }

    void OSelectionBrwBoxHeader::Select()
    {
        EditBrowserHeader::Select();
        m_pBrowseBox->GrabFocus();

        BrowserMode nMode = m_pBrowseBox->GetMode();
        if ( 0 == m_pBrowseBox->GetSelectColumnCount() )
        {
            m_pBrowseBox->DeactivateCell();
            // we are in the right mode if a row has been selected row
            if ( nMode & BrowserMode::HIDESELECT )
            {
                nMode &= ~BrowserMode::HIDESELECT;
                nMode |= BrowserMode::MULTISELECTION;
                m_pBrowseBox->SetMode( nMode );
            }
        }
        m_pBrowseBox->SelectColumnId( GetCurItemId() );
        m_pBrowseBox->DeactivateCell();
    }
}

VclPtr<BrowserHeader> OSelectionBrowseBox::imp_CreateHeaderBar(BrowseBox* /*pParent*/)<--- The function 'imp_CreateHeaderBar' is never used.
{
    return VclPtr<OSelectionBrwBoxHeader>::Create(this);
}

void OSelectionBrowseBox::ColumnMoved( sal_uInt16 nColId, bool _bCreateUndo )
{
    EditBrowseBox::ColumnMoved( nColId );
    // swap the two columns
    sal_uInt16 nNewPos = GetColumnPos( nColId );
    OTableFields& rFields = getFields();
    if ( rFields.size() > o3tl::make_unsigned(nNewPos-1) )
    {
        sal_uInt16 nOldPos = 0;
        bool bFoundElem = false;
        for (auto const& field : rFields)
        {
            if (field->GetColumnId() == nColId)
            {
                bFoundElem = true;
                break;
            }
            ++nOldPos;
        }

        OSL_ENSURE( (nNewPos-1) != nOldPos && nOldPos < rFields.size(),"Old and new position are equal!");
        if (bFoundElem)
        {
            OTableFieldDescRef pOldEntry = rFields[nOldPos];
            rFields.erase(rFields.begin() + nOldPos);
            rFields.insert(rFields.begin() + nNewPos - 1,pOldEntry);

            // create the undo action
            if ( !m_bInUndoMode && _bCreateUndo )
            {
                std::unique_ptr<OTabFieldMovedUndoAct> pUndoAct(new OTabFieldMovedUndoAct(this));
                pUndoAct->SetColumnPosition( nOldPos + 1);
                pUndoAct->SetTabFieldDescr(pOldEntry);

                getDesignView()->getController().addUndoActionAndInvalidate(std::move(pUndoAct));
            }
        }
    }
    else
        OSL_FAIL("Invalid column id!");
}

void OSelectionBrowseBox::Init()
{

    EditBrowseBox::Init();

    // set the header bar
    VclPtr<BrowserHeader> pNewHeaderBar = CreateHeaderBar(this);
    pNewHeaderBar->SetMouseTransparent(false);

    SetHeaderBar(pNewHeaderBar);
    SetMode(m_nMode);

    vcl::Font aFont( GetDataWindow().GetFont() );
    aFont.SetWeight( WEIGHT_NORMAL );
    GetDataWindow().SetFont( aFont );

    Size aHeight;
    const Control* pControls[] = { m_pTextCell,m_pVisibleCell,m_pTableCell,m_pFieldCell };

    for (const Control* pControl : pControls)
    {
        const Size aTemp(pControl->GetOptimalSize());
        if ( aTemp.Height() > aHeight.Height() )
            aHeight.setHeight( aTemp.Height() );
    }
    SetDataRowHeight(aHeight.Height());
    SetTitleLines(1);
    // get number of visible rows
    for(long i=0;i<BROW_ROW_CNT;i++)
    {
        if(m_bVisibleRow[i])
            m_nVisibleCount++;
    }
    RowInserted(0, m_nVisibleCount, false);
    try
    {
        Reference< XConnection> xConnection = static_cast<OQueryController&>(getDesignView()->getController()).getConnection();
        if(xConnection.is())
        {
            Reference< XDatabaseMetaData >  xMetaData = xConnection->getMetaData();
            m_nMaxColumns = xMetaData.is() ? xMetaData->getMaxColumnsInSelect() : 0;

        }
        else
            m_nMaxColumns = 0;
    }
    catch(const SQLException&)
    {
        OSL_FAIL("Caught Exception when asking for database metadata options!");
        m_nMaxColumns = 0;
    }
}

void OSelectionBrowseBox::PreFill()
{
    SetUpdateMode(false);

    if (GetCurRow() != 0)
        GoToRow(0);

    static_cast< OQueryController& >( getDesignView()->getController() ).clearFields();

    DeactivateCell();

    RemoveColumns();
    InsertHandleColumn( HANDLE_COLUMN_WIDTH );
    SetUpdateMode(true);
}

void OSelectionBrowseBox::ClearAll()
{
    SetUpdateMode(false);

    OTableFields::const_reverse_iterator aIter = getFields().rbegin();
    for ( ;aIter != getFields().rend(); ++aIter )
    {
        if ( !(*aIter)->IsEmpty() )
        {
            RemoveField( (*aIter)->GetColumnId() );
            aIter = getFields().rbegin();
        }
    }
    m_nLastSortColumn = SORT_COLUMN_NONE;
    SetUpdateMode(true);
}

void OSelectionBrowseBox::SetReadOnly(bool bRO)
{
    if (bRO)
    {
        DeactivateCell();
        m_nMode &= ~BrowserMode::HIDECURSOR;
        SetMode(m_nMode);
    }
    else
    {
        m_nMode |= BrowserMode::HIDECURSOR;
        SetMode(m_nMode);
        ActivateCell();
    }
}

CellController* OSelectionBrowseBox::GetController(long nRow, sal_uInt16 nColId)
{
    if ( nColId > getFields().size() )
        return nullptr;
    OTableFieldDescRef pEntry = getFields()[nColId-1];
    OSL_ENSURE(pEntry.is(), "OSelectionBrowseBox::GetController : invalid FieldDescription !");

    if (!pEntry.is())
        return nullptr;

    if (static_cast<OQueryController&>(getDesignView()->getController()).isReadOnly())
        return nullptr;

    long nCellIndex = GetRealRow(nRow);
    switch (nCellIndex)
    {
        case BROW_FIELD_ROW:
            return new ComboBoxCellController(m_pFieldCell);
        case BROW_TABLE_ROW:
            return new ListBoxCellController(m_pTableCell);
        case BROW_VIS_ROW:
            return new CheckBoxCellController(m_pVisibleCell);
        case BROW_ORDER_ROW:
            return new ListBoxCellController(m_pOrderCell);
        case BROW_FUNCTION_ROW:
            return new ListBoxCellController(m_pFunctionCell);
        default:
            return new EditCellController(m_pTextCell);
    }
}

void OSelectionBrowseBox::InitController(CellControllerRef& /*rController*/, long nRow, sal_uInt16 nColId)
{
    OSL_ENSURE(nColId != BROWSER_INVALIDID,"An Invalid Id was set!");
    if ( nColId == BROWSER_INVALIDID )
        return;
    sal_uInt16 nPos = GetColumnPos(nColId);
    if ( nPos == 0 || nPos == BROWSER_INVALIDID || nPos > getFields().size() )
        return;
    OTableFieldDescRef pEntry = getFields()[nPos-1];
    OSL_ENSURE(pEntry.is(), "OSelectionBrowseBox::InitController : invalid FieldDescription !");
    long nCellIndex = GetRealRow(nRow);

    switch (nCellIndex)
    {
        case BROW_FIELD_ROW:
        {
            weld::ComboBox& rComboBox = m_pFieldCell->get_widget();
            rComboBox.clear();
            rComboBox.set_entry_text(OUString());

            OUString aField(pEntry->GetField());
            OUString aTable(pEntry->GetAlias());

            getDesignView()->fillValidFields(aTable, rComboBox);

            // replace with alias.*
            if (aField.trim() == "*")
            {
                aField = aTable + ".*";
            }
            rComboBox.set_entry_text(aField);
        }   break;
        case BROW_TABLE_ROW:
        {
            weld::ComboBox& rComboBox = m_pTableCell->get_widget();
            rComboBox.clear();
            enableControl(pEntry, m_pTableCell);
            if ( !pEntry->isCondition() )
            {
                for (auto const& tabWin : getDesignView()->getTableView()->GetTabWinMap())
                    rComboBox.append_text(static_cast<OQueryTableWindow*>(tabWin.second.get())->GetAliasName());

                rComboBox.insert_text(0, DBA_RES(STR_QUERY_NOTABLE));
                if (!pEntry->GetAlias().isEmpty())
                    rComboBox.set_active_text(pEntry->GetAlias());
                else
                    rComboBox.set_active_text(DBA_RES(STR_QUERY_NOTABLE));
            }
        }   break;
        case BROW_VIS_ROW:
        {
            m_pVisibleCell->GetBox().Check(pEntry->IsVisible());
            m_pVisibleCell->GetBox().SaveValue();

            enableControl(pEntry,m_pTextCell);

            if(!pEntry->IsVisible() && pEntry->GetOrderDir() != ORDER_NONE && !m_bOrderByUnRelated)
            {
               // a column has to visible in order to show up in ORDER BY
                pEntry->SetVisible();
                m_pVisibleCell->GetBox().Check(pEntry->IsVisible());
                m_pVisibleCell->GetBox().SaveValue();
                m_pVisibleCell->GetBox().Disable();
                m_pVisibleCell->GetBox().EnableInput(false);
                OUString aMessage(DBA_RES(STR_QRY_ORDERBY_UNRELATED));
                OQueryDesignView* paDView = getDesignView();
                std::unique_ptr<weld::MessageDialog> xInfoBox(Application::CreateMessageDialog(paDView ? paDView->GetFrameWeld() : nullptr,
                                                              VclMessageType::Info, VclButtonsType::Ok,
                                                              aMessage));
                xInfoBox->run();
            }
        }   break;
        case BROW_ORDER_ROW:
        {
            weld::ComboBox& rComboBox = m_pOrderCell->get_widget();
            rComboBox.set_active(
                sal::static_int_cast< sal_uInt16 >(pEntry->GetOrderDir()));
            enableControl(pEntry,m_pOrderCell);
            break;
        }
        case BROW_COLUMNALIAS_ROW:
            setTextCellContext(pEntry,pEntry->GetFieldAlias(),HID_QRYDGN_ROW_ALIAS);
            break;
        case BROW_FUNCTION_ROW:
            setFunctionCell(pEntry);
            break;
        default:
        {
            sal_uInt16  nIdx = sal_uInt16(nCellIndex - BROW_CRIT1_ROW);
            setTextCellContext(pEntry,pEntry->GetCriteria( nIdx ),HID_QRYDGN_ROW_CRIT);
        }
    }
    Controller()->ClearModified();
}

void OSelectionBrowseBox::notifyTableFieldChanged(const OUString& _sOldAlias, const OUString& _sAlias, bool& _bListAction, sal_uInt16 _nColumnId)
{
    appendUndoAction(_sOldAlias,_sAlias,BROW_TABLE_ROW,_bListAction);
    if ( m_bVisibleRow[BROW_TABLE_ROW] )
        RowModified(GetBrowseRow(BROW_TABLE_ROW), _nColumnId);
}

void OSelectionBrowseBox::notifyFunctionFieldChanged(const OUString& _sOldFunctionName, const OUString& _sFunctionName, bool& _bListAction, sal_uInt16 _nColumnId)
{
    appendUndoAction(_sOldFunctionName,_sFunctionName,BROW_FUNCTION_ROW,_bListAction);
    if ( !m_bVisibleRow[BROW_FUNCTION_ROW] )
        SetRowVisible(BROW_FUNCTION_ROW, true);
    RowModified(GetBrowseRow(BROW_FUNCTION_ROW), _nColumnId);
}

void OSelectionBrowseBox::clearEntryFunctionField(const OUString& _sFieldName,OTableFieldDescRef const & _pEntry, bool& _bListAction,sal_uInt16 _nColumnId)
{
    if ( !(isFieldNameAsterisk( _sFieldName ) && (!_pEntry->isNoneFunction() || _pEntry->IsGroupBy())) )
        return;

    OUString sFunctionName;
    GetFunctionName(SQL_TOKEN_COUNT,sFunctionName);
    OUString sOldLocalizedFunctionName = _pEntry->GetFunction();
    if ( sOldLocalizedFunctionName != sFunctionName || _pEntry->IsGroupBy() )
    {
        // append undo action for the function field
        _pEntry->SetFunctionType(FKT_NONE);
        _pEntry->SetFunction(OUString());
        _pEntry->SetGroupBy(false);
        notifyFunctionFieldChanged(sOldLocalizedFunctionName,_pEntry->GetFunction(),_bListAction,_nColumnId);
    }
}

bool OSelectionBrowseBox::fillColumnRef(const OSQLParseNode* _pColumnRef, const Reference< XConnection >& _rxConnection, OTableFieldDescRef const & _pEntry, bool& _bListAction )
{
    OSL_ENSURE(_pColumnRef,"No valid parsenode!");
    OUString sColumnName,sTableRange;
    OSQLParseTreeIterator::getColumnRange(_pColumnRef,_rxConnection,sColumnName,sTableRange);
    return fillColumnRef(sColumnName,sTableRange,_rxConnection->getMetaData(),_pEntry,_bListAction);
}

bool OSelectionBrowseBox::fillColumnRef(const OUString& _sColumnName, const OUString& _sTableRange, const Reference<XDatabaseMetaData>& _xMetaData, OTableFieldDescRef const & _pEntry, bool& _bListAction)
{
    bool bError = false;
    ::comphelper::UStringMixEqual bCase(_xMetaData->supportsMixedCaseQuotedIdentifiers());
    // check if the table name is the same
    if ( !_sTableRange.isEmpty() && (bCase(_pEntry->GetTable(),_sTableRange) || bCase(_pEntry->GetAlias(),_sTableRange)) )
    { // a table was already inserted and the tables contains that column name

        if ( !_pEntry->GetTabWindow() )
        { // fill tab window
            OUString sOldAlias = _pEntry->GetAlias();
            if ( !fillEntryTable(_pEntry,_pEntry->GetTable()) )
                fillEntryTable(_pEntry,_pEntry->GetAlias()); // only when the first failed
            if ( !bCase(sOldAlias,_pEntry->GetAlias()) )
                notifyTableFieldChanged(sOldAlias,_pEntry->GetAlias(),_bListAction,GetCurColumnId());
        }
    }
    // check if the table window
    OQueryTableWindow* pEntryTab = static_cast<OQueryTableWindow*>(_pEntry->GetTabWindow());
    if ( !pEntryTab ) // no table found with this name so we have to travel through all tables
    {
        sal_uInt16 nTabCount = 0;
        if ( !static_cast<OQueryTableView*>(getDesignView()->getTableView())->FindTableFromField(_sColumnName,_pEntry,nTabCount) ) // error occurred: column not in table window
        {
            OUString sErrorMsg(DBA_RES(RID_STR_FIELD_DOESNT_EXIST));
            sErrorMsg = sErrorMsg.replaceFirst("$name$",_sColumnName);
            OSQLErrorBox aWarning(GetFrameWeld(), sErrorMsg);
            aWarning.run();
            bError = true;
        }
        else
        {
            pEntryTab = static_cast<OQueryTableWindow*>(_pEntry->GetTabWindow());
            notifyTableFieldChanged(OUString(),_pEntry->GetAlias(),_bListAction,GetCurColumnId());
        }
    }
    if ( pEntryTab ) // here we got a valid table
        _pEntry->SetField(_sColumnName);

    return bError;
}

bool OSelectionBrowseBox::saveField(OUString& _sFieldName ,OTableFieldDescRef const & _pEntry, bool& _bListAction)
{
    bool bError = false;

    OQueryController& rController = static_cast<OQueryController&>(getDesignView()->getController());

    // first look if the name can be found in our tables
    sal_uInt16 nTabCount = 0;
    OUString sOldAlias = _pEntry->GetAlias();
    if ( static_cast<OQueryTableView*>(getDesignView()->getTableView())->FindTableFromField(_sFieldName,_pEntry,nTabCount) )
    {
        // append undo action for the alias name
        _pEntry->SetField(_sFieldName);
        notifyTableFieldChanged(sOldAlias,_pEntry->GetAlias(),_bListAction,GetCurColumnId());
        clearEntryFunctionField(_sFieldName,_pEntry,_bListAction,_pEntry->GetColumnId());
        return bError;
    }

    Reference<XConnection> xConnection( rController.getConnection() );
    Reference< XDatabaseMetaData > xMetaData;
    if ( xConnection.is() )
        xMetaData = xConnection->getMetaData();
    OSL_ENSURE( xMetaData.is(), "OSelectionBrowseBox::saveField: invalid connection/meta data!" );
    if ( !xMetaData.is() )
        return true;

    OUString sErrorMsg;
    // second test if the name can be set as select columns in a pseudo statement
    // we have to look which entries  we should quote

    const OUString sFieldAlias = _pEntry->GetFieldAlias();
    ::connectivity::OSQLParser& rParser( rController.getParser() );
    {
        // automatically add parentheses around subqueries
        OUString devnull;
        std::unique_ptr<OSQLParseNode> pParseNode = rParser.parseTree( devnull, _sFieldName, true );
        if (pParseNode == nullptr)
            pParseNode = rParser.parseTree( devnull, _sFieldName );
        if (pParseNode != nullptr && SQL_ISRULE(pParseNode, select_statement))
            _sFieldName = "(" + _sFieldName + ")";
    }

    std::unique_ptr<OSQLParseNode> pParseNode;
    {
        // 4 passes in trying to interpret the field name
        // - don't quote the field name, parse internationally
        // - don't quote the field name, parse en-US
        // - quote the field name, parse internationally
        // - quote the field name, parse en-US
        size_t nPass = 4;
        OUString sQuotedFullFieldName(::dbtools::quoteName( xMetaData->getIdentifierQuoteString(), _sFieldName ));
        OUString sFullFieldName(_sFieldName);

        if  ( _pEntry->isAggregateFunction() )
        {
            OSL_ENSURE(!_pEntry->GetFunction().isEmpty(),"No empty Function name allowed here! ;-(");
            sQuotedFullFieldName = _pEntry->GetFunction() + "(" + sQuotedFullFieldName + ")";
            sFullFieldName = _pEntry->GetFunction() + "(" + sFullFieldName + ")";
        }

        do
        {
            bool bQuote = ( nPass <= 2 );
            bool bInternational = ( nPass % 2 ) == 0;

            OUString sSql {"SELECT "};
            if ( bQuote )
                sSql += sQuotedFullFieldName;
            else
                sSql += sFullFieldName;

            if ( !sFieldAlias.isEmpty() )
            { // always quote the alias name: there cannot be a function in it
                sSql += " " + ::dbtools::quoteName( xMetaData->getIdentifierQuoteString(), sFieldAlias );
            }
            sSql += " FROM x";

            pParseNode = rParser.parseTree( sErrorMsg, sSql, bInternational );
        }
        while ( ( pParseNode == nullptr ) && ( --nPass > 0 ) );
    }

    if ( pParseNode == nullptr )
    {
        // something different which we have to check
        OUString sErrorMessage( DBA_RES( STR_QRY_COLUMN_NOT_FOUND ) );
        sErrorMessage = sErrorMessage.replaceFirst("$name$",_sFieldName);
        OSQLErrorBox aWarning(GetFrameWeld(), sErrorMessage);
        aWarning.run();

        return true;
    }

    // we got a valid select column
    // find what type of column has be inserted
    ::connectivity::OSQLParseNode* pSelection = pParseNode->getChild(2);
    if ( SQL_ISRULE(pSelection,selection) ) // we found the asterisk
    {
        _pEntry->SetField(_sFieldName);
        clearEntryFunctionField(_sFieldName,_pEntry,_bListAction,_pEntry->GetColumnId());
    }
    else // travel through the select column parse node
    {
        OTableFieldDescRef aSelEntry = _pEntry;
        sal_uInt16 nColumnId = aSelEntry->GetColumnId();

        sal_uInt32 nCount = pSelection->count();
        for (sal_uInt32 i = 0; i < nCount; ++i)
        {
            if ( i > 0 ) // may we have to append more than one field
            {
                sal_uInt16 nColumnPosition;
                aSelEntry = FindFirstFreeCol(nColumnPosition);
                if ( !aSelEntry.is() )
                {
                    AppendNewCol();
                    aSelEntry = FindFirstFreeCol(nColumnPosition);
                }
                ++nColumnPosition;
                nColumnId = GetColumnId(nColumnPosition);
            }

            ::connectivity::OSQLParseNode* pChild = pSelection->getChild( i );
            OSL_ENSURE(SQL_ISRULE(pChild,derived_column), "No derived column found!");
            // get the column alias
            OUString sColumnAlias = OSQLParseTreeIterator::getColumnAlias(pChild);
            if ( !sColumnAlias.isEmpty() ) // we found an as clause
            {
                OUString aSelectionAlias = aSelEntry->GetFieldAlias();
                aSelEntry->SetFieldAlias( sColumnAlias );
                // append undo
                appendUndoAction(aSelectionAlias,aSelEntry->GetFieldAlias(),BROW_COLUMNALIAS_ROW,_bListAction);
                if ( m_bVisibleRow[BROW_COLUMNALIAS_ROW] )
                    RowModified(GetBrowseRow(BROW_COLUMNALIAS_ROW), nColumnId);
            }

            ::connectivity::OSQLParseNode* pColumnRef = pChild->getChild(0);
            if (
                    pColumnRef->getKnownRuleID() != OSQLParseNode::subquery &&
                    pColumnRef->count() == 3 &&
                    SQL_ISPUNCTUATION(pColumnRef->getChild(0),"(") &&
                    SQL_ISPUNCTUATION(pColumnRef->getChild(2),")")
                )
                pColumnRef = pColumnRef->getChild(1);

            if ( SQL_ISRULE(pColumnRef,column_ref) ) // we found a valid column name or more column names
            {
                // look if we can find the corresponding table
                bError = fillColumnRef( pColumnRef, xConnection, aSelEntry, _bListAction );

                // we found a simple column so we must clear the function fields but only when the column name is '*'
                // and the function is different to count
                clearEntryFunctionField(_sFieldName,aSelEntry,_bListAction,nColumnId);
            }
            // do we have an aggregate function and only a function?
            else if ( SQL_ISRULE(pColumnRef,general_set_fct) )
            {
                OUString sLocalizedFunctionName;
                if ( GetFunctionName(pColumnRef->getChild(0)->getTokenID(),sLocalizedFunctionName) )
                {
                    OUString sOldLocalizedFunctionName = aSelEntry->GetFunction();
                    aSelEntry->SetFunction(sLocalizedFunctionName);
                    sal_uInt32 nFunCount = pColumnRef->count() - 1;
                    sal_Int32 nFunctionType = FKT_AGGREGATE;
                    bool bQuote = false;
                    // may be there exists only one parameter which is a column, fill all information into our fields
                    if ( nFunCount == 4 && SQL_ISRULE(pColumnRef->getChild(3),column_ref) )
                        bError = fillColumnRef( pColumnRef->getChild(3), xConnection, aSelEntry, _bListAction );
                    else if ( nFunCount == 3 ) // we have a COUNT(*) here, so take the first table
                        bError = fillColumnRef( "*", OUString(), xMetaData, aSelEntry, _bListAction );
                    else
                    {
                        nFunctionType |= FKT_NUMERIC;
                        bQuote = true;
                        aSelEntry->SetDataType(DataType::DOUBLE);
                        aSelEntry->SetFieldType(TAB_NORMAL_FIELD);
                    }

                    // now parse the parameters
                    OUString sParameters;
                    for(sal_uInt32 function = 2; function < nFunCount; ++function) // we only want to parse the parameters of the function
                        pColumnRef->getChild(function)->parseNodeToStr( sParameters, xConnection, &rParser.getContext(), true, bQuote );

                    aSelEntry->SetFunctionType(nFunctionType);
                    aSelEntry->SetField(sParameters);
                    if ( aSelEntry->IsGroupBy() )
                    {
                        sOldLocalizedFunctionName = m_aFunctionStrings.copy(m_aFunctionStrings.lastIndexOf(';')+1);
                        aSelEntry->SetGroupBy(false);
                    }

                    // append undo action
                    notifyFunctionFieldChanged(sOldLocalizedFunctionName,sLocalizedFunctionName,_bListAction, nColumnId);
                }
                else
                    OSL_FAIL("Unsupported function inserted!");

            }
            else
            {
                // so we first clear the function field
                clearEntryFunctionField(_sFieldName,aSelEntry,_bListAction,nColumnId);
                OUString sFunction;
                pColumnRef->parseNodeToStr( sFunction,
                                            xConnection,
                                            &rController.getParser().getContext(),
                                            true); // quote is to true because we need quoted elements inside the function

                getDesignView()->fillFunctionInfo(pColumnRef,sFunction,aSelEntry);

                if( SQL_ISRULEOR3(pColumnRef, position_exp, extract_exp, fold) ||
                    SQL_ISRULEOR3(pColumnRef, char_substring_fct, length_exp, char_value_fct) )
                    // a calculation has been found ( can be calc and function )
                {
                    // now parse the whole statement
                    sal_uInt32 nFunCount = pColumnRef->count();
                    OUString sParameters;
                    for(sal_uInt32 function = 0; function < nFunCount; ++function)
                        pColumnRef->getChild(function)->parseNodeToStr( sParameters, xConnection, &rParser.getContext(), true );

                    sOldAlias = aSelEntry->GetAlias();
                    sal_Int32 nNewFunctionType = aSelEntry->GetFunctionType() | FKT_NUMERIC | FKT_OTHER;
                    aSelEntry->SetFunctionType(nNewFunctionType);
                    aSelEntry->SetField(sParameters);
                }
                else
                {
                    aSelEntry->SetFieldAlias(sColumnAlias);
                    if ( SQL_ISRULE(pColumnRef,set_fct_spec) )
                        aSelEntry->SetFunctionType(/*FKT_NUMERIC | */FKT_OTHER);
                    else
                        aSelEntry->SetFunctionType(FKT_NUMERIC | FKT_OTHER);
                }

                aSelEntry->SetAlias(OUString());
                notifyTableFieldChanged(sOldAlias,aSelEntry->GetAlias(),_bListAction, nColumnId);
            }

            if ( i > 0 && !InsertField(aSelEntry,BROWSER_INVALIDID,true,false).is() ) // may we have to append more than one field
            { // the field could not be inserted
                OUString sErrorMessage( DBA_RES( RID_STR_FIELD_DOESNT_EXIST ) );
                sErrorMessage = sErrorMessage.replaceFirst("$name$",aSelEntry->GetField());
                OSQLErrorBox aWarning(GetFrameWeld(), sErrorMessage);
                aWarning.run();
                bError = true;
            }
        }
    }

    return bError;
}

bool OSelectionBrowseBox::SaveModified()
{
    OQueryController& rController = static_cast<OQueryController&>(getDesignView()->getController());
    OTableFieldDescRef pEntry;
    sal_uInt16 nCurrentColumnPos = GetColumnPos(GetCurColumnId());
    if(getFields().size() > o3tl::make_unsigned(nCurrentColumnPos - 1))
        pEntry = getEntry(nCurrentColumnPos - 1);

    bool bWasEmpty      = pEntry.is() && pEntry->IsEmpty();
    bool bError         = false;
    bool bListAction    = false;

    if (pEntry.is() && Controller().is() && Controller()->IsModified())
    {
        // for the Undo-action
        OUString strOldCellContents,sNewValue;
        long nRow = GetRealRow(GetCurRow());
        bool bAppendRow = false;
        switch (nRow)
        {
            case BROW_VIS_ROW:
                {
                    bool bOldValue = m_pVisibleCell->GetBox().GetSavedValue() != TRISTATE_FALSE;
                    strOldCellContents = bOldValue ? OUStringLiteral("1") : OUStringLiteral("0");
                    sNewValue          = !bOldValue ? OUStringLiteral("1") : OUStringLiteral("0");
                }
                if((m_bOrderByUnRelated || pEntry->GetOrderDir() == ORDER_NONE) &&
                   (m_bGroupByUnRelated || !pEntry->IsGroupBy()))
                {
                    pEntry->SetVisible(m_pVisibleCell->GetBox().IsChecked());
                }
                else
                {
                    pEntry->SetVisible();
                    m_pVisibleCell->GetBox().Check();
                }
                break;

            case BROW_FIELD_ROW:
            {
                weld::ComboBox& rComboBox = m_pFieldCell->get_widget();
                OUString aFieldName(rComboBox.get_active_text());
                try
                {
                    if (aFieldName.isEmpty())
                    {
                        OTableFieldDescRef pNewEntry = new OTableFieldDesc();
                        pNewEntry->SetColumnId( pEntry->GetColumnId() );
                        std::replace(getFields().begin(),getFields().end(),pEntry,pNewEntry);
                        sal_uInt16 nCol = GetCurColumnId();
                        for (int i = 0; i < m_nVisibleCount; i++)   // redraw column
                            RowModified(i,nCol);
                    }
                    else
                    {
                        strOldCellContents = pEntry->GetField();
                        bListAction = true;
                        if ( !m_bInUndoMode )
                            rController.GetUndoManager().EnterListAction(OUString(),OUString(),0,ViewShellId(-1));

                        sal_Int32 nPos = rComboBox.find_text(aFieldName);
                        OUString aAliasName = pEntry->GetAlias();
                        if ( nPos != -1 && aAliasName.isEmpty() && aFieldName.indexOf('.') >= 0 )
                        { // special case, we have a table field so we must cut the table name
                            OUString sTableAlias = aFieldName.getToken(0,'.');
                            pEntry->SetAlias(sTableAlias);
                            OUString sColumnName = aFieldName.copy(sTableAlias.getLength()+1);
                            const Reference<XConnection>& xConnection = rController.getConnection();
                            if ( !xConnection.is() )
                                return false;
                            bError = fillColumnRef( sColumnName, sTableAlias, xConnection->getMetaData(), pEntry, bListAction );
                        }
                        else
                            bError = true;

                        if ( bError )
                            bError = saveField(aFieldName,pEntry,bListAction);
                    }
                }
                catch(Exception&)
                {
                    bError = true;
                }
                if ( bError )
                {
                    sNewValue = aFieldName;
                    if ( !m_bInUndoMode )
                        static_cast<OQueryController&>(getDesignView()->getController()).GetUndoManager().LeaveListAction();
                    bListAction = false;
                }
                else
                    sNewValue = pEntry->GetField();
                rController.InvalidateFeature( ID_BROWSER_QUERY_EXECUTE );
            }
            break;

            case BROW_TABLE_ROW:
            {
                weld::ComboBox& rComboBox = m_pTableCell->get_widget();
                OUString aAliasName = rComboBox.get_active_text();
                strOldCellContents = pEntry->GetAlias();
                if (rComboBox.get_active() != 0)
                {
                    pEntry->SetAlias(aAliasName);
                    // we have to set the table name as well as the table window
                    OJoinTableView::OTableWindowMap& rTabWinList = getDesignView()->getTableView()->GetTabWinMap();
                    OJoinTableView::OTableWindowMap::const_iterator aIter = rTabWinList.find(aAliasName);
                    if(aIter != rTabWinList.end())
                    {
                        OQueryTableWindow* pEntryTab = static_cast<OQueryTableWindow*>(aIter->second.get());
                        if (pEntryTab)
                        {
                            pEntry->SetTable(pEntryTab->GetTableName());
                            pEntry->SetTabWindow(pEntryTab);
                        }
                    }
                }
                else
                {
                    pEntry->SetAlias(OUString());
                    pEntry->SetTable(OUString());
                    pEntry->SetTabWindow(nullptr);
                }
                sNewValue = pEntry->GetAlias();

            }   break;

            case BROW_ORDER_ROW:
            {
                strOldCellContents = OUString::number(static_cast<sal_uInt16>(pEntry->GetOrderDir()));
                weld::ComboBox& rComboBox = m_pOrderCell->get_widget();
                sal_Int32 nIdx = rComboBox.get_active();
                if (nIdx == -1)
                    nIdx = 0;
                pEntry->SetOrderDir(EOrderDir(nIdx));
                if(!m_bOrderByUnRelated)
                {
                    pEntry->SetVisible();
                    m_pVisibleCell->GetBox().Check();
                    RowModified(GetBrowseRow(BROW_VIS_ROW), GetCurColumnId());
                }
                sNewValue = OUString::number(static_cast<sal_uInt16>(pEntry->GetOrderDir()));
            }   break;

            case BROW_COLUMNALIAS_ROW:
                strOldCellContents = pEntry->GetFieldAlias();
                pEntry->SetFieldAlias(m_pTextCell->GetText());
                sNewValue = pEntry->GetFieldAlias();
                break;
            case BROW_FUNCTION_ROW:
                {
                    strOldCellContents = pEntry->GetFunction();
                    weld::ComboBox& rComboBox = m_pFunctionCell->get_widget();
                    sal_Int32 nPos = rComboBox.get_active();
                    // these functions are only available in CORE
                    OUString sFunctionName        = rComboBox.get_text(nPos);
                    OUString sGroupFunctionName   = m_aFunctionStrings.copy(m_aFunctionStrings.lastIndexOf(';')+1);
                    bool bGroupBy = false;
                    if ( sGroupFunctionName == sFunctionName ) // check if the function name is GROUP
                    {
                        bGroupBy = true;

                        if ( !m_bGroupByUnRelated && !pEntry->IsVisible() )
                        {
                            // we have to change the visible flag, so we must append also an undo action
                            pEntry->SetVisible();
                            m_pVisibleCell->GetBox().Check();
                            appendUndoAction("0","1",BROW_VIS_ROW,bListAction);
                            RowModified(GetBrowseRow(BROW_VIS_ROW), GetCurColumnId());
                        }

                        pEntry->SetFunction(OUString());
                        pEntry->SetFunctionType(pEntry->GetFunctionType() & ~FKT_AGGREGATE );
                    }
                    else if ( nPos ) // we found an aggregate function
                    {
                        pEntry->SetFunctionType(pEntry->GetFunctionType() | FKT_AGGREGATE );
                        pEntry->SetFunction(sFunctionName);
                    }
                    else
                    {
                        sFunctionName.clear();
                        pEntry->SetFunction(OUString());
                        pEntry->SetFunctionType(pEntry->GetFunctionType() & ~FKT_AGGREGATE );
                    }

                    pEntry->SetGroupBy(bGroupBy);

                    sNewValue = sFunctionName;
                }
                break;
            default:
            {
                Reference< XConnection> xConnection = static_cast<OQueryController&>(getDesignView()->getController()).getConnection();
                if(!xConnection.is())
                    break;

                sal_uInt16  nIdx = sal_uInt16(nRow - BROW_CRIT1_ROW);
                OUString aText = comphelper::string::stripStart(m_pTextCell->GetText(), ' ');

                OUString aCrit;
                if(!aText.isEmpty())
                {
                    OUString aErrorMsg;
                    Reference<XPropertySet> xColumn;
                    std::unique_ptr<OSQLParseNode> pParseNode = getDesignView()->getPredicateTreeFromEntry(pEntry,aText,aErrorMsg,xColumn);

                    if (pParseNode)
                    {
                        pParseNode->parseNodeToPredicateStr(aCrit,
                                                            xConnection,
                                                            static_cast<OQueryController&>(getDesignView()->getController()).getNumberFormatter(),
                                                            xColumn,
                                                            pEntry->GetAlias(),
                                                            getDesignView()->getLocale(),
                                                            getDesignView()->getDecimalSeparator(),
                                                            &(static_cast<OQueryController&>(getDesignView()->getController()).getParser().getContext()));
                    }
                    else
                    {
                        if(xColumn.is())
                        {
                            sal_Int32 nType = 0;
                            xColumn->getPropertyValue(PROPERTY_TYPE) >>= nType;
                            switch(nType)
                            {
                                case DataType::CHAR:
                                case DataType::VARCHAR:
                                case DataType::LONGVARCHAR:
                                case DataType::CLOB:
                                    if(!aText.startsWith("'") || !aText.endsWith("'"))
                                    {
                                        aText = aText.replaceAll("'", "''");
                                        aText = "'" + aText + "'";
                                    }
                                    break;
                                default:
                                    ;
                            }
                            ::connectivity::OSQLParser& rParser = static_cast<OQueryController&>(getDesignView()->getController()).getParser();
                            pParseNode = rParser.predicateTree(aErrorMsg,
                                                                aText,
                                                                static_cast<OQueryController&>(getDesignView()->getController()).getNumberFormatter(),
                                                                xColumn);
                            if (pParseNode)
                            {
                                pParseNode->parseNodeToPredicateStr(aCrit,
                                                                    xConnection,
                                                                    static_cast<OQueryController&>(getDesignView()->getController()).getNumberFormatter(),
                                                                    xColumn,
                                                                    pEntry->GetAlias(),
                                                                    getDesignView()->getLocale(),
                                                                    getDesignView()->getDecimalSeparator(),
                                                                    &(static_cast<OQueryController&>(getDesignView()->getController()).getParser().getContext()));
                            }
                            else
                            {
                                if ( !m_bDisableErrorBox )
                                {
                                    OSQLWarningBox aWarning(GetFrameWeld(), aErrorMsg);
                                    aWarning.run();
                                }
                                bError = true;
                            }
                        }
                        else
                        {
                            if ( !m_bDisableErrorBox )
                            {
                                OSQLWarningBox aWarning(GetFrameWeld(), aErrorMsg);
                                aWarning.run();
                            }
                            bError = true;
                        }
                    }
                }
                strOldCellContents = pEntry->GetCriteria(nIdx);
                pEntry->SetCriteria(nIdx, aCrit);
                sNewValue = pEntry->GetCriteria(nIdx);
                if(!aCrit.isEmpty() && nRow >= (GetRowCount()-1))
                    bAppendRow = true;
            }
        }
        if( !bError && Controller().is() )
            Controller()->ClearModified();

        RowModified(GetCurRow(), GetCurColumnId());

        if ( bAppendRow )
        {
            RowInserted( GetRowCount()-1 );
            m_bVisibleRow.push_back(true);
            ++m_nVisibleCount;
        }

        if(!bError)
        {
            // and now the undo-action for the total
            appendUndoAction(strOldCellContents,sNewValue,nRow);

        }
    }

    // did I store data in a FieldDescription which was empty before and which is not empty anymore after the changes?
    if ( pEntry.is() && bWasEmpty && !pEntry->IsEmpty() && !bError )
    {
        // Default to visible
        pEntry->SetVisible();
        appendUndoAction("0","1",BROW_VIS_ROW,bListAction);
        RowModified(BROW_VIS_ROW, GetCurColumnId());

        // if required add empty columns
        sal_uInt16 nDummy;
        CheckFreeColumns(nDummy);
    }

    if ( bListAction && !m_bInUndoMode )
        static_cast<OQueryController&>(getDesignView()->getController()).GetUndoManager().LeaveListAction();

    return pEntry != nullptr && !bError;
}

bool OSelectionBrowseBox::SeekRow(long nRow)
{
    m_nSeekRow = nRow;
    return nRow < m_nVisibleCount;
}

void OSelectionBrowseBox::PaintCell(OutputDevice& rDev, const tools::Rectangle& rRect, sal_uInt16 nColumnId) const
{
    rDev.SetClipRegion(vcl::Region(rRect));

    OTableFieldDescRef pEntry;
    sal_uInt16 nPos = GetColumnPos(nColumnId);
    if(getFields().size() > o3tl::make_unsigned(nPos - 1))
        pEntry = getFields()[nPos - 1];

    if (!pEntry.is())
        return;

    long nRow = GetRealRow(m_nSeekRow);
    if (nRow == BROW_VIS_ROW)
        PaintTristate(rRect, pEntry->IsVisible() ? TRISTATE_TRUE : TRISTATE_FALSE);
    else
        rDev.DrawText(rRect, GetCellText(nRow, nColumnId),DrawTextFlags::VCenter);

    rDev.SetClipRegion( );
}

void OSelectionBrowseBox::PaintStatusCell(OutputDevice& rDev, const tools::Rectangle& rRect) const<--- The function 'PaintStatusCell' is never used.
{
    tools::Rectangle aRect(rRect);
    aRect.TopLeft().AdjustY( -2 );
    OUString  aLabel(DBA_RES(STR_QUERY_HANDLETEXT));

   // from BROW_CRIT2_ROW onwards all rows are shown "or"
    sal_Int32 nToken = (m_nSeekRow >= GetBrowseRow(BROW_CRIT2_ROW))
        ?  BROW_CRIT2_ROW : GetRealRow(m_nSeekRow);
    rDev.DrawText(aRect, aLabel.getToken(nToken, ';'),DrawTextFlags::VCenter);
}

void OSelectionBrowseBox::RemoveColumn(sal_uInt16 _nColumnId)
{
    OQueryController& rController = static_cast<OQueryController&>(getDesignView()->getController());

    sal_uInt16 nPos = GetColumnPos(_nColumnId);
    // the control should always have exactly one more column: the HandleColumn
    OSL_ENSURE((nPos == 0) || (nPos <= getFields().size()), "OSelectionBrowseBox::RemoveColumn : invalid parameter nColId");
    // ColId is synonymous to Position, and the condition should be valid

    sal_uInt16 nCurCol = GetCurColumnId();
    long nCurrentRow = GetCurRow();

    DeactivateCell();

    getFields().erase( getFields().begin() + (nPos - 1) );
    OTableFieldDescRef pEntry = new OTableFieldDesc();
    pEntry->SetColumnId(_nColumnId);
    getFields().push_back(pEntry);

    EditBrowseBox::RemoveColumn( _nColumnId );
    InsertDataColumn( _nColumnId , OUString(), DEFAULT_SIZE );

    // redraw
    tools::Rectangle aInvalidRect = GetInvalidRect( _nColumnId );
    Invalidate( aInvalidRect );

    ActivateCell( nCurrentRow, nCurCol );

    rController.setModified( true );

    invalidateUndoRedo();
}

void OSelectionBrowseBox::RemoveField(sal_uInt16 nColumnId )
{
    OQueryController& rController = static_cast<OQueryController&>(getDesignView()->getController());

    sal_uInt16 nPos = GetColumnPos(nColumnId);
    OSL_ENSURE(getFields().size() > o3tl::make_unsigned(nPos-1),"ID is to great!");

    OTableFieldDescRef pDesc = getEntry(static_cast<sal_uInt32>(nPos - 1)) ;
    pDesc->SetColWidth( static_cast<sal_uInt16>(GetColumnWidth(nColumnId)) );    // was not stored this before

    // trigger UndoAction
    if ( !m_bInUndoMode )
    {
        std::unique_ptr<OTabFieldDelUndoAct> pUndoAction(new OTabFieldDelUndoAct( this ));
        pUndoAction->SetTabFieldDescr(pDesc);
        pUndoAction->SetColumnPosition(nPos);
        rController.addUndoActionAndInvalidate( std::move(pUndoAction) );
    }

    RemoveColumn(nColumnId);

    invalidateUndoRedo();
}

void OSelectionBrowseBox::adjustSelectionMode( bool _bClickedOntoHeader, bool _bClickedOntoHandleCol )
{
    // if a Header has been selected it should be shown otherwise not
    if ( _bClickedOntoHeader )
    {
        if (0 == GetSelectColumnCount() )
            // I am in the correct mode if a selected column exists
            if ( BrowserMode::HIDESELECT == ( m_nMode & BrowserMode::HIDESELECT ) )
            {
                m_nMode &= ~BrowserMode::HIDESELECT;
                m_nMode |= BrowserMode::MULTISELECTION;
                SetMode( m_nMode );
            }
    }
    else if ( BrowserMode::HIDESELECT != ( m_nMode & BrowserMode::HIDESELECT ) )
    {
        if ( GetSelectColumnCount() != 0 )
            SetNoSelection();

        if ( _bClickedOntoHandleCol )
        {
            m_nMode |= BrowserMode::HIDESELECT;
            m_nMode &= ~BrowserMode::MULTISELECTION;
            SetMode( m_nMode );
        }
    }
}

void OSelectionBrowseBox::MouseButtonDown(const BrowserMouseEvent& rEvt)
{
    if( rEvt.IsLeft() )
    {
        bool bOnHandle = HANDLE_ID == rEvt.GetColumnId();
        bool bOnHeader = ( rEvt.GetRow() < 0 ) && !bOnHandle;
        adjustSelectionMode( bOnHeader, bOnHandle );
    }
    EditBrowseBox::MouseButtonDown(rEvt);
}

void OSelectionBrowseBox::MouseButtonUp(const BrowserMouseEvent& rEvt)
{
    EditBrowseBox::MouseButtonUp( rEvt );
    static_cast<OQueryController&>(getDesignView()->getController()).InvalidateFeature( ID_BROWSER_QUERY_EXECUTE );
}

void OSelectionBrowseBox::KeyInput( const KeyEvent& rEvt )
{
    if (IsColumnSelected(GetCurColumnId()))
    {
        if (rEvt.GetKeyCode().GetCode() == KEY_DELETE &&    // Delete rows
            !rEvt.GetKeyCode().IsShift() &&
            !rEvt.GetKeyCode().IsMod1())
        {
            RemoveField(GetCurColumnId());
            return;
        }
    }
    EditBrowseBox::KeyInput(rEvt);
}

sal_Int8 OSelectionBrowseBox::AcceptDrop( const BrowserAcceptDropEvent& rEvt )
{
    sal_Int8 nDropAction = DND_ACTION_NONE;
    if  ( rEvt.GetRow() >= -1 )
    {
        if ( IsEditing() )
        {
            // allow the asterisk again
            m_bDisableErrorBox = true;
            SaveModified();
            m_bDisableErrorBox = false;
            DeactivateCell();
        }
        // check if the format is already supported, if not deactivate the current cell and try again
        if ( OJoinExchObj::isFormatAvailable(GetDataFlavors()) )
            nDropAction = DND_ACTION_LINK;
    }

    return nDropAction;
}

sal_Int8 OSelectionBrowseBox::ExecuteDrop( const BrowserExecuteDropEvent& _rEvt )
{

    TransferableDataHelper aDropped(_rEvt.maDropEvent.Transferable);
    if (!OJoinExchObj::isFormatAvailable(aDropped.GetDataFlavorExVector()))
    {
        OSL_FAIL("OSelectionBrowseBox::ExecuteDrop: this should never have passed AcceptDrop!");
        return DND_ACTION_NONE;
    }

    // insert the field at the selected position
    OJoinExchangeData jxdSource = OJoinExchObj::GetSourceDescription(_rEvt.maDropEvent.Transferable);
    InsertField(jxdSource);

    return DND_ACTION_LINK;
}

OTableFieldDescRef const & OSelectionBrowseBox::AppendNewCol( sal_uInt16 nCnt)
{
    // one or more can be created, but the first one will is not returned
    sal_uInt32 nCount = getFields().size();
    for (sal_uInt16 i=0 ; i<nCnt ; i++)
    {
        OTableFieldDescRef pEmptyEntry = new OTableFieldDesc();
        getFields().push_back(pEmptyEntry);
        sal_uInt16 nColumnId = sal::static_int_cast< sal_uInt16 >(getFields().size());
        pEmptyEntry->SetColumnId( nColumnId );

        InsertDataColumn( nColumnId , OUString(), DEFAULT_SIZE );
    }

    return getFields()[nCount];
}

void OSelectionBrowseBox::DeleteFields(const OUString& rAliasName)
{
    if (getFields().empty())
        return;

    sal_uInt16 nColId = GetCurColumnId();
    sal_uInt32 nRow = GetCurRow();

    bool bWasEditing = IsEditing();
    if (bWasEditing)
        DeactivateCell();

    auto aIter = std::find_if(getFields().rbegin(), getFields().rend(),
        [&rAliasName](const OTableFieldDescRef pEntry) { return pEntry->GetAlias() == rAliasName; });
    if (aIter != getFields().rend())
    {
        sal_uInt16 nPos = sal::static_int_cast<sal_uInt16>(std::distance(aIter, getFields().rend()));
        RemoveField( GetColumnId( nPos ) );
    }

    if (bWasEditing)
        ActivateCell(nRow , nColId);
}

void OSelectionBrowseBox::SetColWidth(sal_uInt16 nColId, long nNewWidth)
{
    bool bWasEditing = IsEditing();
    if (bWasEditing)
        DeactivateCell();

    // create the BaseClass
    SetColumnWidth(nColId, nNewWidth);

    // tell it the FieldDescription
    OTableFieldDescRef pEntry = getEntry(GetColumnPos(nColId) - 1);
    if (pEntry.is())
        pEntry->SetColWidth(sal_uInt16(GetColumnWidth(nColId)));

    if (bWasEditing)
        ActivateCell(GetCurRow(), GetCurColumnId());
}

tools::Rectangle OSelectionBrowseBox::GetInvalidRect( sal_uInt16 nColId )
{
    // The rectangle is the full output area of the window
    tools::Rectangle aInvalidRect( Point(0,0), GetOutputSizePixel() );

    // now update the left side
    tools::Rectangle aFieldRect(GetCellRect( 0, nColId )); // used instead of GetFieldRectPixel
    aInvalidRect.SetLeft( aFieldRect.Left() );

    return aInvalidRect;
}

void OSelectionBrowseBox::InsertColumn(const OTableFieldDescRef& pEntry, sal_uInt16& _nColumnPosition)
{
    // the control should have exactly one more column: the HandleColumn
    OSL_ENSURE(_nColumnPosition == BROWSER_INVALIDID || (_nColumnPosition <= static_cast<long>(getFields().size())), "OSelectionBrowseBox::InsertColumn : invalid parameter nColId.");
     // -1 means at the end. Count means at the end, others denotes a correct position

    sal_uInt16 nCurCol = GetCurColumnId();
    long nCurrentRow = GetCurRow();

    DeactivateCell();

    // remember the column id of the current position
    sal_uInt16 nColumnId = GetColumnId(_nColumnPosition);
    // put at the end of the list if too small or too big,
    if ((_nColumnPosition == BROWSER_INVALIDID) || (_nColumnPosition >= getFields().size()))   // append the field
    {
        if (FindFirstFreeCol(_nColumnPosition) == nullptr)  // no more free columns
        {
            AppendNewCol();
            _nColumnPosition = sal::static_int_cast< sal_uInt16 >(
                getFields().size());
        }
        else
            ++_nColumnPosition; // within the list
        nColumnId = GetColumnId(_nColumnPosition);
        pEntry->SetColumnId( nColumnId );
        getFields()[ _nColumnPosition - 1] = pEntry;
    }

    // check if the column ids are identical, if not we have to move
    if ( pEntry->GetColumnId() != nColumnId )
    {
        sal_uInt16 nOldPosition = GetColumnPos(pEntry->GetColumnId());
        OSL_ENSURE( nOldPosition != 0,"Old position was 0. Not possible!");
        SetColumnPos(pEntry->GetColumnId(),_nColumnPosition);
        // we have to delete an empty field for the fields list, because the columns must have equal length
        if ( nOldPosition > 0 && nOldPosition <= getFields().size() )
            getFields()[nOldPosition - 1] = pEntry;

        ColumnMoved(pEntry->GetColumnId(),false);
    }

    if ( pEntry->GetFunctionType() & FKT_AGGREGATE )
    {
        OUString sFunctionName = pEntry->GetFunction();
        if ( GetFunctionName(sal_uInt32(-1),sFunctionName) )
            pEntry->SetFunction(sFunctionName);
    }

    nColumnId = pEntry->GetColumnId();

    SetColWidth(nColumnId,getDesignView()->getColWidth(GetColumnPos(nColumnId)-1));
    // redraw
    tools::Rectangle aInvalidRect = GetInvalidRect( nColumnId );
    Invalidate( aInvalidRect );

    ActivateCell( nCurrentRow, nCurCol );
    static_cast<OQueryController&>(getDesignView()->getController()).setModified( true );

    invalidateUndoRedo();
}

OTableFieldDescRef OSelectionBrowseBox::InsertField(const OJoinExchangeData& jxdSource)
{
    OQueryTableWindow* pSourceWin = static_cast<OQueryTableWindow*>(jxdSource.pListBox->GetTabWin());
    if (!pSourceWin)
        return nullptr;

    // name and position of the selected field
    OUString aFieldName = jxdSource.pListBox->GetEntryText(jxdSource.pEntry);
    sal_uInt32 nFieldIndex = jxdSource.pListBox->GetModel()->GetAbsPos(jxdSource.pEntry);
    OTableFieldInfo* pInf = static_cast<OTableFieldInfo*>(jxdSource.pEntry->GetUserData());

    // construct DragInfo, such that I use the other InsertField
    OTableFieldDescRef aInfo = new OTableFieldDesc(pSourceWin->GetTableName(),aFieldName);
    aInfo->SetTabWindow(pSourceWin);
    aInfo->SetFieldIndex(nFieldIndex);
    aInfo->SetFieldType(pInf->GetKeyType());
    aInfo->SetAlias(pSourceWin->GetAliasName());

    aInfo->SetDataType(pInf->GetDataType());
    aInfo->SetVisible();

    return InsertField(aInfo);
}

OTableFieldDescRef OSelectionBrowseBox::InsertField(const OTableFieldDescRef& _rInfo, sal_uInt16 _nColumnPosition, bool bVis, bool bActivate)
{

    if(m_nMaxColumns && m_nMaxColumns <= FieldsCount())
        return nullptr;
    if (bActivate)
        SaveModified();

    // new column description
    OTableFieldDescRef pEntry = _rInfo;
    pEntry->SetVisible(bVis);

    // insert column
    InsertColumn( pEntry, _nColumnPosition );

    if ( !m_bInUndoMode )
    {
        // trigger UndoAction
        std::unique_ptr<OTabFieldCreateUndoAct> pUndoAction(new OTabFieldCreateUndoAct( this ));
        pUndoAction->SetTabFieldDescr( pEntry );
        pUndoAction->SetColumnPosition(_nColumnPosition);
        getDesignView()->getController().addUndoActionAndInvalidate( std::move(pUndoAction) );
    }

    return pEntry;
}

sal_uInt16 OSelectionBrowseBox::FieldsCount()
{
    sal_uInt16 nCount = 0;
    for (auto const& field : getFields())
    {
        if (field.is() && !field->IsEmpty())
            ++nCount;<--- Consider using std::count_if algorithm instead of a raw loop.
    }

    return nCount;
}

OTableFieldDescRef OSelectionBrowseBox::FindFirstFreeCol(sal_uInt16& _rColumnPosition )
{

    _rColumnPosition = BROWSER_INVALIDID;

    for (auto const& field : getFields())
    {
        ++_rColumnPosition;
        OTableFieldDescRef pEntry = field;
        if ( pEntry.is() && pEntry->IsEmpty() )
            return pEntry;
    }

    return nullptr;
}

void OSelectionBrowseBox::CheckFreeColumns(sal_uInt16& _rColumnPosition)
{
    if (FindFirstFreeCol(_rColumnPosition) == nullptr)
    {
        // it is full, so append a pack of columns
        AppendNewCol(DEFAULT_QUERY_COLS);
        OSL_VERIFY(FindFirstFreeCol(_rColumnPosition).is());
    }
}

void OSelectionBrowseBox::AddGroupBy( const OTableFieldDescRef& rInfo )
{
    Reference< XConnection> xConnection = static_cast<OQueryController&>(getDesignView()->getController()).getConnection();
    if(!xConnection.is())
        return;
    OSL_ENSURE(!rInfo->IsEmpty(),"AddGroupBy:: OTableFieldDescRef should not be empty!");
    OTableFieldDescRef pEntry;
    const Reference<XDatabaseMetaData> xMeta = xConnection->getMetaData();
    const ::comphelper::UStringMixEqual bCase(xMeta.is() && xMeta->supportsMixedCaseQuotedIdentifiers());
    //sal_Bool bAppend = sal_False;

    bool bAllFieldsSearched = true;
    for (auto const& field : getFields())
    {
        pEntry = field;
        OSL_ENSURE(pEntry.is(),"OTableFieldDescRef was null!");

        const OUString   aField = pEntry->GetField();
        const OUString   aAlias = pEntry->GetAlias();

        if (bCase(aField,rInfo->GetField()) &&
            bCase(aAlias,rInfo->GetAlias()) &&
            pEntry->GetFunctionType() == rInfo->GetFunctionType() &&
            pEntry->GetFunction() == rInfo->GetFunction())
        {
            if ( pEntry->isNumericOrAggregateFunction() && rInfo->IsGroupBy() )
            {
                pEntry->SetGroupBy(false);
                // we do want to consider that bAllFieldsSearched still true here
                // bAllFieldsSearched = false;
                break;
            }
            else
            {
                if ( !pEntry->IsGroupBy() && !pEntry->HasCriteria() ) // here we have a where condition which is no having clause
                {
                    pEntry->SetGroupBy(rInfo->IsGroupBy());
                    if(!m_bGroupByUnRelated && pEntry->IsGroupBy())
                        pEntry->SetVisible();
                    bAllFieldsSearched = false;
                    break;
                }
            }

        }
    }

    if (bAllFieldsSearched)
    {
        OTableFieldDescRef pTmp = InsertField(rInfo, BROWSER_INVALIDID, false, false );
        if ( pTmp->isNumericOrAggregateFunction() && rInfo->IsGroupBy() ) // the GroupBy is inherited from rInfo
            pTmp->SetGroupBy(false);
    }
}

void OSelectionBrowseBox::DuplicateConditionLevel( const sal_uInt16 nLevel)
{
    const sal_uInt16 nNewLevel = nLevel +1;
    for (auto const& field : getFields())
    {
        const OTableFieldDescRef& pEntry = field;
        OUString sValue = pEntry->GetCriteria(nLevel);
        if ( !sValue.isEmpty() )
        {
            pEntry->SetCriteria( nNewLevel, sValue);
            if ( nNewLevel == (m_nVisibleCount-BROW_CRIT1_ROW-1) )
            {
                RowInserted( GetRowCount()-1 );
                m_bVisibleRow.push_back(true);
                ++m_nVisibleCount;
            }
            m_bVisibleRow[BROW_CRIT1_ROW + nNewLevel] = true;
        }
    }
}

void OSelectionBrowseBox::AddCondition( const OTableFieldDescRef& rInfo, const OUString& rValue, const sal_uInt16 nLevel,bool _bAddOrOnOneLine )
{
    Reference< XConnection> xConnection = static_cast<OQueryController&>(getDesignView()->getController()).getConnection();
    if(!xConnection.is())
        return;
    OSL_ENSURE(rInfo.is() && !rInfo->IsEmpty(),"AddCondition:: OTableFieldDescRef should not be Empty!");

    OTableFieldDescRef pLastEntry;
    Reference<XDatabaseMetaData> xMeta = xConnection->getMetaData();
    ::comphelper::UStringMixEqual bCase(xMeta.is() && xMeta->supportsMixedCaseQuotedIdentifiers());

    bool bAllFieldsSearched = true;
    for (auto const& field : getFields())
    {
        const OTableFieldDescRef& pEntry = field;
        const OUString   aField = pEntry->GetField();
        const OUString   aAlias = pEntry->GetAlias();

        if (bCase(aField,rInfo->GetField()) &&
            bCase(aAlias,rInfo->GetAlias()) &&
            pEntry->GetFunctionType() == rInfo->GetFunctionType() &&
            pEntry->GetFunction() == rInfo->GetFunction() &&
            pEntry->IsGroupBy() == rInfo->IsGroupBy() )
        {
            if ( pEntry->isNumericOrAggregateFunction() && rInfo->IsGroupBy() )
                pEntry->SetGroupBy(false);
            else
            {
                if(!m_bGroupByUnRelated && pEntry->IsGroupBy())
                    pEntry->SetVisible();
            }
            if (pEntry->GetCriteria(nLevel).isEmpty() )
            {
                pEntry->SetCriteria( nLevel, rValue);
                if(nLevel == (m_nVisibleCount-BROW_CRIT1_ROW-1))
                {
                    RowInserted( GetRowCount()-1 );
                    m_bVisibleRow.push_back(true);
                    ++m_nVisibleCount;
                }
                m_bVisibleRow[BROW_CRIT1_ROW + nLevel] = true;
                bAllFieldsSearched = false;
                break;
            }
            if ( _bAddOrOnOneLine )
            {
                pLastEntry = pEntry;
            }
        }
    }
    if ( pLastEntry.is() )
    {
        OUString sCriteria = rValue;
        OUString sOldCriteria = pLastEntry->GetCriteria( nLevel );
        if ( !sOldCriteria.isEmpty() )
        {
            sCriteria = "( " + sOldCriteria + " OR " + rValue + " )";
        }
        pLastEntry->SetCriteria( nLevel, sCriteria);
        if(nLevel == (m_nVisibleCount-BROW_CRIT1_ROW-1))
        {
            RowInserted( GetRowCount()-1 );
            m_bVisibleRow.push_back(true);
            ++m_nVisibleCount;
        }
        m_bVisibleRow[BROW_CRIT1_ROW + nLevel] = true;
    }
    else if (bAllFieldsSearched)
    {
        OTableFieldDescRef pTmp = InsertField(rInfo, BROWSER_INVALIDID, false, false );
        if ( pTmp->isNumericOrAggregateFunction() && rInfo->IsGroupBy() ) // the GroupBy was inherited from rInfo
            pTmp->SetGroupBy(false);
        if ( pTmp.is() )
        {
            pTmp->SetCriteria( nLevel, rValue);
            if(nLevel == (m_nVisibleCount-BROW_CRIT1_ROW-1))
            {
                RowInserted( GetRowCount()-1 );
                m_bVisibleRow.push_back(true);
                ++m_nVisibleCount;
            }
        }
    }
}

void OSelectionBrowseBox::AddOrder( const OTableFieldDescRef& rInfo, const EOrderDir eDir, sal_uInt32 _nCurrentPos)
{
    if (_nCurrentPos == 0)
        m_nLastSortColumn = SORT_COLUMN_NONE;

    Reference< XConnection> xConnection = static_cast<OQueryController&>(getDesignView()->getController()).getConnection();
    if(!xConnection.is())
        return;
    OSL_ENSURE(!rInfo->IsEmpty(),"AddOrder:: OTableFieldDescRef should not be Empty!");
    OTableFieldDescRef pEntry;
    Reference<XDatabaseMetaData> xMeta = xConnection->getMetaData();
    ::comphelper::UStringMixEqual bCase(xMeta.is() && xMeta->supportsMixedCaseQuotedIdentifiers());

    bool bAppend = false;
    sal_uInt32 nPos = 0;
    bool bAllFieldsSearched = true;
    for (auto const& field : getFields())
    {
        pEntry = field;
        OUString aField = pEntry->GetField();
        OUString aAlias = pEntry->GetAlias();

        if (bCase(aField,rInfo->GetField()) &&
            bCase(aAlias,rInfo->GetAlias()))
        {
            bAppend = (m_nLastSortColumn != SORT_COLUMN_NONE) && (nPos <= m_nLastSortColumn);
            if ( bAppend )
            {
                // we do want to consider that bAllFieldsSearched still true here
                // bAllFieldsSearched = false;
                break;
            }
            else
            {
                if ( !m_bOrderByUnRelated )
                    pEntry->SetVisible();
                pEntry->SetOrderDir( eDir );
                m_nLastSortColumn = nPos;
            }
            bAllFieldsSearched = false;
            break;
        }
        ++nPos;
    }

    if (bAllFieldsSearched)
    {
        OTableFieldDescRef pTmp = InsertField(rInfo, BROWSER_INVALIDID, false, false );
        if(pTmp.is())
        {
            m_nLastSortColumn = pTmp->GetColumnId() - 1;
            if ( !m_bOrderByUnRelated && !bAppend )
                pTmp->SetVisible();
            pTmp->SetOrderDir( eDir );
        }
    }
}

bool OSelectionBrowseBox::Save()
{
    bool bRet = true;
    if (IsModified())
        bRet = SaveModified();
    return bRet;
}

void OSelectionBrowseBox::CellModified()
{
    long nRow = GetRealRow(GetCurRow());
    switch (nRow)
    {
        case BROW_VIS_ROW:
            {
                OTableFieldDescRef  pEntry = getEntry(GetColumnPos(GetCurColumnId()) - 1);

                weld::ComboBox& rComboBox = m_pOrderCell->get_widget();
                sal_Int32 nIdx = rComboBox.get_active();
                if(!m_bOrderByUnRelated && nIdx > 0 &&
                    nIdx != -1 &&
                    !pEntry->IsEmpty()              &&
                    pEntry->GetOrderDir() != ORDER_NONE)
                {
                    m_pVisibleCell->GetBox().Check();
                    pEntry->SetVisible();
                }
                else
                    pEntry->SetVisible(m_pVisibleCell->GetBox().IsChecked());
            }
            break;
    }
    static_cast<OQueryController&>(getDesignView()->getController()).setModified( true );
}

void OSelectionBrowseBox::Fill()
{
    OSL_ENSURE(ColCount() >= 1, "OSelectionBrowseBox::Fill : please call only after inserting the handle column !");

    sal_uInt16 nColCount = ColCount() - 1;
    if (nColCount < DEFAULT_QUERY_COLS)
        AppendNewCol(DEFAULT_QUERY_COLS - nColCount);
}

Size OSelectionBrowseBox::CalcOptimalSize( const Size& _rAvailable )
{
    Size aReturn( _rAvailable.Width(), GetTitleHeight() );

    aReturn.AdjustHeight(( m_nVisibleCount ? m_nVisibleCount : 15 ) * GetDataRowHeight() );
    aReturn.AdjustHeight(40 ); // just some space

    return aReturn;
}

void OSelectionBrowseBox::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
                {
                    EditBrowseBox::Command(rEvt);
                    return;
                }
            }

            sal_uInt16 nColId = GetColumnId(GetColumnAtXPosPixel( aMenuPos.X() ));
            long   nRow = GetRowAtYPosPixel( aMenuPos.Y() );

            if (nRow < 0 && nColId > HANDLE_ID )
            {
                if ( !IsColumnSelected( nColId ) )
                {
                    adjustSelectionMode( true /* clicked onto a header */ , false /* not onto the handle col */ );
                    SelectColumnId( nColId );
                }

                if (!static_cast<OQueryController&>(getDesignView()->getController()).isReadOnly())
                {
                    VclBuilder aBuilder(nullptr, VclBuilderContainer::getUIRootDir(), "dbaccess/ui/querycolmenu.ui", "");
                    VclPtr<PopupMenu> aContextMenu(aBuilder.get_menu("menu"));
                    sal_uInt16 nItemId = aContextMenu->Execute(this, aMenuPos);
                    if (nItemId == aContextMenu->GetItemId("delete"))
                       RemoveField(nColId);
                    else if (nItemId == aContextMenu->GetItemId("width"))
                        adjustBrowseBoxColumnWidth( this, nColId );
                }
            }
            else if(nRow >= 0 && nColId <= HANDLE_ID)
            {
                if (!static_cast<OQueryController&>(getDesignView()->getController()).isReadOnly())
                {
                    VclBuilder aBuilder(nullptr, VclBuilderContainer::getUIRootDir(), "dbaccess/ui/queryfuncmenu.ui", "");
                    VclPtr<PopupMenu> aContextMenu(aBuilder.get_menu("menu"));
                    aContextMenu->CheckItem("functions", m_bVisibleRow[BROW_FUNCTION_ROW]);
                    aContextMenu->CheckItem("tablename", m_bVisibleRow[BROW_TABLE_ROW]);
                    aContextMenu->CheckItem("alias", m_bVisibleRow[BROW_COLUMNALIAS_ROW]);
                    aContextMenu->CheckItem("distinct", static_cast<OQueryController&>(getDesignView()->getController()).isDistinct());

                    aContextMenu->Execute(this, aMenuPos);

                    OString sIdent = aContextMenu->GetCurItemIdent();
                    if (sIdent == "functions")
                    {
                        SetRowVisible(BROW_FUNCTION_ROW, !IsRowVisible(BROW_FUNCTION_ROW));
                        static_cast<OQueryController&>(getDesignView()->getController()).InvalidateFeature( SID_QUERY_VIEW_FUNCTIONS );
                    }
                    else if (sIdent == "tablename")
                    {
                        SetRowVisible(BROW_TABLE_ROW, !IsRowVisible(BROW_TABLE_ROW));
                        static_cast<OQueryController&>(getDesignView()->getController()).InvalidateFeature( SID_QUERY_VIEW_TABLES );
                    }
                    else if (sIdent == "alias")
                    {
                        SetRowVisible(BROW_COLUMNALIAS_ROW, !IsRowVisible(BROW_COLUMNALIAS_ROW));
                        static_cast<OQueryController&>(getDesignView()->getController()).InvalidateFeature( SID_QUERY_VIEW_ALIASES );
                    }
                    else if (sIdent == "distinct")
                    {
                        static_cast<OQueryController&>(getDesignView()->getController()).setDistinct(!static_cast<OQueryController&>(getDesignView()->getController()).isDistinct());
                        static_cast<OQueryController&>(getDesignView()->getController()).setModified( true );
                        static_cast<OQueryController&>(getDesignView()->getController()).InvalidateFeature( SID_QUERY_DISTINCT_VALUES );
                    }

                    static_cast<OQueryController&>(getDesignView()->getController()).setModified( true );
                }
            }
            else
            {
                EditBrowseBox::Command(rEvt);
                return;
            }

            [[fallthrough]];
        }
        default:
            EditBrowseBox::Command(rEvt);
    }
}

bool OSelectionBrowseBox::IsRowVisible(sal_uInt16 _nWhich) const
{
    OSL_ENSURE(_nWhich<(m_bVisibleRow.size()), "OSelectionBrowseBox::IsRowVisible : invalid parameter !");
    return m_bVisibleRow[_nWhich];
}

void OSelectionBrowseBox::SetRowVisible(sal_uInt16 _nWhich, bool _bVis)
{
    OSL_ENSURE(_nWhich<m_bVisibleRow.size(), "OSelectionBrowseBox::SetRowVisible : invalid parameter !");

    bool bWasEditing = IsEditing();
    if (bWasEditing)
        DeactivateCell();

    // do this before removing or inserting rows, as this triggers ActivateCell-calls, which rely on m_bVisibleRow
    m_bVisibleRow[_nWhich] = !m_bVisibleRow[_nWhich];

    long nId = GetBrowseRow(_nWhich);
    if (_bVis)
    {
        RowInserted(nId);
        ++m_nVisibleCount;
    }
    else
    {
        RowRemoved(nId);
        --m_nVisibleCount;
    }

    if (bWasEditing)
        ActivateCell();
}

long OSelectionBrowseBox::GetBrowseRow(long nRowId) const
{
    sal_uInt16 nCount(0);
    for(long i = 0 ; i < nRowId ; ++i)
    {
        if ( m_bVisibleRow[i] )
            ++nCount;
    }
    return nCount;
}

long OSelectionBrowseBox::GetRealRow(long nRowId) const
{
    long nErg=0,i;
    const long nCount = m_bVisibleRow.size();
    for(i=0;i < nCount; ++i)
    {
        if(m_bVisibleRow[i] && nErg++ == nRowId)
            break;
    }
    OSL_ENSURE(nErg <= long(m_bVisibleRow.size()),"nErg cannot be greater than BROW_ROW_CNT!");
    return i;
}

static const long nVisibleRowMask[] =
                    {
                            0x0001,
                            0x0002,
                            0x0004,
                            0x0008,
                            0x0010,
                            0x0020,
                            0x0040,
                            0x0080,
                            0x0100,
                            0x0200,
                            0x0400,
                            0x0800
                    };
sal_Int32 OSelectionBrowseBox::GetNoneVisibleRows() const
{
    sal_Int32 nErg(0);
    // only the first 11 rows are interesting
    sal_Int32 const nSize = SAL_N_ELEMENTS(nVisibleRowMask);
    for(sal_Int32 i=0;i<nSize;i++)
    {
        if(!m_bVisibleRow[i])
            nErg |= nVisibleRowMask[i];
    }
    return nErg;
}

void OSelectionBrowseBox::SetNoneVisbleRow(long nRows)
{
    // only the first 11 rows are interesting
    sal_Int32 const nSize = SAL_N_ELEMENTS(nVisibleRowMask);
    for(sal_Int32 i=0;i< nSize;i++)
        m_bVisibleRow[i] = !(nRows & nVisibleRowMask[i]);
}

OUString OSelectionBrowseBox::GetCellText(long nRow, sal_uInt16 nColId) const
{

    sal_uInt16 nPos = GetColumnPos(nColId);

    OTableFieldDescRef pEntry = getFields()[nPos-1];
    OSL_ENSURE(pEntry != nullptr, "OSelectionBrowseBox::GetCellText : invalid column id, prepare for GPF ... ");
    if ( pEntry->IsEmpty() )
        return OUString();

    OUString aText;
    switch (nRow)
    {
        case BROW_TABLE_ROW:
            aText = pEntry->GetAlias();
            break;
        case BROW_FIELD_ROW:
        {
            OUString aField = pEntry->GetField();
            if (!aField.isEmpty() && aField[0] == '*')                   // * replace with alias.*
            {
                aField = pEntry->GetAlias();
                if(!aField.isEmpty())
                    aField += ".";
                aField += "*";
            }
            aText = aField;
        }   break;
        case BROW_ORDER_ROW:
            if (pEntry->GetOrderDir() != ORDER_NONE)
                aText = DBA_RES(STR_QUERY_SORTTEXT).getToken(sal::static_int_cast< sal_uInt16 >(pEntry->GetOrderDir()), ';');
            break;
        case BROW_VIS_ROW:
            break;
        case BROW_COLUMNALIAS_ROW:
            aText = pEntry->GetFieldAlias();
            break;
        case BROW_FUNCTION_ROW:
            // we always show the group function at first
            if ( pEntry->IsGroupBy() )
                aText = m_aFunctionStrings.copy(m_aFunctionStrings.lastIndexOf(';')+1);
            else if ( pEntry->isNumericOrAggregateFunction() )
                aText = pEntry->GetFunction();
            break;
        default:
            aText = pEntry->GetCriteria(sal_uInt16(nRow - BROW_CRIT1_ROW));
    }
    return aText;
}

bool OSelectionBrowseBox::GetFunctionName(sal_uInt32 _nFunctionTokenId, OUString& rFkt)
{
    weld::ComboBox& rComboBox = m_pFunctionCell->get_widget();
    switch(_nFunctionTokenId)
    {
        case SQL_TOKEN_COUNT:
            rFkt = (rComboBox.get_count() < 3) ? rComboBox.get_text(1) : rComboBox.get_text(2);
            break;
        case SQL_TOKEN_AVG:
            rFkt = rComboBox.get_text(1);
            break;
        case SQL_TOKEN_MAX:
            rFkt = rComboBox.get_text(3);
            break;
        case SQL_TOKEN_MIN:
            rFkt = rComboBox.get_text(4);
            break;
        case SQL_TOKEN_SUM:
            rFkt = rComboBox.get_text(5);
            break;
        case SQL_TOKEN_EVERY:
            rFkt = rComboBox.get_text(6);
            break;
        case SQL_TOKEN_ANY:
            rFkt = rComboBox.get_text(7);
            break;
        case SQL_TOKEN_SOME:
            rFkt = rComboBox.get_text(8);
            break;
        case SQL_TOKEN_STDDEV_POP:
            rFkt = rComboBox.get_text(9);
            break;
        case SQL_TOKEN_STDDEV_SAMP:
            rFkt = rComboBox.get_text(10);
            break;
        case SQL_TOKEN_VAR_SAMP:
            rFkt = rComboBox.get_text(11);
            break;
        case SQL_TOKEN_VAR_POP:
            rFkt = rComboBox.get_text(12);
            break;
        case SQL_TOKEN_COLLECT:
            rFkt = rComboBox.get_text(13);
            break;
        case SQL_TOKEN_FUSION:
            rFkt = rComboBox.get_text(14);
            break;
        case SQL_TOKEN_INTERSECTION:
            rFkt = rComboBox.get_text(15);
            break;
        default:
            {
                const sal_Int32 nStopIdx = m_aFunctionStrings.lastIndexOf(';'); // grouping is not counted
                for (sal_Int32 nIdx {0}; nIdx<nStopIdx;)
                {
                    const OUString sFunc {m_aFunctionStrings.getToken(0, ';', nIdx)};
                    if (rFkt.equalsIgnoreAsciiCase(sFunc))
                    {
                        rFkt = sFunc;
                        return true;
                    }
                }
                return false;
            }
    }

    return true;
}

OUString OSelectionBrowseBox::GetCellContents(sal_Int32 nCellIndex, sal_uInt16 nColId)
{
    if ( GetCurColumnId() == nColId && !m_bInUndoMode )
        SaveModified();

    sal_uInt16 nPos = GetColumnPos(nColId);
    OTableFieldDescRef pEntry = getFields()[nPos - 1];
    OSL_ENSURE(pEntry != nullptr, "OSelectionBrowseBox::GetCellContents : invalid column id, prepare for GPF ... ");

    switch (nCellIndex)
    {
        case BROW_VIS_ROW :
            return pEntry->IsVisible() ? OUStringLiteral("1") : OUStringLiteral("0");
        case BROW_ORDER_ROW:
        {
            sal_Int32 nIdx = m_pOrderCell->get_widget().get_active();
            if (nIdx == -1)
                nIdx = 0;
            return OUString::number(nIdx);
        }
        default:
            return GetCellText(nCellIndex, nColId);
    }
}

void OSelectionBrowseBox::SetCellContents(sal_Int32 nRow, sal_uInt16 nColId, const OUString& strNewText)
{
    bool bWasEditing = IsEditing() && (GetCurColumnId() == nColId) && IsRowVisible(static_cast<sal_uInt16>(nRow)) && (GetCurRow() == static_cast<sal_uInt16>(GetBrowseRow(nRow)));
    if (bWasEditing)
        DeactivateCell();

    sal_uInt16 nPos = GetColumnPos(nColId);
    OTableFieldDescRef pEntry = getEntry(nPos - 1);
    OSL_ENSURE(pEntry != nullptr, "OSelectionBrowseBox::SetCellContents : invalid column id, prepare for GPF ... ");

    switch (nRow)
    {
        case BROW_VIS_ROW:
            pEntry->SetVisible(strNewText == "1");
            break;
        case BROW_FIELD_ROW:
            pEntry->SetField(strNewText);
            break;
        case BROW_TABLE_ROW:
            pEntry->SetAlias(strNewText);
            break;
        case BROW_ORDER_ROW:
        {
            sal_uInt16 nIdx = static_cast<sal_uInt16>(strNewText.toInt32());
            pEntry->SetOrderDir(EOrderDir(nIdx));
        }   break;
        case BROW_COLUMNALIAS_ROW:
            pEntry->SetFieldAlias(strNewText);
            break;
        case BROW_FUNCTION_ROW:
        {
            OUString sGroupFunctionName = m_aFunctionStrings.copy(m_aFunctionStrings.lastIndexOf(';')+1);
            pEntry->SetFunction(strNewText);
            // first reset this two member
            sal_Int32 nFunctionType = pEntry->GetFunctionType();
            nFunctionType &= ~FKT_AGGREGATE;
            pEntry->SetFunctionType(nFunctionType);
            if ( pEntry->IsGroupBy() && !sGroupFunctionName.equalsIgnoreAsciiCase(strNewText) )
                pEntry->SetGroupBy(false);

            if ( sGroupFunctionName.equalsIgnoreAsciiCase(strNewText) )
                pEntry->SetGroupBy(true);
            else if ( !strNewText.isEmpty() )
            {
                nFunctionType |= FKT_AGGREGATE;
                pEntry->SetFunctionType(nFunctionType);
            }
        }   break;
        default:
            pEntry->SetCriteria(sal_uInt16(nRow - BROW_CRIT1_ROW), strNewText);
    }

    long nCellIndex = GetRealRow(nRow);
    if(IsRowVisible(static_cast<sal_uInt16>(nRow)))
        RowModified(nCellIndex, nColId);

    // the appropriate field-description is now empty -> set Visible to sal_False (now it is consistent to normal empty rows)
    if (pEntry->IsEmpty())
        pEntry->SetVisible(false);

    if (bWasEditing)
        ActivateCell(nCellIndex, nColId);

    static_cast<OQueryController&>(getDesignView()->getController()).setModified( true );
}

void OSelectionBrowseBox::ColumnResized(sal_uInt16 nColId)
{
    if (static_cast<OQueryController&>(getDesignView()->getController()).isReadOnly())
        return;
    // The resizing of columns can't be suppressed (BrowseBox doesn't support that) so we have to do this
    // fake. It's not _that_ bad : the user may change column widths while in read-only mode to see all details
    // but the changes aren't permanent ...

    sal_uInt16 nPos = GetColumnPos(nColId);
    OSL_ENSURE(nPos <= getFields().size(),"ColumnResized:: nColId should not be greater than List::count!");
    OTableFieldDescRef pEntry = getEntry(nPos-1);
    OSL_ENSURE(pEntry.is(), "OSelectionBrowseBox::ColumnResized : invalid FieldDescription !");
    static_cast<OQueryController&>(getDesignView()->getController()).setModified( true );
    EditBrowseBox::ColumnResized(nColId);

    if ( pEntry.is())
    {
        if ( !m_bInUndoMode )
        {
            // create the undo action
            std::unique_ptr<OTabFieldSizedUndoAct> pUndo(new OTabFieldSizedUndoAct(this));
            pUndo->SetColumnPosition( nPos );
            pUndo->SetOriginalWidth(pEntry->GetColWidth());
            getDesignView()->getController().addUndoActionAndInvalidate(std::move(pUndo));
        }
        pEntry->SetColWidth(sal_uInt16(GetColumnWidth(nColId)));
    }
}

sal_uInt32 OSelectionBrowseBox::GetTotalCellWidth(long nRowId, sal_uInt16 nColId)<--- The function 'GetTotalCellWidth' is never used.
{
    sal_uInt16 nPos = GetColumnPos(nColId);
    OSL_ENSURE((nPos == 0) || (nPos <= getFields().size()), "OSelectionBrowseBox::GetTotalCellWidth : invalid parameter nColId");

    OTableFieldDescRef pEntry = getFields()[nPos-1];
    OSL_ENSURE(pEntry.is(), "OSelectionBrowseBox::GetTotalCellWidth : invalid FieldDescription !");

    long nRow = GetRealRow(nRowId);
    OUString strText(GetCellText(nRow, nColId));
    return GetDataWindow().LogicToPixel(Size(GetDataWindow().GetTextWidth(strText),0)).Width();
}

bool OSelectionBrowseBox::isCutAllowed() const
{
    bool bCutAllowed = false;
    long nRow = GetRealRow(GetCurRow());
    switch (nRow)
    {
        case BROW_VIS_ROW:
        case BROW_ORDER_ROW:
        case BROW_TABLE_ROW:
        case BROW_FUNCTION_ROW:
            break;
        case BROW_FIELD_ROW:
        {
            weld::ComboBox& rComboBox = m_pFieldCell->get_widget();
            int nStartPos, nEndPos;
            bCutAllowed = rComboBox.get_entry_selection_bounds(nStartPos, nEndPos);
            break;
        }
        default:
            bCutAllowed = !m_pTextCell->GetSelected().isEmpty();
            break;
    }
    return bCutAllowed;
}

void OSelectionBrowseBox::cut()
{
    long nRow = GetRealRow(GetCurRow());
    switch (nRow)
    {
        case BROW_FIELD_ROW:
        {
            weld::ComboBox& rComboBox = m_pFieldCell->get_widget();
            rComboBox.cut_entry_clipboard();
            break;
        }
        default:
            m_pTextCell->Cut();
            m_pTextCell->SetModifyFlag();
    }
    SaveModified();
    RowModified(GetBrowseRow(nRow), GetCurColumnId());

    invalidateUndoRedo();
}

void OSelectionBrowseBox::paste()
{
    long nRow = GetRealRow(GetCurRow());
    switch (nRow)
    {
        case BROW_FIELD_ROW:
        {
            weld::ComboBox& rComboBox = m_pFieldCell->get_widget();
            rComboBox.paste_entry_clipboard();
            break;
        }
        default:
            m_pTextCell->Paste();
            m_pTextCell->SetModifyFlag();
    }
    RowModified(GetBrowseRow(nRow), GetCurColumnId());
    invalidateUndoRedo();
}

bool OSelectionBrowseBox::isPasteAllowed() const
{
    bool bPasteAllowed = true;
    long nRow = GetRealRow(GetCurRow());
    switch (nRow)
    {
        case BROW_VIS_ROW:
        case BROW_ORDER_ROW:
        case BROW_TABLE_ROW:
        case BROW_FUNCTION_ROW:
            bPasteAllowed = false;
            break;
    }
    return bPasteAllowed;
}

bool OSelectionBrowseBox::isCopyAllowed() const
{
    return isCutAllowed();
}

void OSelectionBrowseBox::copy()
{
    long nRow = GetRealRow(GetCurRow());
    switch (nRow)
    {
        case BROW_FIELD_ROW:
        {
            weld::ComboBox& rComboBox = m_pFieldCell->get_widget();
            rComboBox.copy_entry_clipboard();
            break;
        }
        default:
            m_pTextCell->Copy();
    }
}

void OSelectionBrowseBox::appendUndoAction(const OUString& _rOldValue, const OUString& _rNewValue, sal_Int32 _nRow, bool& _bListAction)
{
    if ( !m_bInUndoMode && _rNewValue != _rOldValue )
    {
        if ( !_bListAction )
        {
            _bListAction = true;
            static_cast<OQueryController&>(getDesignView()->getController()).GetUndoManager().EnterListAction(OUString(),OUString(),0,ViewShellId(-1));
        }
        appendUndoAction(_rOldValue,_rNewValue,_nRow);
    }
}

void OSelectionBrowseBox::appendUndoAction(const OUString& _rOldValue,const OUString& _rNewValue,sal_Int32 _nRow)
{
    if ( !m_bInUndoMode && _rNewValue != _rOldValue )
    {
        std::unique_ptr<OTabFieldCellModifiedUndoAct> pUndoAct(new OTabFieldCellModifiedUndoAct(this));
        pUndoAct->SetCellIndex(_nRow);
        OSL_ENSURE(GetColumnPos(GetCurColumnId()) != BROWSER_INVALIDID,"Current position isn't valid!");
        pUndoAct->SetColumnPosition( GetColumnPos(GetCurColumnId()) );
        pUndoAct->SetCellContents(_rOldValue);
        getDesignView()->getController().addUndoActionAndInvalidate(std::move(pUndoAct));
    }
}

IMPL_LINK_NOARG(OSelectionBrowseBox, OnInvalidateTimer, Timer *, void)
{
    static_cast<OQueryController&>(getDesignView()->getController()).InvalidateFeature(SID_CUT);
    static_cast<OQueryController&>(getDesignView()->getController()).InvalidateFeature(SID_COPY);
    static_cast<OQueryController&>(getDesignView()->getController()).InvalidateFeature(SID_PASTE);
    if(!m_bStopTimer)
        m_timerInvalidate.Start();
}

void OSelectionBrowseBox::stopTimer()
{
    m_bStopTimer = true;
    if (m_timerInvalidate.IsActive())
        m_timerInvalidate.Stop();
}

void OSelectionBrowseBox::startTimer()
{
    m_bStopTimer = false;
    if (!m_timerInvalidate.IsActive())
        m_timerInvalidate.Start();
}

OTableFields& OSelectionBrowseBox::getFields() const
{
    OQueryController& rController = static_cast<OQueryController&>(getDesignView()->getController());
    return rController.getTableFieldDesc();
}

void OSelectionBrowseBox::enableControl(const OTableFieldDescRef& _rEntry,Window* _pControl)
{
    bool bEnable = !_rEntry->isCondition();
    _pControl->Enable(bEnable);
    _pControl->EnableInput(bEnable);
}

void OSelectionBrowseBox::setTextCellContext(const OTableFieldDescRef& _rEntry,const OUString& _sText,const OString& _sHelpId)
{
    m_pTextCell->SetText(_sText);
    m_pTextCell->ClearModifyFlag();
    if (!m_pTextCell->HasFocus())
        m_pTextCell->GrabFocus();

    enableControl(_rEntry,m_pTextCell);

    if (m_pTextCell->GetHelpId() != _sHelpId)
        // as TextCell is used in various contexts I will delete the cached HelpText
        m_pTextCell->SetHelpText(OUString());
    m_pTextCell->SetHelpId(_sHelpId);
}

void OSelectionBrowseBox::invalidateUndoRedo()
{
    OQueryController& rController = static_cast<OQueryController&>(getDesignView()->getController());
    rController.InvalidateFeature( ID_BROWSER_UNDO );
    rController.InvalidateFeature( ID_BROWSER_REDO );
    rController.InvalidateFeature( ID_BROWSER_QUERY_EXECUTE );
}

OTableFieldDescRef OSelectionBrowseBox::getEntry(OTableFields::size_type _nPos)
{
    // we have to check if we need a new entry at this position
    OTableFields& aFields = getFields();
    OSL_ENSURE(aFields.size() > _nPos,"ColID is to great!");

    OTableFieldDescRef pEntry = aFields[_nPos];
    OSL_ENSURE(pEntry.is(),"Invalid entry!");
    if ( !pEntry.is() )
    {
        pEntry = new OTableFieldDesc();
        pEntry->SetColumnId(
            GetColumnId(sal::static_int_cast< sal_uInt16 >(_nPos+1)));
        aFields[_nPos] = pEntry;
    }
    return pEntry;
}

void OSelectionBrowseBox::GetFocus()
{
    if(!IsEditing() && !m_bWasEditing)
        ActivateCell();
    EditBrowseBox::GetFocus();
}

void OSelectionBrowseBox::DeactivateCell(bool _bUpdate)
{
    m_bWasEditing = true;
    EditBrowseBox::DeactivateCell(_bUpdate);
    m_bWasEditing = false;
}

OUString OSelectionBrowseBox::GetRowDescription( sal_Int32 _nRow ) const
{
    OUString  aLabel(DBA_RES(STR_QUERY_HANDLETEXT));

    // from BROW_CRIT2_ROW onwards all rows are shown as "or"
    sal_Int32 nToken = (_nRow >= GetBrowseRow(BROW_CRIT2_ROW))
        ?  BROW_CRIT2_ROW : GetRealRow(_nRow);
    return aLabel.getToken(nToken, ';');
}

OUString OSelectionBrowseBox::GetAccessibleObjectName( ::vcl::AccessibleBrowseBoxObjType _eObjType,sal_Int32 _nPosition) const
{
    OUString sRetText;
    switch( _eObjType )
    {
        case ::vcl::BBTYPE_ROWHEADERCELL:
            sRetText = GetRowDescription(_nPosition);
            break;
        default:
            sRetText = EditBrowseBox::GetAccessibleObjectDescription(_eObjType,_nPosition);
    }
    return sRetText;
}

bool OSelectionBrowseBox::fillEntryTable(OTableFieldDescRef const & _pEntry,const OUString& _sTableName)
{
    bool bRet = false;
    OJoinTableView::OTableWindowMap& rTabWinList = getDesignView()->getTableView()->GetTabWinMap();
    OJoinTableView::OTableWindowMap::const_iterator aIter = rTabWinList.find(_sTableName);
    if(aIter != rTabWinList.end())
    {
        OQueryTableWindow* pEntryTab = static_cast<OQueryTableWindow*>(aIter->second.get());
        if (pEntryTab)
        {
            _pEntry->SetTable(pEntryTab->GetTableName());
            _pEntry->SetTabWindow(pEntryTab);
            bRet = true;
        }
    }
    return bRet;
}

void OSelectionBrowseBox::setFunctionCell(OTableFieldDescRef const & _pEntry)
{
    Reference< XConnection> xConnection = static_cast<OQueryController&>(getDesignView()->getController()).getConnection();
    if ( !xConnection.is() )
        return;

    // Aggregate functions in general only available with Core SQL
    if ( lcl_SupportsCoreSQLGrammar(xConnection) )
    {
        sal_Int32 nIdx {0};
        // if we have an asterisk, no other function than count is allowed
        weld::ComboBox& rComboBox = m_pFunctionCell->get_widget();
        rComboBox.clear();
        rComboBox.append_text(m_aFunctionStrings.getToken(0, ';', nIdx));
        if ( isFieldNameAsterisk(_pEntry->GetField()) )
            rComboBox.append_text(m_aFunctionStrings.getToken(1, ';', nIdx)); // 2nd token: COUNT
        else
        {
            const bool bSkipLastToken {_pEntry->isNumeric()};
            while (nIdx>0)
            {
                const OUString sTok {m_aFunctionStrings.getToken(0, ';', nIdx)};
                if (bSkipLastToken && nIdx<0)
                    break;
                rComboBox.append_text(sTok);
            }
        }

        if ( _pEntry->IsGroupBy() )
        {
            OSL_ENSURE(!_pEntry->isNumeric(),"Not allowed to combine group by and numeric values!");
            rComboBox.set_active_text(rComboBox.get_text(rComboBox.get_count() - 1));
        }
        else if (rComboBox.find_text(_pEntry->GetFunction()) != -1)
            rComboBox.set_active_text(_pEntry->GetFunction());
        else
            rComboBox.set_active(0);

        enableControl(_pEntry, m_pFunctionCell);
    }
    else
    {
        // only COUNT(*) and COUNT("table".*) allowed
        bool bCountRemoved = !isFieldNameAsterisk(_pEntry->GetField());
        weld::ComboBox& rComboBox = m_pFunctionCell->get_widget();
        if ( bCountRemoved )
            rComboBox.remove(1);

        if ( !bCountRemoved && rComboBox.get_count() < 2)
            rComboBox.append_text(m_aFunctionStrings.getToken(2, ';')); // 2 -> COUNT

        if (rComboBox.find_text(_pEntry->GetFunction()) != -1)
            rComboBox.set_active_text(_pEntry->GetFunction());
        else
            rComboBox.set_active(0);
    }
}

Reference< XAccessible > OSelectionBrowseBox::CreateAccessibleCell( sal_Int32 _nRow, sal_uInt16 _nColumnPos )
{
    OTableFieldDescRef pEntry;
    if(getFields().size() > o3tl::make_unsigned(_nColumnPos - 1))
        pEntry = getFields()[_nColumnPos - 1];

    if ( _nRow == BROW_VIS_ROW && pEntry.is() )
        return EditBrowseBox::CreateAccessibleCheckBoxCell( _nRow, _nColumnPos,pEntry->IsVisible() ? TRISTATE_TRUE : TRISTATE_FALSE );

    return EditBrowseBox::CreateAccessibleCell( _nRow, _nColumnPos );
}

bool OSelectionBrowseBox::HasFieldByAliasName(const OUString& rFieldName, OTableFieldDescRef const & rInfo) const
{
    for (auto const& field : getFields())
    {
        if ( field->GetFieldAlias() == rFieldName )
        {<--- Consider using std::find_if algorithm instead of a raw loop.
            *rInfo = *field;
            return true;
        }
    }
    return false;
}

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