File: base.py

package info (click to toggle)
grass 8.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 277,040 kB
  • sloc: ansic: 460,798; python: 227,732; cpp: 42,026; sh: 11,262; makefile: 7,007; xml: 3,637; sql: 968; lex: 520; javascript: 484; yacc: 450; asm: 387; perl: 157; sed: 25; objc: 6; ruby: 4
file content (4110 lines) | stat: -rw-r--r-- 144,063 bytes parent folder | download | duplicates (2)
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
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
"""
@package dbmgr.base

@brief GRASS Attribute Table Manager base classes

List of classes:
 - base::Log
 - base::VirtualAttributeList
 - base::DbMgrBase
 - base::DbMgrNotebookBase
 - base::DbMgrBrowsePage
 - base::DbMgrTablesPage
 - base::DbMgrLayersPage
 - base::TableListCtrl
 - base::LayerListCtrl
 - base::LayerBook
 - base::FieldStatistics

.. todo::
    Implement giface class

(C) 2007-2014 by the GRASS Development Team

This program is free software under the GNU General Public License
(>=v2). Read the file COPYING that comes with GRASS for details.

@author Jachym Cepicky <jachym.cepicky gmail.com>
@author Martin Landa <landa.martin gmail.com>
@author Refactoring by Stepan Turek <stepan.turek seznam.cz>
        (GSoC 2012, mentor: Martin Landa)
"""

import os
import locale
import tempfile
import copy
import math
import functools

from core import globalvar
import wx
import wx.lib.mixins.listctrl as listmix

if globalvar.wxPythonPhoenix:
    try:
        import agw.flatnotebook as FN
    except ImportError:  # if it's not there locally, try the wxPython lib.
        import wx.lib.agw.flatnotebook as FN
else:
    import wx.lib.flatnotebook as FN
import wx.lib.scrolledpanel as scrolled

import grass.script as grass
from grass.script.utils import decode

from dbmgr.sqlbuilder import SQLBuilderSelect, SQLBuilderUpdate
from core.gcmd import RunCommand, GException, GError, GMessage, GWarning
from core.utils import ListOfCatsToRange
from gui_core.dialogs import CreateNewVector
from gui_core.widgets import GNotebook
from dbmgr.vinfo import VectorDBInfo, GetUnicodeValue, CreateDbInfoDesc, GetDbEncoding
from core.debug import Debug
from dbmgr.dialogs import ModifyTableRecord, AddColumnDialog
from core.settings import UserSettings
from gui_core.wrap import (
    Button,
    CheckBox,
    ComboBox,
    ListCtrl,
    Menu,
    NewId,
    SpinCtrl,
    StaticBox,
    StaticText,
    TextCtrl,
)
from core.utils import cmp


class Log:
    """The log output SQL is redirected to the status bar of the
    containing frame.
    """

    def __init__(self, parent):
        self.parent = parent

    def write(self, text_string):
        """Update status bar"""
        if self.parent:
            self.parent.SetStatusText(text_string.strip())


class VirtualAttributeList(
    ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin
):
    """Support virtual list class for Attribute Table Manager (browse page)"""

    def __init__(self, parent, log, dbMgrData, layer, pages):
        # initialize variables
        self.parent = parent
        self.log = log
        self.dbMgrData = dbMgrData
        self.mapDBInfo = self.dbMgrData["mapDBInfo"]
        self.layer = layer
        self.pages = pages

        self.fieldCalc = None
        self.fieldStats = None
        self.columns = {}  # <- LoadData()

        self.sqlFilter = {}

        ListCtrl.__init__(
            self,
            parent=parent,
            id=wx.ID_ANY,
            style=wx.LC_REPORT
            | wx.LC_HRULES
            | wx.LC_VRULES
            | wx.LC_VIRTUAL
            | wx.LC_SORT_ASCENDING,
        )

        try:
            keyColumn = self.LoadData(layer)
        except GException as e:
            GError(parent=self, message=e.value)
            return

        self.EnableAlternateRowColours()
        self.il = wx.ImageList(16, 16)
        self.sm_up = self.il.Add(
            wx.ArtProvider.GetBitmap(wx.ART_GO_UP, wx.ART_TOOLBAR, (16, 16))
        )
        self.sm_dn = self.il.Add(
            wx.ArtProvider.GetBitmap(wx.ART_GO_DOWN, wx.ART_TOOLBAR, (16, 16))
        )
        self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)

        # setup mixins
        listmix.ListCtrlAutoWidthMixin.__init__(self)
        listmix.ColumnSorterMixin.__init__(self, len(self.columns))

        # sort item by category (id)
        if keyColumn > -1:
            self.SortListItems(col=keyColumn, ascending=True)
        elif keyColumn:
            self.SortListItems(col=0, ascending=True)

        # events
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
        self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColumnSort)
        self.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self.OnColumnMenu)

    def Update(self, mapDBInfo=None):
        """Update list according new mapDBInfo description"""
        if mapDBInfo:
            self.mapDBInfo = mapDBInfo
            self.LoadData(self.layer)
        else:
            self.LoadData(self.layer, **self.sqlFilter)

    def LoadData(self, layer, columns=None, where=None, sql=None):
        """Load data into list

        :param layer: layer number
        :param columns: list of columns for output (-> v.db.select)
        :param where: where statement (-> v.db.select)
        :param sql: full sql statement (-> db.select)

        :return: id of key column
        :return: -1 if key column is not displayed
        """
        self.log.write(_("Loading data..."))

        tableName = self.mapDBInfo.layers[layer]["table"]
        keyColumn = self.mapDBInfo.layers[layer]["key"]
        try:
            self.columns = self.mapDBInfo.tables[tableName]
        except KeyError:
            raise GException(
                _(
                    "Attribute table <%s> not found. "
                    "For creating the table switch to "
                    "'Manage layers' tab."
                )
                % tableName
            )

        if not columns:
            columns = self.mapDBInfo.GetColumns(tableName)
        else:
            all = self.mapDBInfo.GetColumns(tableName)
            for col in columns:
                if col not in all:
                    GError(
                        parent=self,
                        message=_(
                            "Column <%(column)s> not found in "
                            "in the table <%(table)s>."
                        )
                        % {"column": col, "table": tableName},
                    )
                    return

        try:
            # for maps connected via v.external
            keyId = columns.index(keyColumn)
        except:
            keyId = -1

        # read data
        # FIXME: Max. number of rows, while the GUI is still usable

        # stdout can be very large, do not use PIPE, redirect to temp file
        # TODO: more effective way should be implemented...

        # split on field sep breaks if varchar() column contains the
        # values, so while sticking with ASCII we make it something
        # highly unlikely to exist naturally.
        fs = "{_sep_}"

        outFile = tempfile.NamedTemporaryFile(mode="w+b")

        cmdParams = dict(quiet=True, parent=self, flags="c", separator=fs)

        if sql:
            cmdParams.update(dict(sql=sql, output=outFile.name, overwrite=True))
            ret = RunCommand("db.select", **cmdParams)
            self.sqlFilter = {"sql": sql}
        else:
            cmdParams.update(
                dict(map=self.mapDBInfo.map, layer=layer, where=where, stdout=outFile)
            )

            self.sqlFilter = {"where": where}

            if columns:
                # Enclose column name with SQL standard double quotes
                cmdParams.update(
                    dict(columns=",".join([f'"{col}"' for col in columns]))
                )

            ret = RunCommand("v.db.select", **cmdParams)

        # These two should probably be passed to init more cleanly
        # setting the numbers of items = number of elements in the dictionary
        self.itemDataMap = {}
        self.itemIndexMap = []
        self.itemCatsMap = {}

        self.DeleteAllItems()

        # self.ClearAll()
        for i in range(self.GetColumnCount()):
            self.DeleteColumn(0)

        i = 0
        info = wx.ListItem()
        if globalvar.wxPythonPhoenix:
            info.Mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
            info.Image = -1
            info.Format = 0
        else:
            info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
            info.m_image = -1
            info.m_format = 0
        for column in columns:
            if globalvar.wxPythonPhoenix:
                info.Text = column
                self.InsertColumn(i, info)
            else:
                info.m_text = column
                self.InsertColumnInfo(i, info)
            i += 1
            if i >= 256:
                self.log.write(_("Can display only 256 columns."))

        i = 0
        outFile.seek(0)

        enc = GetDbEncoding()
        first_wrong_encoding = True
        while True:
            # os.linesep doesn't work here (MSYS)
            # not sure what the replace is for?
            # but we need strip to get rid of the ending newline
            # which on windows leaves \r in a last empty attribute table cell
            # and causes error
            try:
                record = (
                    decode(outFile.readline(), encoding=enc).strip().replace("\n", "")
                )
            except UnicodeDecodeError as e:
                record = (
                    outFile.readline()
                    .decode(encoding=enc, errors="replace")
                    .strip()
                    .replace("\n", "")
                )
                if first_wrong_encoding:
                    first_wrong_encoding = False
                    GWarning(
                        parent=self,
                        message=_(
                            "Incorrect encoding {enc} used. Set encoding in GUI "
                            "Settings or set GRASS_DB_ENCODING variable."
                        ).format(enc=enc),
                    )

            if not record:
                break

            record = record.split(fs)
            if len(columns) != len(record):
                # Assuming there will be always at least one.
                last = record[-1]
                show_max = 3
                if len(record) > show_max:
                    record = record[:show_max]
                # TODO: The real fix here is to use JSON output from v.db.select or
                # proper CSV output and real CSV reader here (Python csv and json
                # packages).
                raise GException(
                    _(
                        "Unable to read the table <{table}> from the database due"
                        " to seemingly inconsistent number of columns in the data"
                        " transfer."
                        " Check row: {row}..."
                        " Likely, a newline character is present in the attribute value"
                        " starting with: '{value}'"
                        " Use the v.db.select module to investigate."
                    ).format(table=tableName, row=" | ".join(record), value=last)
                )
                self.columns = {}  # because of IsEmpty method
                return None

            self.AddDataRow(i, record, columns, keyId)

            i += 1
            if i >= 100000:
                self.log.write(_("Viewing limit: 100000 records."))
                break

        self.SetItemCount(i)

        if where:
            item = -1
            while True:
                item = self.GetNextItem(item)
                if item == -1:
                    break
                self.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)

        i = 0
        for col in columns:
            width = self.columns[col]["length"] * 6  # FIXME
            if width < 60:
                width = 60
            if width > 300:
                width = 300
            self.SetColumnWidth(col=i, width=width)
            i += 1

        self.SendSizeEvent()

        self.log.write(_("Number of loaded records: %d") % self.GetItemCount())

        return keyId

    def AddDataRow(self, i, record, columns, keyId):
        """Add row to the data list"""
        self.itemDataMap[i] = []
        keyColumn = self.mapDBInfo.layers[self.layer]["key"]
        j = 0
        cat = None

        if keyColumn == "OGC_FID":
            self.itemDataMap[i].append(i + 1)
            j += 1
            cat = i + 1

        for value in record:
            if self.columns[columns[j]]["ctype"] != str:
                try:
                    # casting disabled (2009/03)
                    # self.itemDataMap[i].append(self.columns[columns[j]]['ctype'](value))
                    self.itemDataMap[i].append(value)
                except ValueError:
                    self.itemDataMap[i].append(_("Unknown value"))
            else:
                # encode string values
                try:
                    self.itemDataMap[i].append(GetUnicodeValue(value))
                except UnicodeDecodeError:
                    self.itemDataMap[i].append(
                        _(
                            "Unable to decode value. "
                            "Set encoding in GUI preferences ('Attributes')."
                        )
                    )

            if not cat and keyId > -1 and keyId == j:
                try:
                    cat = self.columns[columns[j]]["ctype"](value)
                except ValueError as e:
                    cat = -1
                    GError(
                        parent=self,
                        message=_(
                            "Error loading attribute data. "
                            "Record number: %(rec)d. Unable to convert value '%(val)s' "
                            "in key column (%(key)s) to integer.\n\n"
                            "Details: %(detail)s"
                        )
                        % {"rec": i + 1, "val": value, "key": keyColumn, "detail": e},
                    )
            j += 1

        self.itemIndexMap.append(i)
        if keyId > -1:  # load cats only when LoadData() is called first time
            self.itemCatsMap[i] = cat

    def OnItemSelected(self, event):
        """Item selected. Add item to selected cats..."""
        #         cat = int(self.GetItemText(event.m_itemIndex))
        #         if cat not in self.selectedCats:
        #             self.selectedCats.append(cat)
        #             self.selectedCats.sort()

        event.Skip()

    def OnItemDeselected(self, event):
        """Item deselected. Remove item from selected cats..."""
        #         cat = int(self.GetItemText(event.m_itemIndex))
        #         if cat in self.selectedCats:
        #             self.selectedCats.remove(cat)
        #             self.selectedCats.sort()

        event.Skip()

    def GetSelectedItems(self):
        """Return list of selected items (category numbers)"""
        cats = []
        item = self.GetFirstSelected()
        while item != -1:
            cats.append(self.GetItemText(item))
            item = self.GetNextSelected(item)

        return cats

    def GetItems(self):
        """Return list of items (category numbers)"""
        cats = []
        for item in range(self.GetItemCount()):
            cats.append(self.GetItemText(item))

        return cats

    def GetColumnText(self, index, col):
        """Return column text"""
        item = self.GetItem(index, col)
        return item.GetText()

    def GetListCtrl(self):
        """Returt list"""
        return self

    def OnGetItemText(self, item, col):
        """Get item text"""
        index = self.itemIndexMap[item]
        s = self.itemDataMap[index][col]
        return str(s)

    def OnColumnMenu(self, event):
        """Column heading right mouse button -> pop-up menu"""
        self._col = event.GetColumn()

        popupMenu = Menu()

        if not hasattr(self, "popupID"):
            self.popupId = {
                "sortAsc": NewId(),
                "sortDesc": NewId(),
                "area": NewId(),
                "length": NewId(),
                "compact": NewId(),
                "fractal": NewId(),
                "perimeter": NewId(),
                "ncats": NewId(),
                "slope": NewId(),
                "lsin": NewId(),
                "lazimuth": NewId(),
                "calculator": NewId(),
                "stats": NewId(),
            }

        popupMenu.Append(self.popupId["sortAsc"], _("Sort ascending"))
        popupMenu.Append(self.popupId["sortDesc"], _("Sort descending"))
        popupMenu.AppendSeparator()
        subMenu = Menu()
        subMenuItem = popupMenu.AppendSubMenu(
            subMenu,
            _("Calculate (only numeric columns)"),
        )
        popupMenu.Append(self.popupId["calculator"], _("Field calculator"))
        popupMenu.AppendSeparator()
        popupMenu.Append(self.popupId["stats"], _("Statistics"))

        if not self.pages["manageTable"]:
            popupMenu.AppendSeparator()
            self.popupId["addCol"] = NewId()
            popupMenu.Append(self.popupId["addCol"], _("Add column"))
            if not self.dbMgrData["editable"]:
                popupMenu.Enable(self.popupId["addCol"], False)

        if not self.dbMgrData["editable"]:
            popupMenu.Enable(self.popupId["calculator"], False)

        if not self.dbMgrData["editable"] or self.columns[
            self.GetColumn(self._col).GetText()
        ]["ctype"] not in (int, float):
            subMenuItem.Enable(False)

        subMenu.Append(self.popupId["area"], _("Area size"))
        subMenu.Append(self.popupId["length"], _("Line length"))
        subMenu.Append(self.popupId["compact"], _("Compactness of an area"))
        subMenu.Append(
            self.popupId["fractal"],
            _("Fractal dimension of boundary defining a polygon"),
        )
        subMenu.Append(self.popupId["perimeter"], _("Perimeter length of an area"))
        subMenu.Append(self.popupId["ncats"], _("Number of features for each category"))
        subMenu.Append(self.popupId["slope"], _("Slope steepness of 3D line"))
        subMenu.Append(self.popupId["lsin"], _("Line sinuousity"))
        subMenu.Append(self.popupId["lazimuth"], _("Line azimuth"))

        self.Bind(wx.EVT_MENU, self.OnColumnSortAsc, id=self.popupId["sortAsc"])
        self.Bind(wx.EVT_MENU, self.OnColumnSortDesc, id=self.popupId["sortDesc"])
        self.Bind(wx.EVT_MENU, self.OnFieldCalculator, id=self.popupId["calculator"])
        self.Bind(wx.EVT_MENU, self.OnFieldStatistics, id=self.popupId["stats"])
        if not self.pages["manageTable"]:
            self.Bind(wx.EVT_MENU, self.OnAddColumn, id=self.popupId["addCol"])

        for id in (
            self.popupId["area"],
            self.popupId["length"],
            self.popupId["compact"],
            self.popupId["fractal"],
            self.popupId["perimeter"],
            self.popupId["ncats"],
            self.popupId["slope"],
            self.popupId["lsin"],
            self.popupId["lazimuth"],
        ):
            self.Bind(wx.EVT_MENU, self.OnColumnCompute, id=id)

        self.PopupMenu(popupMenu)
        popupMenu.Destroy()

    def OnColumnSort(self, event):
        """Column heading left mouse button -> sorting"""
        self._col = event.GetColumn()
        self._updateColSortFlag()
        self.ColumnSort()
        event.Skip()

    def OnColumnSortAsc(self, event):
        """Sort values of selected column (ascending)"""
        self._updateColSortFlag()
        self.SortListItems(col=self._col, ascending=True)
        event.Skip()

    def OnColumnSortDesc(self, event):
        """Sort values of selected column (descending)"""
        self._updateColSortFlag()
        self.SortListItems(col=self._col, ascending=False)
        event.Skip()

    def OnColumnCompute(self, event):
        """Compute values of selected column"""
        id = event.GetId()

        option = None
        if id == self.popupId["area"]:
            option = "area"
        elif id == self.popupId["length"]:
            option = "length"
        elif id == self.popupId["compact"]:
            option = "compact"
        elif id == self.popupId["fractal"]:
            option = "fd"
        elif id == self.popupId["perimeter"]:
            option = "perimeter"
        elif id == self.popupId["ncats"]:
            option = "count"
        elif id == self.popupId["slope"]:
            option = "slope"
        elif id == self.popupId["lsin"]:
            option = "sinuous"
        elif id == self.popupId["lazimuth"]:
            option = "azimuth"

        if not option:
            return

        RunCommand(
            "v.to.db",
            parent=self.parent,
            map=self.mapDBInfo.map,
            layer=self.layer,
            option=option,
            columns=self.GetColumn(self._col).GetText(),
            overwrite=True,
        )

        self.LoadData(self.layer)

    def ColumnSort(self):
        """Sort values of selected column (self._col)"""
        # remove duplicated arrow symbol from column header
        # FIXME: should be done automatically
        info = wx.ListItem()
        info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE
        info.m_image = -1
        for column in range(self.GetColumnCount()):
            info.m_text = self.GetColumn(column).GetText()
            self.SetColumn(column, info)

    def OnFieldCalculator(self, event):
        """Calls SQLBuilderUpdate instance"""
        if not self.fieldCalc:
            self.fieldCalc = SQLBuilderUpdate(
                parent=self,
                id=wx.ID_ANY,
                vectmap=self.dbMgrData["vectName"],
                layer=self.layer,
                column=self.GetColumn(self._col).GetText(),
            )
            self.fieldCalc.Show()
        else:
            self.fieldCalc.Raise()

    def OnFieldStatistics(self, event):
        """Calls FieldStatistics instance"""
        if not self.fieldStats:
            self.fieldStats = FieldStatistics(parent=self, id=wx.ID_ANY)
            self.fieldStats.Show()
        else:
            self.fieldStats.Raise()

        selLayer = self.dbMgrData["mapDBInfo"].layers[self.layer]
        self.fieldStats.Update(
            driver=selLayer["driver"],
            database=selLayer["database"],
            table=selLayer["table"],
            column=self.GetColumn(self._col).GetText(),
        )

    def OnAddColumn(self, event):
        """Add column into table"""
        table = self.dbMgrData["mapDBInfo"].layers[self.layer]["table"]
        dlg = AddColumnDialog(parent=self, title=_("Add column to table <%s>") % table)
        if not dlg:
            return
        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetData()
            self.pages["browse"].AddColumn(
                name=data["name"], ctype=data["ctype"], length=data["length"]
            )
        dlg.Destroy()

    def SortItems(self, sorter=cmp):
        """Sort items"""
        wx.BeginBusyCursor()
        items = list(self.itemDataMap.keys())
        items.sort(key=functools.cmp_to_key(self.Sorter))
        self.itemIndexMap = items

        # redraw the list
        self.Refresh()
        wx.EndBusyCursor()

    def Sorter(self, key1, key2):
        colName = self.GetColumn(self._col).GetText()
        ascending = self._colSortFlag[self._col]
        try:
            item1 = self.columns[colName]["ctype"](self.itemDataMap[key1][self._col])
            item2 = self.columns[colName]["ctype"](self.itemDataMap[key2][self._col])
        except ValueError:
            item1 = self.itemDataMap[key1][self._col]
            item2 = self.itemDataMap[key2][self._col]

        if isinstance(item1, str) or isinstance(item2, str):
            cmpVal = locale.strcoll(GetUnicodeValue(item1), GetUnicodeValue(item2))
        else:
            cmpVal = cmp(item1, item2)

        # If the items are equal then pick something else to make the sort
        # value unique
        if cmpVal == 0:
            cmpVal = cmp(*self.GetSecondarySortValues(self._col, key1, key2))

        if ascending:
            return cmpVal
        else:
            return -cmpVal

    def GetSortImages(self):
        """Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py"""
        return (self.sm_dn, self.sm_up)

    def OnGetItemImage(self, item):
        return -1

    def IsEmpty(self):
        """Check if list if empty"""
        if self.columns:
            return False

        return True

    def _updateColSortFlag(self):
        """
        Update listmix.ColumnSorterMixin class self._colSortFlag list
        private variable for new column which was added (required for
        sorting new added column values)
        """
        self._colSortFlag.extend([0] * (len(self.columns) - len(self._colSortFlag)))


