File: MainForm_Functions.cs

package info (click to toggle)
keepass2 2.19%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 11,496 kB
  • sloc: cs: 87,098; xml: 6,569; cpp: 311; makefile: 49; sh: 9
file content (4761 lines) | stat: -rw-r--r-- 150,590 bytes parent folder | download
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
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
/*
  KeePass Password Safe - The Open-Source Password Manager
  Copyright (C) 2003-2012 Dominik Reichl <dominik.reichl@t-online.de>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

using System;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

using KeePass.App;
using KeePass.App.Configuration;
using KeePass.DataExchange;
using KeePass.Ecas;
using KeePass.Native;
using KeePass.Plugins;
using KeePass.Resources;
using KeePass.UI;
using KeePass.Util;
using KeePass.Util.Spr;

using KeePassLib;
using KeePassLib.Collections;
using KeePassLib.Cryptography;
using KeePassLib.Delegates;
using KeePassLib.Interfaces;
using KeePassLib.Keys;
using KeePassLib.Utility;
using KeePassLib.Security;
using KeePassLib.Serialization;

namespace KeePass.Forms
{
	public partial class MainForm : Form
	{
		private DocumentManagerEx m_docMgr = new DocumentManagerEx();

		private ListViewGroup m_lvgLastEntryGroup = null;
		private bool m_bEntryGrouping = false;
		private DateTime m_dtCachedNow = DateTime.Now;
		private bool m_bOnlyTans = false;
		private Font m_fontExpired = null;
		private Font m_fontBoldUI = null;
		private Font m_fontBoldTree = null;
		private Font m_fontItalicTree = null;
		private Color m_clrAlternateItemBgColor = Color.Empty;
		private Point m_ptLastEntriesMouseClick = new Point(0, 0);
		private RichTextBoxContextMenu m_ctxEntryPreviewContextMenu = new RichTextBoxContextMenu();
		private DynamicMenu m_dynCustomStrings;
		private DynamicMenu m_dynCustomBinaries;
		private DynamicMenu m_dynShowEntriesByTagsEditMenu;
		private DynamicMenu m_dynShowEntriesByTagsToolBar;
		private DynamicMenu m_dynAddTag;
		private DynamicMenu m_dynRemoveTag;
		private OpenWithMenu m_dynOpenUrl;

		private AsyncPwListUpdate m_asyncListUpdate = null;

		private MruList m_mruList = new MruList();

		private SessionLockNotifier m_sessionLockNotifier = new SessionLockNotifier();

		private DefaultPluginHost m_pluginDefaultHost = new DefaultPluginHost();
		private PluginManager m_pluginManager = new PluginManager();

		private object m_objLockTimerSync = new object();
		private int m_nLockTimerMax = 0;
		// private volatile int m_nLockTimerCur = 0;
		private long m_lLockAtTicks = long.MaxValue;
		private uint m_uLastInputTime = uint.MaxValue;
		private long m_lLockAtGlobalTicks = long.MaxValue;

		private bool m_bBlockQuickFind = false;
		private object m_objQuickFindSync = new object();
		private int m_iLastQuickFindTicks = Environment.TickCount - 1500;
		private string m_strLastQuickSearch = string.Empty;

		private ToolStripSeparator m_tsSepCustomToolBar = null;
		private List<ToolStripButton> m_vCustomToolBarButtons = new List<ToolStripButton>();

		private int m_nClipClearMax = 0;
		private int m_nClipClearCur = -1;

		private string m_strNeverExpiresText = string.Empty;

		private bool m_bSimpleTanView = true;
		private bool m_bShowTanIndices = true;

		private Image m_imgFileSaveEnabled = null;
		private Image m_imgFileSaveDisabled = null;
		// private Image m_imgFileSaveAllEnabled = null;
		// private Image m_imgFileSaveAllDisabled = null;
		private ImageList m_ilCurrentIcons = null;

		private KeyValuePair<Color, Icon> m_kvpIcoMain =
			new KeyValuePair<Color, Icon>(Color.Empty, null);
		private KeyValuePair<Color, Icon> m_kvpIcoTrayNormal =
			new KeyValuePair<Color, Icon>(Color.Empty, null);
		private KeyValuePair<Color, Icon> m_kvpIcoTrayLocked =
			new KeyValuePair<Color, Icon>(Color.Empty, null);

		private List<Image> m_lTabImages = new List<Image>();
		private ImageList m_ilTabImages = null;

		private bool m_bIsAutoTyping = false;
		private bool m_bBlockTabChanged = false;
		private bool m_bForceSave = false;
		private volatile uint m_uUIBlocked = 0;
		private uint m_uUnlockAutoBlocked = 0;
		private MouseButtons m_mbLastTrayMouseButtons = MouseButtons.None;

		private bool m_bUpdateUIStateOnce = false;
		private int m_nLastSelChUpdateUIStateTicks = 0;

		private readonly int m_nAppMessage = Program.ApplicationMessage;
		private readonly int m_nTaskbarButtonMessage;
		private bool m_bTaskbarButtonMessage;

		private List<KeyValuePair<ToolStripItem, ToolStripItem>> m_vLinkedToolStripItems =
			new List<KeyValuePair<ToolStripItem, ToolStripItem>>();

		private FormWindowState m_fwsLast = FormWindowState.Normal;
		private PwGroup m_pgActiveAtDragStart = null;

		private Stack<Form> m_vRedirectActivation = new Stack<Form>();

		public DocumentManagerEx DocumentManager { get { return m_docMgr; } }
		public PwDatabase ActiveDatabase { get { return m_docMgr.ActiveDatabase; } }
		public ImageList ClientIcons { get { return m_ilCurrentIcons; } }

		/// <summary>
		/// Get a reference to the main menu.
		/// </summary>
		public MenuStrip MainMenu { get { return m_menuMain; } }
		/// <summary>
		/// Get a reference to the 'Tools' popup menu in the main menu. It is
		/// recommended that you use this reference instead of searching the
		/// main menu for the 'Tools' item.
		/// </summary>
		public ToolStripMenuItem ToolsMenu { get { return m_menuTools; } }

		public ContextMenuStrip EntryContextMenu { get { return m_ctxPwList; } }
		public ContextMenuStrip GroupContextMenu { get { return m_ctxGroupList; } }
		public ContextMenuStrip TrayContextMenu { get { return m_ctxTray; } }

		public ToolStripProgressBar MainProgressBar { get { return m_statusPartProgress; } }
		public NotifyIcon MainNotifyIcon { get { return m_ntfTray.NotifyIcon; } }

		public MruList FileMruList { get { return m_mruList; } }

		/// <summary>
		/// Get a reference to the plugin host. This should not be used by plugins.
		/// Plugins should directly use the reference they get in the initialization
		/// function.
		/// </summary>
		public IPluginHost PluginHost
		{
			get { return m_pluginDefaultHost; }
		}

		internal PluginManager PluginManager { get { return m_pluginManager; } }

		private sealed class EditableBinaryAttachment
		{
			private string m_strName;
			public string Name { get { return m_strName; } }

			public EditableBinaryAttachment(string strName)
			{
				m_strName = strName;
			}
		}

		private struct MainAppState
		{
			public bool FileLocked;
			public bool DatabaseOpened;
			public int EntriesCount;
			public int EntriesSelected;
			public bool EnableLockCmd;
			public bool NoWindowShown;
			public PwEntry SelectedEntry;
			public bool CanCopyUserName;
			public bool CanCopyPassword;
			public bool IsOneTan;
			public string LockUnlock;
		}

		private enum AppCommandType
		{
			Window = 0,
			Lock = 1
		}

		/// <summary>
		/// Check if the main window is trayed (i.e. only the tray icon is visible).
		/// </summary>
		/// <returns>Returns <c>true</c>, if the window is trayed.</returns>
		public bool IsTrayed()
		{
			return !this.Visible;
		}

		public bool IsFileLocked(PwDocument ds)
		{
			if(ds == null) ds = m_docMgr.ActiveDocument;

			return (ds.LockedIoc.Path.Length != 0);
		}

		public bool IsAtLeastOneFileOpen()
		{
			foreach(PwDocument ds in m_docMgr.Documents)
			{
				if(ds.Database.IsOpen) return true;
			}

			return false;
		}

		private void CleanUpEx()
		{
			m_asyncListUpdate.CancelPendingUpdatesAsync();

			Program.TriggerSystem.RaiseEvent(EcasEventIDs.AppExit);

			m_nClipClearCur = -1;
			if(Program.Config.Security.ClipboardClearOnExit)
				ClipboardUtil.ClearIfOwner();

			m_pluginManager.UnloadAllPlugins(); // Before SaveConfig

			// Just unregister the events; no need to remove the buttons
			foreach(ToolStripButton tbCustom in m_vCustomToolBarButtons)
				tbCustom.Click -= OnCustomToolBarButtonClicked;
			m_vCustomToolBarButtons.Clear();

			SaveConfig();

			m_sessionLockNotifier.Uninstall();
			HotKeyManager.UnregisterAll();

			EntryTemplates.Release();

			m_dynCustomBinaries.MenuClick -= this.OnEntryBinaryView;
			m_dynCustomStrings.MenuClick -= this.OnCopyCustomString;
			m_dynShowEntriesByTagsEditMenu.MenuClick -= this.OnShowEntriesByTag;
			m_dynShowEntriesByTagsToolBar.MenuClick -= this.OnShowEntriesByTag;
			m_dynAddTag.MenuClick -= this.OnAddEntryTag;
			m_dynRemoveTag.MenuClick -= this.OnRemoveEntryTag;
			m_dynOpenUrl.Destroy();

			m_ctxEntryPreviewContextMenu.Detach();

			m_lvsmMenu.Release();

			m_ntfTray.Visible = false;

			Debug.Assert(m_vRedirectActivation.Count == 0);
			Debug.Assert(m_uUIBlocked == 0);
			Debug.Assert(m_uUnlockAutoBlocked == 0);
			this.Visible = false;

			if(m_fontBoldUI != null) { m_fontBoldUI.Dispose(); m_fontBoldUI = null; }
			if(m_fontBoldTree != null) { m_fontBoldTree.Dispose(); m_fontBoldTree = null; }
			if(m_fontItalicTree != null) { m_fontItalicTree.Dispose(); m_fontItalicTree = null; }

			m_asyncListUpdate.WaitAll();
			m_bCleanedUp = true;
		}

		/// <summary>
		/// Save the current configuration. The configuration is saved using the
		/// cascading configuration files mechanism and the default paths are used.
		/// </summary>
		public void SaveConfig()
		{
			SaveWindowPositionAndSize();

			AceMainWindow mw = Program.Config.MainWindow;

			mw.Layout = ((m_splitHorizontal.Orientation != Orientation.Horizontal) ?
				AceMainWindowLayout.SideBySide : AceMainWindowLayout.Default);

			UpdateColumnsEx(true);

			Debug.Assert(m_bSimpleTanView == m_menuViewTanSimpleList.Checked);
			mw.TanView.UseSimpleView = m_bSimpleTanView;
			Debug.Assert(m_bShowTanIndices == m_menuViewTanIndices.Checked);
			mw.TanView.ShowIndices = m_bShowTanIndices;

			Program.Config.MainWindow.ListSorting = m_pListSorter;

			SerializeMruList(true);

			// mw.ShowGridLines = m_lvEntries.GridLines;

			AppConfigSerializer.Save(Program.Config);
		}

		private void SaveWindowPositionAndSize()
		{
			FormWindowState ws = this.WindowState;

			if(ws == FormWindowState.Normal)
			{
				Program.Config.MainWindow.X = this.Location.X;
				Program.Config.MainWindow.Y = this.Location.Y;
				Program.Config.MainWindow.Width = this.Size.Width;
				Program.Config.MainWindow.Height = this.Size.Height;
			}

			if((ws == FormWindowState.Normal) || (ws == FormWindowState.Maximized))
			{
				Program.Config.MainWindow.SplitterHorizontalFrac =
					(float)m_splitHorizontal.SplitterDistance /
					(float)m_splitHorizontal.Height;
				Program.Config.MainWindow.SplitterVerticalFrac =
					(float)m_splitVertical.SplitterDistance /
					(float)m_splitVertical.Width;
			}

			// Program.Config.MainWindow.Maximized = (ws == FormWindowState.Maximized);
		}

		/// <summary>
		/// Update the UI state, i.e. enable/disable menu items depending on the state
		/// of the database (open, closed, locked, modified) and the selected items in
		/// the groups and entries list. You must call this function after all
		/// state-changing operations. For example, if you add a new entry the state
		/// needs to be updated (as the database has been modified) and you must call
		/// this function.
		/// </summary>
		/// <param name="bSetModified">If this parameter is <c>true</c>, the currently
		/// opened database is marked as modified.</param>
		private void UpdateUIState(bool bSetModified)
		{
			UpdateUIState(bSetModified, null);
		}

		private void UpdateUIState(bool bSetModified, Control cOptFocus)
		{
			NotifyUserActivity();
			m_bUpdateUIStateOnce = false; // We do it now

			MainAppState s = GetMainAppState();

			if(s.DatabaseOpened && bSetModified)
				m_docMgr.ActiveDatabase.Modified = true;

			bool bGroupsEnabled = m_tvGroups.Enabled;
			if(bGroupsEnabled && !s.DatabaseOpened)
			{
				m_tvGroups.BackColor = AppDefs.ColorControlDisabled;
				m_tvGroups.Enabled = false;
			}
			else if(!bGroupsEnabled && s.DatabaseOpened)
			{
				m_tvGroups.Enabled = true;
				m_tvGroups.BackColor = AppDefs.ColorControlNormal;
			}

			m_lvEntries.Enabled = s.DatabaseOpened;

			m_statusPartSelected.Text = s.EntriesSelected.ToString() +
				" " + KPRes.OfLower + " " + s.EntriesCount.ToString() +
				" " + KPRes.SelectedLower;
			SetStatusEx(null);

			string strWindowText = string.Empty;
			string strNtfText = string.Empty;

			if(s.FileLocked)
			{
				IOConnectionInfo iocLck = m_docMgr.ActiveDocument.LockedIoc;

				strWindowText = iocLck.Path + @" [" + KPRes.Locked +
					@"] - " + PwDefs.ProductName;

				string strNtfPre = PwDefs.ShortProductName + " - " +
					KPRes.WorkspaceLocked + MessageService.NewLine;

				strNtfText = strNtfPre + WinUtil.CompactPath(iocLck.Path, 63 -
					strNtfPre.Length);

				Icon icoDisposable, icoAssignable;
				CreateColorizedIcon(new Icon("/usr/share/keepass2/QuadLocked.ico"), false,
					ref m_kvpIcoTrayLocked, out icoAssignable, out icoDisposable);
				m_ntfTray.Icon = icoAssignable;
				if(icoDisposable != null) icoDisposable.Dispose();

				TaskbarList.SetOverlayIcon(this, new Icon("/usr/share/keepass2/LockOverlay.ico"),
					KPRes.Locked);
				NativeMethods.EnableWindowPeekPreview(this.Handle, false);
			}
			else if(s.DatabaseOpened == false)
			{
				strWindowText = PwDefs.ProductName;
				strNtfText = strWindowText;

				Icon icoDisposable, icoAssignable;
				CreateColorizedIcon(new Icon("/usr/share/keepass2/QuadNormal.ico"), false,
					ref m_kvpIcoTrayNormal, out icoAssignable, out icoDisposable);
				m_ntfTray.Icon = icoAssignable;
				if(icoDisposable != null) icoDisposable.Dispose();

				TaskbarList.SetOverlayIcon(this, null, string.Empty);
				NativeMethods.EnableWindowPeekPreview(this.Handle, true);
			}
			else // Database open and not locked
			{
				string strFileDesc;
				if(Program.Config.MainWindow.ShowFullPathInTitle)
					strFileDesc = m_docMgr.ActiveDatabase.IOConnectionInfo.GetDisplayName();
				else
					strFileDesc = UrlUtil.GetFileName(
						m_docMgr.ActiveDatabase.IOConnectionInfo.Path);

				strFileDesc = WinUtil.CompactPath(strFileDesc, 63 -
					PwDefs.ProductName.Length - 4);

				if(m_docMgr.ActiveDatabase.Modified)
					strWindowText = strFileDesc + "* - " + PwDefs.ProductName;
				else
					strWindowText = strFileDesc + " - " + PwDefs.ProductName;

				string strNtfPre = PwDefs.ProductName + MessageService.NewLine;
				strNtfText = strNtfPre + WinUtil.CompactPath(
					m_docMgr.ActiveDatabase.IOConnectionInfo.Path, 63 - strNtfPre.Length);

				Icon icoDisposable, icoAssignable;
				CreateColorizedIcon(new Icon("/usr/share/keepass2/QuadNormal.ico"), false,
					ref m_kvpIcoTrayNormal, out icoAssignable, out icoDisposable);
				m_ntfTray.Icon = icoAssignable;
				if(icoDisposable != null) icoDisposable.Dispose();

				TaskbarList.SetOverlayIcon(this, null, string.Empty);
				NativeMethods.EnableWindowPeekPreview(this.Handle, true);
			}

			// Clip the strings again (it could be that a translator used
			// a string in KPRes that is too long to be displayed)
			this.Text = StrUtil.CompactString3Dots(strWindowText, 63);
			m_ntfTray.Text = StrUtil.CompactString3Dots(strNtfText, 63);

			Icon icoToDispose, icoToAssign;
			if(CreateColorizedIcon(new Icon("/usr/share/keepass2/KeePass.ico"), true,
				ref m_kvpIcoMain, out icoToAssign, out icoToDispose))
				this.Icon = icoToAssign;
			if(icoToDispose != null) icoToDispose.Dispose();

			// Main menu
			m_menuFileSaveAs.Enabled = m_menuFileSaveAsLocal.Enabled =
				m_menuFileSaveAsUrl.Enabled = m_menuFileSaveAsCopy.Enabled =
				m_menuFileDbSettings.Enabled = m_menuFileChangeMasterKey.Enabled =
				m_menuFilePrint.Enabled = s.DatabaseOpened;

			m_menuFileClose.Enabled = (s.DatabaseOpened || s.FileLocked);

			m_menuFileLock.Enabled = m_tbLockWorkspace.Enabled = s.EnableLockCmd;

			m_menuEditFind.Enabled = m_menuToolsGeneratePwList.Enabled =
				m_menuToolsTanWizard.Enabled =
				m_menuEditShowAllEntries.Enabled = m_menuEditShowExpired.Enabled =
				m_menuEditShowByTag.Enabled = s.DatabaseOpened;
			m_menuToolsDbMaintenance.Enabled = m_menuToolsDbDelDupEntries.Enabled =
				m_menuToolsDbDelEmptyGroups.Enabled = m_menuToolsDbDelUnusedIcons.Enabled =
				s.DatabaseOpened;

			m_menuFileImport.Enabled = m_menuFileExport.Enabled = s.DatabaseOpened;

			m_menuFileSync.Enabled = m_menuFileSyncFile.Enabled =
				m_menuFileSyncUrl.Enabled = (s.DatabaseOpened &&
				m_docMgr.ActiveDatabase.IOConnectionInfo.IsLocalFile() &&
				(m_docMgr.ActiveDatabase.IOConnectionInfo.Path.Length > 0));

			m_tbFind.Enabled = m_tbViewsShowAll.Enabled = m_tbViewsShowExpired.Enabled =
				s.DatabaseOpened;
			m_tbEntryViewsDropDown.Enabled = s.DatabaseOpened;

			if(Program.Config.MainWindow.DisableSaveIfNotModified)
			{
				m_tbSaveDatabase.Image = m_imgFileSaveEnabled;
				m_menuFileSave.Enabled = m_tbSaveDatabase.Enabled = (s.DatabaseOpened &&
					m_docMgr.ActiveDatabase.Modified);
			}
			else
			{
				m_tbSaveDatabase.Image = (m_docMgr.ActiveDatabase.Modified ?
					m_imgFileSaveEnabled : m_imgFileSaveDisabled);
				m_menuFileSave.Enabled = m_tbSaveDatabase.Enabled = s.DatabaseOpened;
			}

			m_tbQuickFind.Enabled = s.DatabaseOpened;

			m_tbAddEntry.Enabled = s.DatabaseOpened;

			PwEntry pe = s.SelectedEntry;
			ShowEntryDetails(pe);

			m_tbCopyUserName.Enabled = s.CanCopyUserName;
			m_tbCopyPassword.Enabled = s.CanCopyPassword;

			m_menuFileLock.Text = s.LockUnlock;
			string strLockText = StrUtil.RemoveAccelerator(s.LockUnlock);
			m_tbLockWorkspace.Text = m_ctxTrayLock.Text = strLockText;
			m_tbLockWorkspace.ToolTipText = strLockText + " (" +
				m_menuFileLock.ShortcutKeyDisplayString + ")";

			m_tabMain.Visible = m_tbSaveAll.Visible = m_tbCloseTab.Visible =
				(m_docMgr.DocumentCount > 1);
			m_tbCloseTab.Enabled = (s.DatabaseOpened || s.FileLocked);

			bool bAtLeastOneModified = false;
			foreach(TabPage tabPage in m_tabMain.TabPages)
			{
				PwDocument dsPage = (PwDocument)tabPage.Tag;
				bAtLeastOneModified |= dsPage.Database.Modified;

				string strTabText = tabPage.Text;
				if(dsPage.Database.Modified && !strTabText.EndsWith("*"))
					tabPage.Text += "*";
				else if(!dsPage.Database.Modified && strTabText.EndsWith("*"))
					tabPage.Text = strTabText.Substring(0, strTabText.Length - 1);
			}

			// m_tbSaveAll.Image = (bAtLeastOneModified ? m_imgFileSaveAllEnabled :
			//	m_imgFileSaveAllDisabled);
			m_tbSaveAll.Enabled = bAtLeastOneModified;

			UpdateUITabs();
			UpdateLinkedMenuItems();

			if(cOptFocus != null) ResetDefaultFocus(cOptFocus);

			if(this.UIStateUpdated != null) this.UIStateUpdated(this, EventArgs.Empty);
			Program.TriggerSystem.RaiseEvent(EcasEventIDs.UpdatedUIState);
		}

		private MainAppState UpdateUIGroupCtxState(MainAppState? stOpt)
		{
			MainAppState s = (stOpt.HasValue ? stOpt.Value : GetMainAppState());

			PwGroup pg = GetSelectedGroup();
			PwGroup pgParent = ((pg != null) ? pg.ParentGroup : null);
			PwDatabase pd = m_docMgr.ActiveDatabase;
			if((pd != null) && !pd.IsOpen) pd = null; // Null if closed
			PwGroup pgRoot = ((pd != null) ? pd.RootGroup : null);

			bool bChildOps = (s.DatabaseOpened && (pg != pgRoot));
			bool bMoveOps = (bChildOps && (pgParent != null) &&
				(pgParent.Groups.UCount > 1));
			uint uSubGroups = 0, uSubEntries = 0;
			if(pg != null) pg.GetCounts(true, out uSubGroups, out uSubEntries);

			m_ctxGroupAdd.Enabled = m_ctxGroupEdit.Enabled = m_ctxGroupFind.Enabled =
				m_ctxGroupPrint.Enabled = s.DatabaseOpened;

			m_ctxGroupDelete.Enabled = bChildOps;

			m_ctxGroupMoveToTop.Enabled = m_ctxGroupMoveOneUp.Enabled =
				(bMoveOps && (pgParent.Groups.IndexOf(pg) >= 1));
			m_ctxGroupMoveOneDown.Enabled = m_ctxGroupMoveToBottom.Enabled =
				(bMoveOps && (pgParent.Groups.IndexOf(pg) < ((int)pgParent.Groups.UCount - 1)));

			m_ctxGroupSort.Enabled = ((pg != null) && (pg.Groups.UCount > 1));
			m_ctxGroupSortRec.Enabled = (uSubGroups > 1);

			bool bShowEmpty = false, bEnableEmpty = false;
			if((pd != null) && pd.RecycleBinEnabled)
			{
				PwGroup pgRecycleBin = pd.RootGroup.FindGroup(pd.RecycleBinUuid, true);
				bShowEmpty = ((pgRecycleBin != null) && (pg == pgRecycleBin));
				if(bShowEmpty)
					bEnableEmpty = ((pg.Groups.UCount > 0) || (pg.Entries.UCount > 0));
			}
			m_ctxGroupEmpty.Enabled = bEnableEmpty;
			m_ctxGroupEmpty.Visible = bShowEmpty;

			return s;
		}

		private MainAppState UpdateUIEntryCtxState(MainAppState? stOpt)
		{
			MainAppState s = (stOpt.HasValue ? stOpt.Value : GetMainAppState());

			m_ctxEntryAdd.Enabled = s.DatabaseOpened;
			m_ctxEntryEdit.Enabled = (s.EntriesSelected == 1);
			m_ctxEntryDelete.Enabled = (s.EntriesSelected > 0);

			m_ctxEntryDuplicate.Enabled = m_ctxEntryMassSetIcon.Enabled =
				m_ctxEntrySelectedPrint.Enabled = m_ctxEntrySelectedExport.Enabled =
				(s.EntriesSelected > 0);

			m_ctxEntryMoveToTop.Enabled = m_ctxEntryMoveToBottom.Enabled =
				((m_pListSorter.Column < 0) && (s.EntriesSelected > 0));
			m_ctxEntryMoveOneDown.Enabled = m_ctxEntryMoveOneUp.Enabled =
				((m_pListSorter.Column < 0) && (s.EntriesSelected == 1));

			m_ctxEntrySelectAll.Enabled = (s.DatabaseOpened && (s.EntriesCount > 0));

			m_ctxEntryClipCopy.Enabled = (s.EntriesSelected > 0);
			// For the 'Paste' command, see the menu drop-down opening handler

			m_ctxEntryColorStandard.Enabled = m_ctxEntryColorLightRed.Enabled =
				m_ctxEntryColorLightGreen.Enabled = m_ctxEntryColorLightBlue.Enabled =
				m_ctxEntryColorLightYellow.Enabled = m_ctxEntryColorCustom.Enabled =
				(s.EntriesSelected > 0);
			m_ctxEntrySelectedNewTag.Enabled = (s.EntriesSelected > 0);

			PwEntry pe = s.SelectedEntry;

			m_ctxEntryCopyUserName.Enabled = s.CanCopyUserName;
			m_ctxEntryCopyPassword.Enabled = s.CanCopyPassword;
			m_ctxEntryUrlOpenInInternal.Enabled = ((s.EntriesSelected == 1) &&
				(pe != null) && !pe.Strings.GetSafe(PwDefs.UrlField).IsEmpty);
			m_ctxEntryOpenUrl.Enabled = m_ctxEntryCopyUrl.Enabled =
				((s.EntriesSelected > 1) || ((pe != null) &&
				!pe.Strings.GetSafe(PwDefs.UrlField).IsEmpty));

			if(pe != null)
			{
				m_ctxEntryPerformAutoType.Enabled = (pe.GetAutoTypeEnabled() &&
					(s.EntriesSelected == 1));
				m_ctxEntrySaveAttachedFiles.Enabled = ((pe.Binaries.UCount > 0) ||
					(s.EntriesSelected >= 2));
			}
			else // pe == null
			{
				m_ctxEntryPerformAutoType.Enabled = false;
				m_ctxEntrySaveAttachedFiles.Enabled = false;
			}

			m_ctxEntrySaveAttachedFiles.Visible = m_ctxEntrySaveAttachedFiles.Enabled;

			m_ctxEntryCopyUserName.Visible = !s.IsOneTan;
			m_ctxEntryUrl.Visible = !s.IsOneTan;
			m_ctxEntryCopyPassword.Text = (s.IsOneTan ? KPRes.CopyTanMenu :
				KPRes.CopyPasswordMenu);

			return s;
		}

		private MainAppState GetMainAppState()
		{
			MainAppState s = new MainAppState();
			s.FileLocked = IsFileLocked(null);
			s.DatabaseOpened = m_docMgr.ActiveDatabase.IsOpen;
			s.EntriesCount = (s.DatabaseOpened ? m_lvEntries.Items.Count : 0);
			s.EntriesSelected = (s.DatabaseOpened ? m_lvEntries.SelectedIndices.Count : 0);
			s.EnableLockCmd = (s.DatabaseOpened || s.FileLocked);
			s.NoWindowShown = (GlobalWindowManager.WindowCount == 0);
			s.SelectedEntry = GetSelectedEntry(true);
			s.CanCopyUserName = ((s.EntriesSelected == 1) && (s.SelectedEntry != null) &&
				!s.SelectedEntry.Strings.GetSafe(PwDefs.UserNameField).IsEmpty);
			s.CanCopyPassword = ((s.EntriesSelected == 1) && (s.SelectedEntry != null) &&
				!s.SelectedEntry.Strings.GetSafe(PwDefs.PasswordField).IsEmpty);

			s.IsOneTan = (s.EntriesSelected == 1);
			if(s.SelectedEntry != null)
				s.IsOneTan &= PwDefs.IsTanEntry(s.SelectedEntry);
			else s.IsOneTan = false;

			s.LockUnlock = (s.FileLocked ? KPRes.LockMenuUnlock : KPRes.LockMenuLock);

			return s;
		}

		/// <summary>
		/// Set the main status bar text.
		/// </summary>
		/// <param name="strStatusText">New status bar text.</param>
		public void SetStatusEx(string strStatusText)
		{
			if(strStatusText == null) m_statusPartInfo.Text = KPRes.Ready;
			else m_statusPartInfo.Text = strStatusText;
		}

		private void UpdateClipboardStatus()
		{
			// Fix values in case the maximum time has been changed in the
			// options while the countdown is running
			if((m_nClipClearMax < 0) && (m_nClipClearCur > 0))
				m_nClipClearCur = 0;
			else if((m_nClipClearCur > m_nClipClearMax) && (m_nClipClearMax >= 0))
				m_nClipClearCur = m_nClipClearMax;

			if((m_nClipClearCur > 0) && (m_nClipClearMax > 0))
				m_statusClipboard.Value = ((m_nClipClearCur * 100) / m_nClipClearMax);
			else if(m_nClipClearCur == 0)
				m_statusClipboard.Visible = false;
		}

		/// <summary>
		/// Start the clipboard countdown (set the current tick count to the
		/// maximum value and decrease it each second -- at 0 the clipboard
		/// is cleared automatically). This function is asynchronous.
		/// </summary>
		public void StartClipboardCountdown()
		{
			if(m_nClipClearMax >= 0)
			{
				m_nClipClearCur = m_nClipClearMax;

				m_statusClipboard.Visible = true;
				UpdateClipboardStatus();

				string strText = KPRes.ClipboardDataCopied + " " +
					KPRes.ClipboardClearInSeconds + ".";
				strText = strText.Replace(@"[PARAM]", m_nClipClearMax.ToString());

				SetStatusEx(strText);

				// if(m_ntfTray.Visible)
				//	m_ntfTray.ShowBalloonTip(0, KPRes.ClipboardAutoClear,
				//		strText, ToolTipIcon.Info);
			}
		}

		/// <summary>
		/// Gets the focused or first selected entry.
		/// </summary>
		/// <returns>Matching entry or <c>null</c>.</returns>
		public PwEntry GetSelectedEntry(bool bRequireSelected)
		{
			return GetSelectedEntry(bRequireSelected, false);
		}

		public PwEntry GetSelectedEntry(bool bRequireSelected, bool bGetLastSelectedEntry)
		{
			if(!m_docMgr.ActiveDatabase.IsOpen) return null;

			if(!bRequireSelected)
			{
				ListViewItem lviFocused = m_lvEntries.FocusedItem;
				if(lviFocused != null) return ((PwListItem)lviFocused.Tag).Entry;
			}

			ListView.SelectedListViewItemCollection coll = m_lvEntries.SelectedItems;
			if(coll.Count > 0)
			{
				ListViewItem lvi = coll[bGetLastSelectedEntry ? (coll.Count - 1) : 0];
				if(lvi != null) return ((PwListItem)lvi.Tag).Entry;
			}

			return null;
		}

		/// <summary>
		/// Get all selected entries.
		/// </summary>
		/// <returns>A list of all selected entries.</returns>
		public PwEntry[] GetSelectedEntries()
		{
			if(!m_docMgr.ActiveDatabase.IsOpen) return null;

			ListView.SelectedListViewItemCollection coll = m_lvEntries.SelectedItems;
			if((coll == null) || (coll.Count == 0)) return null;

			PwEntry[] vSelected = new PwEntry[coll.Count];
			for(int i = 0; i < coll.Count; ++i)
				vSelected[i] = ((PwListItem)coll[i].Tag).Entry;

			return vSelected;
		}

		public uint GetSelectedEntriesCount()
		{
			if(!m_docMgr.ActiveDatabase.IsOpen) return 0;

			return (uint)m_lvEntries.SelectedIndices.Count;
		}

		public PwGroup GetSelectedEntriesAsGroup()
		{
			PwGroup pg = new PwGroup(true, true);

			// Copying group properties would confuse users
			// PwGroup pgSel = GetSelectedGroup();
			// if(pgSel != null)
			// {
			//	pg.Name = pgSel.Name;
			//	pg.IconId = pgSel.IconId;
			//	pg.CustomIconUuid = pgSel.CustomIconUuid;
			// }

			PwEntry[] vSel = GetSelectedEntries();
			if((vSel == null) || (vSel.Length == 0)) return pg;

			foreach(PwEntry pe in vSel) pg.AddEntry(pe, false);

			return pg;
		}

		/// <summary>
		/// Get the currently selected group. The selected <c>TreeNode</c> is
		/// automatically translated to a <c>PwGroup</c>.
		/// </summary>
		/// <returns>Selected <c>PwGroup</c>.</returns>
		public PwGroup GetSelectedGroup()
		{
			if(!m_docMgr.ActiveDatabase.IsOpen) return null;

			TreeNode tn = m_tvGroups.SelectedNode;
			if(tn == null) return null;
			return (tn.Tag as PwGroup);
		}

		/// <summary>
		/// Create or set an entry list view item.
		/// </summary>
		/// <param name="pe">Entry.</param>
		/// <param name="lviTarget">If <c>null</c>, a new list view item is
		/// created and added to the list (a group is created if necessary).
		/// If not <c>null</c>, the properties are stored in this item (no
		/// list view group is created and the list view item is not added
		/// to the list).</param>
		/// <returns>Created or modified list view item.</returns>
		private ListViewItem SetListEntry(PwEntry pe, ListViewItem lviTarget)
		{
			if(pe == null) { Debug.Assert(false); return null; }

			ListViewItem lvi = (lviTarget ?? new ListViewItem());

			PwListItem pli = new PwListItem(pe);
			if(lviTarget == null) lvi.Tag = pli; // Lock below (when adding it)
			else
			{
				lock(m_asyncListUpdate.ListEditSyncObject) { lvi.Tag = pli; }
			}

			int iIndexHint = ((lviTarget != null) ? lviTarget.Index :
				m_lvEntries.Items.Count);

			if(pe.Expires && (pe.ExpiryTime <= m_dtCachedNow))
			{
				lvi.ImageIndex = (int)PwIcon.Expired;
				if(m_fontExpired != null) lvi.Font = m_fontExpired;
			}
			else // Not expired
			{
				// Reset font, if item was expired previously (i.e. has expired font)
				if((lviTarget != null) && (lvi.ImageIndex == (int)PwIcon.Expired))
					lvi.Font = m_lvEntries.Font;

				if(pe.CustomIconUuid.EqualsValue(PwUuid.Zero))
					lvi.ImageIndex = (int)pe.IconId;
				else
					lvi.ImageIndex = (int)PwIcon.Count +
						m_docMgr.ActiveDatabase.GetCustomIconIndex(pe.CustomIconUuid);
			}

			if(m_bEntryGrouping && (lviTarget == null))
			{
				PwGroup pgContainer = pe.ParentGroup;
				PwGroup pgLast = ((m_lvgLastEntryGroup != null) ?
					(PwGroup)m_lvgLastEntryGroup.Tag : null);

				Debug.Assert(pgContainer != null);
				if(pgContainer != null)
				{
					if(pgContainer != pgLast)
					{
						m_lvgLastEntryGroup = new ListViewGroup(
							pgContainer.GetFullPath());
						m_lvgLastEntryGroup.Tag = pgContainer;

						m_lvEntries.Groups.Add(m_lvgLastEntryGroup);
					}

					lvi.Group = m_lvgLastEntryGroup;
				}
			}

			if(!pe.ForegroundColor.IsEmpty)
				lvi.ForeColor = pe.ForegroundColor;
			else if(lviTarget != null) lvi.ForeColor = m_lvEntries.ForeColor;
			else { Debug.Assert(UIUtil.ColorsEqual(lvi.ForeColor, m_lvEntries.ForeColor)); }

			if(!pe.BackgroundColor.IsEmpty)
				lvi.BackColor = pe.BackgroundColor;
			// else if(Program.Config.MainWindow.EntryListAlternatingBgColors &&
			//	((m_lvEntries.Items.Count & 1) == 1))
			//	lvi.BackColor = m_clrAlternateItemBgColor;
			else if(lviTarget != null) lvi.BackColor = m_lvEntries.BackColor;
			else { Debug.Assert(UIUtil.ColorsEqual(lvi.BackColor, m_lvEntries.BackColor)); }

			bool bAsync;

			// m_bOnlyTans &= PwDefs.IsTanEntry(pe);
			if(m_bShowTanIndices && m_bOnlyTans)
			{
				string strIndex = pe.Strings.ReadSafe(PwDefs.TanIndexField);

				if(strIndex.Length > 0) lvi.Text = strIndex;
				else lvi.Text = PwDefs.TanTitle;
			}
			else
			{
				string strMain = GetEntryFieldEx(pe, 0, true, out bAsync);
				lvi.Text = strMain;
				if(bAsync)
					m_asyncListUpdate.Queue(strMain, pli, iIndexHint, 0,
						AsyncPwListUpdate.SprCompileFn);
			}

			int nColumns = m_lvEntries.Columns.Count;
			if(lviTarget == null)
			{
				for(int iColumn = 1; iColumn < nColumns; ++iColumn)
				{
					string strSub = GetEntryFieldEx(pe, iColumn, true, out bAsync);
					lvi.SubItems.Add(strSub);
					if(bAsync)
						m_asyncListUpdate.Queue(strSub, pli, iIndexHint, iColumn,
							AsyncPwListUpdate.SprCompileFn);
				}
			}
			else
			{
				int nSubItems = lvi.SubItems.Count;
				for(int iColumn = 1; iColumn < nColumns; ++iColumn)
				{
					string strSub = GetEntryFieldEx(pe, iColumn, true, out bAsync);

					if(iColumn < nSubItems) lvi.SubItems[iColumn].Text = strSub;
					else lvi.SubItems.Add(strSub);

					if(bAsync)
						m_asyncListUpdate.Queue(strSub, pli, iIndexHint, iColumn,
							AsyncPwListUpdate.SprCompileFn);
				}

				Debug.Assert(lvi.SubItems.Count == nColumns);
			}

			if(lviTarget == null)
			{
				lock(m_asyncListUpdate.ListEditSyncObject)
				{
					m_lvEntries.Items.Add(lvi);
				}
			}
			return lvi;
		}

		private void AddEntriesToList(PwObjectList<PwEntry> vEntries)
		{
			if(vEntries == null) { Debug.Assert(false); return; }

			m_bEntryGrouping = m_lvEntries.ShowGroups;

			ListViewStateEx lvseCachedState = new ListViewStateEx(m_lvEntries);
			foreach(PwEntry pe in vEntries)
			{
				if(pe == null) { Debug.Assert(false); continue; }

				if(m_bEntryGrouping)
				{
					PwGroup pg = pe.ParentGroup;

					foreach(ListViewGroup lvg in m_lvEntries.Groups)
					{
						PwGroup pgList = (lvg.Tag as PwGroup);
						Debug.Assert(pgList != null);
						if((pgList != null) && (pg == pgList))
						{
							m_lvgLastEntryGroup = lvg;
							break;
						}
					}
				}

				SetListEntry(pe, null);
			}

			Debug.Assert(lvseCachedState.CompareTo(m_lvEntries));

			UIUtil.SetAlternatingBgColors(m_lvEntries, m_clrAlternateItemBgColor,
				Program.Config.MainWindow.EntryListAlternatingBgColors);
		}

		/// <summary>
		/// Update the group list. This function completely rebuilds the groups
		/// view. You must call this function after you made any changes to the
		/// groups structure of the currently opened database.
		/// </summary>
		/// <param name="pgNewSelected">If this parameter is <c>null</c>, the
		/// previously selected group is selected again (after the list was
		/// rebuilt). If this parameter is non-<c>null</c>, the specified
		/// <c>PwGroup</c> is selected after the function returns.</param>
		private void UpdateGroupList(PwGroup pgNewSelected)
		{
			NotifyUserActivity();

			PwDatabase pwDb = m_docMgr.ActiveDatabase;
			PwGroup pg = (pgNewSelected ?? GetSelectedGroup());

			UpdateImageLists();

			m_tvGroups.BeginUpdate();
			m_tvGroups.Nodes.Clear();

			m_dtCachedNow = DateTime.Now;

			TreeNode tnRoot = null;
			if(pwDb.RootGroup != null)
			{
				int nIconID = ((!pwDb.RootGroup.CustomIconUuid.EqualsValue(PwUuid.Zero)) ?
					((int)PwIcon.Count + pwDb.GetCustomIconIndex(
					pwDb.RootGroup.CustomIconUuid)) : (int)pwDb.RootGroup.IconId);
				if(pwDb.RootGroup.Expires && (pwDb.RootGroup.ExpiryTime <= m_dtCachedNow))
					nIconID = (int)PwIcon.Expired;

				tnRoot = new TreeNode(pwDb.RootGroup.Name, // + GetGroupSuffixText(pwDb.RootGroup),
					nIconID, nIconID);

				tnRoot.Tag = pwDb.RootGroup;
				if(m_fontBoldTree != null) tnRoot.NodeFont = m_fontBoldTree;
				UIUtil.SetGroupNodeToolTip(tnRoot, pwDb.RootGroup);

				m_tvGroups.Nodes.Add(tnRoot);
			}

			TreeNode tnSelected = null;
			RecursiveAddGroup(tnRoot, pwDb.RootGroup, pg, ref tnSelected);

			if(tnRoot != null) tnRoot.Expand();

			m_tvGroups.EndUpdate();

			if(tnSelected != null)
			{
				// Ensure all parent tree nodes are expanded
				List<TreeNode> lParents = new List<TreeNode>();
				TreeNode tnUp = tnSelected;
				while(true)
				{
					tnUp = tnUp.Parent;
					if(tnUp == null) break;
					lParents.Add(tnUp);
				}
				for(int i = (lParents.Count - 1); i >= 0; --i)
					lParents[i].Expand();

				m_tvGroups.SelectedNode = tnSelected;
			}
			else if(m_tvGroups.Nodes.Count > 0)
				m_tvGroups.SelectedNode = m_tvGroups.Nodes[0];
		}

		/// <summary>
		/// Update the entries list. This function completely rebuilds the entries
		/// list. You must call this function after you've made any changes to
		/// the entries of the currently selected group. Note that if you only
		/// made small changes (like editing an existing entry), the
		/// <c>RefreshEntriesList</c> function could be a better choice, as it only
		/// updates currently listed items and doesn't rebuild the whole list as
		/// <c>UpdateEntryList</c>.
		/// </summary>
		/// <param name="pgSelected">Group whose entries should be shown. If this
		/// parameter is <c>null</c>, the entries of the currently selected group
		/// (groups view) are displayed, otherwise the entries of the <c>pgSelected</c>
		/// group are displayed.</param>
		private void UpdateEntryList(PwGroup pgSelected, bool bOnlyUpdateCurrentlyShown)
		{
			NotifyUserActivity();

			UpdateImageLists();

			PwEntry peTop = GetTopEntry(), peFocused = GetSelectedEntry(false);
			PwEntry[] vSelected = GetSelectedEntries();
			int iScrollY = NativeMethods.GetScrollPosY(m_lvEntries.Handle);

			bool bSubEntries = Program.Config.MainWindow.ShowEntriesOfSubGroups;

			PwGroup pg = (pgSelected ?? GetSelectedGroup());

			if(bOnlyUpdateCurrentlyShown)
			{
				Debug.Assert(pgSelected == null);
				pg = GetCurrentEntries();
			}

			PwObjectList<PwEntry> pwlSource = ((pg != null) ?
				pg.GetEntries(bSubEntries) : new PwObjectList<PwEntry>());

			m_bOnlyTans = ListContainsOnlyTans(pwlSource);

			m_asyncListUpdate.CancelPendingUpdatesAsync();

			m_lvEntries.BeginUpdate();
			lock(m_asyncListUpdate.ListEditSyncObject)
			{
				m_lvEntries.Items.Clear();
			}
			m_lvEntries.Groups.Clear();
			m_lvgLastEntryGroup = null;

			// m_bEntryGrouping = (((pg != null) ? pg.IsVirtual : false) || bSubEntries);
			m_bEntryGrouping = bSubEntries;
			if(pg != null)
			{
				if(bOnlyUpdateCurrentlyShown && !m_lvEntries.ShowGroups &&
					EntryUtil.EntriesHaveSameParent(pwlSource))
				{
					// Just reorder, don't enable grouping
					EntryUtil.ReorderEntriesAsInDatabase(pwlSource,
						m_docMgr.ActiveDatabase);
					peTop = null; // Don't scroll to previous top item
				}
				else m_bEntryGrouping |= pg.IsVirtual;
			}
			m_lvEntries.ShowGroups = m_bEntryGrouping;

			int nTopIndex = -1;
			ListViewItem lviFocused = null;

			m_dtCachedNow = DateTime.Now;
			ListViewStateEx lvseCachedState = new ListViewStateEx(m_lvEntries);

			if(pg != null)
			{
				foreach(PwEntry pe in pwlSource)
				{
					ListViewItem lvi = SetListEntry(pe, null);

					if(vSelected != null)
					{
						if(Array.IndexOf(vSelected, pe) >= 0)
							lvi.Selected = true;
					}

					if(pe == peTop) nTopIndex = m_lvEntries.Items.Count - 1;
					if(pe == peFocused) lviFocused = lvi;
				}
			}

			Debug.Assert(lvseCachedState.CompareTo(m_lvEntries));

			UIUtil.SetAlternatingBgColors(m_lvEntries, m_clrAlternateItemBgColor,
				Program.Config.MainWindow.EntryListAlternatingBgColors);

			Debug.Assert(m_bEntryGrouping == m_lvEntries.ShowGroups);
			if(m_lvEntries.ShowGroups)
			{
				// Test nTopIndex to ensure we're not scrolling an unrelated list
				if((nTopIndex >= 0) && (iScrollY > 0))
					NativeMethods.Scroll(m_lvEntries, 0, iScrollY);
			}
			else
			{
				if(nTopIndex >= 0)
				{
					m_lvEntries.EnsureVisible(m_lvEntries.Items.Count - 1);
					m_lvEntries.EnsureVisible(nTopIndex);
				}
			}

			if(lviFocused != null)
				UIUtil.SetFocusedItem(m_lvEntries, lviFocused, false);

			View view = m_lvEntries.View;
			if(m_bSimpleTanView)
			{
				if(m_lvEntries.Items.Count == 0)
					m_lvEntries.View = View.Details;
				else if(m_bOnlyTans && (view != View.List))
				{
					// SortPasswordList(false, 0, false);
					m_lvEntries.View = View.List;
				}
				else if(!m_bOnlyTans && (view != View.Details))
					m_lvEntries.View = View.Details;
			}
			else // m_bSimpleTanView == false
			{
				if(view != View.Details)
					m_lvEntries.View = View.Details;
			}

			m_lvEntries.EndUpdate();

			if(Program.Config.MainWindow.EntryListAutoResizeColumns &&
				(m_lvEntries.View == View.Details))
				UIUtil.ResizeColumns(m_lvEntries, true);
		}

		/// <summary>
		/// Refresh the entries list. All currently displayed entries are updated.
		/// If you made changes to the list that change the number of visible entries
		/// (like adding or removing an entry), you must use the <c>UpdateEntryList</c>
		/// function instead.
		/// </summary>
		public void RefreshEntriesList()
		{
			UpdateImageLists(); // Important

			m_lvEntries.BeginUpdate();
			m_dtCachedNow = DateTime.Now;

			foreach(ListViewItem lvi in m_lvEntries.Items)
			{
				SetListEntry(((PwListItem)lvi.Tag).Entry, lvi);
			}

			UIUtil.SetAlternatingBgColors(m_lvEntries, m_clrAlternateItemBgColor,
				Program.Config.MainWindow.EntryListAlternatingBgColors);
			m_lvEntries.EndUpdate();
		}

		private PwEntry GetTopEntry()
		{
			if(m_lvEntries.Items.Count == 0) return null;

			PwEntry peTop = null;
			try
			{
				ListViewItem lviTop = m_lvEntries.TopItem;
				if(lviTop != null) peTop = ((PwListItem)lviTop.Tag).Entry;
			}
			catch(Exception) { }

			return peTop;
		}

		private void RecursiveAddGroup(TreeNode tnParent, PwGroup pgContainer,
			PwGroup pgFind, ref TreeNode tnFound)
		{
			if(pgContainer == null) return;

			TreeNodeCollection tnc;
			if(tnParent == null) tnc = m_tvGroups.Nodes;
			else tnc = tnParent.Nodes;

			PwDatabase pd = m_docMgr.ActiveDatabase;
			foreach(PwGroup pg in pgContainer.Groups)
			{
				bool bExpired = (pg.Expires && (pg.ExpiryTime <= m_dtCachedNow));
				string strName = pg.Name; // + GetGroupSuffixText(pg);

				int nIconID = ((!pg.CustomIconUuid.EqualsValue(PwUuid.Zero)) ?
					((int)PwIcon.Count + pd.GetCustomIconIndex(pg.CustomIconUuid)) :
					(int)pg.IconId);
				if(bExpired) nIconID = (int)PwIcon.Expired;

				TreeNode tn = new TreeNode(strName, nIconID, nIconID);
				tn.Tag = pg;
				UIUtil.SetGroupNodeToolTip(tn, pg);

				if(pd.RecycleBinEnabled && pg.Uuid.EqualsValue(pd.RecycleBinUuid) &&
					(m_fontItalicTree != null))
					tn.NodeFont = m_fontItalicTree;
				else if(bExpired && (m_fontExpired != null))
					tn.NodeFont = m_fontExpired;

				tnc.Add(tn);

				RecursiveAddGroup(tn, pg, pgFind, ref tnFound);

				if(tn.Nodes.Count > 0)
				{
					if((tn.IsExpanded) && (!pg.IsExpanded)) tn.Collapse();
					else if((!tn.IsExpanded) && (pg.IsExpanded)) tn.Expand();
				}

				if(pg == pgFind) tnFound = tn;
			}
		}

		private void SortPasswordList(bool bEnableSorting, int nColumn,
			SortOrder? soForce, bool bUpdateEntryList)
		{
			AceColumnType colType = GetAceColumn(nColumn).Type;

			if(bEnableSorting)
			{
				bool bSortTimes = AceColumn.IsTimeColumn(colType);
				bool bSortNaturally = (colType != AceColumnType.Uuid);

				int nOldColumn = m_pListSorter.Column;
				SortOrder sortOrder = m_pListSorter.Order;

				if(soForce.HasValue) sortOrder = soForce.Value;
				else if(nColumn == nOldColumn)
				{
					if(sortOrder == SortOrder.None)
						sortOrder = SortOrder.Ascending;
					else if(sortOrder == SortOrder.Ascending)
						sortOrder = SortOrder.Descending;
					else if(sortOrder == SortOrder.Descending)
						sortOrder = SortOrder.None;
					else { Debug.Assert(false); }
				}
				else sortOrder = SortOrder.Ascending;

				if(sortOrder != SortOrder.None)
				{
					m_pListSorter = new ListSorter(nColumn, sortOrder,
						bSortNaturally, bSortTimes);
					m_lvEntries.ListViewItemSorter = m_pListSorter;

					// Workaround for XP bug
					if(bUpdateEntryList && !KeePassLib.Native.NativeLib.IsUnix() &&
						WinUtil.IsWindowsXP)
						UpdateEntryList(null, true); // Only required on XP
				}
				else
				{
					m_pListSorter = new ListSorter();
					m_lvEntries.ListViewItemSorter = null;

					if(bUpdateEntryList) UpdateEntryList(null, true);
				}
			}
			else // Disable sorting
			{
				m_pListSorter = new ListSorter();
				m_lvEntries.ListViewItemSorter = null;

				if(bUpdateEntryList) UpdateEntryList(null, true);
			}

			UpdateColumnSortingIcons();
			UIUtil.SetAlternatingBgColors(m_lvEntries, m_clrAlternateItemBgColor,
				Program.Config.MainWindow.EntryListAlternatingBgColors);
		}

		private void UpdateColumnSortingIcons()
		{
			if(UIUtil.SetSortIcon(m_lvEntries, m_pListSorter.Column,
				m_pListSorter.Order)) return;

			// if(m_lvEntries.SmallImageList == null) return;

			if(m_pListSorter.Column < 0) { Debug.Assert(m_lvEntries.ListViewItemSorter == null); }

			string strAsc = "  \u2191"; // Must have same length
			string strDsc = "  \u2193"; // Must have same length
			if(WinUtil.IsWindows9x || WinUtil.IsWindows2000 || WinUtil.IsWindowsXP ||
				KeePassLib.Native.NativeLib.IsUnix())
			{
				strAsc = @"  ^";
				strDsc = @"  v";
			}
			else if(WinUtil.IsAtLeastWindowsVista)
			{
				strAsc = "  \u25B3";
				strDsc = "  \u25BD";
			}

			foreach(ColumnHeader ch in m_lvEntries.Columns)
			{
				string strCur = ch.Text, strNew = null;

				if(strCur.EndsWith(strAsc) || strCur.EndsWith(strDsc))
				{
					strNew = strCur.Substring(0, strCur.Length - strAsc.Length);
					strCur = strNew;
				}

				if((ch.Index == m_pListSorter.Column) &&
					(m_pListSorter.Order != SortOrder.None))
				{
					if(m_pListSorter.Order == SortOrder.Ascending)
						strNew = strCur + strAsc;
					else if(m_pListSorter.Order == SortOrder.Descending)
						strNew = strCur + strDsc;
				}

				if(strNew != null) ch.Text = strNew;
			}
		}

		private void ShowEntryView(bool bShow)
		{
			m_menuViewShowEntryView.Checked = bShow;

			Program.Config.MainWindow.EntryView.Show = bShow;

			m_richEntryView.Visible = bShow;
			m_splitHorizontal.Panel2Collapsed = !bShow;
		}

		private void ShowEntryDetails(PwEntry pe)
		{
			if(pe == null)
			{
				m_richEntryView.Text = string.Empty;
				return;
			}

			RichTextBuilder rb = new RichTextBuilder();

			AceFont af = Program.Config.UI.StandardFont;
			Font fontUI = (UISystemFonts.ListFont ?? m_lvEntries.Font);
			// string strFontFace = (af.OverrideUIDefault ? af.Family : fontUI.Name);
			// float fFontSize = (af.OverrideUIDefault ? af.ToFont().SizeInPoints : fontUI.SizeInPoints);
			if(af.OverrideUIDefault) rb.DefaultFont = af.ToFont();
			else rb.DefaultFont = fontUI;

			string strItemSeparator = ((m_splitHorizontal.Orientation == Orientation.Horizontal) ?
				", " : Environment.NewLine);

			// StringBuilder sb = new StringBuilder();
			// StrUtil.InitRtf(sb, strFontFace, fFontSize);

			rb.Append(KPRes.Group, FontStyle.Bold, null, null, ":", " ");
			int nGroupUrlStart = KPRes.Group.Length + 2;
			PwGroup pg = pe.ParentGroup;
			if(pg != null) rb.Append(pg.Name);

			AceMainWindow mw = Program.Config.MainWindow;
			EvAppendEntryField(rb, strItemSeparator, KPRes.Title,
				mw.IsColumnHidden(AceColumnType.Title) ? PwDefs.HiddenPassword :
				pe.Strings.ReadSafe(PwDefs.TitleField), pe);
			EvAppendEntryField(rb, strItemSeparator, KPRes.UserName,
				mw.IsColumnHidden(AceColumnType.UserName) ? PwDefs.HiddenPassword :
				pe.Strings.ReadSafe(PwDefs.UserNameField), pe);
			EvAppendEntryField(rb, strItemSeparator, KPRes.Password,
				mw.IsColumnHidden(AceColumnType.Password) ? PwDefs.HiddenPassword :
				pe.Strings.ReadSafe(PwDefs.PasswordField), pe);
			EvAppendEntryField(rb, strItemSeparator, KPRes.Url,
				mw.IsColumnHidden(AceColumnType.Url) ? PwDefs.HiddenPassword :
				pe.Strings.ReadSafe(PwDefs.UrlField), pe);

			foreach(KeyValuePair<string, ProtectedString> kvp in pe.Strings)
			{
				if(PwDefs.IsStandardField(kvp.Key)) continue;

				string strCustomValue = (mw.ShouldHideCustomString(kvp.Key,
					kvp.Value) ? PwDefs.HiddenPassword : kvp.Value.ReadString());
				EvAppendEntryField(rb, strItemSeparator, kvp.Key, strCustomValue, pe);
			}

			EvAppendEntryField(rb, strItemSeparator, KPRes.CreationTime,
				TimeUtil.ToDisplayString(pe.CreationTime), null);
			EvAppendEntryField(rb, strItemSeparator, KPRes.LastAccessTime,
				TimeUtil.ToDisplayString(pe.LastAccessTime), null);
			EvAppendEntryField(rb, strItemSeparator, KPRes.LastModificationTime,
				TimeUtil.ToDisplayString(pe.LastModificationTime), null);

			if(pe.Expires)
				EvAppendEntryField(rb, strItemSeparator, KPRes.ExpiryTime,
					TimeUtil.ToDisplayString(pe.ExpiryTime), null);

			if(pe.Binaries.UCount > 0)
			{
				StringBuilder sbBinaries = new StringBuilder();

				foreach(KeyValuePair<string, ProtectedBinary> kvpBin in pe.Binaries)
				{
					if(sbBinaries.Length > 0) sbBinaries.Append(", ");
					sbBinaries.Append(kvpBin.Key);
				}

				EvAppendEntryField(rb, strItemSeparator, KPRes.Attachments,
					sbBinaries.ToString(), null);
			}

			EvAppendEntryField(rb, strItemSeparator, KPRes.UrlOverride,
				pe.OverrideUrl, pe);
			EvAppendEntryField(rb, strItemSeparator, KPRes.Tags,
				StrUtil.TagsToString(pe.Tags, true), null);

			string strNotes = (mw.IsColumnHidden(AceColumnType.Notes) ?
				PwDefs.HiddenPassword : pe.Strings.ReadSafe(PwDefs.NotesField));
			if(strNotes.Length != 0)
			{
				rb.AppendLine();
				rb.AppendLine();

				KeyValuePair<string, string> kvpBold = RichTextBuilder.GetStyleIdCodes(
					FontStyle.Bold);
				KeyValuePair<string, string> kvpItalic = RichTextBuilder.GetStyleIdCodes(
					FontStyle.Italic);
				KeyValuePair<string, string> kvpUnderline = RichTextBuilder.GetStyleIdCodes(
					FontStyle.Underline);

				strNotes = strNotes.Replace(@"<b>", kvpBold.Key);
				strNotes = strNotes.Replace(@"</b>", kvpBold.Value);
				strNotes = strNotes.Replace(@"<i>", kvpItalic.Key);
				strNotes = strNotes.Replace(@"</i>", kvpItalic.Value);
				strNotes = strNotes.Replace(@"<u>", kvpUnderline.Key);
				strNotes = strNotes.Replace(@"</u>", kvpUnderline.Value);

				rb.Append(strNotes);
			}

			// sb.Append("\\pard }");
			// m_richEntryView.Rtf = sb.ToString();
			rb.Build(m_richEntryView);

			UIUtil.RtfLinkifyReferences(m_richEntryView, false);

			Debug.Assert(m_richEntryView.HideSelection); // Flicker otherwise
			if(pg != null)
			{
				m_richEntryView.Select(nGroupUrlStart, pg.Name.Length);
				UIUtil.RtfSetSelectionLink(m_richEntryView);
			}

			// Linkify the URL
			string strUrl = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.UrlField),
				GetEntryListSprContext(pe, m_docMgr.SafeFindContainerOf(pe)));
			if(strUrl != PwDefs.HiddenPassword)
				UIUtil.RtfLinkifyText(m_richEntryView, strUrl, false);

			// Linkify the attachments
			foreach(KeyValuePair<string, ProtectedBinary> kvpBin in pe.Binaries)
				UIUtil.RtfLinkifyText(m_richEntryView, kvpBin.Key, false);

			m_richEntryView.Select(0, 0);
		}

		private void EvAppendEntryField(RichTextBuilder rb,
			string strItemSeparator, string strName, string strValue,
			PwEntry peSprCompile)
		{
			if(string.IsNullOrEmpty(strValue)) return;

			rb.Append(strName, FontStyle.Bold, strItemSeparator, null, ":", " ");

			if((peSprCompile == null) || !SprEngine.MightDeref(strValue))
				rb.Append(strValue);
			else
			{
				string strCmp = SprEngine.Compile(strValue,
					GetEntryListSprContext(peSprCompile,
					m_docMgr.SafeFindContainerOf(peSprCompile)));
				if(strCmp == strValue) rb.Append(strValue);
				else
				{
					rb.Append(strCmp + " - ");
					rb.Append(strValue, FontStyle.Italic);
				}
			}
		}

		private void PerformDefaultAction(object sender, EventArgs e, PwEntry pe,
			int colID)
		{
			Debug.Assert(pe != null); if(pe == null) return;

			if(this.DefaultEntryAction != null)
			{
				CancelEntryEventArgs args = new CancelEntryEventArgs(pe, colID);
				this.DefaultEntryAction(sender, args);
				if(args.Cancel) return;
			}

			bool bCnt = false;

			AceColumn col = GetAceColumn(colID);
			AceColumnType colType = col.Type;
			switch(colType)
			{
				case AceColumnType.Title:
					if(PwDefs.IsTanEntry(pe)) OnEntryCopyPassword(sender, e);
					else OnEntryEdit(sender, e);
					break;
				case AceColumnType.UserName:
					OnEntryCopyUserName(sender, e);
					break;
				case AceColumnType.Password:
					OnEntryCopyPassword(sender, e);
					break;
				case AceColumnType.Url:
					PerformDefaultUrlAction(null, false);
					break;
				case AceColumnType.Notes:
					bCnt = ClipboardUtil.CopyAndMinimize(pe.Strings.GetSafe(
						PwDefs.NotesField), true, this, pe, m_docMgr.ActiveDatabase);
					break;
				case AceColumnType.CreationTime:
					bCnt = ClipboardUtil.CopyAndMinimize(TimeUtil.ToDisplayString(
						pe.CreationTime), true, this, pe, null);
					break;
				case AceColumnType.LastAccessTime:
					bCnt = ClipboardUtil.CopyAndMinimize(TimeUtil.ToDisplayString(
						pe.LastAccessTime), true, this, pe, null);
					break;
				case AceColumnType.LastModificationTime:
					bCnt = ClipboardUtil.CopyAndMinimize(TimeUtil.ToDisplayString(
						pe.LastModificationTime), true, this, pe, null);
					break;
				case AceColumnType.ExpiryTime:
					if(pe.Expires)
						bCnt = ClipboardUtil.CopyAndMinimize(TimeUtil.ToDisplayString(
							pe.ExpiryTime), true, this, pe, null);
					else
						bCnt = ClipboardUtil.CopyAndMinimize(m_strNeverExpiresText,
							true, this, pe, null);
					break;
				case AceColumnType.Attachment:
					PerformDefaultAttachmentAction();
					break;
				case AceColumnType.Uuid:
					bCnt = ClipboardUtil.CopyAndMinimize(pe.Uuid.ToHexString(),
						true, this, pe, null);
					break;
				case AceColumnType.CustomString:
					bCnt = ClipboardUtil.CopyAndMinimize(pe.Strings.ReadSafe(
						col.CustomName), true, this, pe, m_docMgr.ActiveDatabase);
					break;
				case AceColumnType.PluginExt:
					if(Program.ColumnProviderPool.SupportsCellAction(col.CustomName))
						Program.ColumnProviderPool.PerformCellAction(col.CustomName, pe);
					else
						bCnt = ClipboardUtil.CopyAndMinimize(
							Program.ColumnProviderPool.GetCellData(col.CustomName, pe),
							true, this, pe, m_docMgr.ActiveDatabase);
					break;
				case AceColumnType.OverrideUrl:
					bCnt = ClipboardUtil.CopyAndMinimize(pe.OverrideUrl,
						true, this, pe, null);
					break;
				case AceColumnType.Tags:
					bCnt = ClipboardUtil.CopyAndMinimize(StrUtil.TagsToString(pe.Tags, true),
						true, this, pe, null);
					break;
				case AceColumnType.ExpiryTimeDateOnly:
					if(pe.Expires)
						bCnt = ClipboardUtil.CopyAndMinimize(TimeUtil.ToDisplayStringDateOnly(
							pe.ExpiryTime), true, this, pe, null);
					else
						bCnt = ClipboardUtil.CopyAndMinimize(m_strNeverExpiresText,
							true, this, pe, null);
					break;
				case AceColumnType.Size:
					bCnt = ClipboardUtil.CopyAndMinimize(StrUtil.FormatDataSizeKB(
						pe.GetSize()), true, this, pe, null);
					break;
				case AceColumnType.HistoryCount:
					EditSelectedEntry(true);
					break;
				default:
					Debug.Assert(false);
					break;
			}

			if(bCnt) StartClipboardCountdown();
		}

		internal void PerformDefaultUrlAction(PwEntry[] vOptEntries, bool bForceOpen)
		{
			PwEntry[] v = (vOptEntries ?? GetSelectedEntries());
			Debug.Assert(v != null); if(v == null) return;

			bool bCopy = Program.Config.MainWindow.CopyUrlsInsteadOfOpening;
			if(bForceOpen) bCopy = false;

			if(bCopy)
			{
				// bool bMinimize = Program.Config.MainWindow.MinimizeAfterClipboardCopy;
				// Form frmMin = (bMinimize ? this : null);

				if(ClipboardUtil.CopyAndMinimize(UrlsToString(v, true), true, this, null, null))
					StartClipboardCountdown();
			}
			else // Open
			{
				foreach(PwEntry pe in v) WinUtil.OpenEntryUrl(pe);
			}
		}

		private void PerformDefaultAttachmentAction()
		{
			PwEntry pe = GetSelectedEntry(false);
			if(pe == null) return;

			if(pe.Binaries.UCount == 0) return;

			foreach(KeyValuePair<string, ProtectedBinary> kvp in pe.Binaries)
			{
				ExecuteBinaryEditView(kvp.Key, kvp.Value);
				break;
			}
		}

		private void ExecuteBinaryEditView(string strBinName, ProtectedBinary pb)
		{
			BinaryDataClass bdc = BinaryDataClassifier.Classify(strBinName,
				pb.ReadData());
			DynamicMenuEventArgs args = new DynamicMenuEventArgs(strBinName,
				DataEditorForm.SupportsDataType(bdc) ?
				new EditableBinaryAttachment(strBinName) : null);
			OnEntryBinaryView(null, args);
		}

		private string UrlsToString(PwEntry[] vEntries, bool bActive)
		{
			if((vEntries == null) || (vEntries.Length == 0)) return string.Empty;

			StringBuilder sb = new StringBuilder();
			foreach(PwEntry pe in vEntries)
			{
				if(sb.Length > 0) sb.Append(MessageService.NewLine);

				PwDatabase pd = m_docMgr.SafeFindContainerOf(pe);

				string strUrl = pe.Strings.ReadSafe(PwDefs.UrlField);
				strUrl = SprEngine.Compile(strUrl, new SprContext(pe, pd,
					(bActive ? SprCompileFlags.All : SprCompileFlags.NonActive)));

				sb.Append(strUrl);
			}

			UpdateUIState(false); // SprEngine.Compile might have modified the database
			return sb.ToString();
		}

		private delegate void PerformQuickFindDelegate(string strSearch,
			string strGroupName, bool bForceShowExpired);

		/// <summary>
		/// Do a quick find. All entries of the currently opened database are searched
		/// for a string and the results are automatically displayed in the main window.
		/// </summary>
		/// <param name="strSearch">String to search the entries for.</param>
		/// <param name="strGroupName">Group name of the group that receives the search
		/// results.</param>
		private void PerformQuickFind(string strSearch, string strGroupName,
			bool bForceShowExpired)
		{
			Debug.Assert(strSearch != null); if(strSearch == null) return;
			Debug.Assert(strGroupName != null); if(strGroupName == null) return;

			PwGroup pg = new PwGroup(true, true, strGroupName, PwIcon.EMailSearch);
			pg.IsVirtual = true;

			SearchParameters sp = new SearchParameters();
			sp.SearchString = strSearch;
			sp.SearchInTitles = sp.SearchInUserNames =
				sp.SearchInUrls = sp.SearchInNotes = sp.SearchInOther =
				sp.SearchInUuids = sp.SearchInGroupNames = sp.SearchInTags = true;
			sp.SearchInPasswords = Program.Config.MainWindow.QuickFindSearchInPasswords;

			if(!bForceShowExpired)
				sp.ExcludeExpired = Program.Config.MainWindow.QuickFindExcludeExpired;

			SearchUtil.SetTransformation(sp, (Program.Config.MainWindow.QuickFindDerefData ?
				SearchUtil.StrTrfDeref : string.Empty));

			StatusBarLogger sl = null;
			bool bBlock = (strSearch.Length > 0); // Showing all is fast
			if(bBlock)
			{
				Application.DoEvents(); // Finalize UI messages before blocking
				UIBlockInteraction(true);
				sl = CreateStatusBarLogger();
				sl.StartLogging(KPRes.SearchingOp + "...", false);
			}

			AutoAdjustMemProtSettings(m_docMgr.ActiveDatabase, sp);
			m_docMgr.ActiveDatabase.RootGroup.SearchEntries(sp, pg.Entries, sl);

			if(bBlock)
			{
				sl.EndLogging();
				UIBlockInteraction(false);
			}

			UpdateEntryList(pg, false);
			SelectFirstEntryIfNoneSelected();

			UpdateUIState(false);
			ShowSearchResultsStatusMessage();

			if(Program.Config.MainWindow.FocusResultsAfterQuickFind &&
				(pg.Entries.UCount > 0))
			{
				ResetDefaultFocus(m_lvEntries);
			}
		}

		private void ShowExpiredEntries(bool bOnlyIfExists, bool bShowExpired,
			bool bShowSoonToExpire)
		{
			if(!bShowExpired && !bShowSoonToExpire) return;

			PwGroup pg = new PwGroup(true, true, string.Empty, PwIcon.Expired);
			pg.IsVirtual = true;

			const int iSkipDays = 7;
			DateTime dtNow = DateTime.Now;
			DateTime dtLimit = dtNow.Add(new TimeSpan(iSkipDays, 0, 0, 0));

			EntryHandler eh = delegate(PwEntry pe)
			{
				if(!pe.Expires) return true;
				if(PwDefs.IsTanEntry(pe)) return true; // Exclude TANs

				if((bShowExpired && (pe.ExpiryTime <= dtNow)) ||
					(bShowSoonToExpire && (pe.ExpiryTime <= dtLimit) &&
					(pe.ExpiryTime > dtNow)))
					pg.AddEntry(pe, false);
				return true;
			};

			m_docMgr.ActiveDatabase.RootGroup.TraverseTree(
				TraversalMethod.PreOrder, null, eh);

			if((pg.Entries.UCount > 0) || !bOnlyIfExists)
			{
				UpdateEntryList(pg, false);
				UpdateUIState(false);
				ShowSearchResultsStatusMessage();
			}
		}

		public void PerformExport(PwGroup pgDataSource, bool bExportDeleted)
		{
			Debug.Assert(m_docMgr.ActiveDatabase.IsOpen); if(!m_docMgr.ActiveDatabase.IsOpen) return;

			if(!AppPolicy.Try(AppPolicyId.Export)) return;

			PwDatabase pd = m_docMgr.ActiveDatabase;
			if((pd == null) || !pd.IsOpen) return;
			if(!AppPolicy.Current.ExportNoKey)
			{
				if(!KeyUtil.ReAskKey(pd, true)) return;
			}

			PwGroup pg = (pgDataSource ?? pd.RootGroup);
			PwExportInfo pwInfo = new PwExportInfo(pg, pd, bExportDeleted);

			MessageService.ExternalIncrementMessageCount();
			ShowWarningsLogger swLogger = CreateShowWarningsLogger();
			swLogger.StartLogging(KPRes.ExportingStatusMsg, true);

			ExportUtil.Export(pwInfo, swLogger);

			swLogger.EndLogging();
			MessageService.ExternalDecrementMessageCount();
			UpdateUIState(false);
		}

		internal static IOConnectionInfo CompleteConnectionInfo(IOConnectionInfo ioc,
			bool bSave, bool bCanRememberCred, bool bTestConnection, bool bForceShow)
		{
			if(ioc == null) { Debug.Assert(false); return null; }
			if(!bForceShow && ((ioc.CredSaveMode == IOCredSaveMode.SaveCred) ||
				ioc.IsLocalFile()))
				return ioc.CloneDeep();

			IOConnectionForm dlg = new IOConnectionForm();
			dlg.InitEx(bSave, ioc.CloneDeep(), bCanRememberCred, bTestConnection);
			if(UIUtil.ShowDialogNotValue(dlg, DialogResult.OK)) return null;

			IOConnectionInfo iocResult = dlg.IOConnectionInfo;
			UIUtil.DestroyForm(dlg);
			return iocResult;
		}

		internal IOConnectionInfo CompleteConnectionInfoUsingMru(IOConnectionInfo ioc)
		{
			if(ioc == null) { Debug.Assert(false); return null; }

			if(string.IsNullOrEmpty(ioc.UserName) && string.IsNullOrEmpty(ioc.Password))
			{
				for(uint u = 0; u < m_mruList.ItemCount; ++u)
				{
					IOConnectionInfo iocMru = (m_mruList.GetItem(u).Value as IOConnectionInfo);
					if(iocMru == null) { Debug.Assert(false); continue; }

					if(iocMru.Path.Equals(ioc.Path, StrUtil.CaseIgnoreCmp))
					{
						ioc = iocMru.CloneDeep();
						break;
					}
				}
			}

			return ioc;
		}

		private sealed class OdKpfConstructParams
		{
			public IOConnectionInfo IOConnectionInfo = null;
			public bool CanExit = false;
			public bool SecureDesktopMode = false; // Must be false by default
		}

		private static Form OdKpfConstruct(object objParam)
		{
			OdKpfConstructParams p = (objParam as OdKpfConstructParams);
			if(p == null) { Debug.Assert(false); return null; }

			KeyPromptForm kpf = new KeyPromptForm();
			kpf.InitEx(p.IOConnectionInfo, p.CanExit, true);
			kpf.SecureDesktopMode = p.SecureDesktopMode;
			return kpf;
		}

		private sealed class OdKpfResult
		{
			public CompositeKey Key = null;
			public bool ShowHelpAfterClose = false;
			public bool HasClosedWithExit = false;
		}

		private static object OdKpfBuildResult(Form f)
		{
			KeyPromptForm kpf = (f as KeyPromptForm);
			if(kpf == null) { Debug.Assert(false); return null; }

			OdKpfResult kpfResult = new OdKpfResult();
			kpfResult.Key = kpf.CompositeKey;
			kpfResult.ShowHelpAfterClose = kpf.ShowHelpAfterClose;
			kpfResult.HasClosedWithExit = kpf.HasClosedWithExit;

			return kpfResult;
		}

		/// <summary>
		/// Open a database. This function opens the specified database and updates
		/// the user interface.
		/// </summary>
		public void OpenDatabase(IOConnectionInfo ioConnection, CompositeKey cmpKey,
			bool bOpenLocal)
		{
			// OnFileClose(null, null);
			// if(m_docMgr.ActiveDatabase.IsOpen) return;

			if(m_bFormLoading && Program.Config.Application.Start.MinimizedAndLocked &&
				(ioConnection != null) && (ioConnection.Path.Length > 0))
			{
				PwDocument ds = m_docMgr.CreateNewDocument(true);
				ds.LockedIoc = ioConnection.CloneDeep();
				UpdateUI(true, ds, true, null, true, null, false);
				return;
			}

			IOConnectionInfo ioc;
			if(ioConnection == null)
			{
				if(bOpenLocal)
				{
					OpenFileDialog ofdDb = UIUtil.CreateOpenFileDialog(KPRes.OpenDatabaseFile,
						UIUtil.CreateFileTypeFilter(AppDefs.FileExtension.FileExt,
						KPRes.KdbxFiles, true), 1, null, false, false);

					GlobalWindowManager.AddDialog(ofdDb);
					DialogResult dr = ofdDb.ShowDialog();
					GlobalWindowManager.RemoveDialog(ofdDb);
					if(dr != DialogResult.OK) return;

					ioc = IOConnectionInfo.FromPath(ofdDb.FileName);
				}
				else
				{
					ioc = CompleteConnectionInfo(new IOConnectionInfo(), false,
						true, true, true);
					if(ioc == null) return;
				}
			}
			else // ioConnection != null
			{
				ioc = CompleteConnectionInfo(ioConnection, false, true, true, false);
				if(ioc == null) return;
			}

			if(!ioc.CanProbablyAccess())
			{
				MessageService.ShowWarning(ioc.GetDisplayName(), KPRes.FileNotFoundError);
				return;
			}

			if(OpenDatabaseRestoreIfOpened(ioc)) return;

			PwDatabase pwOpenedDb = null;
			if(cmpKey == null)
			{
				for(int iTry = 0; iTry < 3; ++iTry)
				{
					OdKpfConstructParams kpfParams = new OdKpfConstructParams();
					kpfParams.IOConnectionInfo = ioc;
					kpfParams.CanExit = IsFileLocked(null);

					DialogResult dr;
					OdKpfResult kpfResult;

					if(Program.Config.Security.MasterKeyOnSecureDesktop &&
						WinUtil.IsAtLeastWindows2000 &&
						!KeePassLib.Native.NativeLib.IsUnix())
					{
						kpfParams.SecureDesktopMode = true;

						ProtectedDialog dlg = new ProtectedDialog(OdKpfConstruct,
							OdKpfBuildResult);
						object objResult;
						dr = dlg.ShowDialog(out objResult, kpfParams);
						if(dr == DialogResult.None) { Debug.Assert(false); dr = DialogResult.Cancel; }
						
						kpfResult = (objResult as OdKpfResult);
						if(kpfResult == null) { Debug.Assert(false); continue; }

						if(kpfResult.ShowHelpAfterClose)
							AppHelp.ShowHelp(AppDefs.HelpTopics.KeySources, null);
					}
					else // Show dialog on normal desktop
					{
						Form dlg = OdKpfConstruct(kpfParams);
						dr = dlg.ShowDialog();

						kpfResult = (OdKpfBuildResult(dlg) as OdKpfResult);
						UIUtil.DestroyForm(dlg);
						if(kpfResult == null) { Debug.Assert(false); continue; }
					}

					if(dr == DialogResult.Cancel) break;
					else if(kpfResult.HasClosedWithExit)
					{
						Debug.Assert(dr == DialogResult.Abort);
						OnFileExit(null, null);
						return;
					}

					pwOpenedDb = OpenDatabaseInternal(ioc, kpfResult.Key);
					if(pwOpenedDb != null) break;
				}
			}
			else // cmpKey != null
			{
				pwOpenedDb = OpenDatabaseInternal(ioc, cmpKey);
			}

			if((pwOpenedDb == null) || !pwOpenedDb.IsOpen)
			{
				UpdateUIState(false); // Reset status bar text
				return;
			}

			string strName = pwOpenedDb.IOConnectionInfo.GetDisplayName();
			m_mruList.AddItem(strName, pwOpenedDb.IOConnectionInfo.CloneDeep(), true);

			PwDocument dsExisting = m_docMgr.FindDocument(pwOpenedDb);
			if(dsExisting != null) m_docMgr.ActiveDocument = dsExisting;

			bool bCorrectDbActive = (m_docMgr.ActiveDocument.Database == pwOpenedDb);
			Debug.Assert(bCorrectDbActive);

			// AutoEnableVisualHiding();

			SetLastUsedFile(pwOpenedDb.IOConnectionInfo);
			RememberKeyFilePath(pwOpenedDb);

			PwGroup pgRestoreSelect = null;
			if(bCorrectDbActive)
			{
				m_docMgr.ActiveDocument.LockedIoc = new IOConnectionInfo(); // Clear

				pgRestoreSelect = pwOpenedDb.RootGroup.FindGroup(
					pwOpenedDb.LastSelectedGroup, true);
			}

			UpdateUI(true, null, true, pgRestoreSelect, true, null, false);
			if(bCorrectDbActive)
			{
				SetTopVisibleGroup(pwOpenedDb.LastTopVisibleGroup);
				if(pgRestoreSelect != null)
					SetTopVisibleEntry(pgRestoreSelect.LastTopVisibleEntry);
			}
			UpdateColumnSortingIcons();

			if((pwOpenedDb.MasterKeyChangeForce >= 0) &&
				((DateTime.Now - pwOpenedDb.MasterKeyChanged).Days >=
				pwOpenedDb.MasterKeyChangeForce))
			{
				while(true)
				{
					MessageService.ShowInfo(pwOpenedDb.IOConnectionInfo.GetDisplayName() +
						MessageService.NewParagraph + KPRes.MasterKeyChangeForce +
						MessageService.NewParagraph + KPRes.MasterKeyChangeInfo);
					if(ChangeMasterKey(pwOpenedDb))
					{
						UpdateUIState(true);
						break;
					}
					if(!AppPolicy.Current.ChangeMasterKey) break; // Prevent endless loop
				}
			}
			else if((pwOpenedDb.MasterKeyChangeRec >= 0) &&
				((DateTime.Now - pwOpenedDb.MasterKeyChanged).Days >=
				pwOpenedDb.MasterKeyChangeRec))
			{
				if(MessageService.AskYesNo(pwOpenedDb.IOConnectionInfo.GetDisplayName() +
					MessageService.NewParagraph + KPRes.MasterKeyChangeRec +
					MessageService.NewParagraph + KPRes.MasterKeyChangeQ))
					UpdateUIState(ChangeMasterKey(pwOpenedDb));
			}

			if(this.FileOpened != null)
			{
				FileOpenedEventArgs ea = new FileOpenedEventArgs(pwOpenedDb);
				this.FileOpened(this, ea);
			}
			Program.TriggerSystem.RaiseEvent(EcasEventIDs.OpenedDatabaseFile,
				pwOpenedDb.IOConnectionInfo.Path);

			if(bCorrectDbActive && pwOpenedDb.IsOpen)
			{
				ShowExpiredEntries(true,
					Program.Config.Application.FileOpening.ShowExpiredEntries,
					Program.Config.Application.FileOpening.ShowSoonToExpireEntries);

				// Avoid view being destroyed by the unlocking routine
				pwOpenedDb.LastSelectedGroup = PwUuid.Zero;
			}

			if(Program.Config.MainWindow.MinimizeAfterOpeningDatabase)
				UIUtil.SetWindowState(this, FormWindowState.Minimized);

			ResetDefaultFocus(null);
		}

		private PwDatabase OpenDatabaseInternal(IOConnectionInfo ioc, CompositeKey cmpKey)
		{
			PerformSelfTest();

			ShowWarningsLogger swLogger = CreateShowWarningsLogger();
			swLogger.StartLogging(KPRes.OpeningDatabase, true);

			PwDocument ds = null;
			string strPathNrm = ioc.Path.Trim().ToLower();
			for(int iScan = 0; iScan < m_docMgr.Documents.Count; ++iScan)
			{
				if(m_docMgr.Documents[iScan].LockedIoc.Path.Trim().ToLower() == strPathNrm)
					ds = m_docMgr.Documents[iScan];
				else if(m_docMgr.Documents[iScan].Database.IOConnectionInfo.Path == strPathNrm)
					ds = m_docMgr.Documents[iScan];
			}

			PwDatabase pwDb;
			if(ds == null) pwDb = m_docMgr.CreateNewDocument(true).Database;
			else pwDb = ds.Database;

			try
			{
				pwDb.Open(ioc, cmpKey, swLogger);

#if DEBUG
				byte[] pbDiskDirect = WinUtil.HashFile(ioc);
				Debug.Assert(MemUtil.ArraysEqual(pbDiskDirect, pwDb.HashOfFileOnDisk));
#endif
			}
			catch(Exception ex)
			{
				MessageService.ShowLoadWarning(ioc.GetDisplayName(), ex,
					(Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null));
				pwDb = null;
			}

			swLogger.EndLogging();

			if(pwDb == null)
			{
				if(ds == null) m_docMgr.CloseDatabase(m_docMgr.ActiveDatabase);
			}

			return pwDb;
		}

		private bool OpenDatabaseRestoreIfOpened(IOConnectionInfo ioc)
		{
			if(ioc == null) { Debug.Assert(false); return false; }

			string strPathNrm = ioc.Path.Trim().ToLower();

			foreach(PwDocument ds in m_docMgr.Documents)
			{
				if(((ds.LockedIoc == null) || (ds.LockedIoc.Path.Length == 0)) &&
					(ds.Database.IOConnectionInfo.Path.Trim().ToLower() == strPathNrm))
				{
					MakeDocumentActive(ds);
					return true;
				}
			}

			return false;
		}

		// private void AutoEnableVisualHiding()
		// {
		//	// KPF 1802197
		//	// Turn on visual hiding if option is selected
		//	if(m_docMgr.ActiveDatabase.MemoryProtection.AutoEnableVisualHiding)
		//	{
		//		if(m_docMgr.ActiveDatabase.MemoryProtection.ProtectTitle && !m_viewHideFields.ProtectTitle)
		//			m_menuViewHideTitles.Checked = m_viewHideFields.ProtectTitle = true;
		//		if(m_docMgr.ActiveDatabase.MemoryProtection.ProtectUserName && !m_viewHideFields.ProtectUserName)
		//			m_menuViewHideUserNames.Checked = m_viewHideFields.ProtectUserName = true;
		//		if(m_docMgr.ActiveDatabase.MemoryProtection.ProtectPassword && !m_viewHideFields.ProtectPassword)
		//			m_menuViewHidePasswords.Checked = m_viewHideFields.ProtectPassword = true;
		//		if(m_docMgr.ActiveDatabase.MemoryProtection.ProtectUrl && !m_viewHideFields.ProtectUrl)
		//			m_menuViewHideURLs.Checked = m_viewHideFields.ProtectUrl = true;
		//		if(m_docMgr.ActiveDatabase.MemoryProtection.ProtectNotes && !m_viewHideFields.ProtectNotes)
		//			m_menuViewHideNotes.Checked = m_viewHideFields.ProtectNotes = true;
		//	}
		// }

		private TreeNode GuiFindGroup(PwUuid puSearch, TreeNode tnContainer)
		{
			Debug.Assert(puSearch != null);
			if(puSearch == null) return null;

			if(m_tvGroups.Nodes.Count == 0) return null;

			if(tnContainer == null) tnContainer = m_tvGroups.Nodes[0];

			foreach(TreeNode tn in tnContainer.Nodes)
			{
				if(((PwGroup)tn.Tag).Uuid.EqualsValue(puSearch))
					return tn;

				if(tn != tnContainer)
				{
					TreeNode tnSub = GuiFindGroup(puSearch, tn);
					if(tnSub != null) return tnSub;
				}
				else { Debug.Assert(false); }
			}

			return null;
		}

		private ListViewItem GuiFindEntry(PwUuid puSearch)
		{
			Debug.Assert(puSearch != null);
			if(puSearch == null) return null;

			foreach(ListViewItem lvi in m_lvEntries.Items)
			{
				if(((PwListItem)lvi.Tag).Entry.Uuid.EqualsValue(puSearch))
					return lvi;
			}

			return null;
		}

		private void PrintGroup(PwGroup pg)
		{
			Debug.Assert(pg != null); if(pg == null) return;
			if(!AppPolicy.Try(AppPolicyId.Print)) return;

			PwDatabase pd = m_docMgr.ActiveDatabase;
			if((pd == null) || !pd.IsOpen) return;
			if(!AppPolicy.Current.PrintNoKey)
			{
				if(!KeyUtil.ReAskKey(pd, true)) return;
			}

			PrintForm pf = new PrintForm();
			pf.InitEx(pg, true, m_pListSorter.Column);
			UIUtil.ShowDialogAndDestroy(pf);
		}

		private ToolStripMenuItem InsertToolStripItem(ToolStripMenuItem tsContainer,
			ToolStripMenuItem tsTemplate, EventHandler ev, bool bPermanentlyLinkToTemplate)
		{
			ToolStripMenuItem tsmi = new ToolStripMenuItem(tsTemplate.Text, tsTemplate.Image);
			tsmi.Click += ev;

			Debug.Assert(tsTemplate.ShortcutKeys == Keys.None);
			// tsmi.ShortcutKeys = tsTemplate.ShortcutKeys;
			tsmi.ShowShortcutKeys = tsTemplate.ShowShortcutKeys;

			string strKeys = tsTemplate.ShortcutKeyDisplayString;
			if(!string.IsNullOrEmpty(strKeys))
				tsmi.ShortcutKeyDisplayString = strKeys;

			if(bPermanentlyLinkToTemplate)
				m_vLinkedToolStripItems.Add(new KeyValuePair<ToolStripItem, ToolStripItem>(
					tsTemplate, tsmi));

			tsContainer.DropDownItems.Insert(0, tsmi);
			return tsmi;
		}

		/// <summary>
		/// Set the linked menu item's Enabled state to the state of their parents.
		/// </summary>
		public void UpdateLinkedMenuItems()
		{
			foreach(KeyValuePair<ToolStripItem, ToolStripItem> kvp in m_vLinkedToolStripItems)
				kvp.Value.Enabled = kvp.Key.Enabled;
		}

		/// <summary>
		/// Handler function that is called when an MRU item is clicked (see MRU interface).
		/// </summary>
		public void OnMruExecute(string strDisplayName, object oTag)
		{
			Debug.Assert(oTag is IOConnectionInfo);
			OpenDatabase(oTag as IOConnectionInfo, null, false);
		}

		public void OnMruExecute2(string strDisplayName, object oTag)
		{
			Debug.Assert(oTag is IOConnectionInfo);
			IOConnectionInfo ioc = (oTag as IOConnectionInfo);
			ioc = CompleteConnectionInfo(ioc, false, true, true, false);
			if(ioc == null) return;

			bool? b = ImportUtil.Synchronize(m_docMgr.ActiveDatabase, this, ioc, false, this);
			UpdateUI(false, null, true, null, true, null, false);
			if(b.HasValue) SetStatusEx(b.Value ? KPRes.SyncSuccess : KPRes.SyncFailed);
		}

		/// <summary>
		/// Handler function that is called when the MRU list must be cleared (see MRU interface).
		/// </summary>
		public void OnMruClear()
		{
			m_mruList.Clear();
			m_mruList.UpdateMenu();
		}

		/// <summary>
		/// Function to update the tray icon based on the current window state.
		/// </summary>
		public void UpdateTrayIcon()
		{
			if(m_ntfTray == null) { Debug.Assert(false); return; } // Required

			bool bWindowVisible = this.Visible;
			bool bTrayVisible = m_ntfTray.Visible;

			if(Program.Config.UI.TrayIcon.ShowOnlyIfTrayed)
				m_ntfTray.Visible = !bWindowVisible;
			else if(bWindowVisible && !bTrayVisible)
				m_ntfTray.Visible = true;
		}

		private void OnSessionLock(object sender, SessionLockEventArgs e)
		{
			if((e.Reason == SessionLockReason.RemoteControlChange) &&
				Program.Config.Security.WorkspaceLocking.LockOnRemoteControlChange) { }
			else if(((e.Reason == SessionLockReason.Lock) || (e.Reason == SessionLockReason.Ending)) &&
				Program.Config.Security.WorkspaceLocking.LockOnSessionSwitch) { }
			else if((e.Reason == SessionLockReason.Suspend) &&
				Program.Config.Security.WorkspaceLocking.LockOnSuspend) { }
			else return;

			if(IsAtLeastOneFileOpen()) LockAllDocuments();
		}

		/// <summary>
		/// This function resets the internal user-inactivity timer.
		/// </summary>
		public void NotifyUserActivity()
		{
			// m_nLockTimerCur = m_nLockTimerMax;

			if(m_nLockTimerMax == 0) m_lLockAtTicks = long.MaxValue;
			else
			{
				DateTime utcLockAt = DateTime.UtcNow;
				utcLockAt = utcLockAt.AddSeconds((double)m_nLockTimerMax);
				m_lLockAtTicks = utcLockAt.Ticks;
			}
		}

		private void UpdateGlobalLockTimeout(DateTime utcNow)
		{
			uint uLockGlobal = Program.Config.Security.WorkspaceLocking.LockAfterGlobalTime;
			if(uLockGlobal == 0) { m_lLockAtGlobalTicks = long.MaxValue; return; }

			uint? uLastInputTime = NativeMethods.GetLastInputTime();
			if(!uLastInputTime.HasValue) return;

			if(uLastInputTime.Value != m_uLastInputTime)
			{
				DateTime utcLockAt = utcNow.AddSeconds((double)uLockGlobal);
				m_lLockAtGlobalTicks = utcLockAt.Ticks;

				m_uLastInputTime = uLastInputTime.Value;
			}
		}

		/// <summary>
		/// Move selected entries.
		/// </summary>
		/// <param name="nMove">Must be 2/-2 to move to top/bottom, 1/-1 to
		/// move one up/down.</param>
		private void MoveSelectedEntries(int nMove)
		{
			// Don't allow moving when sorting is enabled
			if((m_pListSorter.Column >= 0) && (m_pListSorter.Order != SortOrder.None))
				return;

			PwEntry[] vEntries = GetSelectedEntries();
			Debug.Assert(vEntries != null); if(vEntries == null) return;
			Debug.Assert(vEntries.Length > 0); if(vEntries.Length == 0) return;

			DateTime dtNow = DateTime.Now;
			PwGroup pg = vEntries[0].ParentGroup;
			foreach(PwEntry pe in vEntries)
			{
				if(pe.ParentGroup != pg)
				{
					MessageService.ShowWarning(KPRes.CannotMoveEntriesBcsGroup);
					return;
				}
			}

			if(nMove == -1)
			{
				Debug.Assert(vEntries.Length == 1);
				pg.Entries.MoveOne(vEntries[0], false);
			}
			else if(nMove == 1)
			{
				Debug.Assert(vEntries.Length == 1);
				pg.Entries.MoveOne(vEntries[0], true);
			}
			else if(nMove == -2) pg.Entries.MoveTopBottom(vEntries, false);
			else if(nMove == 2) pg.Entries.MoveTopBottom(vEntries, true);
			else { Debug.Assert(false); }

			if((nMove == -1) || (nMove == 1)) vEntries[0].LocationChanged = dtNow;
			else if((nMove == -2) || (nMove == 2))
			{
				foreach(PwEntry peUpd in vEntries) peUpd.LocationChanged = dtNow;
			}
			else { Debug.Assert(false); }

			UpdateEntryList(null, false);
			UpdateUIState(true);
		}

		public StatusBarLogger CreateStatusBarLogger()
		{
			StatusBarLogger sl = new StatusBarLogger();
			sl.SetControls(m_statusPartInfo, m_statusPartProgress);
			return sl;
		}

		/// <summary>
		/// Create a new warnings logger object that logs directly into
		/// the main status bar until the first warning is shown (in that
		/// case a dialog is opened displaying the warning).
		/// </summary>
		/// <returns>Reference to the new logger object.</returns>
		public ShowWarningsLogger CreateShowWarningsLogger()
		{
			StatusBarLogger sl = CreateStatusBarLogger();
			return new ShowWarningsLogger(sl, this);
		}

		internal void HandleHotKey(int wParam)
		{
			switch(wParam)
			{
				case AppDefs.GlobalHotKeyId.AutoType:
					ExecuteGlobalAutoType();
					break;

				case AppDefs.GlobalHotKeyId.AutoTypeSelected:
					ExecuteEntryAutoType();
					break;

				case AppDefs.GlobalHotKeyId.ShowWindow:
					bool bWndVisible = ((this.WindowState != FormWindowState.Minimized) &&
						!IsTrayed());
					EnsureVisibleForegroundWindow(true, true);
					if(bWndVisible && IsFileLocked(null))
						OnFileLock(null, EventArgs.Empty); // Unlock
					break;

				case AppDefs.GlobalHotKeyId.EntryMenu:
					EntryMenu.Show();
					break;

				default:
					Debug.Assert(false);
					break;
			}
		}

		protected override void WndProc(ref Message m)
		{
			if(m.Msg == NativeMethods.WM_HOTKEY)
			{
				NotifyUserActivity();
				HandleHotKey((int)m.WParam);
			}
			else if((m.Msg == m_nAppMessage) && (m_nAppMessage != 0))
				ProcessAppMessage(m.WParam, m.LParam);
			else if(m.Msg == NativeMethods.WM_SYSCOMMAND)
			{
				if((m.WParam == (IntPtr)NativeMethods.SC_MINIMIZE) ||
					(m.WParam == (IntPtr)NativeMethods.SC_MAXIMIZE))
				{
					SaveWindowPositionAndSize();
				}
			}
			else if((m.Msg == NativeMethods.WM_POWERBROADCAST) &&
				((m.WParam == (IntPtr)NativeMethods.PBT_APMQUERYSUSPEND) ||
				(m.WParam == (IntPtr)NativeMethods.PBT_APMSUSPEND)))
			{
				OnSessionLock(null, new SessionLockEventArgs(SessionLockReason.Suspend));
			}
			else if((m.Msg == m_nTaskbarButtonMessage) && m_bTaskbarButtonMessage)
			{
				m_bTaskbarButtonMessage = false;
				UpdateUIState(false, null); // Set overlay icon
				m_bTaskbarButtonMessage = true;
			}

			base.WndProc(ref m);
		}

		public void ProcessAppMessage(IntPtr wParam, IntPtr lParam)
		{
			NotifyUserActivity();

			if(wParam == (IntPtr)Program.AppMessage.RestoreWindow)
				EnsureVisibleForegroundWindow(true, true);
			else if(wParam == (IntPtr)Program.AppMessage.Exit)
				OnFileExit(null, EventArgs.Empty);
			else if(wParam == (IntPtr)Program.AppMessage.IpcByFile)
				IpcUtilEx.ProcessGlobalMessage(lParam.ToInt32(), this);
			else if(wParam == (IntPtr)Program.AppMessage.AutoType)
				ExecuteGlobalAutoType();
			else if(wParam == (IntPtr)Program.AppMessage.Lock)
				LockAllDocuments();
			else if(wParam == (IntPtr)Program.AppMessage.Unlock)
			{
				if(IsFileLocked(null))
				{
					EnsureVisibleForegroundWindow(false, false);
					OnFileLock(null, EventArgs.Empty); // Unlock
				}
			}
		}

		public void ExecuteGlobalAutoType()
		{
			if(m_bIsAutoTyping) return;
			m_bIsAutoTyping = true;

			if(IsAtLeastOneFileOpen() == false)
			{
				try
				{
					IntPtr hPrevWnd = NativeMethods.GetForegroundWindowHandle();

					EnsureVisibleForegroundWindow(false, false);

					// The window restoration function above maybe
					// restored the window already, therefore only
					// try to unlock if it's locked *now*
					if(IsFileLocked(null)) OnFileLock(null, EventArgs.Empty);

					NativeMethods.EnsureForegroundWindow(hPrevWnd);
				}
				catch(Exception exAT)
				{
					MessageService.ShowWarning(exAT);
				}
			}
			if(!IsAtLeastOneFileOpen()) { m_bIsAutoTyping = false; return; }

			try
			{
				AutoType.PerformGlobal(m_docMgr.GetOpenDatabases(),
					m_ilCurrentIcons);
			}
			catch(Exception exGlobal)
			{
				MessageService.ShowWarning(exGlobal);
			}

			m_bIsAutoTyping = false;
		}

		private void ExecuteEntryAutoType()
		{
			try
			{
				IntPtr hFG = NativeMethods.GetForegroundWindowHandle();
				if(!AutoType.IsValidAutoTypeWindow(hFG, true)) return;
			}
			catch(Exception) { Debug.Assert(false); return; }

			PwEntry peSel = GetSelectedEntry(true);
			if(peSel != null)
				AutoType.PerformIntoCurrentWindow(peSel,
					m_docMgr.SafeFindContainerOf(peSel));
			else
			{
				EnsureVisibleForegroundWindow(true, true);
				MessageService.ShowWarning(KPRes.AutoTypeSelectedNoEntry,
					KPRes.AutoTypeGlobalHint);
			}
		}

		public void EnsureVisibleForegroundWindow(bool bUntray, bool bRestoreWindow)
		{
			if(bUntray && IsTrayed()) MinimizeToTray(false);

			if(bRestoreWindow && (this.WindowState == FormWindowState.Minimized))
				UIUtil.SetWindowState(this, FormWindowState.Normal);

			try
			{
				if(this.Visible) // && (this.WindowState != FormWindowState.Minimized)
				{
					this.BringToFront();
					this.Activate();
				}
			}
			catch(Exception) { Debug.Assert(false); }
		}

		private void SetListFont(AceFont font)
		{
			if((font != null) && font.OverrideUIDefault)
			{
				m_tvGroups.Font = font.ToFont();
				m_lvEntries.Font = font.ToFont();
				m_richEntryView.Font = font.ToFont();

				Program.Config.UI.StandardFont = font;
			}
			else
			{
				if(UIUtil.VistaStyleListsSupported)
				{
					Font fontUI = UISystemFonts.ListFont;
					m_tvGroups.Font = fontUI;
					m_lvEntries.Font = fontUI;
					m_richEntryView.Font = fontUI;
				}

				Program.Config.UI.StandardFont.OverrideUIDefault = false;
			}

			m_fontExpired = FontUtil.CreateFont(m_lvEntries.Font, FontStyle.Strikeout);
			m_fontBoldUI = FontUtil.CreateFont(m_tabMain.Font, FontStyle.Bold);
			m_fontBoldTree = FontUtil.CreateFont(m_lvEntries.Font, FontStyle.Bold);
			m_fontItalicTree = FontUtil.CreateFont(m_lvEntries.Font, FontStyle.Italic);
		}

		private void SetSelectedEntryColor(Color clrBack)
		{
			if(m_docMgr.ActiveDatabase.IsOpen == false) return;
			PwEntry[] vSelected = GetSelectedEntries();
			if((vSelected == null) || (vSelected.Length == 0)) return;

			foreach(PwEntry pe in vSelected)
			{
				pe.BackgroundColor = clrBack;
				pe.Touch(true, false);
			}

			RefreshEntriesList();
			UpdateUIState(true);
		}

		private void OnCopyCustomString(object sender, DynamicMenuEventArgs e)
		{
			PwEntry pe = GetSelectedEntry(false);
			if(pe == null) return;

			if(ClipboardUtil.CopyAndMinimize(pe.Strings.GetSafe(e.ItemName), true,
				this, pe, m_docMgr.ActiveDatabase))
				StartClipboardCountdown();
		}

		private void SetMainWindowLayout(bool bSideBySide)
		{
			if(!bSideBySide && (m_splitHorizontal.Orientation != Orientation.Horizontal))
			{
				m_splitHorizontal.Orientation = Orientation.Horizontal;
				UpdateUIState(false);
			}
			else if(bSideBySide && (m_splitHorizontal.Orientation != Orientation.Vertical))
			{
				m_splitHorizontal.Orientation = Orientation.Vertical;
				UpdateUIState(false);
			}

			UIUtil.SetChecked(m_menuViewWindowsStacked, !bSideBySide);
			UIUtil.SetChecked(m_menuViewWindowsSideBySide, bSideBySide);
		}

		private void AssignMenuShortcuts()
		{
			UIUtil.AssignShortcut(m_menuFileNew, Keys.Control | Keys.N);
			UIUtil.AssignShortcut(m_menuFileOpenLocal, Keys.Control | Keys.O);
			UIUtil.AssignShortcut(m_menuFileOpenUrl, Keys.Control | Keys.Shift | Keys.O);
			UIUtil.AssignShortcut(m_menuFileClose, Keys.Control | Keys.W);
			UIUtil.AssignShortcut(m_menuFileSave, Keys.Control | Keys.S);
			UIUtil.AssignShortcut(m_menuFilePrint, Keys.Control | Keys.P);
			UIUtil.AssignShortcut(m_menuFileSyncFile, Keys.Control | Keys.R);
			UIUtil.AssignShortcut(m_menuFileSyncUrl, Keys.Control | Keys.Shift | Keys.R);
			UIUtil.AssignShortcut(m_menuFileLock, Keys.Control | Keys.L);

			UIUtil.AssignShortcut(m_menuEditFind, Keys.Control | Keys.F);

			// UIUtil.AssignShortcut(m_menuViewHidePasswords, Keys.Control | Keys.H);
			// UIUtil.AssignShortcut(m_menuViewHideUserNames, Keys.Control | Keys.J);

			UIUtil.AssignShortcut(m_menuHelpContents, Keys.F1);

			UIUtil.AssignShortcut(m_ctxGroupFind, Keys.Control | Keys.Shift | Keys.F);

			string strCtrl = KPRes.KeyboardKeyCtrl + "+", strAlt = KPRes.KeyboardKeyAlt + "+",
				strShift = KPRes.KeyboardKeyShift + "+";
			string strCtrlShift = strCtrl + strShift;

			m_ctxEntryCopyUserName.ShortcutKeyDisplayString = strCtrl + "B";
			m_ctxEntryCopyPassword.ShortcutKeyDisplayString = strCtrl + "C";
			m_ctxEntryOpenUrl.ShortcutKeyDisplayString = strCtrl + "U";
			m_ctxEntryCopyUrl.ShortcutKeyDisplayString = strCtrlShift + "U";
			m_ctxEntryPerformAutoType.ShortcutKeyDisplayString = strCtrl + "V";
			m_ctxEntryAdd.ShortcutKeyDisplayString = strCtrl + "I";
			m_ctxEntryEdit.ShortcutKeyDisplayString = KPRes.KeyboardKeyReturn;
			m_ctxEntryDelete.ShortcutKeyDisplayString = UIUtil.GetKeysName(Keys.Delete); // "Del"
			m_ctxEntrySelectAll.ShortcutKeyDisplayString = strCtrl + "A";

			m_ctxEntryMoveToTop.ShortcutKeyDisplayString = strAlt +
				UIUtil.GetKeysName(Keys.Home); // "Home"
			m_ctxEntryMoveOneUp.ShortcutKeyDisplayString = strAlt +
				UIUtil.GetKeysName(Keys.Up); // "Up"
			m_ctxEntryMoveOneDown.ShortcutKeyDisplayString = strAlt +
				UIUtil.GetKeysName(Keys.Down); // "Down"
			m_ctxEntryMoveToBottom.ShortcutKeyDisplayString = strAlt +
				UIUtil.GetKeysName(Keys.End); // "End"

			m_ctxGroupDelete.ShortcutKeyDisplayString = UIUtil.GetKeysName(Keys.Delete); // "Del"

			m_ctxGroupMoveToTop.ShortcutKeyDisplayString = strAlt +
				UIUtil.GetKeysName(Keys.Home); // "Home"
			m_ctxGroupMoveOneUp.ShortcutKeyDisplayString = strAlt +
				UIUtil.GetKeysName(Keys.Up); // "Up"
			m_ctxGroupMoveOneDown.ShortcutKeyDisplayString = strAlt +
				UIUtil.GetKeysName(Keys.Down); // "Down"
			m_ctxGroupMoveToBottom.ShortcutKeyDisplayString = strAlt +
				UIUtil.GetKeysName(Keys.End); // "End"
		}

		private static void CopyMenuItemText(ToolStripMenuItem tsmiTarget,
			ToolStripMenuItem tsmiCopyFrom)
		{
			tsmiTarget.Text = tsmiCopyFrom.Text;

			string strSh = tsmiCopyFrom.ShortcutKeyDisplayString;
			if(!string.IsNullOrEmpty(strSh))
				tsmiTarget.ShortcutKeyDisplayString = strSh;
		}

		private void SaveDatabaseAs(bool bOnline, object sender, bool bCopy)
		{
			if(!m_docMgr.ActiveDatabase.IsOpen) return;
			if(!AppPolicy.Try(AppPolicyId.SaveFile)) return;

			PwDatabase pd = m_docMgr.ActiveDatabase;

			Guid eventGuid = Guid.NewGuid();
			if(this.FileSaving != null)
			{
				FileSavingEventArgs args = new FileSavingEventArgs(true, bCopy, pd, eventGuid);
				this.FileSaving(sender, args);
				if(args.Cancel) return;
			}

			DialogResult dr;
			IOConnectionInfo ioc = new IOConnectionInfo();

			if(bOnline)
			{
				IOConnectionForm iocf = new IOConnectionForm();
				iocf.InitEx(true, pd.IOConnectionInfo.CloneDeep(), true, true);

				dr = iocf.ShowDialog();
				ioc = iocf.IOConnectionInfo;
				UIUtil.DestroyForm(iocf);
			}
			else
			{
				SaveFileDialog sfdDb = UIUtil.CreateSaveFileDialog(KPRes.SaveDatabase,
					UrlUtil.GetFileName(pd.IOConnectionInfo.Path),
					UIUtil.CreateFileTypeFilter(AppDefs.FileExtension.FileExt,
					KPRes.KdbxFiles, true), 1, AppDefs.FileExtension.FileExt, false, true);

				GlobalWindowManager.AddDialog(sfdDb);
				dr = sfdDb.ShowDialog();
				GlobalWindowManager.RemoveDialog(sfdDb);

				if(dr == DialogResult.OK)
					ioc = IOConnectionInfo.FromPath(sfdDb.FileName);
			}

			if(dr == DialogResult.OK)
			{
				Program.TriggerSystem.RaiseEvent(EcasEventIDs.SavingDatabaseFile,
					ioc.Path);

				UIBlockInteraction(true);

				ShowWarningsLogger swLogger = CreateShowWarningsLogger();
				swLogger.StartLogging(KPRes.SavingDatabase, true);

				bool bSuccess = true;
				try
				{
					PreSavingEx(pd);
					pd.SaveAs(ioc, !bCopy, swLogger);
					PostSavingEx(!bCopy, pd, ioc, swLogger);
				}
				catch(Exception exSaveAs)
				{
					MessageService.ShowSaveWarning(ioc, exSaveAs, true);
					bSuccess = false;
				}

				swLogger.EndLogging();

				// Immediately after the UIBlockInteraction call the form might
				// be closed and UpdateUIState might crash, if the order of the
				// two methods is swapped; so first update state, then unblock
				UpdateUIState(false);
				UIBlockInteraction(false); // Calls Application.DoEvents()

				if(this.FileSaved != null)
				{
					FileSavedEventArgs args = new FileSavedEventArgs(bSuccess, pd, eventGuid);
					this.FileSaved(sender, args);
				}
				if(bSuccess)
					Program.TriggerSystem.RaiseEvent(EcasEventIDs.SavedDatabaseFile,
						ioc.Path);
			}
		}

		private void PreSavingEx(PwDatabase pwDatabase)
		{
			PerformSelfTest();

			pwDatabase.UseFileTransactions = Program.Config.Application.UseTransactedFileWrites;
			pwDatabase.UseFileLocks = Program.Config.Application.UseFileLocks;

			// AceColumn col = Program.Config.MainWindow.FindColumn(AceColumnType.Title);
			// if((col != null) && !col.HideWithAsterisks)
			//	pwDatabase.MemoryProtection.ProtectTitle = false;
			// col = Program.Config.MainWindow.FindColumn(AceColumnType.UserName);
			// if((col != null) && !col.HideWithAsterisks)
			//	pwDatabase.MemoryProtection.ProtectUserName = false;
			// col = Program.Config.MainWindow.FindColumn(AceColumnType.Url);
			// if((col != null) && !col.HideWithAsterisks)
			//	pwDatabase.MemoryProtection.ProtectUrl = false;
			// col = Program.Config.MainWindow.FindColumn(AceColumnType.Notes);
			// if((col != null) && !col.HideWithAsterisks)
			//	pwDatabase.MemoryProtection.ProtectNotes = false;

			if(pwDatabase == m_docMgr.ActiveDatabase) SaveWindowState();
		}

		private void PostSavingEx(bool bPrimary, PwDatabase pwDatabase,
			IOConnectionInfo ioc, IStatusLogger sl)
		{
			if(ioc == null) { Debug.Assert(false); return; }

			byte[] pbIO = null;
			if(Program.Config.Application.VerifyWrittenFileAfterSaving)
			{
				pbIO = WinUtil.HashFile(ioc);
				Debug.Assert((pbIO != null) && (pwDatabase.HashOfLastIO != null));
				if(!MemUtil.ArraysEqual(pbIO, pwDatabase.HashOfLastIO))
					MessageService.ShowWarning(ioc.GetDisplayName(),
						KPRes.FileVerifyHashFail, KPRes.FileVerifyHashFailRec);
			}

			if(bPrimary)
			{
#if DEBUG
				Debug.Assert(MemUtil.ArraysEqual(pbIO, pwDatabase.HashOfFileOnDisk));

				try
				{
					PwDatabase pwCheck = new PwDatabase();
					pwCheck.Open(ioc.CloneDeep(), pwDatabase.MasterKey, null);

					Debug.Assert(MemUtil.ArraysEqual(pwDatabase.HashOfLastIO,
						pwCheck.HashOfLastIO));

					uint uGroups1, uGroups2, uEntries1, uEntries2;
					pwDatabase.RootGroup.GetCounts(true, out uGroups1, out uEntries1);
					pwCheck.RootGroup.GetCounts(true, out uGroups2, out uEntries2);
					Debug.Assert((uGroups1 == uGroups2) && (uEntries1 == uEntries2));
				}
				catch(Exception exVerify) { Debug.Assert(false, exVerify.Message); }
#endif

				m_mruList.AddItem(ioc.GetDisplayName(), ioc.CloneDeep(), true);

				SetLastUsedFile(ioc);

				// if(Program.Config.Application.CreateBackupFileAfterSaving && bHashValid)
				// {
				//	try { pwDatabase.CreateBackupFile(sl); }
				//	catch(Exception exBackup)
				//	{
				//		MessageService.ShowWarning(KPRes.FileBackupFailed, exBackup);
				//	}
				// }

				// ulong uTotalBinSize = 0;
				// EntryHandler ehCnt = delegate(PwEntry pe)
				// {
				//	foreach(KeyValuePair<string, ProtectedBinary> kvpCnt in pe.Binaries)
				//	{
				//		uTotalBinSize += kvpCnt.Value.Length;
				//	}
				//
				//	return true;
				// };
				// pwDatabase.RootGroup.TraverseTree(TraversalMethod.PreOrder, null, ehCnt);
			}

			RememberKeyFilePath(pwDatabase);
			WinUtil.FlushStorageBuffers(ioc.Path, true);
		}

		public bool UIFileSave(bool bForceSave)
		{
			Control cFocus = UIUtil.GetActiveControl(this);

			m_docMgr.ActiveDatabase.Modified = true;

			m_bForceSave = bForceSave;
			OnFileSave(null, null);
			m_bForceSave = false;

			if(cFocus != null) ResetDefaultFocus(cFocus);
			return !m_docMgr.ActiveDatabase.Modified;
		}

		public void ResetDefaultFocus(Control cExplicit)
		{
			Control c = cExplicit;

			if(c == null)
			{
				// QuickFind must be the first choice (see e.g.
				// the option FocusQuickFindOnUntray)
				if(m_tbQuickFind.Visible && m_tbQuickFind.Enabled)
					c = m_tbQuickFind.Control;
				else if(m_lvEntries.Visible && m_lvEntries.Enabled)
					c = m_lvEntries;
				else if(m_tvGroups.Visible && m_tvGroups.Enabled)
					c = m_tvGroups;
				else if(m_richEntryView.Visible && m_richEntryView.Enabled)
					c = m_richEntryView;
				else c = m_lvEntries;
			}

			if(this.FocusChanging != null)
			{
				FocusEventArgs ea = new FocusEventArgs(cExplicit, c);
				this.FocusChanging(null, ea);
				if(ea.Cancel) return;
			}

			UIUtil.SetFocus(c, this);
		}

		private static bool PrepareLock()
		{
			if(GlobalWindowManager.WindowCount == 0) return true;

			if(GlobalWindowManager.CanCloseAllWindows)
			{
				GlobalWindowManager.CloseAllWindows();
				return true;
			}

			return false;
		}

		private void UpdateImageLists()
		{
			if(!m_docMgr.ActiveDatabase.UINeedsIconUpdate) return;
			m_docMgr.ActiveDatabase.UINeedsIconUpdate = false;

			ImageList imgList = new ImageList();
			imgList.ImageSize = new Size(16, 16);
			imgList.ColorDepth = ColorDepth.Depth32Bit;

			// foreach(Image img in m_ilClientIcons.Images) imgList.Images.Add(img);
			List<Image> lStdImages = new List<Image>();
			foreach(Image imgStd in m_ilClientIcons.Images) lStdImages.Add(imgStd);
			imgList.Images.AddRange(lStdImages.ToArray());

			Debug.Assert(imgList.Images.Count == (int)PwIcon.Count);

			// ImageList imgListCustom = UIUtil.BuildImageList(
			//	m_docMgr.ActiveDatabase.CustomIcons, 16, 16);
			// foreach(Image imgCustom in imgListCustom.Images)
			//	imgList.Images.Add(imgCustom); // Breaks alpha partially
			List<Image> lCustom = UIUtil.BuildImageListEx(
				m_docMgr.ActiveDatabase.CustomIcons, 16, 16);
			if((lCustom != null) && (lCustom.Count > 0))
				imgList.Images.AddRange(lCustom.ToArray());

			m_ilCurrentIcons = imgList;

			if(UIUtil.VistaStyleListsSupported)
			{
				m_tvGroups.ImageList = imgList;
				m_lvEntries.SmallImageList = imgList;
			}
			else
			{
				List<Image> vAllImages = new List<Image>();
				foreach(Image imgClient in m_ilClientIcons.Images)
					vAllImages.Add(imgClient);
				vAllImages.AddRange(lCustom);
				Debug.Assert(imgList.Images.Count == vAllImages.Count);

				ImageList imgSafe = UIUtil.ConvertImageList24(vAllImages, 16, 16,
					AppDefs.ColorControlNormal);
				m_tvGroups.ImageList = imgSafe; // TreeView doesn't fully support alpha on < Vista
				m_lvEntries.SmallImageList = ((WinUtil.IsAtLeastWindowsVista ||
					WinUtil.IsWindowsXP) ? imgList : imgSafe);
			}
		}

		private void MoveSelectedGroup(int iMove)
		{
			PwGroup pgMove = GetSelectedGroup();
			if(pgMove == null) { Debug.Assert(false); return; }

			PwGroup pgParent = pgMove.ParentGroup;
			if(pgParent == null) return;

			PwGroup[] pgAffected = new PwGroup[] { pgMove };

			if(iMove == 2)
				pgParent.Groups.MoveTopBottom(pgAffected, true);
			else if(iMove == 1)
				pgParent.Groups.MoveOne(pgMove, true);
			else if(iMove == -1)
				pgParent.Groups.MoveOne(pgMove, false);
			else if(iMove == -2)
				pgParent.Groups.MoveTopBottom(pgAffected, false);
			else { Debug.Assert(false); }

			pgMove.LocationChanged = DateTime.Now;
			UpdateUI(false, null, true, null, true, null, true);
		}

		private void OnEntryBinaryView(object sender, DynamicMenuEventArgs e)
		{
			PwEntry pe = GetSelectedEntry(false);
			if(pe == null) { Debug.Assert(false); return; }

			EditableBinaryAttachment eba = (e.Tag as EditableBinaryAttachment);

			ProtectedBinary pbData = pe.Binaries.Get((eba != null) ? eba.Name :
				e.ItemName);
			if(pbData == null) { Debug.Assert(false); return; }

			if(eba == null) // Not editable
			{
				DataViewerForm dvf = new DataViewerForm();
				dvf.InitEx(e.ItemName, pbData.ReadData());
				UIUtil.ShowDialogAndDestroy(dvf);
			}
			else
			{
				DataEditorForm def = new DataEditorForm();
				def.InitEx(eba.Name, pbData.ReadData());
				def.ShowDialog();

				if(def.EditedBinaryData != null) // User changed the data
				{
					pe.Binaries.Set(eba.Name, new ProtectedBinary(
						pbData.IsProtected, def.EditedBinaryData));
					pe.Touch(true, false);

					RefreshEntriesList();
					UpdateUIState(true);
				}

				UIUtil.DestroyForm(def);
			}
		}

		private void SaveWindowState()
		{
			PwDatabase pd = m_docMgr.ActiveDatabase;

			PwGroup pgSelected = GetSelectedGroup();
			if(pgSelected != null)
				pd.LastSelectedGroup = new PwUuid(pgSelected.Uuid.UuidBytes);

			TreeNode tnTop = m_tvGroups.TopNode;
			if(tnTop != null)
			{
				PwGroup pgTop = (tnTop.Tag as PwGroup);
				pd.LastTopVisibleGroup = new PwUuid(pgTop.Uuid.UuidBytes);
			}

			PwEntry peTop = GetTopEntry();
			if((peTop != null) && (pgSelected != null))
				pgSelected.LastTopVisibleEntry = new PwUuid(peTop.Uuid.UuidBytes);
		}

		private void RestoreWindowState(PwDatabase pd)
		{
			PwGroup pgSelect = null;

			if(!pd.LastSelectedGroup.EqualsValue(PwUuid.Zero))
			{
				pgSelect = pd.RootGroup.FindGroup(pd.LastSelectedGroup, true);
				UpdateGroupList(pgSelect);
				UpdateEntryList(pgSelect, false);
			}

			SetTopVisibleGroup(pd.LastTopVisibleGroup);
			if(pgSelect != null) SetTopVisibleEntry(pgSelect.LastTopVisibleEntry);
		}

		private void SetTopVisibleGroup(PwUuid uuidGroup)
		{
			TreeNode tnTop = GuiFindGroup(uuidGroup, null);
			if(tnTop != null) m_tvGroups.TopNode = tnTop;
		}

		private void SetTopVisibleEntry(PwUuid uuidEntry)
		{
			ListViewItem lviTop = GuiFindEntry(uuidEntry);
			if(lviTop != null)
			{
				m_lvEntries.EnsureVisible(m_lvEntries.Items.Count - 1);
				m_lvEntries.EnsureVisible(lviTop.Index);
			}
		}

		private void CloseDocument(bool bLocking, bool bExiting)
		{
			PwDocument ds = m_docMgr.ActiveDocument;
			PwDatabase pd = ds.Database;

			Program.TriggerSystem.RaiseEvent(EcasEventIDs.ClosingDatabaseFilePre,
				pd.IOConnectionInfo.Path);
			if(this.FileClosingPre != null)
			{
				FileClosingEventArgs fcea = new FileClosingEventArgs(pd);
				this.FileClosingPre(null, fcea);
				if(fcea.Cancel) return;
			}

			if(pd.Modified) // Implies pd.IsOpen
			{
				bool bInvokeSave = false;

				if(Program.Config.Application.FileClosing.AutoSave)
					bInvokeSave = true;
				else
				{
					FileSaveOrigin fso = FileSaveOrigin.Closing;
					if(bLocking) fso = FileSaveOrigin.Locking;
					if(bExiting) fso = FileSaveOrigin.Exiting;

					DialogResult dr = FileDialogsEx.ShowFileSaveQuestion(
						pd.IOConnectionInfo.GetDisplayName(), fso, this.Handle);

					if(dr == DialogResult.Cancel) return;
					else if(dr == DialogResult.Yes) bInvokeSave = true;
					else if(dr == DialogResult.No) { } // Changes are lost
				}

				if(bInvokeSave)
				{
					OnFileSave(null, EventArgs.Empty);
					if(pd.Modified) return;
				}
			}

			Program.TriggerSystem.RaiseEvent(EcasEventIDs.ClosingDatabaseFilePost,
				pd.IOConnectionInfo.Path);
			if(this.FileClosingPost != null)
			{
				FileClosingEventArgs fcea = new FileClosingEventArgs(pd);
				this.FileClosingPost(null, fcea);
				if(fcea.Cancel) return;
			}

			IOConnectionInfo ioClosing = pd.IOConnectionInfo.CloneDeep();

			pd.Close();
			if(!bLocking) m_docMgr.CloseDatabase(pd);

			m_tbQuickFind.Items.Clear();
			m_tbQuickFind.Text = string.Empty;

			if(!bLocking)
			{
				m_docMgr.ActiveDatabase.UINeedsIconUpdate = true;
				UpdateUI(true, null, true, null, true, null, false);
				ResetDefaultFocus(null);
			}

			// NativeMethods.ClearIconicBitmaps(this.Handle);

			if(this.FileClosed != null)
			{
				FileClosedEventArgs fcea = new FileClosedEventArgs(ioClosing);
				this.FileClosed(null, fcea);
			}
		}

		// Public for plugins
		public void LockAllDocuments()
		{
			NotifyUserActivity();

			if(Program.Config.Security.WorkspaceLocking.AlwaysExitInsteadOfLocking)
			{
				OnFileExit(null, EventArgs.Empty);
				return;
			}

			if(UIIsInteractionBlocked()) { Debug.Assert(false); return; }
			if(!PrepareLock()) return; // Unable to lock

			SaveWindowState();

			PwDocument dsPrevActive = m_docMgr.ActiveDocument;

			foreach(PwDocument ds in m_docMgr.Documents)
			{
				PwDatabase pd = ds.Database;
				if(!pd.IsOpen) continue; // Nothing to lock

				IOConnectionInfo ioIoc = pd.IOConnectionInfo;
				Debug.Assert(ioIoc != null);

				m_docMgr.ActiveDocument = ds;
				CloseDocument(true, false);
				if(pd.IsOpen) return;

				ds.LockedIoc = ioIoc;
			}

			m_docMgr.ActiveDocument = dsPrevActive;
			UpdateUI(true, null, true, null, true, null, false);

			if(Program.Config.MainWindow.MinimizeAfterLocking &&
				!IsAtLeastOneFileOpen())
				UIUtil.SetWindowState(this, FormWindowState.Minimized);
		}

		private void SaveAllDocuments()
		{
			PwDocument dsPrevActive = m_docMgr.ActiveDocument;

			foreach(PwDocument ds in m_docMgr.Documents)
			{
				PwDatabase pd = ds.Database;

				if(!IsFileLocked(ds) && pd.Modified)
				{
					m_docMgr.ActiveDocument = ds;
					OnFileSave(null, EventArgs.Empty);
				}
			}

			m_docMgr.ActiveDocument = dsPrevActive;
			UpdateUI(false, null, true, null, true, null, false);
		}

		private bool CloseAllDocuments(bool bExiting)
		{
			if(UIIsInteractionBlocked()) { Debug.Assert(false); return false; }

			bool bProcessedAll = false, bSuccess = true;
			while(bProcessedAll == false)
			{
				bProcessedAll = true;

				foreach(PwDocument ds in m_docMgr.Documents)
				{
					if(ds.Database.IsOpen)
					{
						m_docMgr.ActiveDocument = ds;
						CloseDocument(false, bExiting);

						if(ds.Database.IsOpen)
						{
							bSuccess = false;
							break;
						}

						bProcessedAll = false;
						break;
					}
				}

				if(bSuccess == false) break;
			}

			return bSuccess;
		}

		private void RecreateUITabs()
		{
			m_bBlockTabChanged = true;

			m_tabMain.TabPages.Clear();

			m_tabMain.ImageList = null;
			if(m_ilTabImages != null) m_ilTabImages.Dispose();
			foreach(Image img in m_lTabImages) img.Dispose();
			m_lTabImages.Clear();

			List<TabPage> lPages = new List<TabPage>();
			for(int i = 0; i < m_docMgr.Documents.Count; ++i)
			{
				PwDocument ds = m_docMgr.Documents[i];

				TabPage tb = new TabPage();
				tb.Tag = ds;

				string strName, strTip;
				GetTabText(ds, out strName, out strTip);

				tb.Text = strName;
				tb.ToolTipText = strTip;

				if((ds == null) || (ds.Database == null) || !ds.Database.IsOpen ||
					UIUtil.ColorsEqual(ds.Database.Color, Color.Empty)) { }
				else
				{
					m_lTabImages.Add(UIUtil.CreateTabColorImage(ds.Database.Color,
						m_tabMain));
					tb.ImageIndex = m_lTabImages.Count - 1;
				}

				lPages.Add(tb);
			}

			int qSize = ((m_lTabImages.Count > 0) ? m_lTabImages[0].Height : 15);
			m_ilTabImages = UIUtil.BuildImageListUnscaled(m_lTabImages, qSize, qSize);
			m_tabMain.ImageList = m_ilTabImages;

			m_tabMain.TabPages.AddRange(lPages.ToArray());

			// m_tabMain.SelectedTab.Font = m_fontBoldUI;

			m_bBlockTabChanged = false;
		}

		private void SelectUITab()
		{
			m_bBlockTabChanged = true;

			PwDocument dsSelect = m_docMgr.ActiveDocument;
			foreach(TabPage tb in m_tabMain.TabPages)
			{
				if((PwDocument)tb.Tag == dsSelect)
				{
					m_tabMain.SelectedTab = tb;
					break;
				}
			}

			m_bBlockTabChanged = false;
		}

		public void MakeDocumentActive(PwDocument ds)
		{
			if(ds == null) { Debug.Assert(false); return; }

			ds.Database.UINeedsIconUpdate = true;

			UpdateUI(false, ds, true, null, true, null, false);

			RestoreWindowState(ds.Database);
			UpdateUIState(false);
		}

		private void GetTabText(PwDocument dsInfo, out string strName,
			out string strTip)
		{
			if(!IsFileLocked(dsInfo))
			{
				strTip = dsInfo.Database.IOConnectionInfo.Path;
				strName = UrlUtil.GetFileName(strTip);

				if(dsInfo.Database.Modified) strName += "*";

				if(dsInfo.Database.IsOpen)
				{
					if(dsInfo.Database.Name.Length > 0)
						strTip += "\r\n" + dsInfo.Database.Name;
				}
			}
			else // Locked
			{
				strTip = dsInfo.LockedIoc.Path;
				strName = UrlUtil.GetFileName(strTip);
				strName += " [" + KPRes.Locked + "]";
			}
		}

		private void UpdateUITabs()
		{
			foreach(TabPage tb in m_tabMain.TabPages)
			{
				PwDocument ds = (PwDocument)tb.Tag;
				string strName, strTip;

				GetTabText(ds, out strName, out strTip);

				tb.Text = strName;
				tb.ToolTipText = strTip;
			}
		}

		public void UpdateUI(bool bRecreateTabBar, PwDocument dsSelect,
			bool bUpdateGroupList, PwGroup pgSelect, bool bUpdateEntryList,
			PwGroup pgEntrySource, bool bSetModified)
		{
			UpdateUI(bRecreateTabBar, dsSelect, bUpdateGroupList, pgSelect,
				bUpdateEntryList, pgEntrySource, bSetModified, null);
		}

		public void UpdateUI(bool bRecreateTabBar, PwDocument dsSelect,
			bool bUpdateGroupList, PwGroup pgSelect, bool bUpdateEntryList,
			PwGroup pgEntrySource, bool bSetModified, Control cOptFocus)
		{
			if(bRecreateTabBar) RecreateUITabs();

			if(dsSelect != null) m_docMgr.ActiveDocument = dsSelect;
			SelectUITab();

			UpdateImageLists();

			if(bUpdateGroupList) UpdateGroupList(pgSelect);

			if(bUpdateEntryList) UpdateEntryList(pgEntrySource, false);
			else { Debug.Assert(pgEntrySource == null); }

			UpdateUIState(bSetModified, cOptFocus);
		}

		private void ShowSearchResultsStatusMessage()
		{
			string strItemsFound = m_lvEntries.Items.Count.ToString() + " " +
				KPRes.SearchItemsFoundSmall;

			SetStatusEx(strItemsFound);
		}

		private void MinimizeToTray(bool bMinimize)
		{
			this.Visible = !bMinimize;

			if(bMinimize == false) // Restore
			{
				// EnsureVisibleForegroundWindow(false, false); // Don't!

				if(this.WindowState == FormWindowState.Minimized)
					UIUtil.SetWindowState(this, (Program.Config.MainWindow.Maximized ?
						FormWindowState.Maximized : FormWindowState.Normal));
				else if(IsFileLocked(null) && !UIIsAutoUnlockBlocked())
					OnFileLock(null, EventArgs.Empty); // Unlock

				if(Program.Config.MainWindow.FocusQuickFindOnUntray)
					ResetDefaultFocus(null);
			}

			UpdateTrayIcon();
		}

		private void MinimizeToTrayAtStartIfEnabled(bool bFormLoading)
		{
			if(Program.Config.Application.Start.MinimizedAndLocked ||
				(Program.CommandLineArgs[AppDefs.CommandLineOptions.Minimize] != null))
			{
				if(bFormLoading)
					UIUtil.SetWindowState(this, FormWindowState.Minimized);
				else
				{
					// The following isn't required anymore, because the
					// TaskbarButtonCreated message is handled

					// Set the lock overlay icon again (the first time
					// Windows ignores the call, maybe because the window
					// wasn't fully constructed at that time yet)
					// if(IsFileLocked(null))
					//	TaskbarList.SetOverlayIcon(this,
					//		new Icon("/usr/share/keepass2/LockOverlay.ico"), KPRes.Locked);
				}

				if(Program.Config.MainWindow.MinimizeToTray) MinimizeToTray(true);
				else if(!bFormLoading)
					UIUtil.SetWindowState(this, FormWindowState.Minimized);
			}

			// Remove taskbar item
			if(Program.Config.MainWindow.MinimizeAfterOpeningDatabase &&
				Program.Config.MainWindow.MinimizeToTray && (bFormLoading == false) &&
				IsAtLeastOneFileOpen())
			{
				MinimizeToTray(true);
			}
		}

		private void SelectFirstEntryIfNoneSelected()
		{
			if((m_lvEntries.Items.Count > 0) &&
				(m_lvEntries.SelectedIndices.Count == 0))
				UIUtil.SetFocusedItem(m_lvEntries, m_lvEntries.Items[0], true);
		}

		private void SelectEntries(PwObjectList<PwEntry> lEntries,
			bool bDeselectOthers, bool bFocusFirst)
		{
			m_bBlockEntrySelectionEvent = true;

			bool bFirst = true;
			for(int i = 0; i < m_lvEntries.Items.Count; ++i)
			{
				PwEntry pe = ((PwListItem)m_lvEntries.Items[i].Tag).Entry;
				if(pe == null) { Debug.Assert(false); continue; }

				bool bFound = false;
				foreach(PwEntry peFocus in lEntries)
				{
					if(pe == peFocus)
					{
						m_lvEntries.Items[i].Selected = true;

						if(bFirst && bFocusFirst)
						{
							UIUtil.SetFocusedItem(m_lvEntries,
								m_lvEntries.Items[i], false);
							bFirst = false;
						}

						bFound = true;
						break;
					}
				}

				if(bDeselectOthers && !bFound)
					m_lvEntries.Items[i].Selected = false;
			}

			m_bBlockEntrySelectionEvent = false;
		}

		private PwGroup GetCurrentEntries()
		{
			PwGroup pg = new PwGroup(true, true);
			pg.IsVirtual = true;

			if(m_lvEntries.ShowGroups == false)
			{
				foreach(ListViewItem lvi in m_lvEntries.Items)
					pg.AddEntry(((PwListItem)lvi.Tag).Entry, false);
			}
			else // Groups
			{
				foreach(ListViewGroup lvg in m_lvEntries.Groups)
					foreach(ListViewItem lvi in lvg.Items)
						pg.AddEntry(((PwListItem)lvi.Tag).Entry, false);
			}

			return pg;
		}

		// Public for plugins
		public void EnsureVisibleEntry(PwUuid uuid)
		{
			ListViewItem lvi = GuiFindEntry(uuid);
			if(lvi == null) { Debug.Assert(false); return; }

			m_lvEntries.EnsureVisible(lvi.Index);
		}

		private void EnsureVisibleSelected(bool bLastMatchingEntry)
		{
			PwEntry pe = GetSelectedEntry(true, bLastMatchingEntry);
			if(pe == null) return;

			EnsureVisibleEntry(pe.Uuid);
		}

		private void RemoveEntriesFromList(List<PwEntry> lEntries, bool bLockUIUpdate)
		{
			Debug.Assert(lEntries != null); if(lEntries == null) return;
			if(lEntries.Count == 0) return;

			RemoveEntriesFromList(lEntries.ToArray(), bLockUIUpdate);
		}

		private void RemoveEntriesFromList(PwEntry[] vEntries, bool bLockUIUpdate)
		{
			Debug.Assert(vEntries != null); if(vEntries == null) return;
			if(vEntries.Length == 0) return;

			if(bLockUIUpdate) m_lvEntries.BeginUpdate();

			lock(m_asyncListUpdate.ListEditSyncObject)
			{
				for(int i = m_lvEntries.Items.Count - 1; i >= 0; --i)
				{
					PwEntry pe = ((PwListItem)m_lvEntries.Items[i].Tag).Entry;
					Debug.Assert(pe != null);

					if(Array.IndexOf<PwEntry>(vEntries, pe) >= 0)
						m_lvEntries.Items.RemoveAt(i);
				}
			}

			// Refresh alternating item background colors
			UIUtil.SetAlternatingBgColors(m_lvEntries, m_clrAlternateItemBgColor,
				Program.Config.MainWindow.EntryListAlternatingBgColors);

			if(bLockUIUpdate) m_lvEntries.EndUpdate();
		}

		private bool PreSaveValidate(PwDatabase pd)
		{
			if(m_bForceSave) return true;

			byte[] pbOnDisk = WinUtil.HashFile(pd.IOConnectionInfo);

			if((pbOnDisk != null) && (pd.HashOfFileOnDisk != null) &&
				!MemUtil.ArraysEqual(pbOnDisk, pd.HashOfFileOnDisk))
			{
				DialogResult dr = AskIfSynchronizeInstead(pd.IOConnectionInfo);
				if(dr == DialogResult.Yes) // Synchronize
				{
					bool? b = ImportUtil.Synchronize(pd, this, pd.IOConnectionInfo,
						true, this);
					UpdateUI(false, null, true, null, true, null, false);
					if(b.HasValue) SetStatusEx(b.Value ? KPRes.SyncSuccess : KPRes.SyncFailed);
					return false;
				}
				else if(dr == DialogResult.Cancel) return false;
				else { Debug.Assert(dr == DialogResult.No); }
			}

			return true;
		}

		private DialogResult AskIfSynchronizeInstead(IOConnectionInfo ioc)
		{
			VistaTaskDialog dlg = new VistaTaskDialog(this.Handle);

			string strText = string.Empty;
			if(ioc.GetDisplayName().Length > 0)
				strText += ioc.GetDisplayName() + MessageService.NewParagraph;
			strText += KPRes.FileChanged;

			dlg.CommandLinks = true;
			dlg.WindowTitle = PwDefs.ShortProductName;
			dlg.Content = strText;
			dlg.SetIcon(VtdCustomIcon.Question);

			dlg.MainInstruction = KPRes.OverwriteExistingFileQuestion;
			dlg.AddButton((int)DialogResult.Yes, KPRes.Synchronize, KPRes.FileChangedSync);
			dlg.AddButton((int)DialogResult.No, KPRes.Overwrite, KPRes.FileChangedOverwrite);
			dlg.AddButton((int)DialogResult.Cancel, KPRes.CancelCmd, KPRes.FileSaveQOpCancel);

			DialogResult dr;
			if(dlg.ShowDialog()) dr = (DialogResult)dlg.Result;
			else
			{
				strText += MessageService.NewParagraph;
				strText += @"[" + KPRes.Yes + @"]: " + KPRes.Synchronize + @". " +
					KPRes.FileChangedSync + MessageService.NewParagraph;
				strText += @"[" + KPRes.No + @"]: " + KPRes.Overwrite + @". " +
					KPRes.FileChangedOverwrite + MessageService.NewParagraph;
				strText += @"[" + KPRes.Cancel + @"]: " + KPRes.FileSaveQOpCancel;

				dr = MessageService.Ask(strText, PwDefs.ShortProductName,
					MessageBoxButtons.YesNoCancel);
			}

			return dr;
		}

		private void ActivateNextDocumentEx()
		{
			if(m_tabMain.TabPages.Count > 1)
				m_tabMain.SelectedIndex = ((m_tabMain.SelectedIndex + 1) %
					m_tabMain.TabPages.Count);
		}

		private bool HandleMainWindowKeyMessage(KeyEventArgs e, bool bDown)
		{
			if(e == null) { Debug.Assert(false); return false; }

			bool bHandled = false;

			if(e.Control)
			{
				if(e.KeyCode == Keys.Tab)
				{
					if(bDown) ActivateNextDocumentEx();
					bHandled = true;
				}
				// When changing Ctrl+E, also change the tooltip of the quick search box
				else if(e.KeyCode == Keys.E) // Standard key for quick searches
				{
					ResetDefaultFocus(m_tbQuickFind.Control); // In both cases (RTF)
					bHandled = true;
				}
				else if(e.KeyCode == Keys.H)
				{
					if(bDown) ToggleFieldAsterisks(AceColumnType.Password);
					bHandled = true;
				}
				else if(e.KeyCode == Keys.J)
				{
					if(bDown) ToggleFieldAsterisks(AceColumnType.UserName);
					bHandled = true;
				}
			}

			if(bHandled) { e.Handled = true; e.SuppressKeyPress = true; }
			return bHandled;
		}

		public bool UIIsInteractionBlocked()
		{
			return (m_uUIBlocked > 0);
		}

		public void UIBlockInteraction(bool bBlock)
		{
			NotifyUserActivity();

			if(bBlock) ++m_uUIBlocked;
			else if(m_uUIBlocked > 0) --m_uUIBlocked;
			else { Debug.Assert(false); }

			bool bNotBlocked = !UIIsInteractionBlocked();
			this.Enabled = bNotBlocked;

			if(bNotBlocked)
			{
				try { ResetDefaultFocus(null); } // Set focus on unblock
				catch(Exception) { Debug.Assert(false); }
			}

			Application.DoEvents(); // Allow controls update/redraw
		}

		public bool UIIsAutoUnlockBlocked()
		{
			return (m_uUnlockAutoBlocked > 0);
		}

		public void UIBlockAutoUnlock(bool bBlock)
		{
			if(bBlock) ++m_uUnlockAutoBlocked;
			else if(m_uUnlockAutoBlocked > 0) --m_uUnlockAutoBlocked;
			else { Debug.Assert(false); }
		}

		private static void EnsureRecycleBin(ref PwGroup pgRecycleBin,
			PwDatabase pdContext, ref bool bGroupListUpdateRequired)
		{
			if(pdContext == null) { Debug.Assert(false); return; }

			if(pgRecycleBin == pdContext.RootGroup)
			{
				Debug.Assert(false);
				pgRecycleBin = null;
			}

			if(pgRecycleBin == null)
			{
				pgRecycleBin = new PwGroup(true, true, KPRes.RecycleBin,
					PwIcon.TrashBin);
				pgRecycleBin.EnableAutoType = false;
				pgRecycleBin.EnableSearching = false;
				pgRecycleBin.IsExpanded = !Program.Config.Defaults.RecycleBinCollapse;
				pdContext.RootGroup.AddGroup(pgRecycleBin, true);

				pdContext.RecycleBinUuid = pgRecycleBin.Uuid;

				bGroupListUpdateRequired = true;
			}
			else { Debug.Assert(pgRecycleBin.Uuid.EqualsValue(pdContext.RecycleBinUuid)); }
		}

		private void DeleteSelectedEntries()
		{
			PwEntry[] vSelected = GetSelectedEntries();
			if((vSelected == null) || (vSelected.Length == 0)) return;

			PwDatabase pd = m_docMgr.ActiveDatabase;
			PwGroup pgRecycleBin = pd.RootGroup.FindGroup(pd.RecycleBinUuid, true);
			bool bShiftPressed = ((Control.ModifierKeys & Keys.Shift) != Keys.None);

			bool bAtLeastOnePermanent = false;
			if(pd.RecycleBinEnabled == false) bAtLeastOnePermanent = true;
			else if(bShiftPressed) bAtLeastOnePermanent = true;
			else if(pgRecycleBin == null) { } // Not permanent
			else
			{
				foreach(PwEntry peEnum in vSelected)
				{
					if((peEnum.ParentGroup == pgRecycleBin) ||
						peEnum.ParentGroup.IsContainedIn(pgRecycleBin))
					{
						bAtLeastOnePermanent = true;
						break;
					}
				}
			}

			if(bAtLeastOnePermanent)
			{
				bool bSingle = (vSelected.Length == 1);

				VistaTaskDialog dlg = new VistaTaskDialog(this.Handle);
				dlg.CommandLinks = false;
				dlg.Content = EntryUtil.CreateSummaryList(null, vSelected);
				dlg.MainInstruction = (bSingle ? KPRes.DeleteEntriesQuestionSingle :
					KPRes.DeleteEntriesQuestion);
				dlg.SetIcon(VtdCustomIcon.Question);
				dlg.WindowTitle = PwDefs.ShortProductName;
				dlg.AddButton((int)DialogResult.OK, KPRes.DeleteCmd, null);
				dlg.AddButton((int)DialogResult.Cancel, KPRes.CancelCmd, null);

				if(dlg.ShowDialog())
				{
					if(dlg.Result == (int)DialogResult.Cancel) return;
				}
				else
				{
					if(!MessageService.AskYesNo(bSingle ? KPRes.DeleteEntriesQuestionSingle :
						KPRes.DeleteEntriesQuestion, bSingle ? KPRes.DeleteEntriesTitleSingle :
						KPRes.DeleteEntriesTitle))
						return;
				}
			}

			bool bUpdateGroupList = false;
			DateTime dtNow = DateTime.Now;
			foreach(PwEntry pe in vSelected)
			{
				PwGroup pgParent = pe.ParentGroup;
				if(pgParent == null) continue; // Can't remove

				pgParent.Entries.Remove(pe);

				bool bPermanent = false;
				if(pd.RecycleBinEnabled == false) bPermanent = true;
				else if(bShiftPressed) bPermanent = true;
				else if(pgRecycleBin == null) { } // Recycle
				else if(pgParent == pgRecycleBin) bPermanent = true;
				else if(pgParent.IsContainedIn(pgRecycleBin)) bPermanent = true;

				if(bPermanent)
				{
					PwDeletedObject pdo = new PwDeletedObject(pe.Uuid, dtNow);
					pd.DeletedObjects.Add(pdo);
				}
				else // Recycle
				{
					EnsureRecycleBin(ref pgRecycleBin, pd, ref bUpdateGroupList);

					pgRecycleBin.AddEntry(pe, true, true);
					pe.Touch(false);
				}
			}

			RemoveEntriesFromList(vSelected, true);
			UpdateUI(false, null, bUpdateGroupList, null, false, null, true);
		}

		private void DeleteSelectedGroup()
		{
			PwGroup pg = GetSelectedGroup();
			if(pg == null) { Debug.Assert(false); return; }

			PwGroup pgParent = pg.ParentGroup;
			if(pgParent == null) return; // Can't remove virtual or root group

			PwDatabase pd = m_docMgr.ActiveDatabase;
			PwGroup pgRecycleBin = pd.RootGroup.FindGroup(pd.RecycleBinUuid, true);
			bool bShiftPressed = ((Control.ModifierKeys & Keys.Shift) != Keys.None);

			bool bPermanent = false;
			if(pd.RecycleBinEnabled == false) bPermanent = true;
			else if(bShiftPressed) bPermanent = true;
			else if(pgRecycleBin == null) { }
			else if(pg == pgRecycleBin) bPermanent = true;
			else if(pg.IsContainedIn(pgRecycleBin)) bPermanent = true;
			else if(pgRecycleBin.IsContainedIn(pg)) bPermanent = true;

			if(bPermanent)
			{
				VistaTaskDialog dlg = new VistaTaskDialog(this.Handle);
				dlg.CommandLinks = false;
				dlg.Content = KPRes.DeleteGroupInfo + EntryUtil.CreateSummaryList(pg, true);
				dlg.MainInstruction = KPRes.DeleteGroupQuestion;
				dlg.SetIcon(VtdCustomIcon.Question);
				dlg.WindowTitle = PwDefs.ShortProductName;
				dlg.AddButton((int)DialogResult.OK, KPRes.DeleteCmd, null);
				dlg.AddButton((int)DialogResult.Cancel, KPRes.CancelCmd, null);

				if(dlg.ShowDialog())
				{
					if(dlg.Result == (int)DialogResult.Cancel) return;
				}
				else
				{
					string strText = KPRes.DeleteGroupInfo + MessageService.NewParagraph +
						KPRes.DeleteGroupQuestion;
					if(!MessageService.AskYesNo(strText, KPRes.DeleteGroupTitle))
						return;
				}
			}

			pgParent.Groups.Remove(pg);

			if(bPermanent)
			{
				pg.DeleteAllObjects(pd);

				PwDeletedObject pdo = new PwDeletedObject(pg.Uuid, DateTime.Now);
				pd.DeletedObjects.Add(pdo);
			}
			else // Recycle
			{
				bool bDummy = false;
				EnsureRecycleBin(ref pgRecycleBin, pd, ref bDummy);

				pgRecycleBin.AddGroup(pg, true, true);
				pg.Touch(false);
			}

			UpdateUI(false, null, true, pgParent, true, null, true);
		}

		private void EmptyRecycleBin()
		{
			PwDatabase pd = m_docMgr.ActiveDatabase;
			PwGroup pg = pd.RootGroup.FindGroup(pd.RecycleBinUuid, true);
			if(pg == null) { Debug.Assert(false); return; }
			if(pg != GetSelectedGroup()) { Debug.Assert(false); return; }

			VistaTaskDialog dlg = new VistaTaskDialog(this.Handle);
			dlg.CommandLinks = false;
			dlg.Content = EntryUtil.CreateSummaryList(pg, false);
			dlg.MainInstruction = KPRes.EmptyRecycleBinQuestion;
			dlg.SetIcon(VtdCustomIcon.Question);
			dlg.WindowTitle = PwDefs.ShortProductName;
			dlg.AddButton((int)DialogResult.OK, KPRes.DeleteCmd, null);
			dlg.AddButton((int)DialogResult.Cancel, KPRes.CancelCmd, null);

			if(dlg.ShowDialog())
			{
				if(dlg.Result == (int)DialogResult.Cancel) return;
			}
			else
			{
				if(!MessageService.AskYesNo(KPRes.EmptyRecycleBinQuestion))
					return;
			}

			pg.DeleteAllObjects(pd);

			UpdateUI(false, null, true, pg, true, null, true);
		}


		// private static bool GroupOnlyContainsTans(PwGroup pg, bool bAllowSubgroups)
		// {
		//	if(!bAllowSubgroups && (pg.Groups.UCount > 0))
		//		return false;
		//
		//	foreach(PwEntry pe in pg.Entries)
		//	{
		//		if(!PwDefs.IsTanEntry(pe)) return false;
		//	}
		//
		//	return true;
		// }

		// private static string GetGroupSuffixText(PwGroup pg)
		// {
		// if(pg == null) { Debug.Assert(false); return string.Empty; }
		// if(pg.Entries.UCount == 0) return string.Empty;
		// if(GroupOnlyContainsTans(pg, true) == false) return string.Empty;

		// DateTime dtNow = DateTime.Now;
		// uint uValid = 0;
		// foreach(PwEntry pe in pg.Entries)
		// {
		//	if(pe.Expires && (pe.ExpiryTime <= dtNow)) { }
		//	else ++uValid;
		// }

		// return (" (" + uValid.ToString() + "/" + pg.Entries.UCount.ToString() + ")");
		// }

		public void AddCustomToolBarButton(string strID, string strName, string strDesc)
		{
			if(string.IsNullOrEmpty(strID)) { Debug.Assert(false); return; } // No throw
			if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return; } // No throw

			if(m_vCustomToolBarButtons.Count == 0)
			{
				m_tsSepCustomToolBar = new ToolStripSeparator();
				m_toolMain.Items.Add(m_tsSepCustomToolBar);
			}

			ToolStripButton btn = new ToolStripButton(strName);
			btn.Tag = strID;
			btn.Click += OnCustomToolBarButtonClicked;
			if(!string.IsNullOrEmpty(strDesc)) btn.ToolTipText = strDesc;

			m_toolMain.Items.Add(btn);
			m_vCustomToolBarButtons.Add(btn);
		}

		public void RemoveCustomToolBarButton(string strID)
		{
			if(string.IsNullOrEmpty(strID)) { Debug.Assert(false); return; } // No throw

			foreach(ToolStripButton tb in m_vCustomToolBarButtons)
			{
				string str = (tb.Tag as string);
				if(string.IsNullOrEmpty(str)) { Debug.Assert(false); continue; }

				if(str.Equals(strID, StrUtil.CaseIgnoreCmp))
				{
					tb.Click -= OnCustomToolBarButtonClicked;
					m_toolMain.Items.Remove(tb);
					m_vCustomToolBarButtons.Remove(tb);
					break;
				}
			}

			if((m_vCustomToolBarButtons.Count == 0) && (m_tsSepCustomToolBar != null))
			{
				m_toolMain.Items.Remove(m_tsSepCustomToolBar);
				m_tsSepCustomToolBar = null;
			}
		}

		private void OnCustomToolBarButtonClicked(object sender, EventArgs e)
		{
			ToolStripButton btn = (sender as ToolStripButton);
			if(btn == null) { Debug.Assert(false); return; }

			string strID = (btn.Tag as string);
			if(string.IsNullOrEmpty(strID)) { Debug.Assert(false); return; }

			Program.TriggerSystem.RaiseEvent(EcasEventIDs.CustomTbButtonClicked, strID);
		}

		private IOConnectionInfo IocFromCommandLine()
		{
			CommandLineArgs args = Program.CommandLineArgs;
			IOConnectionInfo ioc = IOConnectionInfo.FromPath(args.FileName);

			if(ioc.IsLocalFile()) // Expand relative path to absolute
				ioc.Path = UrlUtil.MakeAbsolutePath(UrlUtil.EnsureTerminatingSeparator(
					Directory.GetCurrentDirectory(), false) + "Sentinel", ioc.Path);

			if(args[AppDefs.CommandLineOptions.IoCredFromRecent] != null)
				ioc = CompleteConnectionInfoUsingMru(ioc);

			string strUserName = args[AppDefs.CommandLineOptions.IoCredUserName];
			if(strUserName != null) ioc.UserName = strUserName;

			string strPassword = args[AppDefs.CommandLineOptions.IoCredPassword];
			if(strPassword != null) ioc.Password = strPassword;

			return ioc;
		}

		private static void SetLastUsedFile(IOConnectionInfo ioc)
		{
			if(ioc == null) { Debug.Assert(false); return; }

			if(Program.Config.Application.Start.OpenLastFile)
				Program.Config.Application.LastUsedFile = ioc.CloneDeep();
			else
				Program.Config.Application.LastUsedFile = new IOConnectionInfo();
		}

		private static void RememberKeyFilePath(PwDatabase pwDb)
		{
			if(pwDb == null) { Debug.Assert(false); return; }

			IUserKey kcpFile = pwDb.MasterKey.GetUserKey(typeof(KcpKeyFile));
			IUserKey kcpCustom = pwDb.MasterKey.GetUserKey(typeof(KcpCustomKey));

			if(kcpFile != null)
				Program.Config.Defaults.SetKeySource(pwDb.IOConnectionInfo,
					((KcpKeyFile)kcpFile).Path, true);
			else if(kcpCustom != null)
				Program.Config.Defaults.SetKeySource(pwDb.IOConnectionInfo,
					((KcpCustomKey)kcpCustom).Name, false);
			else
				Program.Config.Defaults.SetKeySource(pwDb.IOConnectionInfo,
					null, false);
		}

		private void SerializeMruList(bool bStore)
		{
			AceMru aceMru = Program.Config.Application.MostRecentlyUsed;

			if(bStore)
			{
				aceMru.MaxItemCount = m_mruList.MaxItemCount;

				aceMru.Items.Clear();
				// Count <= max is not guaranteed, therefore take minimum of both
				uint uMax = Math.Min(m_mruList.MaxItemCount, m_mruList.ItemCount);
				for(uint uMru = 0; uMru < uMax; ++uMru)
				{
					KeyValuePair<string, object> kvpMru = m_mruList.GetItem(uMru);
					IOConnectionInfo ioMru = (kvpMru.Value as IOConnectionInfo);
					if(ioMru != null) aceMru.Items.Add(ioMru);
					else { Debug.Assert(false); }
				}
			}
			else // Load
			{
				m_mruList.MaxItemCount = aceMru.MaxItemCount;

				int nMax = Math.Min((int)m_mruList.MaxItemCount, aceMru.Items.Count);
				for(int iMru = 0; iMru < nMax; ++iMru)
				{
					IOConnectionInfo ioMru = aceMru.Items[nMax - iMru - 1];
					m_mruList.AddItem(ioMru.GetDisplayName(), ioMru.CloneDeep(), false);
				}

				m_mruList.UpdateMenu();
			}
		}

		public void RedirectActivationPush(Form formTarget)
		{
			m_vRedirectActivation.Push(formTarget);
		}

		public void RedirectActivationPop()
		{
			if(m_vRedirectActivation.Count == 0) { Debug.Assert(false); return; }
			m_vRedirectActivation.Pop();
		}

		private bool ChangeMasterKey(PwDatabase pdOf)
		{
			if(!AppPolicy.Try(AppPolicyId.ChangeMasterKey)) return false;

			PwDatabase pd = (pdOf ?? m_docMgr.ActiveDatabase);
			if((pd == null) || !pd.IsOpen) { Debug.Assert(false); return false; }

			if(!AppPolicy.Current.ChangeMasterKeyNoKey)
			{
				if(!KeyUtil.ReAskKey(pd, true)) return false;
			}

			KeyCreationForm kcf = new KeyCreationForm();
			kcf.InitEx(pd.IOConnectionInfo, false);

			if(UIUtil.ShowDialogNotValue(kcf, DialogResult.OK)) return false; // No UI update

			pd.MasterKey = kcf.CompositeKey;
			pd.MasterKeyChanged = DateTime.Now;

			MessageService.ShowInfoEx(PwDefs.ShortProductName + " - " +
				KPRes.KeyChanged, KPRes.MasterKeyChanged, KPRes.MasterKeyChangedSavePrompt);

			UIUtil.DestroyForm(kcf);
			return true; // No UI update
		}

		private void UpdateColumnsEx(bool bGuiToInternal)
		{
			if(m_bBlockColumnUpdates) return;
			m_bBlockColumnUpdates = true;

			if(!bGuiToInternal) // Internal to GUI
			{
				m_asyncListUpdate.CancelPendingUpdatesAsync();

				m_lvEntries.BeginUpdate();
				lock(m_asyncListUpdate.ListEditSyncObject)
				{
					m_lvEntries.Items.Clear();
				}
				m_lvEntries.Columns.Clear();

				if(Program.Config.MainWindow.EntryListColumns.Count == 0)
				{
					int nWidth = (m_lvEntries.ClientRectangle.Width -
						UIUtil.GetVScrollBarWidth()) / 5;
					EntryListAddColumn(AceColumnType.Title, nWidth, false);
					EntryListAddColumn(AceColumnType.UserName, nWidth, false);
					EntryListAddColumn(AceColumnType.Password, nWidth, true);
					EntryListAddColumn(AceColumnType.Url, nWidth, false);
					EntryListAddColumn(AceColumnType.Notes, nWidth, false);
				}

				int nDefaultWidth = m_lvEntries.ClientRectangle.Width /
					Program.Config.MainWindow.EntryListColumns.Count;
				foreach(AceColumn col in Program.Config.MainWindow.EntryListColumns)
				{
					ColumnHeader ch = m_lvEntries.Columns.Add(col.GetDisplayName(),
						col.SafeGetWidth(nDefaultWidth));

					HorizontalAlignment ha;
					if(col.Type == AceColumnType.PluginExt)
						ha = Program.ColumnProviderPool.GetTextAlign(col.CustomName);
					else ha = AceColumn.GetTextAlign(col.Type);
					if(ha != HorizontalAlignment.Left) ch.TextAlign = ha;
				}

				int[] vDisplayIndices = StrUtil.DeserializeIntArray(
					Program.Config.MainWindow.EntryListColumnDisplayOrder);

				for(int i = 0; i < Math.Min(m_lvEntries.Columns.Count,
					vDisplayIndices.Length); ++i)
				{
					int nIdx = vDisplayIndices[i];
					if((nIdx >= 0) && (nIdx < m_lvEntries.Columns.Count))
						m_lvEntries.Columns[i].DisplayIndex = nIdx;
				}

				m_lvEntries.EndUpdate();
				UpdateColumnSortingIcons();
			}
			else // GUI to internal
			{
				List<AceColumn> l = Program.Config.MainWindow.EntryListColumns;
				if(l.Count == m_lvEntries.Columns.Count)
				{
					int[] vDisplayIndices = new int[l.Count];
					for(int i = 0; i < l.Count; ++i)
					{
						l[i].Width = m_lvEntries.Columns[i].Width;
						vDisplayIndices[i] = m_lvEntries.Columns[i].DisplayIndex;
					}

					Program.Config.MainWindow.EntryListColumnDisplayOrder =
						StrUtil.SerializeIntArray(vDisplayIndices);
				}
				else { Debug.Assert(false); }
			}

			m_bBlockColumnUpdates = false;
		}

		private static void EntryListAddColumn(AceColumnType t, int nWidth, bool bHide)
		{
			AceColumn c = new AceColumn(t, string.Empty, bHide, nWidth);
			Program.Config.MainWindow.EntryListColumns.Add(c);
		}

		private string GetEntryFieldEx(PwEntry pe, int iColumnID,
			bool bFormatForDisplay, out bool bRequestAsync)
		{
			List<AceColumn> l = Program.Config.MainWindow.EntryListColumns;
			if((iColumnID < 0) || (iColumnID >= l.Count))
			{
				Debug.Assert(false);
				bRequestAsync = false;
				return string.Empty;
			}

			AceColumn col = l[iColumnID];
			if(bFormatForDisplay && col.HideWithAsterisks)
			{
				bRequestAsync = false;
				return PwDefs.HiddenPassword;
			}

			string str;
			switch(col.Type)
			{
				case AceColumnType.Title: str = pe.Strings.ReadSafe(PwDefs.TitleField); break;
				case AceColumnType.UserName: str = pe.Strings.ReadSafe(PwDefs.UserNameField); break;
				case AceColumnType.Password: str = pe.Strings.ReadSafe(PwDefs.PasswordField); break;
				case AceColumnType.Url: str = pe.Strings.ReadSafe(PwDefs.UrlField); break;
				case AceColumnType.Notes:
					if(!bFormatForDisplay) str = pe.Strings.ReadSafe(PwDefs.NotesField);
					else str = StrUtil.MultiToSingleLine(pe.Strings.ReadSafe(PwDefs.NotesField));
					break;
				case AceColumnType.CreationTime: str = TimeUtil.ToDisplayString(pe.CreationTime); break;
				case AceColumnType.LastAccessTime: str = TimeUtil.ToDisplayString(pe.LastAccessTime); break;
				case AceColumnType.LastModificationTime: str = TimeUtil.ToDisplayString(pe.LastModificationTime); break;
				case AceColumnType.ExpiryTime:
					if(pe.Expires) str = TimeUtil.ToDisplayString(pe.ExpiryTime);
					else str = m_strNeverExpiresText;
					break;
				case AceColumnType.Uuid: str = pe.Uuid.ToHexString(); break;
				case AceColumnType.Attachment: str = pe.Binaries.KeysToString(); break;
				case AceColumnType.CustomString:
					if(!bFormatForDisplay) str = pe.Strings.ReadSafe(col.CustomName);
					else str = StrUtil.MultiToSingleLine(pe.Strings.ReadSafe(col.CustomName));
					break;
				case AceColumnType.PluginExt:
					if(!bFormatForDisplay) str = Program.ColumnProviderPool.GetCellData(col.CustomName, pe);
					else str = StrUtil.MultiToSingleLine(Program.ColumnProviderPool.GetCellData(col.CustomName, pe));
					break;
				case AceColumnType.OverrideUrl: str = pe.OverrideUrl; break;
				case AceColumnType.Tags:
					str = StrUtil.TagsToString(pe.Tags, true);
					break;
				case AceColumnType.ExpiryTimeDateOnly:
					if(pe.Expires) str = TimeUtil.ToDisplayStringDateOnly(pe.ExpiryTime);
					else str = m_strNeverExpiresText;
					break;
				case AceColumnType.Size:
					str = StrUtil.FormatDataSizeKB(pe.GetSize());
					break;
				case AceColumnType.HistoryCount:
					str = pe.History.UCount.ToString();
					break;
				default: Debug.Assert(false); str = string.Empty; break;
			}

			if(Program.Config.MainWindow.EntryListShowDerefData)
			{
				switch(col.Type)
				{
					case AceColumnType.Title:
					case AceColumnType.UserName:
					case AceColumnType.Password:
					case AceColumnType.Url:
					case AceColumnType.Notes:
					case AceColumnType.CustomString:
						bRequestAsync = SprEngine.MightDeref(str);
						break;
					default: bRequestAsync = false; break;
				}

				if(!Program.Config.MainWindow.EntryListShowDerefDataAsync &&
					bRequestAsync)
				{
					PwListItem pli = new PwListItem(pe);
					str = AsyncPwListUpdate.SprCompileFn(str, pli);
					bRequestAsync = false;
				}
			}
			else bRequestAsync = false;

			return str;
		}

		private static AceColumn GetAceColumn(int nColID)
		{
			List<AceColumn> v = Program.Config.MainWindow.EntryListColumns;
			if((nColID < 0) || (nColID >= v.Count)) { Debug.Assert(false); return new AceColumn(); }

			return v[nColID];
		}

		private void ToggleFieldAsterisks(AceColumnType colType)
		{
			List<AceColumn> l = Program.Config.MainWindow.EntryListColumns;
			foreach(AceColumn c in l)
			{
				if(c.Type == colType)
				{
					if((colType == AceColumnType.Password) && c.HideWithAsterisks &&
						!AppPolicy.Try(AppPolicyId.UnhidePasswords))
						return;

					c.HideWithAsterisks = !c.HideWithAsterisks;
				}
			}

			RefreshEntriesList();
		}

		private void EditSelectedEntry(bool bSwitchToHistoryTab)
		{
			PwEntry pe = GetSelectedEntry(false);
			if(pe == null) return; // Do not assert

			PwDatabase pwDb = m_docMgr.ActiveDatabase;
			PwEntryForm pForm = new PwEntryForm();
			pForm.InitEx(pe, PwEditMode.EditExistingEntry, pwDb, m_ilCurrentIcons,
				false, false);

			pForm.InitSwitchToHistoryTab = bSwitchToHistoryTab;

			if(pForm.ShowDialog() == DialogResult.OK)
			{
				bool bUpdImg = pwDb.UINeedsIconUpdate;
				RefreshEntriesList(); // Update entry
				UpdateUI(false, null, bUpdImg, null, false, null, pForm.HasModifiedEntry);
			}
			else
			{
				bool bUpdImg = pwDb.UINeedsIconUpdate;
				RefreshEntriesList(); // Update last access time
				UpdateUI(false, null, bUpdImg, null, false, null, false);
			}
			UIUtil.DestroyForm(pForm);
		}

		private static bool ListContainsOnlyTans(PwObjectList<PwEntry> vEntries)
		{
			if(vEntries == null) { Debug.Assert(false); return true; }

			foreach(PwEntry pe in vEntries)
			{
				if(!PwDefs.IsTanEntry(pe)) return false;
			}

			return true;
		}

		private void OnShowEntriesByTag(object sender, DynamicMenuEventArgs e)
		{
			string strTag = (e.Tag as string);
			if(strTag == null) { Debug.Assert(false); return; }
			if(strTag.Length == 0) return; // No assert

			PwDatabase pd = m_docMgr.ActiveDatabase;
			if((pd == null) || !pd.IsOpen) { Debug.Assert(false); return; }

			PwObjectList<PwEntry> vEntries = new PwObjectList<PwEntry>();
			pd.RootGroup.FindEntriesByTag(strTag, vEntries, true);

			PwGroup pgResults = new PwGroup(true, true);
			pgResults.IsVirtual = true;
			foreach(PwEntry pe in vEntries) pgResults.AddEntry(pe, false);

			UpdateUI(false, null, false, null, true, pgResults, false);
		}

		private void UpdateTagsMenu(DynamicMenu dm, bool bWithSeparator, bool bPrefixTag,
			bool bRequireEntrySelected, bool bEnableOnlySelected)
		{
			if(dm == null) { Debug.Assert(false); return; }
			dm.Clear();

			if(bWithSeparator) dm.AddSeparator();

			string strNoTags = "(" + KPRes.TagsNotFound + ")";
			PwDatabase pd = m_docMgr.ActiveDatabase;
			if(!pd.IsOpen)
			{
				ToolStripMenuItem tsmi = dm.AddItem(strNoTags, null, string.Empty);
				tsmi.Enabled = false;
				return;
			}

			List<string> vTags = pd.RootGroup.BuildEntryTagsList(true);
			string strPrefix = KPRes.Tag + ": ";
			Image imgIcon = Properties.Resources.B16x16_KNotes;
			bool bEnable = (m_lvEntries.SelectedIndices.Count > 0);

			List<string> vEnabledTags = null;
			if(bEnableOnlySelected)
			{
				PwGroup pgSel = GetSelectedEntriesAsGroup();
				vEnabledTags = pgSel.BuildEntryTagsList(true);
			}

			for(int i = 0; i < vTags.Count; ++i)
			{
				string strTag = vTags[i];
				ToolStripMenuItem tsmi = dm.AddItem(bPrefixTag ? (strPrefix + strTag) :
					strTag, imgIcon, strTag);

				if(bRequireEntrySelected && !bEnable) tsmi.Enabled = false;
				else if(vEnabledTags != null)
				{
					if(vEnabledTags.IndexOf(strTag) < 0) tsmi.Enabled = false;
				}
			}

			if(vTags.Count == 0)
			{
				ToolStripMenuItem tsmi = dm.AddItem(strNoTags, null, string.Empty);
				tsmi.Enabled = false;
			}
		}

		private void OnAddEntryTag(object sender, DynamicMenuEventArgs e)
		{
			string strTag = (e.Tag as string);
			if(strTag == null) { Debug.Assert(false); return; }

			if(strTag.Length == 0)
			{
				SingleLineEditForm dlg = new SingleLineEditForm();
				dlg.InitEx(KPRes.TagNew, KPRes.TagAddNew, KPRes.Name + ":",
					Properties.Resources.B48x48_KMag, string.Empty, null);

				if(UIUtil.ShowDialogNotValue(dlg, DialogResult.OK)) return;
				strTag = dlg.ResultString;
				UIUtil.DestroyForm(dlg);
			}

			if(!string.IsNullOrEmpty(strTag))
				AddOrRemoveTagsToFromSelectedEntries(strTag, true);
		}

		private void OnRemoveEntryTag(object sender, DynamicMenuEventArgs e)
		{
			string strTag = (e.Tag as string);
			if(strTag == null) { Debug.Assert(false); return; }
			if(strTag.Length == 0) return;

			AddOrRemoveTagsToFromSelectedEntries(strTag, false);
		}

		private void AddOrRemoveTagsToFromSelectedEntries(string strTags, bool bAdd)
		{
			if(strTags == null) { Debug.Assert(false); return; }
			if(strTags.Length == 0) return;

			PwDatabase pd = m_docMgr.ActiveDatabase;
			PwEntry[] vEntries = GetSelectedEntries();
			if((vEntries == null) || (vEntries.Length == 0)) return;

			List<string> vToProcess = StrUtil.StringToTags(strTags);
			List<PwEntry> vModified = new List<PwEntry>();

			foreach(string strTag in vToProcess)
			{
				foreach(PwEntry pe in vEntries)
				{
					if(bAdd && !pe.HasTag(strTag)) // Add tag
					{
						if(vModified.IndexOf(pe) < 0) // Backup entries only once
						{
							pe.CreateBackup(pd);
							vModified.Add(pe);
						}

						if(!pe.AddTag(strTag)) { Debug.Assert(false); }
					}
					else if(!bAdd && pe.HasTag(strTag)) // Remove tag
					{
						if(vModified.IndexOf(pe) < 0) // Backup entries only once
						{
							pe.CreateBackup(pd);
							vModified.Add(pe);
						}

						if(!pe.RemoveTag(strTag)) { Debug.Assert(false); }
					}
				}
			}

			foreach(PwEntry pe in vModified) { pe.Touch(true, false); }

			RefreshEntriesList();
			UpdateUIState(vModified.Count > 0);
		}

		internal static void AutoAdjustMemProtSettings(PwDatabase pd,
			SearchParameters sp)
		{
			if(pd == null) { Debug.Assert(false); return; }

			// if(sp != null)
			// {
			//	if(sp.SearchInTitles) pd.MemoryProtection.ProtectTitle = false;
			//	if(sp.SearchInUserNames) pd.MemoryProtection.ProtectUserName = false;
			//	// if(sp.SearchInPasswords) pd.MemoryProtection.ProtectPassword = false;
			//	if(sp.SearchInUrls) pd.MemoryProtection.ProtectUrl = false;
			//	if(sp.SearchInNotes) pd.MemoryProtection.ProtectNotes = false;
			// }
		}

		private static bool? m_bCachedSelfTestResult = null;
		private static bool PerformSelfTest()
		{
			if(m_bCachedSelfTestResult.HasValue)
				return m_bCachedSelfTestResult.Value;

			bool bResult = true;
			try { SelfTest.Perform(); }
			catch(Exception exSelfTest)
			{
				MessageService.ShowWarning(KPRes.SelfTestFailed, exSelfTest);
				bResult = false;
			}

			m_bCachedSelfTestResult = bResult;
			return bResult;
		}

		private void SortSubGroups(bool bRecursive)
		{
			PwGroup pg = GetSelectedGroup();
			if(pg == null) return;

			if(!bRecursive && (pg.Groups.UCount <= 1)) return; // Nothing to do
			if(pg.Groups.UCount == 0) return; // Nothing to do

			pg.SortSubGroups(bRecursive);
			UpdateUI(false, null, true, null, false, null, true);
		}

		private bool CreateColorizedIcon(Icon icoBase, bool bLargeIcon,
			ref KeyValuePair<Color, Icon> kvpStore, out Icon icoAssignable,
			out Icon icoDisposable)
		{
			PwDatabase pd = m_docMgr.ActiveDatabase;
			Color clrNew = Color.Empty;
			if((pd == null) || !pd.IsOpen || pd.Color.IsEmpty || (pd.Color.A < 255)) { }
			else clrNew = pd.Color;

			if(UIUtil.ColorsEqual(clrNew, kvpStore.Key))
			{
				icoDisposable = null;
				icoAssignable = (kvpStore.Value ?? icoBase);
				return false;
			}

			icoDisposable = kvpStore.Value;
			if(UIUtil.ColorsEqual(clrNew, Color.Empty))
			{
				kvpStore = new KeyValuePair<Color, Icon>(Color.Empty, null);
				icoAssignable = icoBase;
			}
			else
			{
				kvpStore = new KeyValuePair<Color, Icon>(clrNew,
					UIUtil.CreateColorizedIcon(icoBase, clrNew,
						bLargeIcon ? 0 : 32));
				icoAssignable = kvpStore.Value;
			}

			return true;
		}

		private void SetObjectsDeletedStatus(uint uDeleted, bool bDbMntnc)
		{
			string str = (StrUtil.ReplaceCaseInsensitive(KPRes.ObjectsDeleted,
				@"{PARAM}", uDeleted.ToString()) + ".");
			SetStatusEx(str);
			if(!bDbMntnc || !Program.Config.UI.ShowDbMntncResultsDialog) return;

			VistaTaskDialog dlg = new VistaTaskDialog(this.Handle);
			dlg.CommandLinks = false;
			dlg.Content = str;
			dlg.SetIcon(VtdIcon.Information);
			dlg.VerificationText = KPRes.DialogNoShowAgain;
			dlg.WindowTitle = PwDefs.ShortProductName;
			if(dlg.ShowDialog())
			{
				if(dlg.ResultVerificationChecked)
					Program.Config.UI.ShowDbMntncResultsDialog = false;
			}
			else MessageService.ShowInfo(str);
		}

		private void ApplyUICustomizations()
		{
			ulong u = Program.Config.UI.UIFlags;
			if((u & (ulong)AceUIFlags.DisableOptions) != 0)
				m_menuToolsOptions.Enabled = false;
			if((u & (ulong)AceUIFlags.DisablePlugins) != 0)
				m_menuToolsPlugins.Enabled = false;
			if((u & (ulong)AceUIFlags.DisableTriggers) != 0)
				m_menuToolsTriggers.Enabled = false;
		}

		private static void OnFormLoadParallelAsync(object stateInfo)
		{
			try
			{
				string strShInstUtil = UrlUtil.GetFileDirectory(
					WinUtil.GetExecutable(), true, false) + AppDefs.ShInstUtil;

				// Unblock the application such that the user isn't
				// prompted next time anymore
				WinUtil.RemoveZoneIdentifier(WinUtil.GetExecutable());
				WinUtil.RemoveZoneIdentifier(AppHelp.LocalHelpFile);
				WinUtil.RemoveZoneIdentifier(strShInstUtil);
			}
			catch(Exception) { Debug.Assert(false); }
		}

		private bool IsCommandTypeInvokable(MainAppState? sContext, AppCommandType t)
		{
			MainAppState s = (sContext.HasValue ? sContext.Value : GetMainAppState());

			if(t == AppCommandType.Window)
				return (s.NoWindowShown && !UIIsInteractionBlocked());
			if(t == AppCommandType.Lock)
				return (s.NoWindowShown && !UIIsInteractionBlocked() && s.EnableLockCmd);

			return false;
		}

		private void UpdateTrayState()
		{
			UpdateUIState(false); // Update tray lock text

			ulong u = Program.Config.UI.UIFlags;
			bool bOptions = ((u & (ulong)AceUIFlags.DisableOptions) == 0);

			MainAppState s = GetMainAppState();

			m_ctxTrayTray.Enabled = IsCommandTypeInvokable(s, AppCommandType.Window);
			m_ctxTrayOptions.Enabled = (IsCommandTypeInvokable(s,
				AppCommandType.Window) && bOptions);
			m_ctxTrayLock.Enabled = IsCommandTypeInvokable(s, AppCommandType.Lock);
			m_ctxTrayFileExit.Enabled = IsCommandTypeInvokable(s, AppCommandType.Window);
		}

		internal static SprContext GetEntryListSprContext(PwEntry pe,
			PwDatabase pd)
		{
			SprContext ctx = new SprContext(pe, pd, SprCompileFlags.Deref);
			ctx.ForcePlainTextPasswords = false;
			return ctx;
		}

		private void EnsureAlwaysOnTopOpt()
		{
			bool bWish = Program.Config.MainWindow.AlwaysOnTop;
			if(KeePassLib.Native.NativeLib.IsUnix()) { this.TopMost = bWish; return; }

			// Workaround for issue reported in KPB 3475997
			this.TopMost = false;
			if(bWish) this.TopMost = true;
		}
	}
}