class DbMgrBase:
    def __init__(
        self,
        id=wx.ID_ANY,
        mapdisplay=None,
        vectorName=None,
        item=None,
        giface=None,
        statusbar=None,
        **kwargs,
    ):
        """Base class, which enables usage of separate pages of Attribute Table Manager

        :param id: window id
        :param mapdisplay: MapFrame instance
        :param vectorName: name of vector map
        :param item: item from Layer Tree
        :param log: log window
        :param statusbar: widget with statusbar
        :param kwagrs: other wx.Frame's arguments
        """

        # stores all data, which are shared by pages
        self.dbMgrData = {}
        self.dbMgrData["vectName"] = vectorName
        self.dbMgrData["treeItem"] = item  # item in layer tree

        self.mapdisplay = mapdisplay

        if self.mapdisplay:
            self.map = mapdisplay.Map
        else:
            self.map = None

        if not self.mapdisplay:
            pass
        elif (
            self.mapdisplay.tree
            and self.dbMgrData["treeItem"]
            and not self.dbMgrData["vectName"]
        ):
            maptree = self.mapdisplay.tree
            name = maptree.GetLayerInfo(
                self.dbMgrData["treeItem"], key="maplayer"
            ).GetName()
            self.dbMgrData["vectName"] = name

        # vector attributes can be changed only if vector map is in
        # the current mapset
        mapInfo = None
        if self.dbMgrData["vectName"]:
            mapInfo = grass.find_file(name=self.dbMgrData["vectName"], element="vector")
        if not mapInfo or mapInfo["mapset"] != grass.gisenv()["MAPSET"]:
            self.dbMgrData["editable"] = False
        else:
            self.dbMgrData["editable"] = True

        self.giface = giface

        # status bar log class
        self.log = Log(statusbar)  # -> statusbar

        # -> layers / tables description
        self.dbMgrData["mapDBInfo"] = VectorDBInfo(self.dbMgrData["vectName"])

        # store information, which pages were initialized
        self.pages = {"browse": None, "manageTable": None, "manageLayer": None}

    def ChangeVectorMap(self, vectorName):
        """Change of vector map

        Does not import layers of new vector map into pages.
        For the import use methods addLayer in DbMgrBrowsePage and DbMgrTablesPage
        """
        if self.pages["browse"]:
            self.pages["browse"].DeleteAllPages()
        if self.pages["manageTable"]:
            self.pages["manageTable"].DeleteAllPages()

        self.dbMgrData["vectName"] = vectorName

        # fetch fresh db info
        self.dbMgrData["mapDBInfo"] = VectorDBInfo(self.dbMgrData["vectName"])

        # vector attributes can be changed only if vector map is in
        # the current mapset
        mapInfo = grass.find_file(name=self.dbMgrData["vectName"], element="vector")
        if not mapInfo or mapInfo["mapset"] != grass.gisenv()["MAPSET"]:
            self.dbMgrData["editable"] = False
        else:
            self.dbMgrData["editable"] = True

        # 'manage layers page
        if self.pages["manageLayer"]:
            self.pages["manageLayer"].UpdatePage()

    def CreateDbMgrPage(self, parent, pageName, onlyLayer=-1):
        """Creates chosen page

        :param pageName: can be 'browse' or 'manageTable' or
                         'manageLayer' which corresponds with pages in
                         Attribute Table Manager
        :return: created instance of page, if the page has been already
                 created returns the previously created instance
        :return: None  if wrong identifier was passed
        """
        if pageName == "browse":
            if not self.pages["browse"]:
                self.pages[pageName] = DbMgrBrowsePage(
                    parent=parent, parentDbMgrBase=self, onlyLayer=onlyLayer
                )
            return self.pages[pageName]
        if pageName == "manageTable":
            if not self.pages["manageTable"]:
                self.pages[pageName] = DbMgrTablesPage(
                    parent=parent, parentDbMgrBase=self, onlyLayer=onlyLayer
                )
            return self.pages[pageName]
        if pageName == "manageLayer":
            if not self.pages["manageLayer"]:
                self.pages[pageName] = DbMgrLayersPage(
                    parent=parent, parentDbMgrBase=self
                )
            return self.pages[pageName]
        return None

    def UpdateDialog(self, layer):
        """Updates dialog layout for given layer"""
        # delete page
        if layer in self.dbMgrData["mapDBInfo"].layers.keys():
            # delete page
            # dragging pages disallowed
            # if self.browsePage.GetPageText(page).replace("Layer ", "").strip() == str(
            #     layer
            # ):
            #     self.browsePage.DeletePage(page)
            #     break
            if self.pages["browse"]:
                self.pages["browse"].DeletePage(layer)
            if self.pages["manageTable"]:
                self.pages["manageTable"].DeletePage(layer)

        # fetch fresh db info
        self.dbMgrData["mapDBInfo"] = VectorDBInfo(self.dbMgrData["vectName"])

        #
        # add new page
        #
        if layer in self.dbMgrData["mapDBInfo"].layers.keys():
            # 'browse data' page
            if self.pages["browse"]:
                self.pages["browse"].AddLayer(layer)
            # 'manage tables' page
            if self.pages["manageTable"]:
                self.pages["manageTable"].AddLayer(layer)

        # manage layers page
        if self.pages["manageLayer"]:
            self.pages["manageLayer"].UpdatePage()

    def GetVectorName(self):
        """Get vector name"""
        return self.dbMgrData["vectName"]

    def GetVectorLayers(self):
        """Get layers of vector map which have table"""
        return self.dbMgrData["mapDBInfo"].layers.keys()


class DbMgrNotebookBase(GNotebook):
    def __init__(self, parent, parentDbMgrBase):
        """Base class for notebook with attribute tables in tabs

        :param parent: GUI parent
        :param parentDbMgrBase: instance of DbMgrBase class
        """

        self.parent = parent
        self.parentDbMgrBase = parentDbMgrBase

        self.log = self.parentDbMgrBase.log
        self.giface = self.parentDbMgrBase.giface

        self.map = self.parentDbMgrBase.map
        self.mapdisplay = self.parentDbMgrBase.mapdisplay

        # TODO no need to have it in class scope make it local?
        self.listOfCommands = []
        self.listOfSQLStatements = []

        # initializet pages
        self.pages = self.parentDbMgrBase.pages

        # shared data among pages
        self.dbMgrData = self.parentDbMgrBase.dbMgrData

        # set up virtual lists (each layer)
        # {layer: list, widgets...}
        self.layerPage = {}

        # currently selected layer
        self.selLayer = None

        # list which represents layers numbers in order of tabs
        self.layers = []

        GNotebook.__init__(self, parent=self.parent, style=globalvar.FNPageStyle)

        self.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnLayerPageChanged)

    def OnLayerPageChanged(self, event):
        """Layer tab changed"""

        # because of SQL Query notebook
        if event.GetEventObject() != self:
            return

        pageNum = self.GetSelection()
        self.selLayer = self.layers[pageNum]
        try:
            idCol = self.layerPage[self.selLayer]["whereColumn"]
        except KeyError:
            idCol = None

        try:
            # update statusbar
            self.log.write(
                _("Number of loaded records: %d")
                % self.FindWindowById(
                    self.layerPage[self.selLayer]["data"]
                ).GetItemCount()
            )
        except:
            pass

        if idCol:
            winCol = self.FindWindowById(idCol)
            table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
            self.dbMgrData["mapDBInfo"].GetColumns(table)

    def ApplyCommands(self, listOfCommands, listOfSQLStatements):
        """Apply changes

        .. todo::
            this part should be _completely_ redesigned
        """
        # perform GRASS commands (e.g. v.db.addcolumn)
        wx.BeginBusyCursor()

        if len(listOfCommands) > 0:
            for cmd in listOfCommands:
                RunCommand(prog=cmd[0], quiet=True, parent=self, **cmd[1])

            self.dbMgrData["mapDBInfo"] = VectorDBInfo(self.dbMgrData["vectName"])
            if self.pages["manageTable"]:
                self.pages["manageTable"].UpdatePage(self.selLayer)

            if self.pages["browse"]:
                self.pages["browse"].UpdatePage(self.selLayer)
            # reset list of commands
            listOfCommands = []

        # perform SQL non-select statements (e.g. 'delete from table where
        # cat=1')
        if len(listOfSQLStatements) > 0:
            enc = GetDbEncoding()
            fd, sqlFilePath = tempfile.mkstemp(text=True)
            with open(sqlFilePath, "w", encoding=enc) as sqlFile:
                for sql in listOfSQLStatements:
                    sqlFile.write(sql + ";")
                    sqlFile.write("\n")

            driver = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["driver"]
            database = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["database"]

            Debug.msg(
                3,
                "AttributeManger.ApplyCommands(): %s"
                % ";".join(["%s" % s for s in listOfSQLStatements]),
            )

            RunCommand(
                "db.execute",
                parent=self,
                input=sqlFilePath,
                driver=driver,
                database=database,
            )

            os.close(fd)
            os.remove(sqlFilePath)
            # reset list of statements
            self.listOfSQLStatements = []

        wx.EndBusyCursor()

    def DeletePage(self, layer):
        """Removes layer page"""
        if layer not in self.layers:
            return False

        GNotebook.DeleteNBPage(self, self.layers.index(layer))

        self.layers.remove(layer)
        del self.layerPage[layer]

        if self.GetSelection() >= 0:
            self.selLayer = self.layers[-1]
        else:
            self.selLayer = None

        return True

    def DeleteAllPages(self):
        """Removes all layer pages"""
        GNotebook.DeleteAllPages(self)
        self.layerPage = {}
        self.layers = []
        self.selLayer = None

    def AddColumn(self, name, ctype, length):
        """Add new column to the table"""
        table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]

        if not name:
            GError(
                parent=self,
                message=_(
                    "Unable to add column to the table. " "No column name defined."
                ),
            )
            return False

        # cast type if needed
        if ctype == "double":
            ctype = "double precision"
        if ctype != "varchar":
            length = ""  # FIXME

        # check for duplicate items
        if name in self.dbMgrData["mapDBInfo"].GetColumns(table):
            GError(
                parent=self,
                message=_("Column <%(column)s> already exists in table <%(table)s>.")
                % {
                    "column": name,
                    "table": self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"],
                },
            )
            return False

        # add v.db.addcolumn command to the list
        if ctype == "varchar":
            ctype += " (%d)" % length
        self.listOfCommands.append(
            (
                "v.db.addcolumn",
                {
                    "map": self.dbMgrData["vectName"],
                    "layer": self.selLayer,
                    "columns": "%s %s" % (name, ctype),
                },
            )
        )
        # apply changes
        self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)

        return True

    def GetAddedLayers(self):
        """Get list of added layers"""
        return self.layers[:]


class DbMgrBrowsePage(DbMgrNotebookBase):
    def __init__(self, parent, parentDbMgrBase, onlyLayer=-1):
        """Browse page class

        :param parent: GUI parent
        :param parentDbMgrBase: instance of DbMgrBase class
        :param onlyLayer: create only tab of given layer, if -1 creates
                          tabs of all layers
        """

        DbMgrNotebookBase.__init__(self, parent=parent, parentDbMgrBase=parentDbMgrBase)

        #   for Sql Query notebook adaptation on current width
        self.sqlBestSize = None

        for layer in self.dbMgrData["mapDBInfo"].layers.keys():
            if onlyLayer > 0 and layer != onlyLayer:
                continue
            self.AddLayer(layer)

        if self.layers:
            self.SetSelection(0)
            self.selLayer = self.layers[0]
            self.log.write(
                _("Number of loaded records: %d")
                % self.FindWindowById(
                    self.layerPage[self.selLayer]["data"]
                ).GetItemCount()
            )

        # query map layer (if parent (GMFrame) is given)
        self.qlayer = None

        # sqlbuilder
        self.builder = None

    def AddLayer(self, layer, pos=-1):
        """Adds tab which represents table and enables browse it

        :param layer: vector map layer conntected to table
        :param pos: position of tab, if -1 it is added to end

        :return: True if layer was added
        :return: False if layer was not added - layer has been already
                 added or has empty table or does not exist
        """
        if layer in self.layers or layer not in self.parentDbMgrBase.GetVectorLayers():
            return False

        panel = wx.Panel(parent=self, id=wx.ID_ANY)

        # IMPORTANT NOTE: wx.StaticBox MUST be defined BEFORE any of the
        #   controls that are placed IN the wx.StaticBox, or it will freeze
        #   on the Mac

        listBox = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " % _("Attribute data - right-click to edit/manage records"),
        )
        listSizer = wx.StaticBoxSizer(listBox, wx.VERTICAL)

        win = VirtualAttributeList(panel, self.log, self.dbMgrData, layer, self.pages)
        if win.IsEmpty():
            panel.Destroy()
            return False

        self.layers.append(layer)

        win.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnDataItemActivated)

        self.layerPage[layer] = {"browsePage": panel.GetId()}

        label = _("Table")
        if not self.dbMgrData["editable"]:
            label += _(" (read-only)")

        if pos == -1:
            pos = self.GetPageCount()
        self.InsertNBPage(
            index=pos,
            page=panel,
            text=" %d / %s %s"
            % (layer, label, self.dbMgrData["mapDBInfo"].layers[layer]["table"]),
        )

        pageSizer = wx.BoxSizer(wx.VERTICAL)

        sqlQueryPanel = wx.Panel(parent=panel, id=wx.ID_ANY)

        # attribute data
        sqlBox = StaticBox(
            parent=sqlQueryPanel, id=wx.ID_ANY, label=" %s " % _("SQL Query")
        )

        sqlSizer = wx.StaticBoxSizer(sqlBox, wx.VERTICAL)

        win.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnDataRightUp)  # wxMSW
        win.Bind(wx.EVT_RIGHT_UP, self.OnDataRightUp)  # wxGTK
        if UserSettings.Get(group="atm", key="leftDbClick", subkey="selection") == 0:
            win.Bind(wx.EVT_LEFT_DCLICK, self.OnDataItemEdit)
            win.Bind(wx.EVT_COMMAND_LEFT_DCLICK, self.OnDataItemEdit)
        else:
            win.Bind(wx.EVT_LEFT_DCLICK, self.OnDataDrawSelected)
            win.Bind(wx.EVT_COMMAND_LEFT_DCLICK, self.OnDataDrawSelected)

        listSizer.Add(win, proportion=1, flag=wx.EXPAND | wx.ALL, border=3)

        # sql statement box
        sqlNtb = GNotebook(
            parent=sqlQueryPanel,
            style=FN.FNB_NO_NAV_BUTTONS | FN.FNB_NO_X_BUTTON | FN.FNB_NODRAG,
        )

        # Simple tab
        simpleSqlPanel = wx.Panel(parent=sqlNtb, id=wx.ID_ANY)
        sqlNtb.AddPage(page=simpleSqlPanel, text=_("Simple"))

        btnApply = Button(parent=simpleSqlPanel, id=wx.ID_APPLY, name="btnApply")
        btnApply.SetToolTip(_("Apply SELECT statement and reload data records"))
        btnApply.Bind(wx.EVT_BUTTON, self.OnApplySqlStatement)

        whereSimpleSqlPanel = wx.Panel(
            parent=simpleSqlPanel, id=wx.ID_ANY, name="wherePanel"
        )
        sqlWhereColumn = ComboBox(
            parent=whereSimpleSqlPanel,
            id=wx.ID_ANY,
            size=(150, -1),
            style=wx.CB_READONLY,
            choices=self.dbMgrData["mapDBInfo"].GetColumns(
                self.dbMgrData["mapDBInfo"].layers[layer]["table"]
            ),
        )
        sqlWhereColumn.SetSelection(0)
        sqlWhereCond = wx.Choice(
            parent=whereSimpleSqlPanel,
            id=wx.ID_ANY,
            size=(55, -1),
            choices=["=", "!=", "<", "<=", ">", ">="],
        )
        sqlWhereCond.SetSelection(0)
        sqlWhereValue = TextCtrl(
            parent=whereSimpleSqlPanel,
            id=wx.ID_ANY,
            value="",
            style=wx.TE_PROCESS_ENTER,
        )
        sqlWhereValue.SetToolTip(
            _("Example: %s") % "MULTILANE = 'no' AND OBJECTID < 10"
        )

        sqlLabel = StaticText(
            parent=simpleSqlPanel,
            id=wx.ID_ANY,
            label="SELECT * FROM %s WHERE "
            % self.dbMgrData["mapDBInfo"].layers[layer]["table"],
        )
        # Advanced tab
        advancedSqlPanel = wx.Panel(parent=sqlNtb, id=wx.ID_ANY)
        sqlNtb.AddPage(page=advancedSqlPanel, text=_("Builder"))

        btnSqlBuilder = Button(
            parent=advancedSqlPanel, id=wx.ID_ANY, label=_("SQL Builder")
        )
        btnSqlBuilder.Bind(wx.EVT_BUTTON, self.OnBuilder)

        sqlStatement = TextCtrl(
            parent=advancedSqlPanel,
            id=wx.ID_ANY,
            value="SELECT * FROM %s"
            % self.dbMgrData["mapDBInfo"].layers[layer]["table"],
            style=wx.TE_PROCESS_ENTER,
        )
        sqlStatement.SetToolTip(
            _("Example: %s")
            % "SELECT * FROM roadsmajor WHERE MULTILANE = 'no' AND OBJECTID < 10"
        )
        sqlWhereValue.Bind(wx.EVT_TEXT_ENTER, self.OnApplySqlStatement)
        sqlStatement.Bind(wx.EVT_TEXT_ENTER, self.OnApplySqlStatement)

        # Simple tab layout
        simpleSqlSizer = wx.GridBagSizer(hgap=5, vgap=5)

        sqlSimpleWhereSizer = wx.BoxSizer(wx.HORIZONTAL)

        sqlSimpleWhereSizer.Add(
            sqlWhereColumn, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=3
        )
        sqlSimpleWhereSizer.Add(
            sqlWhereCond, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=3
        )
        sqlSimpleWhereSizer.Add(
            sqlWhereValue,
            proportion=1,
            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
            border=3,
        )
        whereSimpleSqlPanel.SetSizer(sqlSimpleWhereSizer)
        simpleSqlSizer.Add(
            sqlLabel,
            border=5,
            pos=(0, 0),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.LEFT,
        )
        simpleSqlSizer.Add(
            whereSimpleSqlPanel,
            border=5,
            pos=(0, 1),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.EXPAND,
        )
        simpleSqlSizer.Add(
            btnApply, border=5, pos=(0, 2), flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP
        )
        simpleSqlSizer.AddGrowableCol(1)

        simpleSqlPanel.SetSizer(simpleSqlSizer)

        # Advanced tab layout
        advancedSqlSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
        advancedSqlSizer.AddGrowableCol(0)

        advancedSqlSizer.Add(sqlStatement, flag=wx.EXPAND | wx.ALL, border=5)
        advancedSqlSizer.Add(
            btnSqlBuilder, flag=wx.ALIGN_RIGHT | wx.TOP | wx.RIGHT | wx.BOTTOM, border=5
        )

        sqlSizer.Add(sqlNtb, flag=wx.ALL | wx.EXPAND, border=3)

        advancedSqlPanel.SetSizer(advancedSqlSizer)

        pageSizer.Add(listSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)

        sqlQueryPanel.SetSizer(sqlSizer)

        pageSizer.Add(
            sqlQueryPanel,
            proportion=0,
            flag=wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.EXPAND,
            border=5,
        )

        panel.SetSizer(pageSizer)

        sqlNtb.Bind(wx.EVT_SIZE, self.OnSqlQuerySizeWrap(layer))

        self.layerPage[layer]["data"] = win.GetId()
        self.layerPage[layer]["sqlNtb"] = sqlNtb.GetId()
        self.layerPage[layer]["whereColumn"] = sqlWhereColumn.GetId()
        self.layerPage[layer]["whereOperator"] = sqlWhereCond.GetId()
        self.layerPage[layer]["where"] = sqlWhereValue.GetId()
        self.layerPage[layer]["builder"] = btnSqlBuilder.GetId()
        self.layerPage[layer]["statement"] = sqlStatement.GetId()
        # for SQL Query adaptation on width
        self.layerPage[layer]["sqlIsReduced"] = False

        return True

    def OnSqlQuerySizeWrap(self, layer):
        """Helper function"""
        return lambda event: self.OnSqlQuerySize(event, layer)

    def OnSqlQuerySize(self, event, layer):
        """Adapts SQL Query Simple tab on current width"""

        if layer not in self.layers:
            return

        sqlNtb = event.GetEventObject()
        if not self.sqlBestSize:
            self.sqlBestSize = sqlNtb.GetBestSize()

        size = sqlNtb.GetSize()
        sqlReduce = self.sqlBestSize[0] > size[0]
        if (sqlReduce and self.layerPage[layer]["sqlIsReduced"]) or (
            not sqlReduce and not self.layerPage[layer]["sqlIsReduced"]
        ):
            event.Skip()
            return

        wherePanel = sqlNtb.FindWindowByName("wherePanel")
        btnApply = sqlNtb.FindWindowByName("btnApply")
        sqlSimpleSizer = btnApply.GetContainingSizer()

        if sqlReduce:
            self.layerPage[layer]["sqlIsReduced"] = True
            if not sqlSimpleSizer.IsColGrowable(0):
                sqlSimpleSizer.AddGrowableCol(0)
            if sqlSimpleSizer.IsColGrowable(1):
                sqlSimpleSizer.RemoveGrowableCol(1)
            sqlSimpleSizer.SetItemPosition(wherePanel, (1, 0))
            sqlSimpleSizer.SetItemPosition(btnApply, (1, 1))
        else:
            self.layerPage[layer]["sqlIsReduced"] = False
            if not sqlSimpleSizer.IsColGrowable(1):
                sqlSimpleSizer.AddGrowableCol(1)
            if sqlSimpleSizer.IsColGrowable(0):
                sqlSimpleSizer.RemoveGrowableCol(0)
            sqlSimpleSizer.SetItemPosition(wherePanel, (0, 1))
            sqlSimpleSizer.SetItemPosition(btnApply, (0, 2))

        event.Skip()

    def OnDataItemActivated(self, event):
        """Item activated, highlight selected item"""
        self.OnDataDrawSelected(event)

        event.Skip()

    def OnDataRightUp(self, event):
        """Table description area, context menu"""
        if not hasattr(self, "popupDataID1"):
            self.popupDataID1 = NewId()
            self.popupDataID2 = NewId()
            self.popupDataID3 = NewId()
            self.popupDataID4 = NewId()
            self.popupDataID5 = NewId()
            self.popupDataID6 = NewId()
            self.popupDataID7 = NewId()
            self.popupDataID8 = NewId()
            self.popupDataID9 = NewId()
            self.popupDataID10 = NewId()
            self.popupDataID11 = NewId()

            self.Bind(wx.EVT_MENU, self.OnDataItemEdit, id=self.popupDataID1)
            self.Bind(wx.EVT_MENU, self.OnDataItemAdd, id=self.popupDataID2)
            self.Bind(wx.EVT_MENU, self.OnDataItemDelete, id=self.popupDataID3)
            self.Bind(wx.EVT_MENU, self.OnDataItemDeleteAll, id=self.popupDataID4)
            self.Bind(wx.EVT_MENU, self.OnDataSelectAll, id=self.popupDataID5)
            self.Bind(wx.EVT_MENU, self.OnDataSelectNone, id=self.popupDataID6)
            self.Bind(wx.EVT_MENU, self.OnDataDrawSelected, id=self.popupDataID7)
            self.Bind(wx.EVT_MENU, self.OnDataDrawSelectedZoom, id=self.popupDataID8)
            self.Bind(wx.EVT_MENU, self.OnExtractSelected, id=self.popupDataID9)
            self.Bind(wx.EVT_MENU, self.OnDeleteSelected, id=self.popupDataID11)
            self.Bind(wx.EVT_MENU, self.OnDataReload, id=self.popupDataID10)

        tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        # generate popup-menu
        menu = Menu()
        menu.Append(self.popupDataID1, _("Edit selected record"))
        selected = tlist.GetFirstSelected()
        if (
            not self.dbMgrData["editable"]
            or selected == -1
            or tlist.GetNextSelected(selected) != -1
        ):
            menu.Enable(self.popupDataID1, False)
        menu.Append(self.popupDataID2, _("Insert new record"))
        menu.Append(self.popupDataID3, _("Delete selected record(s)"))
        menu.Append(self.popupDataID4, _("Delete all records"))
        if not self.dbMgrData["editable"]:
            menu.Enable(self.popupDataID2, False)
            menu.Enable(self.popupDataID3, False)
            menu.Enable(self.popupDataID4, False)
        menu.AppendSeparator()
        menu.Append(self.popupDataID5, _("Select all"))
        menu.Append(self.popupDataID6, _("Deselect all"))
        menu.AppendSeparator()
        menu.Append(self.popupDataID7, _("Highlight selected features"))
        menu.Append(self.popupDataID8, _("Highlight selected features and zoom"))
        if not self.map or len(tlist.GetSelectedItems()) == 0:
            menu.Enable(self.popupDataID7, False)
            menu.Enable(self.popupDataID8, False)
        menu.Append(self.popupDataID9, _("Extract selected features"))
        menu.Append(self.popupDataID11, _("Delete selected features"))
        if not self.dbMgrData["editable"]:
            menu.Enable(self.popupDataID11, False)
        if tlist.GetFirstSelected() == -1:
            menu.Enable(self.popupDataID3, False)
            menu.Enable(self.popupDataID9, False)
            menu.Enable(self.popupDataID11, False)
        menu.AppendSeparator()
        menu.Append(self.popupDataID10, _("Reload"))

        self.PopupMenu(menu)
        menu.Destroy()

        # update statusbar
        self.log.write(_("Number of loaded records: %d") % tlist.GetItemCount())

    def OnDataItemEdit(self, event):
        """Edit selected record of the attribute table"""
        tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        item = tlist.GetFirstSelected()
        if item == -1:
            return
        table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
        keyColumn = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["key"]
        cat = tlist.itemCatsMap[tlist.itemIndexMap[item]]

        # (column name, value)
        data = []

        # collect names of all visible columns
        columnName = []
        for i in range(tlist.GetColumnCount()):
            columnName.append(tlist.GetColumn(i).GetText())

        # key column must be always presented
        if keyColumn not in columnName:
            # insert key column on first position
            columnName.insert(0, keyColumn)
            data.append((keyColumn, str(cat)))
            keyId = 0
            missingKey = True
        else:
            missingKey = False

        # add other visible columns
        for i in range(len(columnName)):
            ctype = self.dbMgrData["mapDBInfo"].tables[table][columnName[i]]["ctype"]
            ctypeStr = self.dbMgrData["mapDBInfo"].tables[table][columnName[i]]["type"]
            if columnName[i] == keyColumn:  # key
                if missingKey is False:
                    data.append((columnName[i], ctype, ctypeStr, str(cat)))
                    keyId = i
            else:
                if missingKey is True:
                    value = tlist.GetItem(item, i - 1).GetText()
                else:
                    value = tlist.GetItem(item, i).GetText()
                data.append((columnName[i], ctype, ctypeStr, value))

        dlg = ModifyTableRecord(
            parent=self,
            title=_("Update existing record"),
            data=data,
            keyEditable=(keyId, False),
        )

        if dlg.ShowModal() == wx.ID_OK:
            values = dlg.GetValues()  # string
            updateList = list()
            try:
                for i in range(len(values)):
                    if i == keyId:  # skip key column
                        continue
                    if tlist.GetItem(item, i).GetText() == values[i]:
                        continue  # no change

                    column = tlist.columns[columnName[i]]
                    if len(values[i]) > 0:
                        try:
                            if missingKey is True:
                                idx = i - 1
                            else:
                                idx = i

                            if column["ctype"] != str:
                                tlist.itemDataMap[item][idx] = column["ctype"](
                                    values[i]
                                )
                            else:  # -> string
                                tlist.itemDataMap[item][idx] = values[i]
                        except ValueError:
                            raise ValueError(
                                _("Value '%(value)s' needs to be entered as %(type)s.")
                                % {"value": str(values[i]), "type": column["type"]}
                            )

                        if column["ctype"] == str:
                            if "'" in values[i]:  # replace "'" -> "''"
                                values[i] = values[i].replace("'", "''")
                            updateList.append("%s='%s'" % (columnName[i], values[i]))
                        else:
                            updateList.append("%s=%s" % (columnName[i], values[i]))
                    else:  # -> NULL
                        updateList.append("%s=NULL" % (columnName[i]))
            except ValueError as err:
                GError(
                    parent=self,
                    message=_("Unable to update existing record.\n%s") % err,
                    showTraceback=False,
                )
                self.OnDataItemEdit(event)
                return

            if updateList:
                self.listOfSQLStatements.append(
                    "UPDATE %s SET %s WHERE %s=%d"
                    % (table, ",".join(updateList), keyColumn, cat)
                )
                self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)

            tlist.Update()

    def OnDataItemAdd(self, event):
        """Add new record to the attribute table"""
        tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
        keyColumn = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["key"]

        # (column name, value)
        data = []

        # collect names of all visible columns
        columnName = []
        for i in range(tlist.GetColumnCount()):
            columnName.append(tlist.GetColumn(i).GetText())

        # maximal category number
        if len(tlist.itemCatsMap.values()) > 0:
            maxCat = max(tlist.itemCatsMap.values())
        else:
            maxCat = 0  # starting category '1'

        # key column must be always presented
        if keyColumn not in columnName:
            # insert key column on first position
            columnName.insert(0, keyColumn)
            data.append((keyColumn, str(maxCat + 1)))
            missingKey = True
        else:
            missingKey = False

        # add other visible columns
        colIdx = 0
        keyId = -1
        for col in columnName:
            ctype = self.dbMgrData["mapDBInfo"].tables[table][col]["ctype"]
            ctypeStr = self.dbMgrData["mapDBInfo"].tables[table][col]["type"]
            if col == keyColumn:  # key
                if missingKey is False:
                    data.append((col, ctype, ctypeStr, str(maxCat + 1)))
                    keyId = colIdx
            else:
                data.append((col, ctype, ctypeStr, ""))

            colIdx += 1

        dlg = ModifyTableRecord(
            parent=self,
            title=_("Insert new record"),
            data=data,
            keyEditable=(keyId, True),
        )

        if dlg.ShowModal() == wx.ID_OK:
            try:  # get category number
                cat = int(dlg.GetValues(columns=[keyColumn])[0])
            except:
                cat = -1

            try:
                if cat in tlist.itemCatsMap.values():
                    raise ValueError(
                        _(
                            "Record with category number %d "
                            "already exists in the table."
                        )
                        % cat
                    )

                values = dlg.GetValues()  # values (need to be casted)
                columnsString = ""
                valuesString = ""

                for i in range(len(values)):
                    if len(values[i]) == 0:  # NULL
                        if columnName[i] == keyColumn:
                            raise ValueError(
                                _("Category number (column %s)" " is missing.")
                                % keyColumn
                            )
                        else:
                            continue

                    try:
                        if tlist.columns[columnName[i]]["ctype"] == int:
                            # values[i] is stored as text.
                            values[i] = int(float(values[i]))
                        elif tlist.columns[columnName[i]]["ctype"] == float:
                            values[i] = float(values[i])
                    except:
                        raise ValueError(
                            _("Value '%(value)s' needs to be entered as %(type)s.")
                            % {
                                "value": values[i],
                                "type": tlist.columns[columnName[i]]["type"],
                            }
                        )
                    columnsString += "%s," % columnName[i]

                    if tlist.columns[columnName[i]]["ctype"] == str:
                        valuesString += "'%s'," % values[i].replace("'", "''")
                    else:
                        valuesString += "%s," % values[i]

            except ValueError as err:
                GError(
                    parent=self,
                    message=_("Unable to insert new record.\n%s") % err,
                    showTraceback=False,
                )
                self.OnDataItemAdd(event)
                return

            # remove category if need
            if missingKey is True:
                del values[0]

            # add new item to the tlist
            if len(tlist.itemIndexMap) > 0:
                index = max(tlist.itemIndexMap) + 1
            else:
                index = 0

            tlist.itemIndexMap.append(index)
            tlist.itemDataMap[index] = values
            tlist.itemCatsMap[index] = cat
            tlist.SetItemCount(tlist.GetItemCount() + 1)

            self.listOfSQLStatements.append(
                "INSERT INTO %s (%s) VALUES(%s)"
                % (table, columnsString.rstrip(","), valuesString.rstrip(","))
            )

            self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)

    def OnDataItemDelete(self, event):
        """Delete selected item(s) from the tlist (layer/category pair)"""
        dlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        item = dlist.GetFirstSelected()

        table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
        key = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["key"]

        indices = []
        # collect SQL statements
        while item != -1:
            index = dlist.itemIndexMap[item]
            indices.append(index)

            cat = dlist.itemCatsMap[index]

            self.listOfSQLStatements.append(
                "DELETE FROM %s WHERE %s=%d" % (table, key, cat)
            )

            item = dlist.GetNextSelected(item)

        if UserSettings.Get(group="atm", key="askOnDeleteRec", subkey="enabled"):
            deleteDialog = wx.MessageBox(
                parent=self,
                message=_(
                    "Selected data records (%d) will be permanently deleted "
                    "from table. Do you want to delete them?"
                )
                % (len(self.listOfSQLStatements)),
                caption=_("Delete records"),
                style=wx.YES_NO | wx.CENTRE,
            )
            if deleteDialog != wx.YES:
                self.listOfSQLStatements = []
                return False

        # restore maps
        i = 0
        indexTemp = copy.copy(dlist.itemIndexMap)
        dlist.itemIndexMap = []
        dataTemp = copy.deepcopy(dlist.itemDataMap)
        dlist.itemDataMap = {}
        catsTemp = copy.deepcopy(dlist.itemCatsMap)
        dlist.itemCatsMap = {}

        i = 0
        for index in indexTemp:
            if index in indices:
                continue
            dlist.itemIndexMap.append(i)
            dlist.itemDataMap[i] = dataTemp[index]
            dlist.itemCatsMap[i] = catsTemp[index]

            i += 1

        dlist.SetItemCount(len(dlist.itemIndexMap))

        # deselect items
        item = dlist.GetFirstSelected()
        while item != -1:
            dlist.SetItemState(item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
            item = dlist.GetNextSelected(item)

        # submit SQL statements
        self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)

        return True

    def OnDataItemDeleteAll(self, event):
        """Delete all items from the list"""
        dlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        if UserSettings.Get(group="atm", key="askOnDeleteRec", subkey="enabled"):
            deleteDialog = wx.MessageBox(
                parent=self,
                message=_(
                    "All data records (%d) will be permanently deleted "
                    "from table. Do you want to delete them?"
                )
                % (len(dlist.itemIndexMap)),
                caption=_("Delete records"),
                style=wx.YES_NO | wx.CENTRE,
            )
            if deleteDialog != wx.YES:
                return

        dlist.DeleteAllItems()
        dlist.itemDataMap = {}
        dlist.itemIndexMap = []
        dlist.SetItemCount(0)

        table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
        self.listOfSQLStatements.append("DELETE FROM %s" % table)

        self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)

        event.Skip()

    def _drawSelected(self, zoom, selectedOnly=True):
        """Highlight selected features"""
        if not self.map or not self.mapdisplay:
            return

        tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        if selectedOnly:
            fn = tlist.GetSelectedItems
        else:
            fn = tlist.GetItems

        cats = list(map(int, fn()))

        digitToolbar = None
        if "vdigit" in self.mapdisplay.toolbars:
            digitToolbar = self.mapdisplay.toolbars["vdigit"]
        if (
            digitToolbar
            and digitToolbar.GetLayer()
            and digitToolbar.GetLayer().GetName() == self.dbMgrData["vectName"]
        ):
            display = self.mapdisplay.GetMapWindow().GetDisplay()
            display.SetSelected(cats, layer=self.selLayer)
            if zoom:
                n, s, w, e = display.GetRegionSelected()
                self.mapdisplay.Map.GetRegion(n=n, s=s, w=w, e=e, update=True)
        else:
            # add map layer with highlighted vector features
            self.AddQueryMapLayer(selectedOnly)  # -> self.qlayer

            # set opacity based on queried layer
            if self.parent and self.mapdisplay.tree and self.dbMgrData["treeItem"]:
                maptree = self.mapdisplay.tree  # TODO: giface
                opacity = maptree.GetLayerInfo(
                    self.dbMgrData["treeItem"], key="maplayer"
                ).GetOpacity()
                self.qlayer.SetOpacity(opacity)
            if zoom:
                keyColumn = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["key"]
                where = ""
                for range in ListOfCatsToRange(cats).split(","):
                    if "-" in range:
                        min, max = range.split("-")
                        where += "%s >= %d and %s <= %d or " % (
                            keyColumn,
                            int(min),
                            keyColumn,
                            int(max),
                        )
                    else:
                        where += "%s = %d or " % (keyColumn, int(range))
                where = where.rstrip("or ")

                select = RunCommand(
                    "v.db.select",
                    parent=self,
                    read=True,
                    quiet=True,
                    flags="r",
                    map=self.dbMgrData["mapDBInfo"].map,
                    layer=int(self.selLayer),
                    where=where,
                )

                region = {}
                for line in select.splitlines():
                    key, value = line.split("=")
                    region[key.strip()] = float(value.strip())

                nsdist = ewdist = 0
                renderer = self.mapdisplay.GetMap()
                nsdist = 10 * (
                    (
                        renderer.GetCurrentRegion()["n"]
                        - renderer.GetCurrentRegion()["s"]
                    )
                    / renderer.height
                )
                ewdist = 10 * (
                    (
                        renderer.GetCurrentRegion()["e"]
                        - renderer.GetCurrentRegion()["w"]
                    )
                    / renderer.width
                )
                north = region["n"] + nsdist
                south = region["s"] - nsdist
                west = region["w"] - ewdist
                east = region["e"] + ewdist
                renderer.GetRegion(n=north, s=south, w=west, e=east, update=True)
                self.mapdisplay.GetMapWindow().ZoomHistory(
                    n=north, s=south, w=west, e=east
                )

        if zoom:
            self.mapdisplay.Map.AdjustRegion()  # adjust resolution
            self.mapdisplay.Map.AlignExtentFromDisplay()  # adjust extent
            self.mapdisplay.MapWindow.UpdateMap(render=True, renderVector=True)
        else:
            self.mapdisplay.MapWindow.UpdateMap(render=False, renderVector=True)

    def AddQueryMapLayer(self, selectedOnly=True):
        """Redraw a map

        :return: True if map has been redrawn, False if no map is given
        """
        tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        if selectedOnly:
            fn = tlist.GetSelectedItems
        else:
            fn = tlist.GetItems

        cats = {self.selLayer: fn()}

        if self.mapdisplay.Map.GetLayerIndex(self.qlayer) < 0:
            self.qlayer = None

        if self.qlayer:
            self.qlayer.SetCmd(
                self.mapdisplay.AddTmpVectorMapLayer(
                    self.dbMgrData["vectName"], cats, addLayer=False
                )
            )
        else:
            self.qlayer = self.mapdisplay.AddTmpVectorMapLayer(
                self.dbMgrData["vectName"], cats
            )

        return self.qlayer

    def OnDataReload(self, event):
        """Reload tlist of records"""
        self.OnApplySqlStatement(None)
        self.listOfSQLStatements = []

    def OnDataSelectAll(self, event):
        """Select all items"""
        tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        item = -1

        while True:
            item = tlist.GetNextItem(item)
            if item == -1:
                break
            tlist.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)

        event.Skip()

    def OnDataSelectNone(self, event):
        """Deselect items"""
        tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        item = -1

        while True:
            item = tlist.GetNextItem(item, wx.LIST_STATE_SELECTED)
            if item == -1:
                break
            tlist.SetItemState(item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
        tlist.Focus(0)

        event.Skip()

    def OnDataDrawSelected(self, event):
        """Reload table description"""
        self._drawSelected(zoom=False)
        event.Skip()

    def OnDataDrawSelectedZoom(self, event):
        self._drawSelected(zoom=True)
        event.Skip()

    def OnExtractSelected(self, event):
        """Extract vector objects selected in attribute browse window
        to new vector map
        """
        tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        # cats = tlist.selectedCats[:]
        cats = tlist.GetSelectedItems()
        if len(cats) == 0:
            GMessage(parent=self, message=_("Nothing to extract."))
            return
        else:
            # dialog to get file name
            dlg = CreateNewVector(
                parent=self,
                title=_("Extract selected features"),
                giface=self.giface,
                cmd=(
                    (
                        "v.extract",
                        {
                            "input": self.dbMgrData["vectName"],
                            "cats": ListOfCatsToRange(cats),
                        },
                        "output",
                    )
                ),
                disableTable=True,
            )
            if not dlg:
                return

            name = dlg.GetName(full=True)

            if not self.mapdisplay and self.mapdisplay.tree:
                pass
            elif name and dlg.IsChecked("add"):
                # add layer to map layer tree
                self.mapdisplay.tree.AddLayer(
                    ltype="vector", lname=name, lcmd=["d.vect", "map=%s" % name]
                )
            dlg.Destroy()

    def OnDeleteSelected(self, event):
        """Delete vector objects selected in attribute browse window
        (attributes and geometry)
        """
        tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        cats = tlist.GetSelectedItems()
        if len(cats) == 0:
            GMessage(parent=self, message=_("Nothing to delete."))

            return

        display = None
        if not self.mapdisplay:
            pass
        elif "vdigit" in self.mapdisplay.toolbars:
            digitToolbar = self.mapdisplay.toolbars["vdigit"]
            if (
                digitToolbar
                and digitToolbar.GetLayer()
                and digitToolbar.GetLayer().GetName() == self.dbMgrData["vectName"]
            ):
                display = self.mapdisplay.GetMapWindow().GetDisplay()
                display.SetSelected(list(map(int, cats)), layer=self.selLayer)
                self.mapdisplay.MapWindow.UpdateMap(render=True, renderVector=True)

        if self.OnDataItemDelete(None) and self.mapdisplay:
            if display:
                self.mapdisplay.GetMapWindow().digit.DeleteSelectedLines()
            else:
                RunCommand(
                    "v.edit",
                    parent=self,
                    quiet=True,
                    map=self.dbMgrData["vectName"],
                    tool="delete",
                    cats=ListOfCatsToRange(cats),
                )

            self.mapdisplay.MapWindow.UpdateMap(render=True, renderVector=True)

    def OnApplySqlStatement(self, event):
        """Apply simple/advanced sql statement"""
        if not self.layerPage:
            return
        keyColumn = -1  # index of key column
        listWin = self.FindWindowById(self.layerPage[self.selLayer]["data"])
        sql = None
        win = self.FindWindowById(self.layerPage[self.selLayer]["sqlNtb"])
        if not win:
            return

        showSelected = False
        wx.BeginBusyCursor()
        if win.GetSelection() == 0:
            # simple sql statement
            whereCol = self.FindWindowById(
                self.layerPage[self.selLayer]["whereColumn"]
            ).GetStringSelection()
            whereOpe = self.FindWindowById(
                self.layerPage[self.selLayer]["whereOperator"]
            ).GetStringSelection()
            whereWin = self.FindWindowById(self.layerPage[self.selLayer]["where"])
            whereVal = whereWin.GetValue().strip()
            table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
            if self.dbMgrData["mapDBInfo"].tables[table][whereCol]["ctype"] == str:
                # string attribute, check for quotes
                whereVal = whereVal.replace('"', "'")
                if whereVal:
                    if not whereVal.startswith("'"):
                        whereVal = "'" + whereVal
                    if not whereVal.endswith("'"):
                        whereVal += "'"
                    whereWin.SetValue(whereVal)

            try:
                if len(whereVal) > 0:
                    showSelected = True
                    # Enclose column name with SQL standard double quotes
                    keyColumn = listWin.LoadData(
                        self.selLayer, where=f'"{whereCol}"' + whereOpe + whereVal
                    )
                else:
                    keyColumn = listWin.LoadData(self.selLayer)
            except GException as e:
                GError(
                    parent=self,
                    message=_("Loading attribute data failed.\n\n%s") % e.value,
                )
                self.FindWindowById(self.layerPage[self.selLayer]["where"]).SetValue("")
        else:
            # advanced sql statement
            win = self.FindWindowById(self.layerPage[self.selLayer]["statement"])
            try:
                cols, where = self.ValidateSelectStatement(win.GetValue())
                if cols is None and where is None:
                    sql = win.GetValue()
                if where:
                    showSelected = True
            except TypeError:
                GError(
                    parent=self,
                    message=_(
                        "Loading attribute data failed.\n"
                        "Invalid SQL select statement.\n\n%s"
                    )
                    % win.GetValue(),
                )
                win.SetValue(
                    "SELECT * FROM %s"
                    % self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
                )
                cols = None
                where = None

            if cols or where or sql:
                try:
                    keyColumn = listWin.LoadData(
                        self.selLayer, columns=cols, where=where, sql=sql
                    )
                except GException as e:
                    GError(
                        parent=self,
                        message=_("Loading attribute data failed.\n\n%s") % e.value,
                    )
                    win.SetValue(
                        "SELECT * FROM %s"
                        % self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
                    )

        # sort by key column
        if sql and "order by" in sql.lower():
            pass  # don't order by key column
        else:
            if keyColumn > -1:
                listWin.SortListItems(col=keyColumn, ascending=True)
            else:
                listWin.SortListItems(col=0, ascending=True)

        wx.EndBusyCursor()

        # update statusbar
        self.log.write(
            _("Number of loaded records: %d")
            % self.FindWindowById(self.layerPage[self.selLayer]["data"]).GetItemCount()
        )

        # update map display if needed
        if self.mapdisplay and UserSettings.Get(
            group="atm", key="highlight", subkey="auto"
        ):
            # TODO: replace by signals
            if showSelected:
                self._drawSelected(zoom=False, selectedOnly=False)
            else:
                self.mapdisplay.RemoveQueryLayer()
                self.mapdisplay.MapWindow.UpdateMap(
                    render=False
                )  # TODO: replace by signals

    def OnBuilder(self, event):
        """SQL Builder button pressed -> show the SQLBuilder dialog"""
        if not self.builder:
            self.builder = SQLBuilderSelect(
                parent=self,
                id=wx.ID_ANY,
                vectmap=self.dbMgrData["vectName"],
                layer=self.selLayer,
                evtHandler=self.OnBuilderEvt,
            )
            self.builder.Show()
        else:
            self.builder.Raise()

    def OnBuilderEvt(self, event):
        if event == "apply":
            sqlstr = self.builder.GetSQLStatement()
            self.FindWindowById(self.layerPage[self.selLayer]["statement"]).SetValue(
                sqlstr
            )
            # apply query
            # self.listOfSQLStatements.append(sqlstr) #TODO probably it was bug
            self.OnApplySqlStatement(None)
            # close builder on apply
            if self.builder.CloseOnApply():
                self.builder = None
        elif event == "close":
            self.builder = None

    def ValidateSelectStatement(self, statement):
        """Validate SQL select statement

        :return: (columns, where)
        :return: None on error
        """
        if statement[0:7].lower() != "select ":
            return None

        cols = ""
        index = 7
        for c in statement[index:]:
            if c == " ":
                break
            cols += c
            index += 1
        if cols == "*":
            cols = None
        else:
            cols = cols.split(",")

        tablelen = len(self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"])

        if statement[index + 1 : index + 6].lower() != "from " or statement[
            index + 6 : index + 6 + tablelen
        ] != "%s" % (self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]):
            return None

        if len(statement[index + 7 + tablelen :]) > 0:
            index = statement.lower().find("where ")
            if index > -1:
                where = statement[index + 6 :]
            else:
                where = None
        else:
            where = None

        return (cols, where)

    def LoadData(self, layer, columns=None, where=None, sql=None):
        """Load data into list

        :param int layer: layer number
        :param list columns: list of columns for output
        :param str where: where statement
        :param str sql: full sql statement

        :return: id of key column
        :return: -1 if key column is not displayed
        """
        listWin = self.FindWindowById(self.layerPage[layer]["data"])
        return listWin.LoadData(layer, columns, where, sql)

    def UpdatePage(self, layer):
        # update data tlist
        if layer in self.layerPage.keys():
            tlist = self.FindWindowById(self.layerPage[layer]["data"])
            tlist.Update(self.dbMgrData["mapDBInfo"])

    def ResetPage(self, layer=None):
        if not layer:
            layer = self.selLayer
        if layer not in self.layerPage.keys():
            return
        win = self.FindWindowById(self.layerPage[self.selLayer]["sqlNtb"])
        if win.GetSelection() == 0:
            self.FindWindowById(self.layerPage[layer]["whereColumn"]).SetSelection(0)
            self.FindWindowById(self.layerPage[layer]["whereOperator"]).SetSelection(0)
            self.FindWindowById(self.layerPage[layer]["where"]).SetValue("")
        else:
            sqlWin = self.FindWindowById(self.layerPage[self.selLayer]["statement"])
            sqlWin.SetValue(
                "SELECT * FROM %s" % self.dbMgrData["mapDBInfo"].layers[layer]["table"]
            )

        self.UpdatePage(layer)


class DbMgrTablesPage(DbMgrNotebookBase):
    def __init__(self, parent, parentDbMgrBase, onlyLayer=-1):
        """Page for managing tables

        :param parent: GUI parent
        :param parentDbMgrBase: instance of DbMgrBase class
        :param onlyLayer: create only tab of given layer, if -1
                          creates tabs of all layers
        """

        DbMgrNotebookBase.__init__(self, parent=parent, parentDbMgrBase=parentDbMgrBase)

        for layer in self.dbMgrData["mapDBInfo"].layers.keys():
            if onlyLayer > 0 and layer != onlyLayer:
                continue
            self.AddLayer(layer)

        if self.layers:
            self.SetSelection(0)  # select first layer
            self.selLayer = self.layers[0]

    def AddLayer(self, layer, pos=-1):
        """Adds tab which represents table

        :param layer: vector map layer connected to table
        :param pos: position of tab, if -1 it is added to end

        :return: True if layer was added
        :return: False if layer was not added - layer has been already added or does
                 not exist
        """
        if layer in self.layers or layer not in self.parentDbMgrBase.GetVectorLayers():
            return False

        self.layers.append(layer)

        self.layerPage[layer] = {}
        panel = wx.Panel(parent=self, id=wx.ID_ANY)
        self.layerPage[layer]["tablePage"] = panel.GetId()
        label = _("Table")
        if not self.dbMgrData["editable"]:
            label += _(" (read-only)")

        if pos == -1:
            pos = self.GetPageCount()
        self.InsertNBPage(
            index=pos,
            page=panel,
            text=" %d / %s %s"
            % (layer, label, self.dbMgrData["mapDBInfo"].layers[layer]["table"]),
        )

        pageSizer = wx.BoxSizer(wx.VERTICAL)

        #
        # dbInfo
        #
        dbBox = StaticBox(
            parent=panel, id=wx.ID_ANY, label=" %s " % _("Database connection")
        )
        dbSizer = wx.StaticBoxSizer(dbBox, wx.VERTICAL)
        dbSizer.Add(
            CreateDbInfoDesc(panel, self.dbMgrData["mapDBInfo"], layer),
            proportion=1,
            flag=wx.EXPAND | wx.ALL,
            border=3,
        )

        #
        # table description
        #
        table = self.dbMgrData["mapDBInfo"].layers[layer]["table"]
        tableBox = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " % _("Table <%s> - right-click to delete column(s)") % table,
        )

        tableSizer = wx.StaticBoxSizer(tableBox, wx.VERTICAL)

        tlist = self._createTableDesc(panel, table)
        tlist.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnTableRightUp)  # wxMSW
        tlist.Bind(wx.EVT_RIGHT_UP, self.OnTableRightUp)  # wxGTK
        self.layerPage[layer]["tableData"] = tlist.GetId()

        # manage columns (add)
        addBox = StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % _("Add column"))
        addSizer = wx.StaticBoxSizer(addBox, wx.HORIZONTAL)

        column = TextCtrl(
            parent=panel,
            id=wx.ID_ANY,
            value="",
            size=(150, -1),
            style=wx.TE_PROCESS_ENTER,
        )
        column.Bind(wx.EVT_TEXT, self.OnTableAddColumnName)
        column.Bind(wx.EVT_TEXT_ENTER, self.OnTableItemAdd)
        self.layerPage[layer]["addColName"] = column.GetId()
        addSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Column")),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
            border=5,
        )
        addSizer.Add(
            column,
            proportion=1,
            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
            border=5,
        )

        ctype = wx.Choice(
            parent=panel, id=wx.ID_ANY, choices=["integer", "double", "varchar", "date"]
        )  # FIXME
        ctype.SetSelection(0)
        ctype.Bind(wx.EVT_CHOICE, self.OnTableChangeType)
        self.layerPage[layer]["addColType"] = ctype.GetId()
        addSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Type")),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
            border=5,
        )
        addSizer.Add(
            ctype, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=5
        )

        length = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(65, -1), initial=250, min=1, max=1e6
        )
        length.Enable(False)
        self.layerPage[layer]["addColLength"] = length.GetId()
        addSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Length")),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
            border=5,
        )
        addSizer.Add(
            length, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=5
        )

        btnAddCol = Button(parent=panel, id=wx.ID_ANY, label=_("Add"))
        btnAddCol.Bind(wx.EVT_BUTTON, self.OnTableItemAdd)
        btnAddCol.Enable(False)
        self.layerPage[layer]["addColButton"] = btnAddCol.GetId()
        addSizer.Add(btnAddCol, flag=wx.ALL | wx.EXPAND, border=3)

        # manage columns (rename)
        renameBox = StaticBox(
            parent=panel, id=wx.ID_ANY, label=" %s " % _("Rename column")
        )
        renameSizer = wx.StaticBoxSizer(renameBox, wx.HORIZONTAL)

        columnFrom = ComboBox(
            parent=panel,
            id=wx.ID_ANY,
            size=(150, -1),
            style=wx.CB_READONLY,
            choices=self.dbMgrData["mapDBInfo"].GetColumns(table),
        )
        columnFrom.SetSelection(0)
        self.layerPage[layer]["renameCol"] = columnFrom.GetId()
        renameSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Column")),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
            border=5,
        )
        renameSizer.Add(
            columnFrom,
            proportion=1,
            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
            border=5,
        )

        columnTo = TextCtrl(
            parent=panel,
            id=wx.ID_ANY,
            value="",
            size=(150, -1),
            style=wx.TE_PROCESS_ENTER,
        )
        columnTo.Bind(wx.EVT_TEXT, self.OnTableRenameColumnName)
        columnTo.Bind(wx.EVT_TEXT_ENTER, self.OnTableItemChange)
        self.layerPage[layer]["renameColTo"] = columnTo.GetId()
        renameSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("To")),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
            border=5,
        )
        renameSizer.Add(
            columnTo,
            proportion=1,
            flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
            border=5,
        )

        btnRenameCol = Button(parent=panel, id=wx.ID_ANY, label=_("&Rename"))
        btnRenameCol.Bind(wx.EVT_BUTTON, self.OnTableItemChange)
        btnRenameCol.Enable(False)
        self.layerPage[layer]["renameColButton"] = btnRenameCol.GetId()
        renameSizer.Add(btnRenameCol, flag=wx.ALL | wx.EXPAND, border=3)

        tableSizer.Add(tlist, flag=wx.ALL | wx.EXPAND, proportion=1, border=3)

        pageSizer.Add(dbSizer, flag=wx.ALL | wx.EXPAND, proportion=0, border=3)

        pageSizer.Add(
            tableSizer,
            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
            proportion=1,
            border=3,
        )

        pageSizer.Add(
            addSizer,
            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
            proportion=0,
            border=3,
        )
        pageSizer.Add(
            renameSizer,
            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
            proportion=0,
            border=3,
        )

        panel.SetSizer(pageSizer)

        if not self.dbMgrData["editable"]:
            for widget in [
                columnTo,
                columnFrom,
                length,
                ctype,
                column,
                btnAddCol,
                btnRenameCol,
            ]:
                widget.Enable(False)

        return True

    def _createTableDesc(self, parent, table):
        """Create list with table description"""
        tlist = TableListCtrl(
            parent=parent,
            id=wx.ID_ANY,
            table=self.dbMgrData["mapDBInfo"].tables[table],
            columns=self.dbMgrData["mapDBInfo"].GetColumns(table),
        )
        tlist.Populate()
        # sorter
        # itemDataMap = list.Populate()
        # listmix.ColumnSorterMixin.__init__(self, 2)

        return tlist

    def OnTableChangeType(self, event):
        """Data type for new column changed. Enable or disable
        data length widget"""
        win = self.FindWindowById(self.layerPage[self.selLayer]["addColLength"])
        if event.GetString() == "varchar":
            win.Enable(True)
        else:
            win.Enable(False)

    def OnTableRenameColumnName(self, event):
        """Editing column name to be added to the table"""
        btn = self.FindWindowById(self.layerPage[self.selLayer]["renameColButton"])
        col = self.FindWindowById(self.layerPage[self.selLayer]["renameCol"])
        colTo = self.FindWindowById(self.layerPage[self.selLayer]["renameColTo"])
        if len(col.GetValue()) > 0 and len(colTo.GetValue()) > 0:
            btn.Enable(True)
        else:
            btn.Enable(False)

        event.Skip()

    def OnTableAddColumnName(self, event):
        """Editing column name to be added to the table"""
        btn = self.FindWindowById(self.layerPage[self.selLayer]["addColButton"])
        if len(event.GetString()) > 0:
            btn.Enable(True)
        else:
            btn.Enable(False)

        event.Skip()

    def OnTableItemChange(self, event):
        """Rename column in the table"""
        tlist = self.FindWindowById(self.layerPage[self.selLayer]["tableData"])
        name = self.FindWindowById(
            self.layerPage[self.selLayer]["renameCol"]
        ).GetValue()
        nameTo = self.FindWindowById(
            self.layerPage[self.selLayer]["renameColTo"]
        ).GetValue()

        table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]

        if not name or not nameTo:
            GError(
                parent=self,
                message=_("Unable to rename column. " "No column name defined."),
            )
            return
        else:
            item = tlist.FindItem(start=-1, str=name)
            if item > -1:
                if tlist.FindItem(start=-1, str=nameTo) > -1:
                    GError(
                        parent=self,
                        message=_(
                            "Unable to rename column <%(column)s> to "
                            "<%(columnTo)s>. Column already exists "
                            "in the table <%(table)s>."
                        )
                        % {"column": name, "columnTo": nameTo, "table": table},
                    )
                    return
                else:
                    tlist.SetItemText(item, nameTo)

                    self.listOfCommands.append(
                        (
                            "v.db.renamecolumn",
                            {
                                "map": self.dbMgrData["vectName"],
                                "layer": self.selLayer,
                                "column": "%s,%s" % (name, nameTo),
                            },
                        )
                    )
            else:
                GError(
                    parent=self,
                    message=_(
                        "Unable to rename column. "
                        "Column <%(column)s> doesn't exist in the table <%(table)s>."
                    )
                    % {"column": name, "table": table},
                )
                return

        # apply changes
        self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)

        # update widgets
        self.FindWindowById(self.layerPage[self.selLayer]["renameCol"]).SetItems(
            self.dbMgrData["mapDBInfo"].GetColumns(table)
        )
        self.FindWindowById(self.layerPage[self.selLayer]["renameCol"]).SetSelection(0)
        self.FindWindowById(self.layerPage[self.selLayer]["renameColTo"]).SetValue("")
        self._updateTableColumnWidgetChoices(table=table)

        event.Skip()

    def OnTableRightUp(self, event):
        """Table description area, context menu"""
        if not hasattr(self, "popupTableID"):
            self.popupTableID1 = NewId()
            self.popupTableID2 = NewId()
            self.popupTableID3 = NewId()
            self.Bind(wx.EVT_MENU, self.OnTableItemDelete, id=self.popupTableID1)
            self.Bind(wx.EVT_MENU, self.OnTableItemDeleteAll, id=self.popupTableID2)
            self.Bind(wx.EVT_MENU, self.OnTableReload, id=self.popupTableID3)

        # generate popup-menu
        menu = Menu()
        menu.Append(self.popupTableID1, _("Drop selected column"))
        if (
            self.FindWindowById(
                self.layerPage[self.selLayer]["tableData"]
            ).GetFirstSelected()
            == -1
        ):
            menu.Enable(self.popupTableID1, False)
        menu.Append(self.popupTableID2, _("Drop all columns"))
        menu.AppendSeparator()
        menu.Append(self.popupTableID3, _("Reload"))

        if not self.dbMgrData["editable"]:
            menu.Enable(self.popupTableID1, False)
            menu.Enable(self.popupTableID2, False)

        self.PopupMenu(menu)
        menu.Destroy()

    def OnTableItemDelete(self, event):
        """Delete selected item(s) from the list"""
        tlist = self.FindWindowById(self.layerPage[self.selLayer]["tableData"])

        item = tlist.GetFirstSelected()
        countSelected = tlist.GetSelectedItemCount()
        if UserSettings.Get(group="atm", key="askOnDeleteRec", subkey="enabled"):
            # if the user select more columns to delete, all the columns name
            # will appear the the warning dialog
            if tlist.GetSelectedItemCount() > 1:
                deleteColumns = "columns '%s'" % tlist.GetItemText(item)
                while item != -1:
                    item = tlist.GetNextSelected(item)
                    if item != -1:
                        deleteColumns += ", '%s'" % tlist.GetItemText(item)
            else:
                deleteColumns = "column '%s'" % tlist.GetItemText(item)
            deleteDialog = wx.MessageBox(
                parent=self,
                message=_(
                    "Selected %s will PERMANENTLY removed "
                    "from table. Do you want to drop the column?"
                )
                % (deleteColumns),
                caption=_("Drop column(s)"),
                style=wx.YES_NO | wx.CENTRE,
            )
            if deleteDialog != wx.YES:
                return False
        item = tlist.GetFirstSelected()
        while item != -1:
            self.listOfCommands.append(
                (
                    "v.db.dropcolumn",
                    {
                        "map": self.dbMgrData["vectName"],
                        "layer": self.selLayer,
                        "column": tlist.GetItemText(item),
                    },
                )
            )
            tlist.DeleteItem(item)
            item = tlist.GetFirstSelected()

        # apply changes
        self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)

        # update widgets
        table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
        self.FindWindowById(self.layerPage[self.selLayer]["renameCol"]).SetItems(
            self.dbMgrData["mapDBInfo"].GetColumns(table)
        )
        self.FindWindowById(self.layerPage[self.selLayer]["renameCol"]).SetSelection(0)
        self._updateTableColumnWidgetChoices(table=table)

        event.Skip()

    def OnTableItemDeleteAll(self, event):
        """Delete all items from the list"""
        table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
        cols = self.dbMgrData["mapDBInfo"].GetColumns(table)
        keyColumn = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["key"]
        if keyColumn in cols:
            cols.remove(keyColumn)

        if UserSettings.Get(group="atm", key="askOnDeleteRec", subkey="enabled"):
            deleteDialog = wx.MessageBox(
                parent=self,
                message=_(
                    "Selected columns\n%s\nwill PERMANENTLY removed "
                    "from table. Do you want to drop the columns?"
                )
                % ("\n".join(cols)),
                caption=_("Drop column(s)"),
                style=wx.YES_NO | wx.CENTRE,
            )
            if deleteDialog != wx.YES:
                return False

        for col in cols:
            self.listOfCommands.append(
                (
                    "v.db.dropcolumn",
                    {
                        "map": self.dbMgrData["vectName"],
                        "layer": self.selLayer,
                        "column": col,
                    },
                )
            )
        self.FindWindowById(self.layerPage[self.selLayer]["tableData"]).DeleteAllItems()

        # apply changes
        self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)

        # update widgets
        table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
        self.FindWindowById(self.layerPage[self.selLayer]["renameCol"]).SetItems(
            self.dbMgrData["mapDBInfo"].GetColumns(table)
        )
        self.FindWindowById(self.layerPage[self.selLayer]["renameCol"]).SetSelection(0)
        self._updateTableColumnWidgetChoices(table=table)

        event.Skip()

    def OnTableReload(self, event=None):
        """Reload table description"""
        self.FindWindowById(self.layerPage[self.selLayer]["tableData"]).Populate(
            update=True
        )
        self.listOfCommands = []

    def OnTableItemAdd(self, event):
        """Add new column to the table"""
        name = self.FindWindowById(
            self.layerPage[self.selLayer]["addColName"]
        ).GetValue()

        ctype = self.FindWindowById(
            self.layerPage[self.selLayer]["addColType"]
        ).GetStringSelection()

        length = int(
            self.FindWindowById(
                self.layerPage[self.selLayer]["addColLength"]
            ).GetValue()
        )

        self.AddColumn(name, ctype, length)

        # update widgets
        table = self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"]
        self.FindWindowById(self.layerPage[self.selLayer]["addColName"]).SetValue("")
        self.FindWindowById(self.layerPage[self.selLayer]["renameCol"]).SetItems(
            self.dbMgrData["mapDBInfo"].GetColumns(table)
        )
        self.FindWindowById(self.layerPage[self.selLayer]["renameCol"]).SetSelection(0)
        self._updateTableColumnWidgetChoices(table=table)
        event.Skip()

    def UpdatePage(self, layer):
        if layer in self.layerPage.keys():
            table = self.dbMgrData["mapDBInfo"].layers[layer]["table"]

            # update table description
            tlist = self.FindWindowById(self.layerPage[layer]["tableData"])
            tlist.Update(
                table=self.dbMgrData["mapDBInfo"].tables[table],
                columns=self.dbMgrData["mapDBInfo"].GetColumns(table),
            )
            self.OnTableReload(None)

    def _updateTableColumnWidgetChoices(self, table):
        """Update table column widget choices

        :param str table: table name
        """
        cols = self.dbMgrData["mapDBInfo"].GetColumns(table)
        # Browse data page SQL Query Simple page WHERE Combobox column names widget
        self.FindWindowById(
            self.pages["browse"].layerPage[self.selLayer]["whereColumn"]
        ).SetItems(cols)
        # Browse data page SQL Query Builder page SQL builder frame ListBox column
        # names widget
        if self.pages["browse"].builder:
            self.pages["browse"].builder.list_columns.Set(cols)
        # Browse data page column Field calculator frame ListBox column names widget
        fieldCalc = self.FindWindowById(
            self.pages["browse"].layerPage[self.selLayer]["data"],
        ).fieldCalc
        if fieldCalc:
            fieldCalc.list_columns.Set(cols)


class DbMgrLayersPage(wx.Panel):
    def __init__(self, parent, parentDbMgrBase):
        """Create layer manage page"""
        self.parentDbMgrBase = parentDbMgrBase
        self.dbMgrData = self.parentDbMgrBase.dbMgrData

        wx.Panel.__init__(self, parent=parent)
        splitterWin = wx.SplitterWindow(parent=self, id=wx.ID_ANY)
        splitterWin.SetMinimumPaneSize(100)

        #
        # list of layers
        #
        panelList = wx.Panel(parent=splitterWin, id=wx.ID_ANY)

        panelListSizer = wx.BoxSizer(wx.VERTICAL)
        layerBox = StaticBox(
            parent=panelList, id=wx.ID_ANY, label=" %s " % _("List of layers")
        )
        layerSizer = wx.StaticBoxSizer(layerBox, wx.VERTICAL)

        self.layerList = self._createLayerDesc(panelList)
        self.layerList.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnLayerRightUp)  # wxMSW
        self.layerList.Bind(wx.EVT_RIGHT_UP, self.OnLayerRightUp)  # wxGTK

        layerSizer.Add(self.layerList, flag=wx.ALL | wx.EXPAND, proportion=1, border=3)

        panelListSizer.Add(layerSizer, flag=wx.ALL | wx.EXPAND, proportion=1, border=3)

        panelList.SetSizer(panelListSizer)

        #
        # manage part
        #
        panelManage = wx.Panel(parent=splitterWin, id=wx.ID_ANY)

        manageSizer = wx.BoxSizer(wx.VERTICAL)

        self.manageLayerBook = LayerBook(
            parent=panelManage, id=wx.ID_ANY, parentDialog=self
        )
        if not self.dbMgrData["editable"]:
            self.manageLayerBook.Enable(False)

        manageSizer.Add(
            self.manageLayerBook,
            proportion=1,
            flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
            border=5,
        )

        panelSizer = wx.BoxSizer(wx.VERTICAL)
        panelSizer.Add(splitterWin, proportion=1, flag=wx.EXPAND)

        panelManage.SetSizer(manageSizer)
        splitterWin.SplitHorizontally(panelList, panelManage, 100)
        splitterWin.Fit()
        self.SetSizer(panelSizer)

    def _createLayerDesc(self, parent):
        """Create list of linked layers"""
        tlist = LayerListCtrl(
            parent=parent, id=wx.ID_ANY, layers=self.dbMgrData["mapDBInfo"].layers
        )

        tlist.Populate()
        # sorter
        # itemDataMap = list.Populate()
        # listmix.ColumnSorterMixin.__init__(self, 2)

        return tlist

    def UpdatePage(self):
        #
        # 'manage layers' page
        #
        # update list of layers

        # self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])

        self.layerList.Update(self.dbMgrData["mapDBInfo"].layers)
        self.layerList.Populate(update=True)
        # update selected widgets
        listOfLayers = list(map(str, self.dbMgrData["mapDBInfo"].layers.keys()))
        # delete layer page
        self.manageLayerBook.deleteLayer.SetItems(listOfLayers)
        if len(listOfLayers) > 0:
            self.manageLayerBook.deleteLayer.SetStringSelection(listOfLayers[0])
            tableName = self.dbMgrData["mapDBInfo"].layers[int(listOfLayers[0])][
                "table"
            ]
            maxLayer = max(self.dbMgrData["mapDBInfo"].layers.keys())
        else:
            tableName = ""
            maxLayer = 0
        self.manageLayerBook.deleteTable.SetLabel(
            _("Drop also linked attribute table (%s)") % tableName
        )
        # add layer page
        self.manageLayerBook.addLayerWidgets["layer"][1].SetValue(maxLayer + 1)
        # modify layer
        self.manageLayerBook.modifyLayerWidgets["layer"][1].SetItems(listOfLayers)
        self.manageLayerBook.OnChangeLayer(event=None)

    def OnLayerRightUp(self, event):
        """Layer description area, context menu"""
        pass


class TableListCtrl(ListCtrl, listmix.ListCtrlAutoWidthMixin):
    #                    listmix.TextEditMixin):
    """Table description list"""

    def __init__(
        self, parent, id, table, columns, pos=wx.DefaultPosition, size=wx.DefaultSize
    ):
        self.parent = parent
        self.table = table
        self.columns = columns
        ListCtrl.__init__(
            self,
            parent,
            id,
            pos,
            size,
            style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES | wx.BORDER_NONE,
        )

        listmix.ListCtrlAutoWidthMixin.__init__(self)
        # listmix.TextEditMixin.__init__(self)

    def Update(self, table, columns):
        """Update column description"""
        self.table = table
        self.columns = columns

    def Populate(self, update=False):
        """Populate the list"""
        itemData = {}  # requested by sorter

        if not update:
            headings = [_("Column name"), _("Data type"), _("Data length")]
            i = 0
            for h in headings:
                self.InsertColumn(col=i, heading=h)
                i += 1
            self.SetColumnWidth(col=0, width=350)
            self.SetColumnWidth(col=1, width=175)
        else:
            self.DeleteAllItems()

        i = 0
        for column in self.columns:
            index = self.InsertItem(i, str(column))
            self.SetItem(index, 0, str(column))
            self.SetItem(index, 1, str(self.table[column]["type"]))
            self.SetItem(index, 2, str(self.table[column]["length"]))
            self.SetItemData(index, i)
            itemData[i] = (
                str(column),
                str(self.table[column]["type"]),
                int(self.table[column]["length"]),
            )
            i = i + 1

        self.SendSizeEvent()

        return itemData


class LayerListCtrl(ListCtrl, listmix.ListCtrlAutoWidthMixin):
    # listmix.ColumnSorterMixin):
    # listmix.TextEditMixin):
    """Layer description list"""

    def __init__(self, parent, id, layers, pos=wx.DefaultPosition, size=wx.DefaultSize):
        self.parent = parent
        self.layers = layers
        ListCtrl.__init__(
            self,
            parent,
            id,
            pos,
            size,
            style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES | wx.BORDER_NONE,
        )

        listmix.ListCtrlAutoWidthMixin.__init__(self)
        # listmix.TextEditMixin.__init__(self)

    def Update(self, layers):
        """Update description"""
        self.layers = layers

    def Populate(self, update=False):
        """Populate the list"""
        itemData = {}  # requested by sorter

        if not update:
            headings = [_("Layer"), _("Driver"), _("Database"), _("Table"), _("Key")]
            i = 0
            for h in headings:
                self.InsertColumn(col=i, heading=h)
                i += 1
        else:
            self.DeleteAllItems()

        i = 0
        for layer in self.layers.keys():
            index = self.InsertItem(i, str(layer))
            self.SetItem(index, 0, str(layer))
            database = str(self.layers[layer]["database"])
            driver = str(self.layers[layer]["driver"])
            table = str(self.layers[layer]["table"])
            key = str(self.layers[layer]["key"])
            self.SetItem(index, 1, driver)
            self.SetItem(index, 2, database)
            self.SetItem(index, 3, table)
            self.SetItem(index, 4, key)
            self.SetItemData(index, i)
            itemData[i] = (str(layer), driver, database, table, key)
            i += 1

        for i in range(self.GetColumnCount()):
            self.SetColumnWidth(col=i, width=wx.LIST_AUTOSIZE)
            if self.GetColumnWidth(col=i) < 60:
                self.SetColumnWidth(col=i, width=60)

        self.SendSizeEvent()

        return itemData


class LayerBook(wx.Notebook):
    """Manage layers (add, delete, modify)"""

    def __init__(self, parent, id, parentDialog, style=wx.BK_DEFAULT):
        wx.Notebook.__init__(self, parent, id, style=style)

        self.parent = parent
        self.parentDialog = parentDialog
        self.mapDBInfo = self.parentDialog.dbMgrData["mapDBInfo"]
        vectName = self.parentDialog.dbMgrData["vectName"]

        #
        # drivers
        #
        drivers = RunCommand("db.drivers", quiet=True, read=True, flags="p")

        self.listOfDrivers = []
        for drv in drivers.splitlines():
            self.listOfDrivers.append(drv.strip())

        #
        # get default values
        #
        self.defaultConnect = {}
        genv = grass.gisenv()
        vectMap = grass.find_file(
            name=vectName,
            element="vector",
        )
        vectGisrc, vectEnv = grass.create_environment(
            gisdbase=genv["GISDBASE"],
            location=genv["LOCATION_NAME"],
            mapset=vectMap["mapset"],
        )
        connect = RunCommand(
            "db.connect",
            flags="p",
            env=vectEnv,
            read=True,
            quiet=True,
        )
        grass.utils.try_remove(vectGisrc)

        for line in connect.splitlines():
            item, value = line.split(":", 1)
            self.defaultConnect[item.strip()] = value.strip()

        # really needed?
        # if len(self.defaultConnect['driver']) == 0 or \
        #        len(self.defaultConnect['database']) == 0:
        #     GWarning(parent = self.parent,
        #              message = _("Unknown default DB connection. "
        #                          "Please define DB connection using db.connect"
        #                          "module."))

        self.defaultTables = self._getTables(
            self.defaultConnect["driver"], self.defaultConnect["database"]
        )
        try:
            self.defaultColumns = self._getColumns(
                self.defaultConnect["driver"],
                self.defaultConnect["database"],
                self.defaultTables[0],
            )
        except IndexError:
            self.defaultColumns = []

        self._createAddPage()
        self._createDeletePage()
        self._createModifyPage()

    def _createAddPage(self):
        """Add new layer"""
        self.addPanel = wx.Panel(parent=self, id=wx.ID_ANY)
        self.AddPage(page=self.addPanel, text=_("Add layer"))

        try:
            maxLayer = max(self.mapDBInfo.layers.keys())
        except ValueError:
            maxLayer = 0

        # layer description

        layerBox = StaticBox(
            parent=self.addPanel, id=wx.ID_ANY, label=" %s " % (_("Layer description"))
        )
        layerSizer = wx.StaticBoxSizer(layerBox, wx.VERTICAL)

        #
        # list of layer widgets (label, value)
        #
        self.addLayerWidgets = {
            "layer": (
                StaticText(
                    parent=self.addPanel, id=wx.ID_ANY, label="%s:" % _("Layer")
                ),
                SpinCtrl(
                    parent=self.addPanel,
                    id=wx.ID_ANY,
                    size=(65, -1),
                    initial=maxLayer + 1,
                    min=1,
                    max=1e6,
                ),
            ),
            "driver": (
                StaticText(
                    parent=self.addPanel, id=wx.ID_ANY, label="%s:" % _("Driver")
                ),
                wx.Choice(
                    parent=self.addPanel,
                    id=wx.ID_ANY,
                    size=(200, -1),
                    choices=self.listOfDrivers,
                ),
            ),
            "database": (
                StaticText(
                    parent=self.addPanel, id=wx.ID_ANY, label="%s:" % _("Database")
                ),
                TextCtrl(
                    parent=self.addPanel,
                    id=wx.ID_ANY,
                    value="",
                    style=wx.TE_PROCESS_ENTER,
                ),
            ),
            "table": (
                StaticText(
                    parent=self.addPanel, id=wx.ID_ANY, label="%s:" % _("Table")
                ),
                wx.Choice(
                    parent=self.addPanel,
                    id=wx.ID_ANY,
                    size=(200, -1),
                    choices=self.defaultTables,
                ),
            ),
            "key": (
                StaticText(
                    parent=self.addPanel, id=wx.ID_ANY, label="%s:" % _("Key column")
                ),
                wx.Choice(
                    parent=self.addPanel,
                    id=wx.ID_ANY,
                    size=(200, -1),
                    choices=self.defaultColumns,
                ),
            ),
            "addCat": (
                CheckBox(
                    parent=self.addPanel,
                    id=wx.ID_ANY,
                    label=_("Insert record for each category into table"),
                ),
                None,
            ),
        }

        # set default values for widgets
        self.addLayerWidgets["driver"][1].SetStringSelection(
            self.defaultConnect["driver"]
        )
        self.addLayerWidgets["database"][1].SetValue(self.defaultConnect["database"])
        self.addLayerWidgets["table"][1].SetSelection(0)
        self.addLayerWidgets["key"][1].SetSelection(0)
        self.addLayerWidgets["addCat"][0].SetValue(True)
        # events
        self.addLayerWidgets["driver"][1].Bind(wx.EVT_CHOICE, self.OnDriverChanged)
        self.addLayerWidgets["database"][1].Bind(
            wx.EVT_TEXT_ENTER, self.OnDatabaseChanged
        )
        self.addLayerWidgets["table"][1].Bind(wx.EVT_CHOICE, self.OnTableChanged)

        # tooltips
        self.addLayerWidgets["addCat"][0].SetToolTip(
            _("You need to add categories " "by v.category module.")
        )

        # table description
        tableBox = StaticBox(
            parent=self.addPanel, id=wx.ID_ANY, label=" %s " % (_("Table description"))
        )
        tableSizer = wx.StaticBoxSizer(tableBox, wx.VERTICAL)

        #
        # list of table widgets
        #
        keyCol = UserSettings.Get(group="atm", key="keycolumn", subkey="value")
        self.tableWidgets = {
            "table": (
                StaticText(
                    parent=self.addPanel, id=wx.ID_ANY, label="%s:" % _("Table name")
                ),
                TextCtrl(
                    parent=self.addPanel,
                    id=wx.ID_ANY,
                    value="",
                    style=wx.TE_PROCESS_ENTER,
                ),
            ),
            "key": (
                StaticText(
                    parent=self.addPanel, id=wx.ID_ANY, label="%s:" % _("Key column")
                ),
                TextCtrl(
                    parent=self.addPanel,
                    id=wx.ID_ANY,
                    value=keyCol,
                    style=wx.TE_PROCESS_ENTER,
                ),
            ),
        }
        # events
        self.tableWidgets["table"][1].Bind(wx.EVT_TEXT_ENTER, self.OnCreateTable)
        self.tableWidgets["key"][1].Bind(wx.EVT_TEXT_ENTER, self.OnCreateTable)

        btnTable = Button(self.addPanel, wx.ID_ANY, _("&Create table"), size=(125, -1))
        btnTable.Bind(wx.EVT_BUTTON, self.OnCreateTable)

        btnLayer = Button(self.addPanel, wx.ID_ANY, _("&Add layer"), size=(125, -1))
        btnLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)

        btnDefault = Button(self.addPanel, wx.ID_ANY, _("&Set default"), size=(125, -1))
        btnDefault.Bind(wx.EVT_BUTTON, self.OnSetDefault)

        # do layout

        pageSizer = wx.BoxSizer(wx.HORIZONTAL)

        # data area
        dataSizer = wx.GridBagSizer(hgap=5, vgap=5)
        row = 0
        for key in ("layer", "driver", "database", "table", "key", "addCat"):
            label, value = self.addLayerWidgets[key]
            if not value:
                span = (1, 2)
            else:
                span = (1, 1)
            dataSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0), span=span)

            if not value:
                row += 1
                continue

            if key == "layer":
                style = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT
            else:
                style = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND

            dataSizer.Add(value, flag=style, pos=(row, 1))

            row += 1

        dataSizer.AddGrowableCol(1)
        layerSizer.Add(dataSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.Add(btnDefault, proportion=0, flag=wx.ALL | wx.ALIGN_LEFT, border=5)

        btnSizer.Add((5, 5), proportion=1, flag=wx.ALL | wx.EXPAND, border=5)

        btnSizer.Add(btnLayer, proportion=0, flag=wx.ALL, border=5)

        layerSizer.Add(btnSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=0)

        # data area
        dataSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
        dataSizer.AddGrowableCol(1)
        for key in ["table", "key"]:
            label, value = self.tableWidgets[key]
            dataSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL)
            dataSizer.Add(value, flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        tableSizer.Add(dataSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)

        tableSizer.Add(btnTable, proportion=0, flag=wx.ALL | wx.ALIGN_RIGHT, border=5)

        pageSizer.Add(layerSizer, proportion=3, flag=wx.ALL | wx.EXPAND, border=3)

        pageSizer.Add(
            tableSizer,
            proportion=2,
            flag=wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND,
            border=3,
        )
        layerSizer.FitInside(self.addPanel)

        self.addPanel.SetAutoLayout(True)
        self.addPanel.SetSizer(pageSizer)
        pageSizer.Fit(self.addPanel)

    def _createDeletePage(self):
        """Delete layer"""
        self.deletePanel = wx.Panel(parent=self, id=wx.ID_ANY)
        self.AddPage(page=self.deletePanel, text=_("Remove layer"))

        label = StaticText(
            parent=self.deletePanel, id=wx.ID_ANY, label="%s:" % _("Layer to remove")
        )

        self.deleteLayer = ComboBox(
            parent=self.deletePanel,
            id=wx.ID_ANY,
            size=(100, -1),
            style=wx.CB_READONLY,
            choices=list(map(str, self.mapDBInfo.layers.keys())),
        )
        self.deleteLayer.SetSelection(0)
        self.deleteLayer.Bind(wx.EVT_COMBOBOX, self.OnChangeLayer)

        try:
            tableName = self.mapDBInfo.layers[
                int(self.deleteLayer.GetStringSelection())
            ]["table"]
        except ValueError:
            tableName = ""

        self.deleteTable = CheckBox(
            parent=self.deletePanel,
            id=wx.ID_ANY,
            label=_("Drop also linked attribute table (%s)") % tableName,
        )

        if tableName == "":
            self.deleteLayer.Enable(False)
            self.deleteTable.Enable(False)

        btnDelete = Button(
            self.deletePanel, wx.ID_DELETE, _("&Remove layer"), size=(125, -1)
        )
        btnDelete.Bind(wx.EVT_BUTTON, self.OnDeleteLayer)

        #
        # do layout
        #
        pageSizer = wx.BoxSizer(wx.VERTICAL)

        dataSizer = wx.BoxSizer(wx.VERTICAL)

        flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)

        flexSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.deleteLayer, flag=wx.ALIGN_CENTER_VERTICAL)

        dataSizer.Add(flexSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=1)

        dataSizer.Add(self.deleteTable, proportion=0, flag=wx.ALL | wx.EXPAND, border=1)

        pageSizer.Add(dataSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)

        pageSizer.Add(btnDelete, proportion=0, flag=wx.ALL | wx.ALIGN_RIGHT, border=5)

        self.deletePanel.SetSizer(pageSizer)

    def _createModifyPage(self):
        """Modify layer"""
        self.modifyPanel = wx.Panel(parent=self, id=wx.ID_ANY)
        self.AddPage(page=self.modifyPanel, text=_("Modify layer"))

        #
        # list of layer widgets (label, value)
        #
        self.modifyLayerWidgets = {
            "layer": (
                StaticText(
                    parent=self.modifyPanel, id=wx.ID_ANY, label="%s:" % _("Layer")
                ),
                ComboBox(
                    parent=self.modifyPanel,
                    id=wx.ID_ANY,
                    size=(100, -1),
                    style=wx.CB_READONLY,
                    choices=list(map(str, self.mapDBInfo.layers.keys())),
                ),
            ),
            "driver": (
                StaticText(
                    parent=self.modifyPanel, id=wx.ID_ANY, label="%s:" % _("Driver")
                ),
                wx.Choice(
                    parent=self.modifyPanel,
                    id=wx.ID_ANY,
                    size=(200, -1),
                    choices=self.listOfDrivers,
                ),
            ),
            "database": (
                StaticText(
                    parent=self.modifyPanel, id=wx.ID_ANY, label="%s:" % _("Database")
                ),
                TextCtrl(
                    parent=self.modifyPanel,
                    id=wx.ID_ANY,
                    value="",
                    size=(350, -1),
                    style=wx.TE_PROCESS_ENTER,
                ),
            ),
            "table": (
                StaticText(
                    parent=self.modifyPanel, id=wx.ID_ANY, label="%s:" % _("Table")
                ),
                wx.Choice(
                    parent=self.modifyPanel,
                    id=wx.ID_ANY,
                    size=(200, -1),
                    choices=self.defaultTables,
                ),
            ),
            "key": (
                StaticText(
                    parent=self.modifyPanel, id=wx.ID_ANY, label="%s:" % _("Key column")
                ),
                wx.Choice(
                    parent=self.modifyPanel,
                    id=wx.ID_ANY,
                    size=(200, -1),
                    choices=self.defaultColumns,
                ),
            ),
        }

        # set default values for widgets
        self.modifyLayerWidgets["layer"][1].SetSelection(0)
        try:
            layer = int(self.modifyLayerWidgets["layer"][1].GetStringSelection())
        except ValueError:
            layer = None
            for label in self.modifyLayerWidgets.keys():
                self.modifyLayerWidgets[label][1].Enable(False)

        if layer:
            driver = self.mapDBInfo.layers[layer]["driver"]
            database = self.mapDBInfo.layers[layer]["database"]
            table = self.mapDBInfo.layers[layer]["table"]

            listOfColumns = self._getColumns(driver, database, table)
            self.modifyLayerWidgets["driver"][1].SetStringSelection(driver)
            self.modifyLayerWidgets["database"][1].SetValue(database)
            if table in self.modifyLayerWidgets["table"][1].GetItems():
                self.modifyLayerWidgets["table"][1].SetStringSelection(table)
            else:
                if self.defaultConnect["schema"] != "":
                    # try with default schema
                    table = self.defaultConnect["schema"] + table
                else:
                    table = "public." + table  # try with 'public' schema
                self.modifyLayerWidgets["table"][1].SetStringSelection(table)
            self.modifyLayerWidgets["key"][1].SetItems(listOfColumns)
            self.modifyLayerWidgets["key"][1].SetSelection(0)

        # events
        self.modifyLayerWidgets["layer"][1].Bind(wx.EVT_COMBOBOX, self.OnChangeLayer)
        # self.modifyLayerWidgets["driver"][1].Bind(wx.EVT_CHOICE, self.OnDriverChanged)
        # self.modifyLayerWidgets["database"][1].Bind(
        #     wx.EVT_TEXT_ENTER, self.OnDatabaseChanged
        # )
        # self.modifyLayerWidgets["table"][1].Bind(wx.EVT_CHOICE, self.OnTableChanged)

        btnModify = Button(
            self.modifyPanel, wx.ID_DELETE, _("&Modify layer"), size=(125, -1)
        )
        btnModify.Bind(wx.EVT_BUTTON, self.OnModifyLayer)

        #
        # do layout
        #
        pageSizer = wx.BoxSizer(wx.VERTICAL)

        # data area
        dataSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
        dataSizer.AddGrowableCol(1)
        for key in ("layer", "driver", "database", "table", "key"):
            label, value = self.modifyLayerWidgets[key]
            dataSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL)
            if key == "layer":
                dataSizer.Add(value, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
            else:
                dataSizer.Add(value, flag=wx.ALIGN_CENTER_VERTICAL)

        pageSizer.Add(dataSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)

        pageSizer.Add(btnModify, proportion=0, flag=wx.ALL | wx.ALIGN_RIGHT, border=5)

        self.modifyPanel.SetSizer(pageSizer)

    def _getTables(self, driver, database):
        """Get list of tables for given driver and database"""
        tables = []

        ret = RunCommand(
            "db.tables",
            parent=self,
            read=True,
            flags="p",
            driver=driver,
            database=database,
        )

        if ret is None:
            GError(
                parent=self,
                message=_(
                    "Unable to get list of tables.\n"
                    "Please use db.connect to set database parameters."
                ),
            )

            return tables

        for table in ret.splitlines():
            tables.append(table)

        return tables

    def _getColumns(self, driver, database, table):
        """Get list of column of given table"""
        columns = []

        ret = RunCommand(
            "db.columns",
            parent=self,
            quiet=True,
            read=True,
            driver=driver,
            database=database,
            table=table,
        )

        if ret is None:
            return columns

        for column in ret.splitlines():
            columns.append(column)

        return columns

    def OnDriverChanged(self, event):
        """Driver selection changed, update list of tables"""
        driver = event.GetString()
        database = self.addLayerWidgets["database"][1].GetValue()

        winTable = self.addLayerWidgets["table"][1]
        winKey = self.addLayerWidgets["key"][1]
        tables = self._getTables(driver, database)

        winTable.SetItems(tables)
        winTable.SetSelection(0)

        if len(tables) == 0:
            winKey.SetItems([])

        event.Skip()

    def OnDatabaseChanged(self, event):
        """Database selection changed, update list of tables"""
        event.Skip()

    def OnTableChanged(self, event):
        """Table name changed, update list of columns"""
        driver = self.addLayerWidgets["driver"][1].GetStringSelection()
        database = self.addLayerWidgets["database"][1].GetValue()
        table = event.GetString()

        win = self.addLayerWidgets["key"][1]
        cols = self._getColumns(driver, database, table)
        win.SetItems(cols)
        win.SetSelection(0)

        event.Skip()

    def OnSetDefault(self, event):
        """Set default values"""
        driver = self.addLayerWidgets["driver"][1]
        database = self.addLayerWidgets["database"][1]
        table = self.addLayerWidgets["table"][1]
        key = self.addLayerWidgets["key"][1]

        driver.SetStringSelection(self.defaultConnect["driver"])
        database.SetValue(self.defaultConnect["database"])
        tables = self._getTables(
            self.defaultConnect["driver"], self.defaultConnect["database"]
        )
        table.SetItems(tables)
        table.SetSelection(0)
        if len(tables) == 0:
            key.SetItems([])
        else:
            cols = self._getColumns(
                self.defaultConnect["driver"],
                self.defaultConnect["database"],
                tables[0],
            )
            key.SetItems(cols)
            key.SetSelection(0)

        event.Skip()

    def OnCreateTable(self, event):
        """Create new table (name and key column given)"""
        driver = self.addLayerWidgets["driver"][1].GetStringSelection()
        database = self.addLayerWidgets["database"][1].GetValue()
        table = self.tableWidgets["table"][1].GetValue()
        key = self.tableWidgets["key"][1].GetValue()

        if not table or not key:
            GError(
                parent=self,
                message=_(
                    "Unable to create new table. "
                    "Table name or key column name is missing."
                ),
            )
            return

        if table in self.addLayerWidgets["table"][1].GetItems():
            GError(
                parent=self,
                message=_(
                    "Unable to create new table. "
                    "Table <%s> already exists in the database."
                )
                % table,
            )
            return

        # create table
        sql = "CREATE TABLE %s (%s INTEGER)" % (table, key)

        RunCommand(
            "db.execute",
            quiet=True,
            parent=self,
            stdin=sql,
            input="-",
            driver=driver,
            database=database,
        )

        # update list of tables
        tableList = self.addLayerWidgets["table"][1]
        tableList.SetItems(self._getTables(driver, database))
        tableList.SetStringSelection(table)

        # update key column selection
        keyList = self.addLayerWidgets["key"][1]
        keyList.SetItems(self._getColumns(driver, database, table))
        keyList.SetStringSelection(key)

        event.Skip()

    def OnAddLayer(self, event):
        """Add new layer to vector map"""
        layer = int(self.addLayerWidgets["layer"][1].GetValue())
        layerWin = self.addLayerWidgets["layer"][1]
        driver = self.addLayerWidgets["driver"][1].GetStringSelection()
        database = self.addLayerWidgets["database"][1].GetValue()
        table = self.addLayerWidgets["table"][1].GetStringSelection()
        key = self.addLayerWidgets["key"][1].GetStringSelection()

        if layer in self.mapDBInfo.layers.keys():
            GError(
                parent=self,
                message=_(
                    "Unable to add new layer to vector map <%(vector)s>. "
                    "Layer %(layer)d already exists."
                )
                % {"vector": self.mapDBInfo.map, "layer": layer},
            )
            return

        # add new layer
        ret = RunCommand(
            "v.db.connect",
            parent=self,
            quiet=True,
            map=self.mapDBInfo.map,
            driver=driver,
            database=database,
            table=table,
            key=key,
            layer=layer,
            getErrorMsg=True,
        )

        if ret[0] == 0 and not ret[1]:
            # insert records into table if required
            if self.addLayerWidgets["addCat"][0].IsChecked():
                RunCommand(
                    "v.to.db",
                    parent=self,
                    quiet=True,
                    map=self.mapDBInfo.map,
                    layer=layer,
                    qlayer=layer,
                    option="cat",
                    columns=key,
                    overwrite=True,
                )
            # update dialog (only for new layer)
            self.parentDialog.parentDbMgrBase.UpdateDialog(layer=layer)
            # update db info
            self.mapDBInfo = self.parentDialog.dbMgrData["mapDBInfo"]
            # increase layer number
            layerWin.SetValue(layer + 1)
        elif ret[1]:
            GWarning(
                parent=self,
                message=ret[1],
            )

        if len(self.mapDBInfo.layers.keys()) == 1:
            # first layer add --- enable previously disabled widgets
            self.deleteLayer.Enable()
            self.deleteTable.Enable()
            for label in self.modifyLayerWidgets.keys():
                self.modifyLayerWidgets[label][1].Enable()

    def OnDeleteLayer(self, event):
        """Delete layer"""
        try:
            layer = int(self.deleteLayer.GetValue())
        except:
            return

        RunCommand(
            "v.db.connect", parent=self, flags="d", map=self.mapDBInfo.map, layer=layer
        )

        # drop also table linked to layer which is deleted
        if self.deleteTable.IsChecked():
            driver = self.addLayerWidgets["driver"][1].GetStringSelection()
            database = self.addLayerWidgets["database"][1].GetValue()
            table = self.mapDBInfo.layers[layer]["table"]
            sql = "DROP TABLE %s" % (table)

            RunCommand(
                "db.execute",
                input="-",
                parent=self,
                stdin=sql,
                quiet=True,
                driver=driver,
                database=database,
            )

            # update list of tables
            tableList = self.addLayerWidgets["table"][1]
            tableList.SetItems(self._getTables(driver, database))
            tableList.SetStringSelection(table)

        # update dialog
        self.parentDialog.parentDbMgrBase.UpdateDialog(layer=layer)
        # update db info
        self.mapDBInfo = self.parentDialog.dbMgrData["mapDBInfo"]

        if len(self.mapDBInfo.layers.keys()) == 0:
            # disable selected widgets
            self.deleteLayer.Enable(False)
            self.deleteTable.Enable(False)
            for label in self.modifyLayerWidgets.keys():
                self.modifyLayerWidgets[label][1].Enable(False)

        event.Skip()

    def OnChangeLayer(self, event):
        """Layer number of layer to be deleted is changed"""
        try:
            layer = int(event.GetString())
        except:
            try:
                layer = self.mapDBInfo.layers.keys()[0]
            except:
                return

        if self.GetCurrentPage() == self.modifyPanel:
            driver = self.mapDBInfo.layers[layer]["driver"]
            database = self.mapDBInfo.layers[layer]["database"]
            table = self.mapDBInfo.layers[layer]["table"]
            listOfColumns = self._getColumns(driver, database, table)
            self.modifyLayerWidgets["driver"][1].SetStringSelection(driver)
            self.modifyLayerWidgets["database"][1].SetValue(database)
            self.modifyLayerWidgets["table"][1].SetStringSelection(table)
            self.modifyLayerWidgets["key"][1].SetItems(listOfColumns)
            self.modifyLayerWidgets["key"][1].SetSelection(0)
        else:
            self.deleteTable.SetLabel(
                _("Drop also linked attribute table (%s)")
                % self.mapDBInfo.layers[layer]["table"]
            )
        if event:
            event.Skip()

    def OnModifyLayer(self, event):
        """Modify layer connection settings"""

        layer = self.modifyLayerWidgets["layer"][1].GetStringSelection()
        if not layer:
            return

        layer = int(layer)

        modify = False
        if (
            self.modifyLayerWidgets["driver"][1].GetStringSelection()
            != self.mapDBInfo.layers[layer]["driver"]
            or self.modifyLayerWidgets["database"][1].GetValue()
            != self.mapDBInfo.layers[layer]["database"]
            or self.modifyLayerWidgets["table"][1].GetStringSelection()
            != self.mapDBInfo.layers[layer]["table"]
            or self.modifyLayerWidgets["key"][1].GetStringSelection()
            != self.mapDBInfo.layers[layer]["key"]
        ):
            modify = True

        if modify:
            # delete layer
            RunCommand(
                "v.db.connect",
                parent=self,
                quiet=True,
                flags="d",
                map=self.mapDBInfo.map,
                layer=layer,
            )

            # add modified layer
            RunCommand(
                "v.db.connect",
                quiet=True,
                map=self.mapDBInfo.map,
                driver=self.modifyLayerWidgets["driver"][1].GetStringSelection(),
                database=self.modifyLayerWidgets["database"][1].GetValue(),
                table=self.modifyLayerWidgets["table"][1].GetStringSelection(),
                key=self.modifyLayerWidgets["key"][1].GetStringSelection(),
                layer=int(layer),
            )

            # update dialog (only for new layer)
            self.parentDialog.parentDbMgrBase.UpdateDialog(layer=layer)
            # update db info
            self.mapDBInfo = self.parentDialog.dbMgrData["mapDBInfo"]

        event.Skip()


class FieldStatistics(wx.Frame):
    def __init__(self, parent, id=wx.ID_ANY, style=wx.DEFAULT_FRAME_STYLE, **kwargs):
        """Dialog to display and save statistics of field stats"""
        self.parent = parent
        wx.Frame.__init__(self, parent, id, style=style, **kwargs)

        self.SetTitle(_("Field statistics"))
        self.SetIcon(
            wx.Icon(
                os.path.join(globalvar.ICONDIR, "grass_sql.ico"), wx.BITMAP_TYPE_ICO
            )
        )

        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)

        self.sp = scrolled.ScrolledPanel(
            parent=self.panel,
            id=wx.ID_ANY,
            size=(250, 150),
            style=wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER,
            name="Statistics",
        )
        self.text = TextCtrl(
            parent=self.sp, id=wx.ID_ANY, style=wx.TE_MULTILINE | wx.TE_READONLY
        )
        self.text.SetBackgroundColour("white")

        # buttons
        self.btnClipboard = Button(parent=self.panel, id=wx.ID_COPY)
        self.btnClipboard.SetToolTip(_("Copy statistics the clipboard (Ctrl+C)"))
        self.btnCancel = Button(parent=self.panel, id=wx.ID_CLOSE)
        self.btnCancel.SetDefault()

        # bindings
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnClose)
        self.btnClipboard.Bind(wx.EVT_BUTTON, self.OnCopy)

        self._layout()

    def _layout(self):
        sizer = wx.BoxSizer(wx.VERTICAL)
        txtSizer = wx.BoxSizer(wx.VERTICAL)
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)

        txtSizer.Add(self.text, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)

        self.sp.SetSizer(txtSizer)
        self.sp.SetAutoLayout(True)
        self.sp.SetupScrolling()

        sizer.Add(
            self.sp,
            proportion=1,
            flag=wx.GROW | wx.LEFT | wx.RIGHT | wx.BOTTOM,
            border=3,
        )

        line = wx.StaticLine(
            parent=self.panel, id=wx.ID_ANY, size=(20, -1), style=wx.LI_HORIZONTAL
        )
        sizer.Add(line, proportion=0, flag=wx.GROW | wx.LEFT | wx.RIGHT, border=3)

        # buttons
        btnSizer.Add(self.btnClipboard, proportion=0, flag=wx.ALL, border=5)
        btnSizer.Add(self.btnCancel, proportion=0, flag=wx.ALL, border=5)
        sizer.Add(btnSizer, proportion=0, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)

        self.panel.SetSizer(sizer)
        sizer.Fit(self.panel)

    def OnCopy(self, event):
        """!Copy the statistics to the clipboard"""
        stats = self.text.GetValue()
        rdata = wx.TextDataObject()
        rdata.SetText(stats)

        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(rdata)
            wx.TheClipboard.Close()

    def OnClose(self, event):
        """!Button 'Close' pressed"""
        self.Close(True)

    def Update(self, driver, database, table, column):
        """!Update statistics for given column

        :param: column column name
        """
        if driver == "dbf":
            GError(parent=self, message=_("Statistics is not support for DBF tables."))
            self.Close()
            return

        fd, sqlFilePath = tempfile.mkstemp(text=True)
        sqlFile = open(sqlFilePath, "w")
        stats = ["count", "min", "max", "avg", "sum", "null"]
        for fn in stats:
            if fn == "null":
                sqlFile.write(
                    "select count(*) from %s where %s is null;%s"
                    % (table, column, "\n")
                )
            else:
                sqlFile.write("select %s(%s) from %s;%s" % (fn, column, table, "\n"))
        sqlFile.close()

        dataStr = RunCommand(
            "db.select",
            parent=self.parent,
            read=True,
            flags="c",
            input=sqlFilePath,
            driver=driver,
            database=database,
        )
        if not dataStr:
            GError(parent=self.parent, message=_("Unable to calculte statistics."))
            self.Close()
            return

        dataLines = dataStr.splitlines()
        if len(dataLines) != len(stats):
            GError(
                parent=self.parent,
                message=_(
                    "Unable to calculte statistics. "
                    "Invalid number of lines %d (should be %d)."
                )
                % (len(dataLines), len(stats)),
            )
            self.Close()
            return

        # calculate stddev
        avg = float(dataLines[stats.index("avg")])
        count = float(dataLines[stats.index("count")])
        sql = "select (%(column)s - %(avg)f)*(%(column)s - %(avg)f) from %(table)s" % {
            "column": column,
            "avg": avg,
            "table": table,
        }
        dataVar = RunCommand(
            "db.select",
            parent=self.parent,
            read=True,
            flags="c",
            sql=sql,
            driver=driver,
            database=database,
        )
        if not dataVar:
            GWarning(
                parent=self.parent, message=_("Unable to calculte standard deviation.")
            )
        varSum = 0
        for var in decode(dataVar).splitlines():
            if var:
                varSum += float(var)
        stddev = math.sqrt(varSum / count)

        self.SetTitle(_("Field statistics <%s>") % column)
        self.text.Clear()
        for idx in range(len(stats)):
            self.text.AppendText("%s: %s\n" % (stats[idx], dataLines[idx]))
        self.text.AppendText("stddev: %f\n" % stddev)