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
|
// **************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under *
// * GNU General Public License: http://www.gnu.org/licenses/gpl.html *
// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved *
// **************************************************************************
#include "main_dlg.h"
#include <zen/format_unit.h>
#include <zen/file_handling.h>
#include <zen/serialize.h>
//#include <zen/perf.h>
#include <zen/thread.h>
#include <wx/clipbrd.h>
#include <wx/wupdlock.h>
#include <wx/msgdlg.h>
#include <wx/sound.h>
#include <wx/filedlg.h>
#include <wx/display.h>
#include <wx+/context_menu.h>
#include <wx+/string_conv.h>
#include <wx+/bitmap_button.h>
#include <wx+/shell_execute.h>
#include <wx+/app_main.h>
#include <wx+/toggle_button.h>
#include <wx+/mouse_move_dlg.h>
#include <wx+/no_flicker.h>
#include <wx+/rtl.h>
#include <wx+/font_size.h>
#include "check_version.h"
#include "gui_status_handler.h"
#include "sync_cfg.h"
#include "small_dlgs.h"
#include "progress_indicator.h"
#include "msg_popup.h"
#include "folder_pair.h"
#include "search.h"
#include "batch_config.h"
#include "triple_splitter.h"
#include "../comparison.h"
#include "../synchronization.h"
#include "../algorithm.h"
#include "../lib/resources.h"
#include "../lib/resolve_path.h"
#include "../lib/ffs_paths.h"
#include "../lib/help_provider.h"
#include "../lib/lock_holder.h"
#include "../lib/localization.h"
#ifdef ZEN_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif
using namespace zen;
using namespace std::rel_ops;
namespace
{
struct wxClientHistoryData : public wxClientData //we need a wxClientData derived class to tell wxWidgets to take object ownership!
{
wxClientHistoryData(const Zstring& cfgFile, int lastUseIndex) : cfgFile_(cfgFile), lastUseIndex_(lastUseIndex) {}
Zstring cfgFile_;
int lastUseIndex_; //support sorting history by last usage, the higher the index the more recent the usage
};
IconBuffer::IconSize convert(xmlAccess::FileIconSize isize)
{
using namespace xmlAccess;
switch (isize)
{
case ICON_SIZE_SMALL:
return IconBuffer::SIZE_SMALL;
case ICON_SIZE_MEDIUM:
return IconBuffer::SIZE_MEDIUM;
case ICON_SIZE_LARGE:
return IconBuffer::SIZE_LARGE;
}
return IconBuffer::SIZE_SMALL;
}
}
class DirectoryNameMainImpl : public DirectoryName<FolderHistoryBox>
{
public:
DirectoryNameMainImpl(MainDialog& mainDlg,
wxWindow& dropWindow1,
Grid& dropGrid,
wxButton& dirSelectButton,
FolderHistoryBox& dirName,
wxStaticText& staticText) :
DirectoryName(dropWindow1, dirSelectButton, dirName, &staticText, &dropGrid.getMainWin()),
mainDlg_(mainDlg) {}
virtual bool acceptDrop(const std::vector<wxString>& droppedFiles, const wxPoint& clientPos, const wxWindow& wnd)
{
if (std::any_of(droppedFiles.begin(), droppedFiles.end(), [](const wxString& filename)
{
using namespace xmlAccess;
switch (getXmlType(utfCvrtTo<Zstring>(filename))) //throw()
{
case XML_TYPE_GUI:
case XML_TYPE_BATCH:
return true;
case XML_TYPE_GLOBAL:
case XML_TYPE_OTHER:
break;
}
return false;
}))
{
mainDlg_.loadConfiguration(toZ(droppedFiles));
return false;
}
//=> return true: change directory selection via drag and drop
return true;
}
private:
DirectoryNameMainImpl(const DirectoryNameMainImpl&);
DirectoryNameMainImpl& operator=(const DirectoryNameMainImpl&);
MainDialog& mainDlg_;
};
//------------------------------------------------------------------
/* class hierarchy:
template<>
FolderPairPanelBasic
/|\
|
template<>
FolderPairCallback FolderPairPanelGenerated
/|\ /|\
_________|________ ________|
| | |
FolderPairFirst FolderPairPanel
*/
template <class GuiPanel>
class FolderPairCallback : public FolderPairPanelBasic<GuiPanel> //implements callback functionality to MainDialog as imposed by FolderPairPanelBasic
{
public:
FolderPairCallback(GuiPanel& basicPanel, MainDialog& mainDialog) :
FolderPairPanelBasic<GuiPanel>(basicPanel), //pass FolderPairPanelGenerated part...
mainDlg(mainDialog) {}
private:
virtual MainConfiguration getMainConfig() const { return mainDlg.getConfig().mainCfg; }
virtual wxWindow* getParentWindow() { return &mainDlg; }
virtual std::unique_ptr<FilterConfig>& getFilterCfgOnClipboardRef() { return mainDlg.filterCfgOnClipboard; }
virtual void onAltCompCfgChange () { mainDlg.applyCompareConfig(); }
virtual void onAltSyncCfgChange () { mainDlg.applySyncConfig(); }
virtual void onLocalFilterCfgChange() { mainDlg.applyFilterConfig(); } //re-apply filter
MainDialog& mainDlg;
};
class FolderPairPanel :
public FolderPairPanelGenerated, //FolderPairPanel "owns" FolderPairPanelGenerated!
public FolderPairCallback<FolderPairPanelGenerated>
{
public:
FolderPairPanel(wxWindow* parent, MainDialog& mainDialog) :
FolderPairPanelGenerated(parent),
FolderPairCallback<FolderPairPanelGenerated>(static_cast<FolderPairPanelGenerated&>(*this), mainDialog), //pass FolderPairPanelGenerated part...
dirNameLeft (*m_panelLeft, *m_buttonSelectDirLeft, *m_directoryLeft),
dirNameRight(*m_panelRight, *m_buttonSelectDirRight, *m_directoryRight)
{
dirNameLeft .Connect(EVENT_ON_DIR_SELECTED, wxCommandEventHandler(MainDialog::onDirSelected), nullptr, &mainDialog);
dirNameRight.Connect(EVENT_ON_DIR_SELECTED, wxCommandEventHandler(MainDialog::onDirSelected), nullptr, &mainDialog);
dirNameLeft .Connect(EVENT_ON_DIR_MANUAL_CORRECTION, wxCommandEventHandler(MainDialog::onDirManualCorrection), nullptr, &mainDialog);
dirNameRight.Connect(EVENT_ON_DIR_MANUAL_CORRECTION, wxCommandEventHandler(MainDialog::onDirManualCorrection), nullptr, &mainDialog);
}
void setValues(const Zstring& leftDir,
const Zstring& rightDir,
AltCompCfgPtr cmpCfg,
AltSyncCfgPtr syncCfg,
const FilterConfig& filter)
{
setConfig(cmpCfg, syncCfg, filter);
dirNameLeft .setName(toWx(leftDir));
dirNameRight.setName(toWx(rightDir));
}
Zstring getLeftDir () const { return toZ(dirNameLeft .getName()); }
Zstring getRightDir() const { return toZ(dirNameRight.getName()); }
private:
//support for drag and drop
DirectoryName<FolderHistoryBox> dirNameLeft;
DirectoryName<FolderHistoryBox> dirNameRight;
};
class FolderPairFirst : public FolderPairCallback<MainDialogGenerated>
{
public:
FolderPairFirst(MainDialog& mainDialog) :
FolderPairCallback<MainDialogGenerated>(mainDialog, mainDialog),
//prepare drag & drop
dirNameLeft(mainDialog,
*mainDialog.m_panelTopLeft,
*mainDialog.m_gridMainL,
*mainDialog.m_buttonSelectDirLeft,
*mainDialog.m_directoryLeft,
*mainDialog.m_staticTextResolvedPathL),
dirNameRight(mainDialog,
*mainDialog.m_panelTopRight,
*mainDialog.m_gridMainR,
*mainDialog.m_buttonSelectDirRight,
*mainDialog.m_directoryRight,
*mainDialog.m_staticTextResolvedPathR)
{
dirNameLeft .Connect(EVENT_ON_DIR_SELECTED, wxCommandEventHandler(MainDialog::onDirSelected), nullptr, &mainDialog);
dirNameRight.Connect(EVENT_ON_DIR_SELECTED, wxCommandEventHandler(MainDialog::onDirSelected), nullptr, &mainDialog);
dirNameLeft .Connect(EVENT_ON_DIR_MANUAL_CORRECTION, wxCommandEventHandler(MainDialog::onDirManualCorrection), nullptr, &mainDialog);
dirNameRight.Connect(EVENT_ON_DIR_MANUAL_CORRECTION, wxCommandEventHandler(MainDialog::onDirManualCorrection), nullptr, &mainDialog);
}
void setValues(const Zstring& leftDir,
const Zstring& rightDir,
AltCompCfgPtr cmpCfg,
AltSyncCfgPtr syncCfg,
const FilterConfig& filter)
{
setConfig(cmpCfg, syncCfg, filter);
dirNameLeft .setName(toWx(leftDir));
dirNameRight.setName(toWx(rightDir));
}
Zstring getLeftDir () const { return toZ(dirNameLeft .getName()); }
Zstring getRightDir() const { return toZ(dirNameRight.getName()); }
private:
//support for drag and drop
DirectoryNameMainImpl dirNameLeft;
DirectoryNameMainImpl dirNameRight;
};
#ifdef ZEN_WIN
class PanelMoveWindow : public MouseMoveWindow
{
public:
PanelMoveWindow(MainDialog& mainDlg) :
MouseMoveWindow(mainDlg, false), //don't include main dialog itself, thereby prevent various mouse capture lost issues
mainDlg_(mainDlg) {}
virtual bool allowMove(const wxMouseEvent& event)
{
if (wxPanel* panel = dynamic_cast<wxPanel*>(event.GetEventObject()))
{
const wxAuiPaneInfo& paneInfo = mainDlg_.auiMgr.GetPane(panel);
if (paneInfo.IsOk() &&
paneInfo.IsFloating())
return false; //prevent main dialog move
}
return true; //allow dialog move
}
private:
MainDialog& mainDlg_;
};
#endif
namespace
{
//workaround for wxWidgets bug failing to update menu item bitmaps (affects Windows- and Linux-build)
void setMenuItemImage(wxMenuItem*& menuItem, const wxBitmap& bmp)
{
assert(menuItem->GetKind() == wxITEM_NORMAL);
//support polling
if (isEqual(bmp, menuItem->GetBitmap()))
return;
if (wxMenu* menu = menuItem->GetMenu())
{
int pos = menu->GetMenuItems().IndexOf(menuItem);
if (pos != wxNOT_FOUND)
{
/*
menu->Remove(menuItem); ->this simple sequence crashes on Kubuntu x64, wxWidgets 2.9.2
menu->Insert(pos, menuItem);
*/
const bool enabled = menuItem->IsEnabled();
wxMenuItem* newItem = new wxMenuItem(menu, menuItem->GetId(), menuItem->GetItemLabel());
newItem->SetBitmap(bmp);
#ifdef __WXMSW__ //not availabe on wxGTK or wxOSX
//for some inconceivable reason wxWidgets is not consistent with itself and renders disabled icons
//just greyscale instead of brightened like bitmap buttons; much better:
newItem->SetDisabledBitmap(bmp.ConvertToDisabled());
#endif
bool isDestroyed = menu->Destroy(menuItem); //actual workaround
assert(isDestroyed);
(void)isDestroyed;
menuItem = menu->Insert(pos, newItem); //don't forget to update input item pointer!
if (!enabled)
menuItem->Enable(false); //do not enable BEFORE appending item! wxWidgets screws up for yet another crappy reason
}
}
}
//##################################################################################################################################
xmlAccess::XmlGlobalSettings retrieveGlobalCfgFromDisk() //blocks on GUI on errors!
{
using namespace xmlAccess;
XmlGlobalSettings globalCfg;
try
{
if (fileExists(getGlobalConfigFile()))
readConfig(globalCfg); //throw FfsXmlError
//else: globalCfg already has default values
}
catch (const FfsXmlError& e)
{
assert(false);
if (e.getSeverity() != FfsXmlError::WARNING) //ignore parsing errors: should be migration problems only *cross-fingers*
wxMessageBox(e.toString(), L"FreeFileSync - " + _("Error"), wxOK | wxICON_ERROR);
}
return globalCfg;
}
}
void MainDialog::create()
{
using namespace xmlAccess;
const XmlGlobalSettings globalSettings = retrieveGlobalCfgFromDisk();
std::vector<Zstring> filenames = globalSettings.gui.lastUsedConfigFiles; //2. now try last used files
//------------------------------------------------------------------------------------------
//check existence of all files in parallel:
RunUntilFirstHit<NullType> findFirstMissing;
std::for_each(filenames.begin(), filenames.end(), [&](const Zstring& filename)
{
findFirstMissing.addJob([=] { return filename.empty() /*ever empty??*/ || !fileExists(filename) ? zen::make_unique<NullType>() : nullptr; });
});
//potentially slow network access: give all checks 500ms to finish
const bool allFilesExist = findFirstMissing.timedWait(boost::posix_time::milliseconds(500)) && //false: time elapsed
!findFirstMissing.get(); //no missing
if (!allFilesExist)
filenames.clear(); //we do NOT want to show an error due to last config file missing on application start!
//------------------------------------------------------------------------------------------
if (filenames.empty())
{
if (zen::fileExists(lastRunConfigName())) //3. try to load auto-save config
filenames.push_back(lastRunConfigName());
}
XmlGuiConfig guiCfg; //structure to receive gui settings with default values
if (filenames.empty())
{
//add default exclusion filter: this is only ever relevant when creating new configurations!
//a default XmlGuiConfig does not need these user-specific exclusions!
Zstring& excludeFilter = guiCfg.mainCfg.globalFilter.excludeFilter;
if (!excludeFilter.empty() && !endsWith(excludeFilter, Zstr("\n")))
excludeFilter += Zstr("\n");
excludeFilter += globalSettings.gui.defaultExclusionFilter;
}
else
try
{
readAnyConfig(filenames, guiCfg); //throw FfsXmlError
}
catch (const FfsXmlError& error)
{
if (error.getSeverity() == FfsXmlError::WARNING)
wxMessageBox(error.toString(), L"FreeFileSync - " + _("Warning"), wxOK | wxICON_WARNING);
//what about simulating changed config on parsing errors????
else
wxMessageBox(error.toString(), L"FreeFileSync - " + _("Error"), wxOK | wxICON_ERROR);
}
//------------------------------------------------------------------------------------------
create(guiCfg, filenames, &globalSettings, false);
}
void MainDialog::create(const xmlAccess::XmlGuiConfig& guiCfg,
const std::vector<Zstring>& referenceFiles,
const xmlAccess::XmlGlobalSettings* globalSettings,
bool startComparison)
{
const xmlAccess::XmlGlobalSettings& globSett = globalSettings ? *globalSettings : retrieveGlobalCfgFromDisk();
try
{
//we need to set language *before* creating MainDialog!
setLanguage(globSett.programLanguage); //throw FileError
}
catch (const FileError& e)
{
wxMessageBox(e.toString().c_str(), L"FreeFileSync - " + _("Error"), wxOK | wxICON_ERROR);
//continue!
}
MainDialog* frame = new MainDialog(guiCfg, referenceFiles, globSett, startComparison);
frame->Show();
#ifdef ZEN_MAC
ProcessSerialNumber psn = { 0, kCurrentProcess };
::TransformProcessType(&psn, kProcessTransformToForegroundApplication); //show dock icon, even if we're not an application bundle
//if the executable is not yet in a bundle or if it is called through a launcher, we need to set focus manually:
::SetFrontProcess(&psn);
#endif
}
MainDialog::MainDialog(const xmlAccess::XmlGuiConfig& guiCfg,
const std::vector<Zstring>& referenceFiles,
const xmlAccess::XmlGlobalSettings& globalSettings,
bool startComparison) :
MainDialogGenerated(nullptr),
folderHistoryLeft (std::make_shared<FolderHistory>()), //make sure it is always bound
folderHistoryRight(std::make_shared<FolderHistory>()), //
focusWindowAfterSearch(nullptr)
{
m_directoryLeft ->init(folderHistoryLeft);
m_directoryRight->init(folderHistoryRight);
//setup sash: detach + reparent:
m_splitterMain->SetSizer(nullptr); //alas wxFormbuilder doesn't allow us to have child windows without a sizer, so we have to remove it here
m_splitterMain->setupWindows(m_gridMainL, m_gridMainC, m_gridMainR);
wxWindowUpdateLocker dummy(this); //avoid display distortion
setRelativeFontSize(*m_buttonCompare, 1.5);
setRelativeFontSize(*m_buttonSync, 1.5);
setRelativeFontSize(*m_buttonCancel, 1.5);
//---------------- support for dockable gui style --------------------------------
bSizerPanelHolder->Detach(m_panelTopButtons);
bSizerPanelHolder->Detach(m_panelDirectoryPairs);
bSizerPanelHolder->Detach(m_gridNavi);
bSizerPanelHolder->Detach(m_panelCenter);
bSizerPanelHolder->Detach(m_panelConfig);
bSizerPanelHolder->Detach(m_panelFilter);
bSizerPanelHolder->Detach(m_panelViewFilter);
bSizerPanelHolder->Detach(m_panelStatistics);
auiMgr.SetManagedWindow(this);
auiMgr.SetFlags(wxAUI_MGR_DEFAULT | wxAUI_MGR_LIVE_RESIZE);
compareStatus = make_unique<CompareProgressDialog>(*this); //integrate the compare status panel (in hidden state)
//caption required for all panes that can be manipulated by the users => used by context menu
auiMgr.AddPane(m_panelCenter,
wxAuiPaneInfo().Name(L"Panel3").CenterPane().PaneBorder(false));
auiMgr.AddPane(m_panelDirectoryPairs,
wxAuiPaneInfo().Name(L"Panel2").Layer(2).Top().Caption(_("Folder pairs")).CaptionVisible(false).PaneBorder(false).Gripper());
auiMgr.AddPane(m_panelSearch,
wxAuiPaneInfo().Name(L"PanelFind").Layer(2).Bottom().Caption(_("Find")).CaptionVisible(false).PaneBorder(false).Gripper().MinSize(200, m_bpButtonHideSearch->GetSize().GetHeight()).Hide());
auiMgr.AddPane(m_gridNavi,
wxAuiPaneInfo().Name(L"Panel10").Layer(3).Left().Position(1).Caption(_("Overview")).MinSize(300, m_gridNavi->GetSize().GetHeight())); //MinSize(): just default size, see comment below
auiMgr.AddPane(m_panelConfig,
wxAuiPaneInfo().Name(L"Panel4").Layer(3).Left().Position(2).Caption(_("Configuration")).MinSize(m_listBoxHistory->GetSize().GetWidth(), m_panelConfig->GetSize().GetHeight()));
auiMgr.AddPane(m_panelTopButtons,
wxAuiPaneInfo().Name(L"Panel1").Layer(4).Top().Row(1).Caption(_("Main bar")).CaptionVisible(false).PaneBorder(false).Gripper().MinSize(-1, m_panelTopButtons->GetSize().GetHeight()));
//note: min height is calculated incorrectly by wxAuiManager if panes with and without caption are in the same row => use smaller min-size
auiMgr.AddPane(compareStatus->getAsWindow(),
wxAuiPaneInfo().Name(L"Panel9").Layer(4).Top().Row(2).CaptionVisible(false).PaneBorder(false).Hide());
auiMgr.AddPane(m_panelFilter,
wxAuiPaneInfo().Name(L"Panel5").Layer(4).Bottom().Position(1).Caption(_("Filter files")).MinSize(m_bpButtonFilter->GetSize().GetWidth(), m_panelFilter->GetSize().GetHeight()));
auiMgr.AddPane(m_panelViewFilter,
wxAuiPaneInfo().Name(L"Panel6").Layer(4).Bottom().Position(2).Caption(_("Select view")).MinSize(m_bpButtonShowDoNothing->GetSize().GetWidth(), m_panelViewFilter->GetSize().GetHeight()));
auiMgr.AddPane(m_panelStatistics,
wxAuiPaneInfo().Name(L"Panel7").Layer(4).Bottom().Position(3).Caption(_("Statistics")).MinSize(m_bitmapData->GetSize().GetWidth() + m_staticTextData->GetSize().GetWidth(), m_panelStatistics->GetSize().GetHeight()));
auiMgr.Update();
//give panel captions bold typeface
if (wxAuiDockArt* artProvider = auiMgr.GetArtProvider())
{
wxFont font = artProvider->GetFont(wxAUI_DOCKART_CAPTION_FONT);
font.SetWeight(wxFONTWEIGHT_BOLD);
font.SetPointSize(wxNORMAL_FONT->GetPointSize()); //= larger than the wxAuiDockArt default; looks better on OS X
artProvider->SetFont(wxAUI_DOCKART_CAPTION_FONT, font);
//accessibility: fix wxAUI drawing black text on black background on high-contrast color schemes:
artProvider->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
}
auiMgr.GetPane(m_gridNavi).MinSize(-1, -1); //we successfully tricked wxAuiManager into setting an initial Window size :> incomplete API anyone??
auiMgr.Update(); //
defaultPerspective = auiMgr.SavePerspective();
//----------------------------------------------------------------------------------
//register view layout context menu
m_panelTopButtons->Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(MainDialog::OnContextSetLayout), nullptr, this);
m_panelConfig ->Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(MainDialog::OnContextSetLayout), nullptr, this);
m_panelFilter ->Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(MainDialog::OnContextSetLayout), nullptr, this);
m_panelViewFilter->Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(MainDialog::OnContextSetLayout), nullptr, this);
m_panelStatistics->Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(MainDialog::OnContextSetLayout), nullptr, this);
m_panelStatusBar ->Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(MainDialog::OnContextSetLayout), nullptr, this);
//----------------------------------------------------------------------------------
//sort grids
m_gridMainL->Connect(EVENT_GRID_COL_LABEL_MOUSE_LEFT, GridClickEventHandler(MainDialog::onGridLabelLeftClickL ), nullptr, this);
m_gridMainC->Connect(EVENT_GRID_COL_LABEL_MOUSE_LEFT, GridClickEventHandler(MainDialog::onGridLabelLeftClickC ), nullptr, this);
m_gridMainR->Connect(EVENT_GRID_COL_LABEL_MOUSE_LEFT, GridClickEventHandler(MainDialog::onGridLabelLeftClickR ), nullptr, this);
m_gridMainL->Connect(EVENT_GRID_COL_LABEL_MOUSE_RIGHT, GridClickEventHandler(MainDialog::onGridLabelContextL ), nullptr, this);
m_gridMainC->Connect(EVENT_GRID_COL_LABEL_MOUSE_RIGHT, GridClickEventHandler(MainDialog::onGridLabelContextC ), nullptr, this);
m_gridMainR->Connect(EVENT_GRID_COL_LABEL_MOUSE_RIGHT, GridClickEventHandler(MainDialog::onGridLabelContextR ), nullptr, this);
//grid context menu
m_gridMainL->Connect(EVENT_GRID_MOUSE_RIGHT_UP, GridClickEventHandler(MainDialog::onMainGridContextL), nullptr, this);
m_gridMainC->Connect(EVENT_GRID_MOUSE_RIGHT_UP, GridClickEventHandler(MainDialog::onMainGridContextC), nullptr, this);
m_gridMainR->Connect(EVENT_GRID_MOUSE_RIGHT_UP, GridClickEventHandler(MainDialog::onMainGridContextR), nullptr, this);
m_gridNavi ->Connect(EVENT_GRID_MOUSE_RIGHT_UP, GridClickEventHandler(MainDialog::onNaviGridContext ), nullptr, this);
m_gridMainL->Connect(EVENT_GRID_MOUSE_LEFT_DOUBLE, GridClickEventHandler(MainDialog::onGridDoubleClickL), nullptr, this );
m_gridMainR->Connect(EVENT_GRID_MOUSE_LEFT_DOUBLE, GridClickEventHandler(MainDialog::onGridDoubleClickR), nullptr, this );
m_gridNavi->Connect(EVENT_GRID_SELECT_RANGE, GridRangeSelectEventHandler(MainDialog::onNaviSelection), nullptr, this);
//----------------------------------------------------------------------------------
m_panelSearch->Connect(wxEVT_CHAR_HOOK, wxKeyEventHandler(MainDialog::OnSearchPanelKeyPressed), nullptr, this);
//set tool tips with (non-translated!) short cut hint
m_bpButtonOpen ->SetToolTip(_("Open...") + L" (Ctrl+O)");
m_bpButtonSave ->SetToolTip(_("Save") + L" (Ctrl+S)");
m_buttonCompare ->SetToolTip(_("Compare both sides") + L" (F5)");
m_bpButtonCmpConfig ->SetToolTip(_("Comparison settings") + L" (F6)");
m_bpButtonSyncConfig->SetToolTip(_("Synchronization settings") + L" (F7)");
m_buttonSync ->SetToolTip(_("Start synchronization") + L" (F8)");
gridDataView = std::make_shared<GridView>();
treeDataView = std::make_shared<TreeView>();
cleanedUp = false;
processingGlobalKeyEvent = false;
#ifdef ZEN_WIN
new PanelMoveWindow(*this); //allow moving main dialog by clicking (nearly) anywhere... //ownership passed to "this"
#endif
SetIcon(GlobalResources::instance().programIconFFS); //set application icon
//notify about (logical) application main window => program won't quit, but stay on this dialog
zen::setMainWindow(this);
//init handling of first folder pair
firstFolderPair = make_unique<FolderPairFirst>(*this);
initViewFilterButtons();
//init grid settings
gridview::init(*m_gridMainL, *m_gridMainC, *m_gridMainR, gridDataView);
treeview::init(*m_gridNavi, treeDataView);
//initialize and load configuration
setGlobalCfgOnInit(globalSettings);
setConfig(guiCfg, referenceFiles);
//set icons for this dialog
m_bpButtonSyncConfig->SetBitmapLabel(getResourceImage(L"cfg_sync"));
m_bpButtonCmpConfig ->SetBitmapLabel(getResourceImage(L"cfg_compare"));
m_bpButtonOpen ->SetBitmapLabel(getResourceImage(L"load"));
m_bpButtonBatchJob ->SetBitmapLabel(getResourceImage(L"batch"));
m_bpButtonAddPair ->SetBitmapLabel(getResourceImage(L"item_add"));
m_bpButtonHideSearch->SetBitmapLabel(getResourceImage(L"close_panel"));
//we can't use a wxButton for cancel: it's rendered smaller on OS X than a wxBitmapButton!
setBitmapTextLabel(*m_buttonCancel, wxImage(), m_buttonCancel->GetLabel());
{
IconBuffer tmp(IconBuffer::SIZE_SMALL);
const wxBitmap& bmpFile = tmp.genericFileIcon();
const wxBitmap& bmpDir = tmp.genericDirIcon();
m_bitmapSmallDirectoryLeft ->SetBitmap(bmpDir);
m_bitmapSmallFileLeft ->SetBitmap(bmpFile);
m_bitmapSmallDirectoryRight->SetBitmap(bmpDir);
m_bitmapSmallFileRight ->SetBitmap(bmpFile);
}
const int dummySize = 5;
wxImage dummyImg(dummySize, dummySize);
if (!dummyImg.HasAlpha())
dummyImg.InitAlpha();
std::fill(dummyImg.GetAlpha(), dummyImg.GetAlpha() + dummySize * dummySize, wxIMAGE_ALPHA_TRANSPARENT);
//menu icons: workaround for wxWidgets: small hack to update menu items: actually this is a wxWidgets bug (affects Windows- and Linux-build)
setMenuItemImage(m_menuItem10, getResourceImage(L"compare_small"));
setMenuItemImage(m_menuItem11, getResourceImage(L"sync_small"));
setMenuItemImage(m_menuItemNew, dummyImg); //it's ridiculous, but wxWidgets screws up aligning short-cut label texts if we don't set an image!
setMenuItemImage(m_menuItemSaveAs, dummyImg);
setMenuItemImage(m_menuItemLoad, getResourceImage(L"load_small"));
setMenuItemImage(m_menuItemSave, getResourceImage(L"save_small"));
setMenuItemImage(m_menuItemGlobSett, getResourceImage(L"settings_small"));
setMenuItemImage(m_menuItem7, getResourceImage(L"batch_small"));
setMenuItemImage(m_menuItemManual, getResourceImage(L"help_small"));
setMenuItemImage(m_menuItemAbout, getResourceImage(L"about_small"));
if (!manualProgramUpdateRequired())
{
m_menuItemCheckVersionNow ->Enable(false);
m_menuItemCheckVersionAuto->Enable(false);
//wxFormbuilder doesn't give us a wxMenuItem for m_menuCheckVersion, so we need this abomination:
wxMenuItemList& items = m_menuHelp->GetMenuItems();
for (auto it = items.begin(); it != items.end(); ++it)
if ((*it)->GetSubMenu() == m_menuCheckVersion)
(*it)->Enable(false);
}
//create language selection menu
std::for_each(zen::ExistingTranslations::get().begin(), ExistingTranslations::get().end(),
[&](const ExistingTranslations::Entry& entry)
{
wxMenuItem* newItem = new wxMenuItem(m_menuLanguages, wxID_ANY, entry.languageName);
newItem->SetBitmap(getResourceImage(entry.languageFlag));
//map menu item IDs with language IDs: evaluated when processing event handler
languageMenuItemMap.insert(std::make_pair(newItem->GetId(), entry.languageID));
//connect event
this->Connect(newItem->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MainDialog::OnMenuLanguageSwitch));
m_menuLanguages->Append(newItem);
});
//support for CTRL + C and DEL on grids
m_gridMainL->getMainWin().Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(MainDialog::onGridButtonEventL), nullptr, this);
m_gridMainC->getMainWin().Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(MainDialog::onGridButtonEventC), nullptr, this);
m_gridMainR->getMainWin().Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(MainDialog::onGridButtonEventR), nullptr, this);
m_gridNavi->getMainWin().Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(MainDialog::onTreeButtonEvent), nullptr, this);
//register global hotkeys (without explicit menu entry)
wxTheApp->Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(MainDialog::OnGlobalKeyEvent), nullptr, this);
wxTheApp->Connect(wxEVT_CHAR_HOOK, wxKeyEventHandler(MainDialog::OnGlobalKeyEvent), nullptr, this); //capture direction keys
//drag & drop on navi panel
setupFileDrop(*m_gridNavi);
m_gridNavi->Connect(EVENT_DROP_FILE, FileDropEventHandler(MainDialog::onNaviPanelFilesDropped), nullptr, this);
timerForAsyncTasks.Connect(wxEVT_TIMER, wxEventHandler(MainDialog::onProcessAsyncTasks), nullptr, this);
//Connect(wxEVT_SIZE, wxSizeEventHandler(MainDialog::OnResize), nullptr, this);
//Connect(wxEVT_MOVE, wxSizeEventHandler(MainDialog::OnResize), nullptr, this);
//calculate witdh of folder pair manually (if scrollbars are visible)
m_panelTopLeft->Connect(wxEVT_SIZE, wxEventHandler(MainDialog::OnResizeLeftFolderWidth), nullptr, this);
//dynamically change sizer direction depending on size
m_panelConfig ->Connect(wxEVT_SIZE, wxEventHandler(MainDialog::OnResizeConfigPanel), nullptr, this);
m_panelViewFilter->Connect(wxEVT_SIZE, wxEventHandler(MainDialog::OnResizeViewPanel), nullptr, this);
m_panelStatistics->Connect(wxEVT_SIZE, wxEventHandler(MainDialog::OnResizeStatisticsPanel), nullptr, this);
wxSizeEvent dummy3;
OnResizeConfigPanel (dummy3); //call once on window creation
OnResizeViewPanel (dummy3); //
OnResizeStatisticsPanel(dummy3); //
//event handler for manual (un-)checking of rows and setting of sync direction
m_gridMainC->Connect(EVENT_GRID_CHECK_ROWS, CheckRowsEventHandler (MainDialog::onCheckRows), nullptr, this);
m_gridMainC->Connect(EVENT_GRID_SYNC_DIRECTION, SyncDirectionEventHandler(MainDialog::onSetSyncDirection), nullptr, this);
//mainly to update row label sizes...
updateGui();
//register regular check for update on next idle event
Connect(wxEVT_IDLE, wxIdleEventHandler(MainDialog::OnRegularUpdateCheck), nullptr, this);
//asynchronous call to wxWindow::Layout(): fix superfluous frame on right and bottom when FFS is started in fullscreen mode
Connect(wxEVT_IDLE, wxIdleEventHandler(MainDialog::OnLayoutWindowAsync), nullptr, this);
wxCommandEvent evtDummy; //call once before OnLayoutWindowAsync()
OnResizeLeftFolderWidth(evtDummy); //
//----------------------------------------------------------------------------------------------------------------------------------------------------------------
//some convenience: if FFS is started with a *.ffs_gui file as commandline parameter AND all directories contained exist, comparison shall be started right away
if (startComparison)
{
const zen::MainConfiguration currMainCfg = getConfig().mainCfg;
//------------------------------------------------------------------------------------------
//check existence of all directories in parallel!
RunUntilFirstHit<NullType> findFirstMissing;
//harmonize checks with comparison.cpp:: checkForIncompleteInput()
//we're really doing two checks: 1. check directory existence 2. check config validity -> don't mix them!
bool havePartialPair = false;
bool haveFullPair = false;
auto addDirCheck = [&](const FolderPairEnh& fp)
{
const Zstring dirLeft = getFormattedDirectoryName(fp.leftDirectory ); //should not block!?
const Zstring dirRight = getFormattedDirectoryName(fp.rightDirectory); //
if (dirLeft.empty() != dirRight.empty()) //only skip check if both sides are empty!
havePartialPair = true;
else if (!dirLeft.empty())
haveFullPair = true;
if (!dirLeft.empty())
findFirstMissing.addJob([=] { return !dirExists(dirLeft ) ? zen::make_unique<NullType>() : nullptr; });
if (!dirRight.empty())
findFirstMissing.addJob([=] { return !dirExists(dirRight) ? zen::make_unique<NullType>() : nullptr; });
};
addDirCheck(currMainCfg.firstPair);
std::for_each(currMainCfg.additionalPairs.begin(), currMainCfg.additionalPairs.end(), addDirCheck);
//------------------------------------------------------------------------------------------
if (havePartialPair != haveFullPair) //either all pairs full or all half-filled -> validity check!
{
//potentially slow network access: give all checks 500ms to finish
const bool allFilesExist = findFirstMissing.timedWait(boost::posix_time::milliseconds(500)) && //true: have result
!findFirstMissing.get(); //no missing
if (allFilesExist)
if (wxEvtHandler* evtHandler = m_buttonCompare->GetEventHandler())
{
wxCommandEvent dummy2(wxEVT_COMMAND_BUTTON_CLICKED);
evtHandler->AddPendingEvent(dummy2); //simulate button click on "compare"
}
}
}
}
MainDialog::~MainDialog()
{
try //save "GlobalSettings.xml"
{
xmlAccess::writeConfig(getGlobalCfgBeforeExit()); //throw FfsXmlError
}
catch (const xmlAccess::FfsXmlError& e)
{
wxMessageBox(e.toString().c_str(), L"FreeFileSync - " + _("Error"), wxOK | wxICON_ERROR, this);
}
try //save "LastRun.ffs_gui"
{
xmlAccess::writeConfig(getConfig(), lastRunConfigName()); //throw FfsXmlError
}
//don't annoy users on read-only drives: it's enough to show a single error message when saving global config
catch (const xmlAccess::FfsXmlError&) {}
//important! event source wxTheApp is NOT dependent on this instance -> disconnect!
wxTheApp->Disconnect(wxEVT_KEY_DOWN, wxKeyEventHandler(MainDialog::OnGlobalKeyEvent), nullptr, this);
wxTheApp->Disconnect(wxEVT_CHAR_HOOK, wxKeyEventHandler(MainDialog::OnGlobalKeyEvent), nullptr, this);
#ifdef ZEN_MAC
//more (non-portable) wxWidgets crap: wxListBox leaks wxClientData, both of the following functions fail to clean up:
// src/common/ctrlsub.cpp:: wxItemContainer::~wxItemContainer() -> empty function body!!!
// src/osx/listbox_osx.cpp: wxListBox::~wxListBox()
//=> finally a manual wxItemContainer::Clear() will render itself useful:
m_listBoxHistory->Clear();
#endif
auiMgr.UnInit();
//no need for wxEventHandler::Disconnect() here; event sources are components of this window and are destroyed, too
}
//-------------------------------------------------------------------------------------------------------------------------------------
void MainDialog::onQueryEndSession()
{
try { xmlAccess::writeConfig(getGlobalCfgBeforeExit()); }
catch (const xmlAccess::FfsXmlError&) {} //we try our best do to something useful in this extreme situation - no reason to notify or even log errors here!
try { xmlAccess::writeConfig(getConfig(), lastRunConfigName()); }
catch (const xmlAccess::FfsXmlError&) {}
}
void MainDialog::setGlobalCfgOnInit(const xmlAccess::XmlGlobalSettings& globalSettings)
{
globalCfg = globalSettings;
//caveat set/get language asymmmetry! setLanguage(globalSettings.programLanguage); //throw FileError
//we need to set langugabe before creating this class!
//set dialog size and position:
// - width/height are invalid if the window is minimized (eg x,y == -32000; height = 28, width = 160)
// - multi-monitor setups: dialog may be placed on second monitor which is currently turned off
if (globalSettings.gui.dlgSize.GetWidth () > 0 &&
globalSettings.gui.dlgSize.GetHeight() > 0)
{
//calculate how much of the dialog will be visible on screen
const int dialogAreaTotal = globalSettings.gui.dlgSize.GetWidth() * globalSettings.gui.dlgSize.GetHeight();
int dialogAreaVisible = 0;
const int monitorCount = wxDisplay::GetCount();
for (int i = 0; i < monitorCount; ++i)
{
wxRect intersection = wxDisplay(i).GetClientArea().Intersect(wxRect(globalSettings.gui.dlgPos, globalSettings.gui.dlgSize));
dialogAreaVisible = std::max(dialogAreaVisible, intersection.GetWidth() * intersection.GetHeight());
}
if (dialogAreaVisible > 0.1 * dialogAreaTotal) //at least 10% of the dialog should be visible!
SetSize(wxRect(globalSettings.gui.dlgPos, globalSettings.gui.dlgSize));
else
{
SetSize(wxRect(globalSettings.gui.dlgSize));
Centre();
}
}
else
Centre();
Maximize(globalSettings.gui.isMaximized);
//set column attributes
m_gridMainL ->setColumnConfig(gridview::convertConfig(globalSettings.gui.columnAttribLeft));
m_gridMainR ->setColumnConfig(gridview::convertConfig(globalSettings.gui.columnAttribRight));
m_splitterMain->setSashOffset(globalSettings.gui.sashOffset);
m_gridNavi->setColumnConfig(treeview::convertConfig(globalSettings.gui.columnAttribNavi));
treeview::setShowPercentage(*m_gridNavi, globalSettings.gui.showPercentBar);
treeDataView->setSortDirection(globalSettings.gui.naviLastSortColumn, globalSettings.gui.naviLastSortAscending);
//--------------------------------------------------------------------------------
//load list of last used configuration files
std::vector<Zstring> cfgFileNames = globalSettings.gui.cfgFileHistory;
std::reverse(cfgFileNames.begin(), cfgFileNames.end()); //list is stored with last used files first in xml, however addFileToCfgHistory() needs them last!!!
cfgFileNames.push_back(lastRunConfigName()); //make sure <Last session> is always part of history list (if existing)
addFileToCfgHistory(cfgFileNames);
removeObsoleteCfgHistoryItems(cfgFileNames); //remove non-existent items (we need this only on startup)
//--------------------------------------------------------------------------------
//load list of last used folders
*folderHistoryLeft = FolderHistory(globalSettings.gui.folderHistoryLeft, globalSettings.gui.folderHistMax);
*folderHistoryRight = FolderHistory(globalSettings.gui.folderHistoryRight, globalSettings.gui.folderHistMax);
//show/hide file icons
gridview::setupIcons(*m_gridMainL, *m_gridMainC, *m_gridMainR, globalSettings.gui.showIcons, convert(globalSettings.gui.iconSize));
//------------------------------------------------------------------------------------------------
m_checkBoxMatchCase->SetValue(globalCfg.gui.textSearchRespectCase);
//wxAuiManager erroneously loads panel captions, we don't want that
typedef std::vector<std::pair<wxString, wxString> > CaptionNameMapping;
CaptionNameMapping captionNameMap;
const wxAuiPaneInfoArray& paneArray = auiMgr.GetAllPanes();
for (size_t i = 0; i < paneArray.size(); ++i)
captionNameMap.push_back(std::make_pair(paneArray[i].caption, paneArray[i].name));
auiMgr.LoadPerspective(globalSettings.gui.guiPerspectiveLast);
//restore original captions
for (auto it = captionNameMap.begin(); it != captionNameMap.end(); ++it)
auiMgr.GetPane(it->second).Caption(it->first);
//if MainDialog::onQueryEndSession() is called while comparison is active, this panel is saved and restored as "visible"
auiMgr.GetPane(compareStatus->getAsWindow()).Hide();
auiMgr.GetPane(m_panelSearch).Hide(); //no need to show it on startup
m_menuItemCheckVersionAuto->Check(globalCfg.gui.lastUpdateCheck != -1);
auiMgr.Update();
}
xmlAccess::XmlGlobalSettings MainDialog::getGlobalCfgBeforeExit()
{
Freeze(); //no need to Thaw() again!!
// wxWindowUpdateLocker dummy(this);
xmlAccess::XmlGlobalSettings globalSettings = globalCfg;
globalSettings.programLanguage = getLanguage();
//retrieve column attributes
globalSettings.gui.columnAttribLeft = gridview::convertConfig(m_gridMainL->getColumnConfig());
globalSettings.gui.columnAttribRight = gridview::convertConfig(m_gridMainR->getColumnConfig());
globalSettings.gui.sashOffset = m_splitterMain->getSashOffset();
globalSettings.gui.columnAttribNavi = treeview::convertConfig(m_gridNavi->getColumnConfig());
globalSettings.gui.showPercentBar = treeview::getShowPercentage(*m_gridNavi);
const std::pair<ColumnTypeNavi, bool> sortInfo = treeDataView->getSortDirection();
globalSettings.gui.naviLastSortColumn = sortInfo.first;
globalSettings.gui.naviLastSortAscending = sortInfo.second;
//--------------------------------------------------------------------------------
//write list of last used configuration files
std::map<int, Zstring> historyDetail; //(cfg-file/last use index)
for (unsigned int i = 0; i < m_listBoxHistory->GetCount(); ++i)
if (auto clientString = dynamic_cast<const wxClientHistoryData*>(m_listBoxHistory->GetClientObject(i)))
historyDetail.insert(std::make_pair(clientString->lastUseIndex_, clientString->cfgFile_));
else
assert(false);
//sort by last use; put most recent items *first* (looks better in xml than the reverse)
std::vector<Zstring> history;
std::transform(historyDetail.rbegin(), historyDetail.rend(), std::back_inserter(history), [](const std::pair<int, Zstring>& item) { return item.second; });
if (history.size() > globalSettings.gui.cfgFileHistMax) //erase oldest elements
history.resize(globalSettings.gui.cfgFileHistMax);
globalSettings.gui.cfgFileHistory = history;
//--------------------------------------------------------------------------------
globalSettings.gui.lastUsedConfigFiles = activeConfigFiles;
//write list of last used folders
globalSettings.gui.folderHistoryLeft = folderHistoryLeft ->getList();
globalSettings.gui.folderHistoryRight = folderHistoryRight->getList();
globalSettings.gui.textSearchRespectCase = m_checkBoxMatchCase->GetValue();
globalSettings.gui.guiPerspectiveLast = auiMgr.SavePerspective();
//we need to portably retrieve non-iconized, non-maximized size and position (non-portable: GetWindowPlacement())
//call *after* wxAuiManager::SavePerspective()!
if (IsIconized())
Iconize(false);
globalSettings.gui.isMaximized = IsMaximized(); //evaluate AFTER uniconizing!
if (IsMaximized())
Maximize(false);
globalSettings.gui.dlgSize = GetSize();
globalSettings.gui.dlgPos = GetPosition();
return globalSettings;
}
void MainDialog::setSyncDirManually(const std::vector<FileSystemObject*>& selection, SyncDirection direction)
{
if (!selection.empty())
{
std::for_each(selection.begin(), selection.end(),
[&](FileSystemObject* fsObj)
{
setSyncDirectionRec(direction, *fsObj); //set new direction (recursively)
zen::setActiveStatus(true, *fsObj); //works recursively for directories
});
updateGui();
}
}
void MainDialog::setFilterManually(const std::vector<FileSystemObject*>& selection, bool setIncluded)
{
//if hidefiltered is active, there should be no filtered elements on screen => current element was filtered out
assert(!currentCfg.hideExcludedItems || !setIncluded);
if (!selection.empty())
{
std::for_each(selection.begin(), selection.end(),
[&](FileSystemObject* fsObj) { zen::setActiveStatus(setIncluded, *fsObj); }); //works recursively for directories
updateGuiDelayedIf(currentCfg.hideExcludedItems); //show update GUI before removing rows
}
}
namespace
{
//perf: wxString doesn't model exponential growth and so is unusable for large data sets
typedef Zbase<wchar_t> zxString; //guaranteed exponential growth
}
void MainDialog::copySelectionToClipboard(const std::vector<const Grid*>& gridRefs)
{
try
{
zxString clipboardString;
auto addSelection = [&](const Grid& grid)
{
if (auto prov = grid.getDataProvider())
{
std::vector<Grid::ColumnAttribute> colAttr = grid.getColumnConfig();
vector_remove_if(colAttr, [](const Grid::ColumnAttribute& ca) { return !ca.visible_; });
if (!colAttr.empty())
{
const std::vector<size_t> selection = grid.getSelectedRows();
std::for_each(selection.begin(), selection.end(),
[&](size_t row)
{
std::for_each(colAttr.begin(), colAttr.end() - 1,
[&](const Grid::ColumnAttribute& ca)
{
clipboardString += copyStringTo<zxString>(prov->getValue(row, ca.type_));
clipboardString += L'\t';
});
clipboardString += copyStringTo<zxString>(prov->getValue(row, colAttr.back().type_));
clipboardString += L'\n';
});
}
}
};
for (auto it = gridRefs.begin(); it != gridRefs.end(); ++it)
addSelection(**it);
//finally write to clipboard
if (!clipboardString.empty())
if (wxClipboard::Get()->Open())
{
ZEN_ON_SCOPE_EXIT(wxClipboard::Get()->Close());
wxClipboard::Get()->SetData(new wxTextDataObject(copyStringTo<wxString>(clipboardString))); //ownership passed
}
}
catch (const std::bad_alloc& e)
{
wxMessageBox(_("Out of memory.") + L" " + utfCvrtTo<std::wstring>(e.what()), L"FreeFileSync - " + _("Error"), wxOK | wxICON_ERROR, this);
}
}
std::vector<FileSystemObject*> MainDialog::getGridSelection(bool fromLeft, bool fromRight) const
{
std::set<size_t> selectedRows;
auto addSelection = [&](const Grid& grid)
{
const std::vector<size_t>& sel = grid.getSelectedRows();
selectedRows.insert(sel.begin(), sel.end());
};
if (fromLeft)
addSelection(*m_gridMainL);
if (fromRight)
addSelection(*m_gridMainR);
return gridDataView->getAllFileRef(selectedRows);
}
std::vector<FileSystemObject*> MainDialog::getTreeSelection() const
{
std::vector<FileSystemObject*> output;
const std::vector<size_t>& sel = m_gridNavi->getSelectedRows();
std::for_each(sel.begin(), sel.end(),
[&](size_t row)
{
if (std::unique_ptr<TreeView::Node> node = treeDataView->getLine(row))
{
if (auto root = dynamic_cast<const TreeView::RootNode*>(node.get()))
{
//select first level of child elements
for (auto& fsObj : root->baseDirObj_.refSubDirs ()) output.push_back(&fsObj);
for (auto& fsObj : root->baseDirObj_.refSubFiles()) output.push_back(&fsObj);
for (auto& fsObj : root->baseDirObj_.refSubLinks()) output.push_back(&fsObj);
}
else if (auto dir = dynamic_cast<const TreeView::DirNode*>(node.get()))
output.push_back(&(dir->dirObj_));
else if (auto file = dynamic_cast<const TreeView::FilesNode*>(node.get()))
output.insert(output.end(), file->filesAndLinks_.begin(), file->filesAndLinks_.end());
}
});
return output;
}
//Exception class used to abort the "compare" and "sync" process
class AbortDeleteProcess {};
class ManualDeletionHandler : private wxEvtHandler, public DeleteFilesHandler //throw AbortDeleteProcess
{
public:
ManualDeletionHandler(MainDialog& main) :
mainDlg(main),
abortRequested(false),
ignoreErrors(false)
{
mainDlg.disableAllElements(true); //disable everything except abort button
//register abort button
mainDlg.m_buttonCancel->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ManualDeletionHandler::OnAbortDeletion), nullptr, this );
mainDlg.Connect(wxEVT_CHAR_HOOK, wxKeyEventHandler(ManualDeletionHandler::OnKeyPressed), nullptr, this);
}
~ManualDeletionHandler()
{
//de-register abort button
mainDlg.Disconnect(wxEVT_CHAR_HOOK, wxKeyEventHandler(ManualDeletionHandler::OnKeyPressed), nullptr, this);
mainDlg.m_buttonCancel->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ManualDeletionHandler::OnAbortDeletion ), nullptr, this );
mainDlg.enableAllElements();
}
virtual Response reportError(const std::wstring& msg)
{
if (ignoreErrors)
return DeleteFilesHandler::IGNORE_ERROR;
forceUiRefresh();
bool ignoreNextErrors = false;
switch (showErrorDlg(&mainDlg,
ReturnErrorDlg::BUTTON_IGNORE | ReturnErrorDlg::BUTTON_RETRY | ReturnErrorDlg::BUTTON_CANCEL,
msg, &ignoreNextErrors))
{
case ReturnErrorDlg::BUTTON_IGNORE:
ignoreErrors = ignoreNextErrors;
return DeleteFilesHandler::IGNORE_ERROR;
case ReturnErrorDlg::BUTTON_RETRY:
return DeleteFilesHandler::RETRY;
case ReturnErrorDlg::BUTTON_CANCEL:
throw AbortDeleteProcess();
}
assert (false);
return DeleteFilesHandler::IGNORE_ERROR; //dummy return value
}
virtual void reportWarning(const std::wstring& msg, bool& warningActive)
{
if (!warningActive || ignoreErrors)
return;
forceUiRefresh();
bool dontWarnAgain = false;
switch (showWarningDlg(&mainDlg, ReturnWarningDlg::BUTTON_IGNORE | ReturnWarningDlg::BUTTON_CANCEL, msg, dontWarnAgain))
{
case ReturnWarningDlg::BUTTON_SWITCH:
assert(false);
case ReturnWarningDlg::BUTTON_CANCEL:
throw AbortDeleteProcess();
case ReturnWarningDlg::BUTTON_IGNORE:
warningActive = !dontWarnAgain;
break;
}
}
virtual void reportStatus (const std::wstring& msg)
{
statusMsg = msg;
requestUiRefresh();
}
private:
virtual void requestUiRefresh()
{
if (updateUiIsAllowed()) //test if specific time span between ui updates is over
forceUiRefresh();
if (abortRequested) //test after (implicit) call to wxApp::Yield()
throw AbortDeleteProcess();
}
void forceUiRefresh()
{
//std::wstring msg = toGuiString(deletionCount) +
mainDlg.setStatusBarFullText(statusMsg);
wxTheApp->Yield();
}
//context: C callstack message loop => throw()!
void OnAbortDeletion(wxCommandEvent& event) //handle abort button click
{
abortRequested = true; //don't throw exceptions in a GUI-Callback!!! (throw zen::AbortThisProcess())
}
void OnKeyPressed(wxKeyEvent& event)
{
const int keyCode = event.GetKeyCode();
if (keyCode == WXK_ESCAPE)
{
abortRequested = true; //don't throw exceptions in a GUI-Callback!!! (throw zen::AbortThisProcess())
return;
}
event.Skip();
}
MainDialog& mainDlg;
bool abortRequested;
bool ignoreErrors;
//size_t deletionCount; //
std::wstring statusMsg; //status reporting
};
void MainDialog::deleteSelectedFiles(const std::vector<FileSystemObject*>& selectionLeft,
const std::vector<FileSystemObject*>& selectionRight)
{
bool deleteOnBothSides = false; //let's keep this disabled by default -> don't save
//=> clenup empty selection on either side:
std::vector<FileSystemObject*> selectionLeftTmp;
std::vector<FileSystemObject*> selectionRightTmp;
std::copy_if(selectionLeft .begin(), selectionLeft .end(), std::back_inserter(selectionLeftTmp ), [](const FileSystemObject* fsObj) { return !fsObj->isEmpty<LEFT_SIDE >(); });
std::copy_if(selectionRight.begin(), selectionRight.end(), std::back_inserter(selectionRightTmp), [](const FileSystemObject* fsObj) { return !fsObj->isEmpty<RIGHT_SIDE>(); });
if (!selectionLeftTmp.empty() || !selectionRightTmp.empty())
{
wxWindow* oldFocus = wxWindow::FindFocus();
ZEN_ON_SCOPE_EXIT(if (oldFocus) oldFocus->SetFocus();)
if (zen::showDeleteDialog(this,
selectionLeftTmp,
selectionRightTmp,
deleteOnBothSides,
globalCfg.gui.useRecyclerForManualDeletion) == ReturnSmallDlg::BUTTON_OKAY)
{
//wxBusyCursor dummy; -> redundant: progress already shown in status bar!
try
{
//handle errors when deleting files/folders
ManualDeletionHandler statusHandler(*this);
zen::deleteFromGridAndHD(selectionLeftTmp,
selectionRightTmp,
folderCmp,
extractDirectionCfg(getConfig().mainCfg),
deleteOnBothSides,
globalCfg.gui.useRecyclerForManualDeletion,
statusHandler,
globalCfg.optDialogs.warningRecyclerMissing);
gridview::clearSelection(*m_gridMainL, *m_gridMainC, *m_gridMainR); //do not clear, if aborted!
}
catch (AbortDeleteProcess&) {}
//remove rows that are empty: just a beautification, invalid rows shouldn't cause issues
gridDataView->removeInvalidRows();
//redraw grid neccessary to update new dimensions and for UI-Backend data linkage
updateGui(); //call immediately after deleteFromGridAndHD!!!
}
}
}
namespace
{
template <SelectedSide side>
Zstring getExistingParentFolder(const FileSystemObject& fsObj)
{
const DirPair* dirObj = dynamic_cast<const DirPair*>(&fsObj);
if (!dirObj)
dirObj = dynamic_cast<const DirPair*>(&fsObj.parent());
while (dirObj)
{
if (!dirObj->isEmpty<side>())
return dirObj->getFullName<side>();
dirObj = dynamic_cast<const DirPair*>(&dirObj->parent());
}
return fsObj.getBaseDirPf<side>();
}
}
void MainDialog::openExternalApplication(const wxString& commandline, const std::vector<FileSystemObject*>& selection, bool leftSide)
{
if (commandline.empty())
return;
auto selectionTmp = selection;
const bool openFileBrowserRequested = [&]() -> bool
{
xmlAccess::XmlGlobalSettings::Gui dummy;
return !dummy.externelApplications.empty() && dummy.externelApplications[0].second == commandline;
}();
//support fallback instead of an error in this special case
if (openFileBrowserRequested)
{
if (selectionTmp.size() > 1) //do not open more than one explorer instance!
selectionTmp.resize(1); //
if (selectionTmp.empty() ||
(leftSide && selectionTmp[0]->isEmpty<LEFT_SIDE >()) ||
(!leftSide && selectionTmp[0]->isEmpty<RIGHT_SIDE>()))
{
Zstring fallbackDir;
if (selectionTmp.empty())
fallbackDir = leftSide ?
getFormattedDirectoryName(firstFolderPair->getLeftDir()) :
getFormattedDirectoryName(firstFolderPair->getRightDir());
else
fallbackDir = leftSide ?
getExistingParentFolder<LEFT_SIDE >(*selectionTmp[0]) :
getExistingParentFolder<RIGHT_SIDE>(*selectionTmp[0]);
#ifdef ZEN_WIN
zen::shellExecute(L"\"" + fallbackDir + L"\"");
#elif defined ZEN_LINUX
zen::shellExecute("xdg-open \"" + fallbackDir + "\"");
#elif defined ZEN_MAC
zen::shellExecute("open \"" + fallbackDir + "\"");
#endif
return;
}
}
const size_t massInvokeThreshold = 10; //more than this is likely a user mistake
if (selectionTmp.size() > massInvokeThreshold)
if (globalCfg.optDialogs.confirmExternalCommandMassInvoke)
{
bool dontAskAgain = false;
switch (showQuestionDlg(this,
ReturnQuestionDlg::BUTTON_YES | ReturnQuestionDlg::BUTTON_CANCEL,
replaceCpy(replaceCpy(_P("Do you really want to execute the command %y for 1 item?",
"Do you really want to execute the command %y for %x items?", selectionTmp.size()),
L"%x", toGuiString(selectionTmp.size())), L"%y", L'\'' + commandline + L'\''),
QuestConfig().setCaption(_("Confirm")).setLabelYes(_("&Execute")).
showCheckBox(dontAskAgain, _("&Don't show this dialog again"), 0)))
{
case ReturnQuestionDlg::BUTTON_YES:
globalCfg.optDialogs.confirmExternalCommandMassInvoke = !dontAskAgain;
break;
case ReturnQuestionDlg::BUTTON_NO:
assert(false);
case ReturnQuestionDlg::BUTTON_CANCEL:
return;
}
}
//regular command evaluation
for (auto it = selectionTmp.begin(); it != selectionTmp.end(); ++it) //context menu calls this function only if selection is not empty!
{
const FileSystemObject* fsObj = *it;
Zstring path1 = fsObj->getBaseDirPf<LEFT_SIDE>() + fsObj->getObjRelativeName(); //full path, even if item is not existing!
Zstring dir1 = beforeLast(path1, FILE_NAME_SEPARATOR); //Win: wrong for root paths like "C:\file.txt"
Zstring path2 = fsObj->getBaseDirPf<RIGHT_SIDE>() + fsObj->getObjRelativeName();
Zstring dir2 = beforeLast(path2, FILE_NAME_SEPARATOR);
if (!leftSide)
{
std::swap(path1, path2);
std::swap(dir1, dir2);
}
Zstring command = utfCvrtTo<Zstring>(commandline);
replace(command, Zstr("%item_path%"), path1);
replace(command, Zstr("%item2_path%"), path2);
replace(command, Zstr("%item_folder%"), dir1 );
replace(command, Zstr("%item2_folder%"), dir2 );
auto cmdExp = expandMacros(command);
//caveat: spawning too many threads asynchronously can easily kill a user's desktop session!
zen::shellExecute(cmdExp, selectionTmp.size() > massInvokeThreshold ? EXEC_TYPE_SYNC : EXEC_TYPE_ASYNC);
}
}
void MainDialog::setStatusBarFileStatistics(size_t filesOnLeftView,
size_t foldersOnLeftView,
size_t filesOnRightView,
size_t foldersOnRightView,
zen::UInt64 filesizeLeftView,
zen::UInt64 filesizeRightView)
{
wxWindowUpdateLocker dummy(m_panelStatusBar); //avoid display distortion
//select state
bSizerFileStatus->Show(true);
m_staticTextFullStatus->Hide();
//update status information
bSizerStatusLeftDirectories->Show(foldersOnLeftView > 0);
bSizerStatusLeftFiles ->Show(filesOnLeftView > 0);
setText(*m_staticTextStatusLeftDirs, replaceCpy(_P("1 directory", "%x directories", foldersOnLeftView), L"%x", toGuiString(foldersOnLeftView), false));
setText(*m_staticTextStatusLeftFiles, replaceCpy(_P("1 file", "%x files", filesOnLeftView), L"%x", toGuiString(filesOnLeftView), false));
setText(*m_staticTextStatusLeftBytes, L"(" + filesizeToShortString(to<Int64>(filesizeLeftView)) + L")");
wxString statusMiddleNew;
if (gridDataView->rowsTotal() > 0)
{
statusMiddleNew = _P("%y of 1 row in view", "%y of %x rows in view", gridDataView->rowsTotal());
replace(statusMiddleNew, L"%x", toGuiString(gridDataView->rowsTotal ()), false); //%x is required to be the plural form placeholder!
replace(statusMiddleNew, L"%y", toGuiString(gridDataView->rowsOnView()), false); //%y is secondary placeholder
}
bSizerStatusRightDirectories->Show(foldersOnRightView > 0);
bSizerStatusRightFiles ->Show(filesOnRightView > 0);
setText(*m_staticTextStatusRightDirs, replaceCpy(_P("1 directory", "%x directories", foldersOnRightView), L"%x", toGuiString(foldersOnRightView), false));
setText(*m_staticTextStatusRightFiles, replaceCpy(_P("1 file", "%x files", filesOnRightView), L"%x", toGuiString(filesOnRightView), false));
setText(*m_staticTextStatusRightBytes, L"(" + filesizeToShortString(to<Int64>(filesizeRightView)) + L")");
//fill middle text (considering flashStatusInformation())
if (oldStatusMsgs.empty())
setText(*m_staticTextStatusMiddle, statusMiddleNew);
else
oldStatusMsgs.front() = statusMiddleNew;
m_panelStatusBar->Layout();
}
void MainDialog::setStatusBarFullText(const wxString& msg)
{
const bool needLayoutUpdate = !m_staticTextFullStatus->IsShown();
//select state
bSizerFileStatus->Show(false);
m_staticTextFullStatus->Show();
//update status information
setText(*m_staticTextFullStatus, msg);
m_panelStatusBar->Layout();
if (needLayoutUpdate)
auiMgr.Update(); //fix status bar height (needed on OS X)
}
void MainDialog::flashStatusInformation(const wxString& text)
{
oldStatusMsgs.push_back(m_staticTextStatusMiddle->GetLabel());
m_staticTextStatusMiddle->SetLabel(text);
m_staticTextStatusMiddle->SetForegroundColour(wxColour(31, 57, 226)); //highlight color: blue
m_panelStatusBar->Layout();
//if (needLayoutUpdate) auiMgr.Update(); -> not needed here, this is called anyway in updateGui()
processAsync2([] { boost::this_thread::sleep(boost::posix_time::millisec(2500)); },
[this] { this->restoreStatusInformation(); });
}
void MainDialog::restoreStatusInformation()
{
if (!oldStatusMsgs.empty())
{
wxString oldMsg = oldStatusMsgs.back();
oldStatusMsgs.pop_back();
if (oldStatusMsgs.empty()) //restore original status text
{
m_staticTextStatusMiddle->SetLabel(oldMsg);
m_staticTextStatusMiddle->SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); //reset color
m_panelStatusBar->Layout();
}
}
}
void MainDialog::onProcessAsyncTasks(wxEvent& event)
{
//schedule and run long-running tasks asynchronously
asyncTasks.evalResults(); //process results on GUI queue
if (asyncTasks.empty())
timerForAsyncTasks.Stop();
}
void MainDialog::disableAllElements(bool enableAbort)
{
//disables all elements (except abort button) that might receive user input during long-running processes:
//when changing consider: comparison, synchronization, manual deletion
EnableCloseButton(false); //not allowed for synchronization! progress indicator is top window! -> not honored on OS X!
//OS X: wxWidgets portability promise is again a mess: http://wxwidgets.10942.n7.nabble.com/Disable-panel-and-appropriate-children-windows-linux-macos-td35357.html
m_menubar1->EnableTop(0, false);
m_menubar1->EnableTop(1, false);
m_menubar1->EnableTop(2, false);
m_bpButtonCmpConfig ->Disable();
m_bpButtonSyncConfig ->Disable();
m_buttonSync ->Disable();
m_panelDirectoryPairs->Disable();
m_splitterMain ->Disable(); //includes m_panelCenter, but not m_panelStatusBar!
m_panelViewFilter ->Disable();
m_panelFilter ->Disable();
m_panelConfig ->Disable();
m_panelStatistics ->Disable();
m_gridNavi ->Disable();
if (enableAbort)
{
//show abort button
m_buttonCancel->Enable();
m_buttonCancel->Show();
if (m_buttonCancel->IsShownOnScreen())
m_buttonCancel->SetFocus();
m_buttonCompare->Disable();
m_buttonCompare->Hide();
m_panelTopButtons->Layout();
}
else
m_panelTopButtons->Disable();
}
void MainDialog::enableAllElements()
{
//wxGTK, yet another QOI issue: some stupid bug, keeps moving main dialog to top!!
EnableCloseButton(true);
m_menubar1->EnableTop(0, true);
m_menubar1->EnableTop(1, true);
m_menubar1->EnableTop(2, true);
m_bpButtonCmpConfig ->Enable();
m_bpButtonSyncConfig ->Enable();
m_buttonSync ->Enable();
m_panelDirectoryPairs->Enable();
m_splitterMain ->Enable();
m_panelViewFilter ->Enable();
m_panelFilter ->Enable();
m_panelConfig ->Enable();
m_panelStatistics ->Enable();
m_gridNavi ->Enable();
//show compare button
m_buttonCancel->Disable();
m_buttonCancel->Hide();
m_buttonCompare->Enable();
m_buttonCompare->Show();
m_panelTopButtons->Enable();
m_panelTopButtons->Layout();
//at least wxWidgets on OS X fails to do this after enabling:
Refresh();
}
namespace
{
void updateSizerOrientation(wxBoxSizer& sizer, wxWindow& window, double horizontalWeight)
{
const int newOrientation = window.GetSize().GetWidth() * horizontalWeight > window.GetSize().GetHeight() ? wxHORIZONTAL : wxVERTICAL; //check window NOT sizer width!
if (sizer.GetOrientation() != newOrientation)
{
sizer.SetOrientation(newOrientation);
window.Layout();
}
}
}
void MainDialog::OnResizeConfigPanel(wxEvent& event)
{
updateSizerOrientation(*bSizerConfig, *m_panelConfig, 0.5);
event.Skip();
}
void MainDialog::OnResizeViewPanel(wxEvent& event)
{
updateSizerOrientation(*bSizerViewFilter, *m_panelViewFilter, 1.0);
event.Skip();
}
void MainDialog::OnResizeStatisticsPanel(wxEvent& event)
{
//updateSizerOrientation(*bSizerStatistics, *m_panelStatistics);
//we need something more fancy:
const int parentOrient = m_panelStatistics->GetSize().GetWidth() > m_panelStatistics->GetSize().GetHeight() ? wxHORIZONTAL : wxVERTICAL; //check window NOT sizer width!
if (bSizerStatistics->GetOrientation() != parentOrient)
{
bSizerStatistics->SetOrientation(parentOrient);
//apply opposite orientation for child sizers
const int childOrient = parentOrient == wxHORIZONTAL ? wxVERTICAL : wxHORIZONTAL;
wxSizerItemList& sl = bSizerStatistics->GetChildren();
for (auto it = sl.begin(); it != sl.end(); ++it) //yet another wxWidgets bug keeps us from using std::for_each
{
wxSizerItem& szItem = **it;
if (auto sizerChild = dynamic_cast<wxBoxSizer*>(szItem.GetSizer()))
if (sizerChild->GetOrientation() != childOrient)
sizerChild->SetOrientation(childOrient);
}
m_panelStatistics->Layout();
}
event.Skip();
}
void MainDialog::OnResizeLeftFolderWidth(wxEvent& event)
{
//adapt left-shift display distortion caused by scrollbars for multiple folder pairs
const int width = m_panelTopLeft->GetSize().GetWidth();
std::for_each(additionalFolderPairs.begin(), additionalFolderPairs.end(),
[&](FolderPairPanel* panel)
{
panel->m_panelLeft->SetMinSize(wxSize(width, -1));
});
event.Skip();
}
void MainDialog::onTreeButtonEvent(wxKeyEvent& event)
{
int keyCode = event.GetKeyCode();
if (m_gridNavi->GetLayoutDirection() == wxLayout_RightToLeft)
{
if (keyCode == WXK_LEFT)
keyCode = WXK_RIGHT;
else if (keyCode == WXK_RIGHT)
keyCode = WXK_LEFT;
else if (keyCode == WXK_NUMPAD_LEFT)
keyCode = WXK_NUMPAD_RIGHT;
else if (keyCode == WXK_NUMPAD_RIGHT)
keyCode = WXK_NUMPAD_LEFT;
}
if (event.ControlDown())
switch (keyCode)
{
case 'C':
case WXK_INSERT: //CTRL + C || CTRL + INS
{
std::vector<const Grid*> gridRefs;
gridRefs.push_back(m_gridNavi);
copySelectionToClipboard(gridRefs);
}
return;
}
else if (event.AltDown())
switch (keyCode)
{
case WXK_NUMPAD_LEFT:
case WXK_LEFT: //ALT + <-
setSyncDirManually(getTreeSelection(), SyncDirection::LEFT);
return;
case WXK_NUMPAD_RIGHT:
case WXK_RIGHT: //ALT + ->
setSyncDirManually(getTreeSelection(), SyncDirection::RIGHT);
return;
case WXK_NUMPAD_UP:
case WXK_NUMPAD_DOWN:
case WXK_UP: /* ALT + /|\ */
case WXK_DOWN: /* ALT + \|/ */
setSyncDirManually(getTreeSelection(), SyncDirection::NONE);
return;
}
else
switch (keyCode)
{
case WXK_SPACE:
case WXK_NUMPAD_SPACE:
{
const std::vector<FileSystemObject*>& selection = getTreeSelection();
if (!selection.empty())
setFilterManually(selection, !selection[0]->isActive());
}
return;
case WXK_DELETE:
case WXK_NUMPAD_DELETE:
deleteSelectedFiles(getTreeSelection(), getTreeSelection());
return;
}
event.Skip(); //unknown keypress: propagate
}
void MainDialog::onGridButtonEventL(wxKeyEvent& event)
{
onGridButtonEvent(event, *m_gridMainL, true);
}
void MainDialog::onGridButtonEventC(wxKeyEvent& event)
{
onGridButtonEvent(event, *m_gridMainC, true);
}
void MainDialog::onGridButtonEventR(wxKeyEvent& event)
{
onGridButtonEvent(event, *m_gridMainR, false);
}
void MainDialog::onGridButtonEvent(wxKeyEvent& event, Grid& grid, bool leftSide)
{
int keyCode = event.GetKeyCode();
if (grid.GetLayoutDirection() == wxLayout_RightToLeft)
{
if (keyCode == WXK_LEFT)
keyCode = WXK_RIGHT;
else if (keyCode == WXK_RIGHT)
keyCode = WXK_LEFT;
else if (keyCode == WXK_NUMPAD_LEFT)
keyCode = WXK_NUMPAD_RIGHT;
else if (keyCode == WXK_NUMPAD_RIGHT)
keyCode = WXK_NUMPAD_LEFT;
}
if (event.ControlDown())
switch (keyCode)
{
case 'C':
case WXK_INSERT: //CTRL + C || CTRL + INS
{
std::vector<const Grid*> gridRefs;
gridRefs.push_back(m_gridMainL);
gridRefs.push_back(m_gridMainR);
copySelectionToClipboard(gridRefs);
}
return; // -> swallow event! don't allow default grid commands!
}
else if (event.AltDown())
switch (keyCode)
{
case WXK_NUMPAD_LEFT:
case WXK_LEFT: //ALT + <-
setSyncDirManually(getGridSelection(), SyncDirection::LEFT);
return;
case WXK_NUMPAD_RIGHT:
case WXK_RIGHT: //ALT + ->
setSyncDirManually(getGridSelection(), SyncDirection::RIGHT);
return;
case WXK_NUMPAD_UP:
case WXK_NUMPAD_DOWN:
case WXK_UP: /* ALT + /|\ */
case WXK_DOWN: /* ALT + \|/ */
setSyncDirManually(getGridSelection(), SyncDirection::NONE);
return;
}
else
switch (keyCode)
{
case WXK_DELETE:
case WXK_NUMPAD_DELETE:
deleteSelectedFiles(getGridSelection(true, false),
getGridSelection(false, true));
return;
case WXK_SPACE:
case WXK_NUMPAD_SPACE:
{
const std::vector<FileSystemObject*>& selection = getGridSelection();
if (!selection.empty())
setFilterManually(selection, !selection[0]->isActive());
}
return;
case WXK_RETURN:
case WXK_NUMPAD_ENTER:
if (!globalCfg.gui.externelApplications.empty())
openExternalApplication(globalCfg.gui.externelApplications[0].second, //open with first external application
getGridSelection(), leftSide);
return;
}
event.Skip(); //unknown keypress: propagate
}
bool isComponentOf(const wxWindow* child, const wxWindow* top)
{
for (const wxWindow* wnd = child; wnd != nullptr; wnd = wnd->GetParent())
if (wnd == top)
return true;
return false;
}
void MainDialog::OnGlobalKeyEvent(wxKeyEvent& event) //process key events without explicit menu entry :)
{
//avoid recursion!!! -> this ugly construct seems to be the only (portable) way to avoid re-entrancy
//recursion may happen in multiple situations: e.g. modal dialogs, wxGrid::ProcessEvent()!
if (processingGlobalKeyEvent ||
!IsShown() ||
!IsActive() ||
!IsEnabled() ||
!m_gridMainL->IsEnabled() || //
!m_gridMainC->IsEnabled() || //only handle if main window is in use
!m_gridMainR->IsEnabled()) //
{
event.Skip();
return;
}
processingGlobalKeyEvent = true;
ZEN_ON_SCOPE_EXIT(processingGlobalKeyEvent = false;)
//----------------------------------------------------
const int keyCode = event.GetKeyCode();
//CTRL + X
if (event.ControlDown())
switch (keyCode)
{
case 'F': //CTRL + F
showFindPanel();
return; //-> swallow event!
}
switch (keyCode)
{
case WXK_F3:
case WXK_NUMPAD_F3:
startFindNext();
return; //-> swallow event!
case WXK_F6:
{
wxCommandEvent dummy2(wxEVT_COMMAND_BUTTON_CLICKED); //simulate button click
if (wxEvtHandler* evtHandler = m_bpButtonCmpConfig->GetEventHandler())
evtHandler->ProcessEvent(dummy2); //synchronous call
}
return; //-> swallow event!
case WXK_F7:
{
wxCommandEvent dummy2(wxEVT_COMMAND_BUTTON_CLICKED); //simulate button click
if (wxEvtHandler* evtHandler = m_bpButtonSyncConfig->GetEventHandler())
evtHandler->ProcessEvent(dummy2); //synchronous call
}
return; //-> swallow event!
case WXK_F9:
setViewTypeSyncAction(!m_bpButtonViewTypeSyncAction->isActive());
return; //-> swallow event!
case WXK_F10:
{
wxCommandEvent dummy2(wxEVT_COMMAND_BUTTON_CLICKED); //simulate button click
if (wxEvtHandler* evtHandler = m_bpButtonFilter->GetEventHandler())
evtHandler->ProcessEvent(dummy2); //synchronous call
}
return; //-> swallow event!
//redirect certain (unhandled) keys directly to grid!
case WXK_UP:
case WXK_DOWN:
case WXK_LEFT:
case WXK_RIGHT:
case WXK_NUMPAD_UP:
case WXK_NUMPAD_DOWN:
case WXK_NUMPAD_LEFT:
case WXK_NUMPAD_RIGHT:
case WXK_PAGEUP:
case WXK_PAGEDOWN:
case WXK_HOME:
case WXK_END:
case WXK_NUMPAD_PAGEUP:
case WXK_NUMPAD_PAGEDOWN:
case WXK_NUMPAD_HOME:
case WXK_NUMPAD_END:
{
const wxWindow* focus = wxWindow::FindFocus();
if (!isComponentOf(focus, m_gridMainL ) && //
!isComponentOf(focus, m_gridMainC ) && //don't propagate keyboard commands if grid is already in focus
!isComponentOf(focus, m_gridMainR ) && //
!isComponentOf(focus, m_gridNavi ) &&
!isComponentOf(focus, m_listBoxHistory) && //don't propagate if selecting config
!isComponentOf(focus, m_directoryLeft ) && //don't propagate if changing directory field
!isComponentOf(focus, m_directoryRight) &&
!isComponentOf(focus, m_panelSearch ) &&
!isComponentOf(focus, m_scrolledWindowFolderPairs))
if (wxEvtHandler* evtHandler = m_gridMainL->getMainWin().GetEventHandler())
{
m_gridMainL->SetFocus();
event.SetEventType(wxEVT_KEY_DOWN); //the grid event handler doesn't expect wxEVT_CHAR_HOOK!
evtHandler->ProcessEvent(event); //propagating event catched at wxTheApp to child leads to recursion, but we prevented it...
event.Skip(false); //definitively handled now!
return;
}
}
break;
}
event.Skip();
}
void MainDialog::onNaviSelection(GridRangeSelectEvent& event)
{
//scroll m_gridMain to user's new selection on m_gridNavi
ptrdiff_t leadRow = -1;
if (event.rowFirst_ != event.rowLast_)
if (std::unique_ptr<TreeView::Node> node = treeDataView->getLine(event.rowFirst_))
{
if (const TreeView::RootNode* root = dynamic_cast<const TreeView::RootNode*>(node.get()))
leadRow = gridDataView->findRowFirstChild(&(root->baseDirObj_));
else if (const TreeView::DirNode* dir = dynamic_cast<const TreeView::DirNode*>(node.get()))
{
leadRow = gridDataView->findRowDirect(&(dir->dirObj_));
if (leadRow < 0) //directory was filtered out! still on tree view (but NOT on grid view)
leadRow = gridDataView->findRowFirstChild(&(dir->dirObj_));
}
else if (const TreeView::FilesNode* files = dynamic_cast<const TreeView::FilesNode*>(node.get()))
{
assert(!files->filesAndLinks_.empty());
if (!files->filesAndLinks_.empty())
leadRow = gridDataView->findRowDirect(files->filesAndLinks_[0]->getId());
}
}
if (leadRow >= 0)
{
leadRow = std::max<ptrdiff_t>(0, leadRow - 1); //scroll one more row
m_gridMainL->scrollTo(leadRow); //scroll all of them (includes the "scroll master")
m_gridMainC->scrollTo(leadRow); //
m_gridMainR->scrollTo(leadRow); //
m_gridNavi->getMainWin().Update(); //draw cursor immediately rather than on next idle event (required for slow CPUs, netbook)
}
//get selection on navigation tree and set corresponding markers on main grid
hash_set<const FileSystemObject*> markedFilesAndLinks; //mark files/symlinks directly
hash_set<const HierarchyObject*> markedContainer; //mark full container including child-objects
const std::vector<size_t>& selection = m_gridNavi->getSelectedRows();
std::for_each(selection.begin(), selection.end(),
[&](size_t row)
{
if (std::unique_ptr<TreeView::Node> node = treeDataView->getLine(row))
{
if (const TreeView::RootNode* root = dynamic_cast<const TreeView::RootNode*>(node.get()))
markedContainer.insert(&(root->baseDirObj_));
else if (const TreeView::DirNode* dir = dynamic_cast<const TreeView::DirNode*>(node.get()))
markedContainer.insert(&(dir->dirObj_));
else if (const TreeView::FilesNode* files = dynamic_cast<const TreeView::FilesNode*>(node.get()))
markedFilesAndLinks.insert(files->filesAndLinks_.begin(), files->filesAndLinks_.end());
}
});
gridview::setNavigationMarker(*m_gridMainL, std::move(markedFilesAndLinks), std::move(markedContainer));
event.Skip();
}
void MainDialog::onNaviGridContext(GridClickEvent& event)
{
const auto& selection = getTreeSelection(); //referenced by lambdas!
ContextMenu menu;
//----------------------------------------------------------------------------------------------------
if (!selection.empty())
//std::any_of(selection.begin(), selection.end(), [](const FileSystemObject* fsObj){ return fsObj->getSyncOperation() != SO_EQUAL; })) -> doesn't consider directories
{
auto getImage = [&](SyncDirection dir, SyncOperation soDefault)
{
return mirrorIfRtl(getSyncOpImage(selection[0]->getSyncOperation() != SO_EQUAL ?
selection[0]->testSyncOperation(dir) : soDefault));
};
const wxBitmap opRight = getImage(SyncDirection::RIGHT, SO_OVERWRITE_RIGHT);
const wxBitmap opNone = getImage(SyncDirection::NONE, SO_DO_NOTHING );
const wxBitmap opLeft = getImage(SyncDirection::LEFT, SO_OVERWRITE_LEFT );
wxString shortCutLeft = L"\tAlt+Left";
wxString shortCutRight = L"\tAlt+Right";
if (wxTheApp->GetLayoutDirection() == wxLayout_RightToLeft)
std::swap(shortCutLeft, shortCutRight);
menu.addItem(_("Set direction:") + L" ->" + shortCutRight, [this, &selection] { setSyncDirManually(selection, SyncDirection::RIGHT); }, &opRight);
menu.addItem(_("Set direction:") + L" -" L"\tAlt+Down", [this, &selection] { setSyncDirManually(selection, SyncDirection::NONE); }, &opNone);
menu.addItem(_("Set direction:") + L" <-" + shortCutLeft, [this, &selection] { setSyncDirManually(selection, SyncDirection::LEFT); }, &opLeft);
//Gtk needs a direction, "<-", because it has no context menu icons!
//Gtk requires "no spaces" for shortcut identifiers!
menu.addSeparator();
}
//----------------------------------------------------------------------------------------------------
//FILE FILTER
auto addFilterMenu = [&](const std::wstring& label, const wxString& iconName, bool include)
{
if (selection.size() == 1)
{
//by relative path
menu.addItem(label + L" " + (FILE_NAME_SEPARATOR + selection[0]->getObjRelativeName()),
[this, &selection, include] { filterItems(selection, include); }, &getResourceImage(iconName));
}
else if (selection.size() > 1)
{
//by relative path
menu.addItem(label + L" <" + _("multiple selection") + L">",
[this, &selection, include] { filterItems(selection, include); }, &getResourceImage(iconName));
}
};
addFilterMenu(_("Include via filter:"), L"filter_include_small", true);
addFilterMenu(_("Exclude via filter:"), L"filter_exclude_small", false);
//----------------------------------------------------------------------------------------------------
if (!selection.empty())
{
if (selection[0]->isActive())
menu.addItem(_("Exclude temporarily") + L"\tSpace", [this, &selection] { setFilterManually(selection, false); }, &getResourceImage(L"checkboxFalse"));
else
menu.addItem(_("Include temporarily") + L"\tSpace", [this, &selection] { setFilterManually(selection, true); }, &getResourceImage(L"checkboxTrue"));
}
else
menu.addItem(_("Exclude temporarily") + L"\tSpace", [] {}, nullptr, false);
//----------------------------------------------------------------------------------------------------
//CONTEXT_DELETE_FILES
menu.addSeparator();
menu.addItem(_("Delete") + L"\tDelete", [&] { deleteSelectedFiles(selection, selection); }, nullptr, !selection.empty());
menu.popup(*this);
}
void MainDialog::onMainGridContextC(GridClickEvent& event)
{
ContextMenu menu;
menu.addItem(_("Include all"), [&]
{
zen::setActiveStatus(true, folderCmp);
updateGui();
}, nullptr, gridDataView->rowsTotal() > 0);
menu.addItem(_("Exclude all"), [&]
{
zen::setActiveStatus(false, folderCmp);
updateGuiDelayedIf(currentCfg.hideExcludedItems); //show update GUI before removing rows
}, nullptr, gridDataView->rowsTotal() > 0);
menu.popup(*this);
}
void MainDialog::onMainGridContextL(GridClickEvent& event)
{
onMainGridContextRim(true);
}
void MainDialog::onMainGridContextR(GridClickEvent& event)
{
onMainGridContextRim(false);
}
void MainDialog::onMainGridContextRim(bool leftSide)
{
const auto& selection = getGridSelection(); //referenced by lambdas!
ContextMenu menu;
if (!selection.empty())
{
auto getImage = [&](SyncDirection dir, SyncOperation soDefault)
{
return mirrorIfRtl(getSyncOpImage(selection[0]->getSyncOperation() != SO_EQUAL ?
selection[0]->testSyncOperation(dir) : soDefault));
};
const wxBitmap opRight = getImage(SyncDirection::RIGHT, SO_OVERWRITE_RIGHT);
const wxBitmap opNone = getImage(SyncDirection::NONE, SO_DO_NOTHING );
const wxBitmap opLeft = getImage(SyncDirection::LEFT, SO_OVERWRITE_LEFT );
wxString shortCutLeft = L"\tAlt+Left";
wxString shortCutRight = L"\tAlt+Right";
if (wxTheApp->GetLayoutDirection() == wxLayout_RightToLeft)
std::swap(shortCutLeft, shortCutRight);
menu.addItem(_("Set direction:") + L" ->" + shortCutRight, [this, &selection] { setSyncDirManually(selection, SyncDirection::RIGHT); }, &opRight);
menu.addItem(_("Set direction:") + L" -" L"\tAlt+Down", [this, &selection] { setSyncDirManually(selection, SyncDirection::NONE); }, &opNone);
menu.addItem(_("Set direction:") + L" <-" + shortCutLeft, [this, &selection] { setSyncDirManually(selection, SyncDirection::LEFT); }, &opLeft);
//Gtk needs a direction, "<-", because it has no context menu icons!
//Gtk requires "no spaces" for shortcut identifiers!
menu.addSeparator();
}
//----------------------------------------------------------------------------------------------------
//FILE FILTER
auto addFilterMenu = [&](const wxString& label, const wxString& iconName, bool include)
{
if (selection.size() == 1)
{
ContextMenu submenu;
//by extension
if (dynamic_cast<const DirPair*>(selection[0]) == nullptr) //non empty && no directory
{
const Zstring filename = afterLast(selection[0]->getObjRelativeName(), FILE_NAME_SEPARATOR);
if (contains(filename, Zchar('.'))) //be careful: AfterLast would return the whole string if '.' were not found!
{
const Zstring extension = afterLast(filename, Zchar('.'));
submenu.addItem(L"*." + utfCvrtTo<wxString>(extension),
[this, extension, include] { filterExtension(extension, include); });
}
}
//by short name
submenu.addItem(utfCvrtTo<wxString>(Zstring(Zstr("*")) + FILE_NAME_SEPARATOR + selection[0]->getObjShortName()),
[this, &selection, include] { filterShortname(*selection[0], include); });
//by relative path
submenu.addItem(utfCvrtTo<wxString>(FILE_NAME_SEPARATOR + selection[0]->getObjRelativeName()),
[this, &selection, include] { filterItems(selection, include); });
menu.addSubmenu(label, submenu, &getResourceImage(iconName));
}
else if (selection.size() > 1)
{
//by relative path
menu.addItem(label + L" <" + _("multiple selection") + L">",
[this, &selection, include] { filterItems(selection, include); }, &getResourceImage(iconName));
}
};
addFilterMenu(_("Include via filter:"), L"filter_include_small", true);
addFilterMenu(_("Exclude via filter:"), L"filter_exclude_small", false);
//----------------------------------------------------------------------------------------------------
if (!selection.empty())
{
if (selection[0]->isActive())
menu.addItem(_("Exclude temporarily") + L"\tSpace", [this, &selection] { setFilterManually(selection, false); }, &getResourceImage(L"checkboxFalse"));
else
menu.addItem(_("Include temporarily") + L"\tSpace", [this, &selection] { setFilterManually(selection, true); }, &getResourceImage(L"checkboxTrue"));
}
else
menu.addItem(_("Exclude temporarily") + L"\tSpace", [] {}, nullptr, false);
//----------------------------------------------------------------------------------------------------
//CONTEXT_EXTERNAL_APP
if (!globalCfg.gui.externelApplications.empty())
{
menu.addSeparator();
for (auto it = globalCfg.gui.externelApplications.begin();
it != globalCfg.gui.externelApplications.end();
++it)
{
//translate default external apps on the fly: 1. "open in explorer" 2. "start directly"
wxString description = zen::implementation::translate(it->first);
if (description.empty())
description = L" "; //wxWidgets doesn't like empty items
const wxString command = it->second; //COPY into lambda
auto openApp = [this, &selection, leftSide, command] { openExternalApplication(command, selection, leftSide); };
if (it == globalCfg.gui.externelApplications.begin())
description += L"\tEnter";
menu.addItem(description, openApp, nullptr, !selection.empty());
}
}
//----------------------------------------------------------------------------------------------------
//CONTEXT_DELETE_FILES
menu.addSeparator();
menu.addItem(_("Delete") + L"\tDelete", [this]
{
deleteSelectedFiles(
getGridSelection(true, false),
getGridSelection(false, true));
}, nullptr, !selection.empty());
menu.popup(*this);
}
void MainDialog::filterPhrase(const Zstring& phrase, bool include, bool addNewLine)
{
Zstring& filterString = [&]() -> Zstring&
{
if (include)
{
Zstring& includeFilter = currentCfg.mainCfg.globalFilter.includeFilter;
if (NameFilter::isNull(includeFilter, FilterConfig().excludeFilter)) //fancy way of checking for "*" include
includeFilter.clear();
return includeFilter;
}
else
return currentCfg.mainCfg.globalFilter.excludeFilter;
}();
if (addNewLine)
{
if (!filterString.empty() && !endsWith(filterString, Zstr("\n")))
filterString += Zstr("\n");
filterString += phrase;
}
else
{
if (!filterString.empty() && !endsWith(filterString, Zstr("\n")) && !endsWith(filterString, Zstr(";")))
filterString += Zstr("\n");
filterString += phrase + Zstr(";"); //';' is appended to 'mark' that next exclude extension entry won't write to new line
}
updateGlobalFilterButton();
if (include)
applyFilterConfig(); //user's temporary exclusions lost!
else //do not fully apply filter, just exclude new items: preserve user's temporary exclusions
{
std::for_each(begin(folderCmp), end(folderCmp), [&](BaseDirPair& baseDirObj) { addHardFiltering(baseDirObj, phrase); });
updateGui();
}
}
void MainDialog::filterExtension(const Zstring& extension, bool include)
{
filterPhrase(Zstr("*.") + extension, include, false);
}
void MainDialog::filterShortname(const FileSystemObject& fsObj, bool include)
{
Zstring phrase = Zstring(Zstr("*")) + FILE_NAME_SEPARATOR + fsObj.getObjShortName();
const bool isDir = dynamic_cast<const DirPair*>(&fsObj) != nullptr;
if (isDir)
phrase += FILE_NAME_SEPARATOR;
filterPhrase(phrase, include, true);
}
void MainDialog::filterItems(const std::vector<FileSystemObject*>& selection, bool include)
{
if (!selection.empty())
{
Zstring phrase;
for (auto it = selection.begin(); it != selection.end(); ++it)
{
FileSystemObject* fsObj = *it;
if (it != selection.begin())
phrase += Zstr("\n");
//#pragma warning(suppress: 6011) -> fsObj bound in this context!
phrase += FILE_NAME_SEPARATOR + fsObj->getObjRelativeName();
const bool isDir = dynamic_cast<const DirPair*>(fsObj) != nullptr;
if (isDir)
phrase += FILE_NAME_SEPARATOR;
}
filterPhrase(phrase, include, true);
}
}
void MainDialog::onGridLabelContextC(GridClickEvent& event)
{
ContextMenu menu;
const bool actionView = m_bpButtonViewTypeSyncAction->isActive();
menu.addRadio(_("Category") + (actionView ? L"\tF9" : L""), [&] { setViewTypeSyncAction(false); }, !actionView);
menu.addRadio(_("Action") + (!actionView ? L"\tF9" : L""), [&] { setViewTypeSyncAction(true ); }, actionView);
//menu.addItem(_("Category") + L"\tF9", [&] { setViewTypeSyncAction(false); }, m_bpButtonViewTypeSyncAction->isActive() ? nullptr : &getResourceImage(L"compare_small"));
//menu.addItem(_("Action"), [&] { setViewTypeSyncAction(true ); }, m_bpButtonViewTypeSyncAction->isActive() ? &getResourceImage(L"sync_small") : nullptr);
menu.popup(*this);
}
void MainDialog::onGridLabelContextL(GridClickEvent& event)
{
onGridLabelContext(*m_gridMainL, static_cast<ColumnTypeRim>(event.colType_), getDefaultColumnAttributesLeft());
}
void MainDialog::onGridLabelContextR(GridClickEvent& event)
{
onGridLabelContext(*m_gridMainR, static_cast<ColumnTypeRim>(event.colType_), getDefaultColumnAttributesRight());
}
void MainDialog::onGridLabelContext(Grid& grid, ColumnTypeRim type, const std::vector<ColumnAttributeRim>& defaultColumnAttributes)
{
ContextMenu menu;
auto toggleColumn = [&](ColumnType ct)
{
auto colAttr = grid.getColumnConfig();
for (Grid::ColumnAttribute& ca : colAttr)
if (ca.type_ == ct)
{
ca.visible_ = !ca.visible_;
grid.setColumnConfig(colAttr);
return;
}
};
if (const GridData* prov = grid.getDataProvider())
for (const Grid::ColumnAttribute& ca : grid.getColumnConfig())
menu.addCheckBox(prov->getColumnLabel(ca.type_), [ca, toggleColumn] { toggleColumn(ca.type_); },
ca.visible_, ca.type_ != static_cast<ColumnType>(COL_TYPE_FILENAME)); //do not allow user to hide file name column!
//----------------------------------------------------------------------------------------------
menu.addSeparator();
auto setDefault = [&]
{
grid.setColumnConfig(gridview::convertConfig(defaultColumnAttributes));
};
menu.addItem(_("&Default"), setDefault); //'&' -> reuse text from "default" buttons elsewhere
//----------------------------------------------------------------------------------------------
menu.addSeparator();
menu.addCheckBox(_("Show icons:"), [&]
{
globalCfg.gui.showIcons = !globalCfg.gui.showIcons;
gridview::setupIcons(*m_gridMainL, *m_gridMainC, *m_gridMainR, globalCfg.gui.showIcons, convert(globalCfg.gui.iconSize));
}, globalCfg.gui.showIcons);
auto setIconSize = [&](xmlAccess::FileIconSize sz)
{
globalCfg.gui.iconSize = sz;
gridview::setupIcons(*m_gridMainL, *m_gridMainC, *m_gridMainR, globalCfg.gui.showIcons, convert(sz));
};
auto addSizeEntry = [&](const wxString& label, xmlAccess::FileIconSize sz)
{
auto setIconSize2 = setIconSize; //bring into scope
menu.addRadio(label, [sz, setIconSize2] { setIconSize2(sz); }, globalCfg.gui.iconSize == sz, globalCfg.gui.showIcons);
};
addSizeEntry(L" " + _("Small" ), xmlAccess::ICON_SIZE_SMALL );
addSizeEntry(L" " + _("Medium"), xmlAccess::ICON_SIZE_MEDIUM);
addSizeEntry(L" " + _("Large" ), xmlAccess::ICON_SIZE_LARGE );
//----------------------------------------------------------------------------------------------
if (type == COL_TYPE_DATE)
{
menu.addSeparator();
auto selectTimeSpan = [&]
{
if (showSelectTimespanDlg(this, manualTimeSpanFrom, manualTimeSpanTo) == ReturnSmallDlg::BUTTON_OKAY)
{
applyTimeSpanFilter(folderCmp, manualTimeSpanFrom, manualTimeSpanTo); //overwrite current active/inactive settings
//updateGuiDelayedIf(currentCfg.hideExcludedItems); //show update GUI before removing rows
updateGui();
}
};
menu.addItem(_("Select time span..."), selectTimeSpan);
}
menu.popup(*this);
}
void MainDialog::OnContextSetLayout(wxMouseEvent& event)
{
ContextMenu menu;
menu.addItem(_("Default view"), [&]
{
m_splitterMain->setSashOffset(0);
auiMgr.LoadPerspective(defaultPerspective);
updateGuiForFolderPair();
});
//----------------------------------------------------------------------------------------
std::vector<std::pair<wxString, wxString>> captionNameMap; //(caption, identifier)
const wxAuiPaneInfoArray& paneArray = auiMgr.GetAllPanes();
for (size_t i = 0; i < paneArray.size(); ++i)
if (!paneArray[i].IsShown() && !paneArray[i].name.empty() &&
paneArray[i].window != compareStatus->getAsWindow() &&
paneArray[i].window != m_panelSearch)
captionNameMap.push_back(std::make_pair(paneArray[i].caption, paneArray[i].name));
if (!captionNameMap.empty())
menu.addSeparator();
auto showPanel = [&](const wxString& identifier)
{
auiMgr.GetPane(identifier).Show();
auiMgr.Update();
};
for (auto it = captionNameMap.begin(); it != captionNameMap.end(); ++it)
{
const wxString label = replaceCpy(_("Show \"%x\""), L"%x", it->first);
const wxString identifier = it->second;
menu.addItem(label, [showPanel, identifier] { showPanel(identifier); });
}
menu.popup(*this);
}
void MainDialog::OnCompSettingsContext(wxMouseEvent& event)
{
ContextMenu menu;
auto setVariant = [&](CompareVariant var)
{
currentCfg.mainCfg.cmpConfig.compareVar = var;
applyCompareConfig(true); //true: switchMiddleGrid
};
auto currentVar = getConfig().mainCfg.cmpConfig.compareVar;
menu.addRadio(_("File time and size"), [&] { setVariant(CMP_BY_TIME_SIZE); }, currentVar == CMP_BY_TIME_SIZE);
menu.addRadio(_("File content" ), [&] { setVariant(CMP_BY_CONTENT); }, currentVar == CMP_BY_CONTENT);
menu.popup(*this);
}
void MainDialog::OnSyncSettingsContext(wxMouseEvent& event)
{
ContextMenu menu;
auto setVariant = [&](DirectionConfig::Variant var)
{
currentCfg.mainCfg.syncCfg.directionCfg.var = var;
applySyncConfig();
};
const auto currentVar = getConfig().mainCfg.syncCfg.directionCfg.var;
menu.addRadio(L"<- " + _("Two way") + L" ->" , [&] { setVariant(DirectionConfig::TWOWAY); }, currentVar == DirectionConfig::TWOWAY);
menu.addRadio( _("Mirror") + L" ->>", [&] { setVariant(DirectionConfig::MIRROR); }, currentVar == DirectionConfig::MIRROR);
menu.addRadio( _("Update") + L" ->" , [&] { setVariant(DirectionConfig::UPDATE); }, currentVar == DirectionConfig::UPDATE);
menu.addRadio( _("Custom") , [&] { setVariant(DirectionConfig::CUSTOM); }, currentVar == DirectionConfig::CUSTOM);
menu.popup(*this);
}
void MainDialog::onNaviPanelFilesDropped(FileDropEvent& event)
{
loadConfiguration(toZ(event.getFiles()));
event.Skip();
}
void MainDialog::onDirSelected(wxCommandEvent& event)
{
//left and right directory text-control and dirpicker are synchronized by MainFolderDragDrop automatically
clearGrid(); //disable the sync button
event.Skip();
}
void MainDialog::onDirManualCorrection(wxCommandEvent& event)
{
updateUnsavedCfgStatus();
event.Skip();
}
wxString getFormattedHistoryElement(const Zstring& filename)
{
Zstring output = afterLast(filename, FILE_NAME_SEPARATOR);
if (endsWith(output, Zstr(".ffs_gui")))
output = beforeLast(output, Zstr('.'));
return utfCvrtTo<wxString>(output);
}
void MainDialog::addFileToCfgHistory(const std::vector<Zstring>& filenames)
{
//determine highest "last use" index number of m_listBoxHistory
int lastUseIndexMax = 0;
for (int i = 0; i < static_cast<int>(m_listBoxHistory->GetCount()); ++i)
if (auto histData = dynamic_cast<const wxClientHistoryData*>(m_listBoxHistory->GetClientObject(i)))
if (histData->lastUseIndex_ > lastUseIndexMax)
lastUseIndexMax = histData->lastUseIndex_;
std::deque<bool> selections(m_listBoxHistory->GetCount()); //items to select after update of history list
for (auto it = filenames.begin(); it != filenames.end(); ++it)
{
const Zstring& filename = *it;
//Do we need to additionally check for aliases of the same physical files here? (and aliases for lastRunConfigName?)
const int itemPos = [&]() -> int
{
const int itemCount = static_cast<int>(m_listBoxHistory->GetCount());
for (int i = 0; i < itemCount; ++i)
if (auto histData = dynamic_cast<const wxClientHistoryData*>(m_listBoxHistory->GetClientObject(i)))
{
if (EqualFilename()(filename, histData->cfgFile_))
return i;
}
else
assert(false);
return -1;
}();
if (itemPos >= 0) //update
{
if (auto histData = dynamic_cast<wxClientHistoryData*>(m_listBoxHistory->GetClientObject(itemPos)))
histData->lastUseIndex_ = ++lastUseIndexMax;
selections[itemPos] = true;
}
else //insert
{
const wxString label = EqualFilename()(filename, lastRunConfigName()) ? //give default config file a different name
L"<" + _("Last session") + L">" : getFormattedHistoryElement(filename);
const int newPos = m_listBoxHistory->Append(label, new wxClientHistoryData(filename, ++lastUseIndexMax)); //*insert* into sorted list
selections.insert(selections.begin() + newPos, true);
}
}
assert(selections.size() == m_listBoxHistory->GetCount());
//do not apply selections immediately but only when needed!
//this prevents problems with m_listBoxHistory losing keyboard selection focus if identical selection is redundantly reapplied
for (int pos = 0; pos < static_cast<int>(selections.size()); ++pos)
if (m_listBoxHistory->IsSelected(pos) != selections[pos])
m_listBoxHistory->SetSelection(pos, selections[pos]);
}
void MainDialog::removeObsoleteCfgHistoryItems(const std::vector<Zstring>& filenames)
{
//don't use wxString: NOT thread-safe! (e.g. non-atomic ref-count)
auto getMissingFilesAsync = [filenames]() -> std::vector<Zstring>
{
//boost::this_thread::sleep(boost::posix_time::millisec(5000));
//check existence of all config files in parallel!
std::list<boost::unique_future<bool>> fileEx;
for (auto it = filenames.begin(); it != filenames.end(); ++it) //avoid VC11 compiler issues with std::for_each
{
const Zstring filename = *it; //don't reference iterator in lambda!
fileEx.push_back(zen::async2<bool>([=] { return fileExists(filename); }));
}
//potentially slow network access => limit maximum wait time!
wait_for_all_timed(fileEx.begin(), fileEx.end(), boost::posix_time::milliseconds(1000));
std::vector<Zstring> missingFiles;
auto itFut = fileEx.begin();
for (auto it = filenames.begin(); it != filenames.end(); ++it, (void)++itFut) //void: prevent ADL from dragging in boost's ,-overload: "MSVC warning C4913: user defined binary operator ',' exists but no overload could convert all operands"
if (itFut->is_ready() && !itFut->get()) //remove only files that are confirmed to be non-existent
missingFiles.push_back(*it);
return missingFiles;
};
processAsync(getMissingFilesAsync, [this](const std::vector<Zstring>& files) { removeCfgHistoryItems(files); });
}
void MainDialog::removeCfgHistoryItems(const std::vector<Zstring>& filenames)
{
std::for_each(filenames.begin(), filenames.end(), [&](const Zstring& filename)
{
const int histSize = m_listBoxHistory->GetCount();
for (int i = 0; i < histSize; ++i)
if (auto histData = dynamic_cast<wxClientHistoryData*>(m_listBoxHistory->GetClientObject(i)))
if (EqualFilename()(filename, histData->cfgFile_))
{
m_listBoxHistory->Delete(i);
break;
}
});
}
void MainDialog::updateUnsavedCfgStatus()
{
const Zstring activeCfgFilename = activeConfigFiles.size() == 1 && activeConfigFiles[0] != lastRunConfigName() ? activeConfigFiles[0] : Zstring();
const bool haveUnsavedCfg = lastConfigurationSaved != getConfig();
//update save config button
const bool allowSave = haveUnsavedCfg ||
activeConfigFiles.size() > 1;
auto makeBrightGrey = [](const wxBitmap& bmp) -> wxBitmap
{
wxImage img = bmp.ConvertToImage().ConvertToGreyscale(1.0/3, 1.0/3, 1.0/3); //treat all channels equally!
brighten(img, 80);
return img;
};
//setImage(*m_bpButtonSave, greyScale(getResourceImage(L"save")));
setImage(*m_bpButtonSave, allowSave ? getResourceImage(L"save") : makeBrightGrey(getResourceImage(L"save")));
m_bpButtonSave->Enable(allowSave);
m_menuItemSave->Enable(allowSave); //bitmap is automatically greyscaled on Win7 (introducing a crappy looking shift), but not on XP
//set main dialog title
wxString title;
if (haveUnsavedCfg)
title += L'*';
if (!activeCfgFilename.empty())
title += toWx(activeCfgFilename);
else if (activeConfigFiles.size() > 1)
{
const wchar_t* EM_DASH = L" \u2014 ";
title += xmlAccess::extractJobName(activeConfigFiles[0]);
std::for_each(activeConfigFiles.begin() + 1, activeConfigFiles.end(), [&](const Zstring& filename) { title += EM_DASH + xmlAccess::extractJobName(filename); });
}
else
title += L"FreeFileSync - " + _("Folder Comparison and Synchronization");
SetTitle(title);
}
void MainDialog::OnConfigSave(wxCommandEvent& event)
{
const Zstring activeCfgFilename = activeConfigFiles.size() == 1 && activeConfigFiles[0] != lastRunConfigName() ? activeConfigFiles[0] : Zstring();
//if we work on a single named configuration document: save directly if changed
//else: always show file dialog
if (!activeCfgFilename.empty())
{
using namespace xmlAccess;
switch (getXmlType(activeCfgFilename)) //throw()
{
case XML_TYPE_GUI:
trySaveConfig(&activeCfgFilename);
return;
case XML_TYPE_BATCH:
trySaveBatchConfig(&activeCfgFilename);
return;
case XML_TYPE_GLOBAL:
case XML_TYPE_OTHER:
assert(false);
return;
}
}
trySaveConfig(nullptr);
}
void MainDialog::OnConfigSaveAs(wxCommandEvent& event)
{
trySaveConfig(nullptr);
}
void MainDialog::OnSaveAsBatchJob(wxCommandEvent& event)
{
trySaveBatchConfig(nullptr);
}
bool MainDialog::trySaveConfig(const Zstring* fileNameGui) //return true if saved successfully
{
Zstring targetFilename;
if (fileNameGui)
{
targetFilename = *fileNameGui;
assert(endsWith(targetFilename, Zstr(".ffs_gui")));
}
else
{
Zstring defaultFileName = activeConfigFiles.size() == 1 && activeConfigFiles[0] != lastRunConfigName() ? activeConfigFiles[0] : Zstr("SyncSettings.ffs_gui");
//attention: activeConfigFiles may be an imported *.ffs_batch file! We don't want to overwrite it with a GUI config!
if (endsWith(defaultFileName, Zstr(".ffs_batch")))
replace(defaultFileName, Zstr(".ffs_batch"), Zstr(".ffs_gui"), false);
wxFileDialog filePicker(this, //put modal dialog on stack: creating this on freestore leads to memleak!
wxEmptyString,
//OS X really needs dir/file separated like this:
utfCvrtTo<wxString>(beforeLast(defaultFileName, FILE_NAME_SEPARATOR)), //default dir; empty string if / not found
utfCvrtTo<wxString>(afterLast (defaultFileName, FILE_NAME_SEPARATOR)), //default file; whole string if / not found
wxString(L"FreeFileSync (*.ffs_gui)|*.ffs_gui") + L"|" +_("All files") + L" (*.*)|*",
wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if (filePicker.ShowModal() != wxID_OK)
return false;
targetFilename = toZ(filePicker.GetPath());
}
const xmlAccess::XmlGuiConfig guiCfg = getConfig();
try
{
xmlAccess::writeConfig(guiCfg, targetFilename); //throw FfsXmlError
setLastUsedConfig(targetFilename, guiCfg);
flashStatusInformation(_("Configuration saved"));
return true;
}
catch (const xmlAccess::FfsXmlError& e)
{
wxMessageBox(e.toString().c_str(), L"FreeFileSync - " + _("Error"), wxOK | wxICON_ERROR, this);
return false;
}
}
bool MainDialog::trySaveBatchConfig(const Zstring* fileNameBatch)
{
//essentially behave like trySaveConfig(): the collateral damage of not saving GUI-only settings "hideExcludedItems, m_bpButtonViewTypeSyncAction" is negliable
const xmlAccess::XmlGuiConfig guiCfg = getConfig();
Zstring targetFilename;
xmlAccess::XmlBatchConfig batchCfg;
if (fileNameBatch)
{
targetFilename = *fileNameBatch;
batchCfg = convertGuiToBatchPreservingExistingBatch(guiCfg, *fileNameBatch);
assert(endsWith(targetFilename, Zstr(".ffs_batch")));
}
else
{
const Zstring activeCfgFilename = activeConfigFiles.size() == 1 && activeConfigFiles[0] != lastRunConfigName() ? activeConfigFiles[0] : Zstring();
batchCfg = convertGuiToBatchPreservingExistingBatch(guiCfg, activeCfgFilename);
//let user change batch config: this should change batch-exclusive settings only, else the "setLastUsedConfig" below would be somewhat of a lie
if (!customizeBatchConfig(this,
batchCfg, //in/out
globalCfg.gui.onCompletionHistory,
globalCfg.gui.onCompletionHistoryMax))
return false;
Zstring defaultFileName = !activeCfgFilename.empty() ? activeCfgFilename : Zstr("BatchRun.ffs_batch");
//attention: activeConfigFiles may be a *.ffs_gui file! We don't want to overwrite it with a BATCH config!
if (endsWith(defaultFileName, Zstr(".ffs_gui")))
replace(defaultFileName, Zstr(".ffs_gui"), Zstr(".ffs_batch"));
wxFileDialog filePicker(this, //put modal dialog on stack: creating this on freestore leads to memleak!
wxEmptyString,
//OS X really needs dir/file separated like this:
utfCvrtTo<wxString>(beforeLast(defaultFileName, FILE_NAME_SEPARATOR)), //default dir; empty string if / not found
utfCvrtTo<wxString>(afterLast (defaultFileName, FILE_NAME_SEPARATOR)), //default file; whole string if / not found
_("FreeFileSync batch") + L" (*.ffs_batch)|*.ffs_batch" + L"|" +_("All files") + L" (*.*)|*",
wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if (filePicker.ShowModal() != wxID_OK)
return false;
targetFilename = toZ(filePicker.GetPath());
}
try
{
xmlAccess::writeConfig(batchCfg, targetFilename); //throw FfsXmlError
setLastUsedConfig(targetFilename, guiCfg); //[!] behave as if we had saved guiCfg
flashStatusInformation(_("Configuration saved"));
return true;
}
catch (const xmlAccess::FfsXmlError& e)
{
wxMessageBox(e.toString().c_str(), L"FreeFileSync - " + _("Error"), wxOK | wxICON_ERROR, this);
return false;
}
}
bool MainDialog::saveOldConfig() //return false on user abort
{
if (lastConfigurationSaved != getConfig())
{
const Zstring activeCfgFilename = activeConfigFiles.size() == 1 && activeConfigFiles[0] != lastRunConfigName() ? activeConfigFiles[0] : Zstring();
//notify user about changed settings
if (globalCfg.optDialogs.popupOnConfigChange)
if (!activeCfgFilename.empty())
//only if check is active and non-default config file loaded
{
bool dontAskAgain = false;
switch (showQuestionDlg(this,
ReturnQuestionDlg::BUTTON_YES | ReturnQuestionDlg::BUTTON_NO | ReturnQuestionDlg::BUTTON_CANCEL,
replaceCpy(_("Do you want to save changes to %x?"), L"%x", fmtFileName(afterLast(activeCfgFilename, FILE_NAME_SEPARATOR))),
QuestConfig().setCaption(toWx(activeCfgFilename)).
setLabelYes(_("&Save")).
setLabelNo(_("Do&n't save")).
showCheckBox(dontAskAgain, _("Never save &changes"), ReturnQuestionDlg::BUTTON_YES)))
{
case ReturnQuestionDlg::BUTTON_YES:
using namespace xmlAccess;
switch (getXmlType(activeCfgFilename)) //throw()
{
case XML_TYPE_GUI:
return trySaveConfig(&activeCfgFilename);
case XML_TYPE_BATCH:
return trySaveBatchConfig(&activeCfgFilename);
case XML_TYPE_GLOBAL:
case XML_TYPE_OTHER:
assert(false);
return false;
}
case ReturnQuestionDlg::BUTTON_NO:
globalCfg.optDialogs.popupOnConfigChange = !dontAskAgain;
break;
case ReturnQuestionDlg::BUTTON_CANCEL:
return false;
}
}
//discard current reference file(s), this ensures next app start will load <last session> instead of the original non-modified config selection
setLastUsedConfig(std::vector<Zstring>(), lastConfigurationSaved);
//this seems to make theoretical sense also: the job of this function is to make sure current (volatile) config and reference file name are in sync
// => if user does not save cfg, it is not attached to a physical file names anymore!
}
return true;
}
void MainDialog::OnConfigLoad(wxCommandEvent& event)
{
const Zstring activeCfgFilename = activeConfigFiles.size() == 1 && activeConfigFiles[0] != lastRunConfigName() ? activeConfigFiles[0] : Zstring();
wxFileDialog filePicker(this,
wxEmptyString,
utfCvrtTo<wxString>(beforeLast(activeCfgFilename, FILE_NAME_SEPARATOR)), //set default dir: empty string if "activeConfigFiles" is empty or has no path separator
wxEmptyString,
wxString(L"FreeFileSync (*.ffs_gui;*.ffs_batch)|*.ffs_gui;*.ffs_batch") + L"|" +_("All files") + L" (*.*)|*",
wxFD_OPEN | wxFD_MULTIPLE);
if (filePicker.ShowModal() == wxID_OK)
{
wxArrayString tmp;
filePicker.GetPaths(tmp);
std::vector<wxString> filenames(tmp.begin(), tmp.end());
loadConfiguration(toZ(filenames));
}
}
void MainDialog::OnConfigNew(wxCommandEvent& event)
{
if (!saveOldConfig()) //notify user about changed settings
return;
xmlAccess::XmlGuiConfig newConfig;
//add default exclusion filter: this is only ever relevant when creating new configurations!
//a default XmlGuiConfig does not need these user-specific exclusions!
Zstring& excludeFilter = newConfig.mainCfg.globalFilter.excludeFilter;
if (!excludeFilter.empty() && !endsWith(excludeFilter, Zstr("\n")))
excludeFilter += Zstr("\n");
excludeFilter += globalCfg.gui.defaultExclusionFilter;
setConfig(newConfig, std::vector<Zstring>());
}
void MainDialog::OnLoadFromHistory(wxCommandEvent& event)
{
wxArrayInt selections;
m_listBoxHistory->GetSelections(selections);
std::vector<Zstring> filenames;
std::for_each(selections.begin(), selections.end(),
[&](int pos)
{
if (auto histData = dynamic_cast<const wxClientHistoryData*>(m_listBoxHistory->GetClientObject(pos)))
filenames.push_back(histData->cfgFile_);
else
assert(false);
});
if (!filenames.empty())
loadConfiguration(filenames);
//user changed m_listBoxHistory selection so it's this method's responsibility to synchronize with activeConfigFiles:
//- if user cancelled saving old config
//- there's an error loading new config
//- filenames is empty and user tried to unselect the current config
addFileToCfgHistory(activeConfigFiles);
}
void MainDialog::OnLoadFromHistoryDoubleClick(wxCommandEvent& event)
{
wxArrayInt selections;
m_listBoxHistory->GetSelections(selections);
std::vector<Zstring> filenames;
std::for_each(selections.begin(), selections.end(), [&](int pos)
{
if (auto histData = dynamic_cast<const wxClientHistoryData*>(m_listBoxHistory->GetClientObject(pos)))
filenames.push_back(histData->cfgFile_);
else
assert(false);
});
if (!filenames.empty())
if (loadConfiguration(filenames))
{
//simulate button click on "compare"
wxCommandEvent dummy2(wxEVT_COMMAND_BUTTON_CLICKED);
if (wxEvtHandler* evtHandler = m_buttonCompare->GetEventHandler())
evtHandler->ProcessEvent(dummy2); //synchronous call
}
//synchronize m_listBoxHistory and activeConfigFiles, see OnLoadFromHistory()
addFileToCfgHistory(activeConfigFiles);
}
bool MainDialog::loadConfiguration(const std::vector<Zstring>& filenames)
{
if (filenames.empty())
return true;
if (!saveOldConfig())
return false; //cancelled by user
//load XML
xmlAccess::XmlGuiConfig newGuiCfg; //structure to receive gui settings, already defaulted!!
try
{
//allow reading batch configurations also
xmlAccess::readAnyConfig(filenames, newGuiCfg); //throw FfsXmlError
setConfig(newGuiCfg, filenames);
//flashStatusInformation(("Configuration loaded")); -> irrelevant!?
return true;
}
catch (const xmlAccess::FfsXmlError& error)
{
if (error.getSeverity() == xmlAccess::FfsXmlError::WARNING)
{
wxMessageBox(error.toString(), L"FreeFileSync - " + _("Warning"), wxOK | wxICON_WARNING, this);
setConfig(newGuiCfg, filenames);
setLastUsedConfig(filenames, xmlAccess::XmlGuiConfig()); //simulate changed config due to parsing errors
}
else
wxMessageBox(error.toString(), L"FreeFileSync - " + _("Error"), wxOK | wxICON_ERROR, this);
return false;
}
}
void MainDialog::deleteSelectedCfgHistoryItems()
{
wxArrayInt tmp;
m_listBoxHistory->GetSelections(tmp);
std::set<int> selections(tmp.begin(), tmp.end()); //sort ascending!
//delete starting with high positions:
std::for_each(selections.rbegin(), selections.rend(), [&](int pos) { m_listBoxHistory->Delete(pos); });
//set active selection on next element to allow "batch-deletion" by holding down DEL key
if (!selections.empty() && m_listBoxHistory->GetCount() > 0)
{
int newSelection = *selections.begin();
if (newSelection >= static_cast<int>(m_listBoxHistory->GetCount()))
newSelection = m_listBoxHistory->GetCount() - 1;
m_listBoxHistory->SetSelection(newSelection);
}
}
void MainDialog::OnCfgHistoryRightClick(wxMouseEvent& event)
{
ContextMenu menu;
menu.addItem(_("Delete"), [this] { deleteSelectedCfgHistoryItems(); });
menu.popup(*this);
}
void MainDialog::OnCfgHistoryKeyEvent(wxKeyEvent& event)
{
const int keyCode = event.GetKeyCode();
if (keyCode == WXK_DELETE || keyCode == WXK_NUMPAD_DELETE)
{
deleteSelectedCfgHistoryItems();
return; //"swallow" event
}
event.Skip();
}
void MainDialog::OnClose(wxCloseEvent& event)
{
//attention: system shutdown: is handled in onQueryEndSession()!
//regular destruction handling
if (event.CanVeto())
{
const bool cancelled = !saveOldConfig(); //notify user about changed settings
if (cancelled)
{
//attention: this Veto() will NOT cancel system shutdown since saveOldConfig() blocks on modal dialog
event.Veto();
return;
}
}
Destroy();
}
void MainDialog::onCheckRows(CheckRowsEvent& event)
{
std::set<size_t> selectedRows;
const size_t rowLast = std::min(event.rowLast_, gridDataView->rowsOnView()); //consider dummy rows
for (size_t i = event.rowFirst_; i < rowLast; ++i)
selectedRows.insert(i);
if (!selectedRows.empty())
{
std::vector<FileSystemObject*> objects = gridDataView->getAllFileRef(selectedRows);
setFilterManually(objects, event.setIncluded_);
}
}
void MainDialog::onSetSyncDirection(SyncDirectionEvent& event)
{
std::set<size_t> selectedRows;
const size_t rowLast = std::min(event.rowLast_, gridDataView->rowsOnView()); //consider dummy rows
for (size_t i = event.rowFirst_; i < rowLast; ++i)
selectedRows.insert(i);
if (!selectedRows.empty())
{
std::vector<FileSystemObject*> objects = gridDataView->getAllFileRef(selectedRows);
setSyncDirManually(objects, event.direction_);
}
}
void MainDialog::setLastUsedConfig(const Zstring& filename, const xmlAccess::XmlGuiConfig& guiConfig)
{
std::vector<Zstring> filenames;
filenames.push_back(filename);
setLastUsedConfig(filenames, guiConfig);
}
void MainDialog::setLastUsedConfig(const std::vector<Zstring>& filenames,
const xmlAccess::XmlGuiConfig& guiConfig)
{
activeConfigFiles = filenames;
lastConfigurationSaved = guiConfig;
addFileToCfgHistory(activeConfigFiles); //put filename on list of last used config files
updateUnsavedCfgStatus();
}
void MainDialog::setConfig(const xmlAccess::XmlGuiConfig& newGuiCfg, const std::vector<Zstring>& referenceFiles)
{
currentCfg = newGuiCfg;
//evaluate new settings...
//(re-)set view filter buttons
setViewFilterDefault();
updateGlobalFilterButton();
//set first folder pair
firstFolderPair->setValues(currentCfg.mainCfg.firstPair.leftDirectory,
currentCfg.mainCfg.firstPair.rightDirectory,
currentCfg.mainCfg.firstPair.altCmpConfig,
currentCfg.mainCfg.firstPair.altSyncConfig,
currentCfg.mainCfg.firstPair.localFilter);
//folderHistoryLeft->addItem(currentCfg.mainCfg.firstPair.leftDirectory);
//folderHistoryRight->addItem(currentCfg.mainCfg.firstPair.rightDirectory);
//clear existing additional folder pairs
clearAddFolderPairs();
//set additional pairs
addFolderPair(currentCfg.mainCfg.additionalPairs);
//read GUI layout
m_checkBoxHideExcluded->SetValue(currentCfg.hideExcludedItems);
setViewTypeSyncAction(currentCfg.highlightSyncAction);
clearGrid(); //+ update GUI!
setLastUsedConfig(referenceFiles, newGuiCfg);
}
inline
FolderPairEnh getEnhancedPair(const FolderPairPanel* panel)
{
return FolderPairEnh(panel->getLeftDir(),
panel->getRightDir(),
panel->getAltCompConfig(),
panel->getAltSyncConfig(),
panel->getAltFilterConfig());
}
xmlAccess::XmlGuiConfig MainDialog::getConfig() const
{
xmlAccess::XmlGuiConfig guiCfg = currentCfg;
//load settings whose ownership lies not in currentCfg:
//first folder pair
guiCfg.mainCfg.firstPair = FolderPairEnh(firstFolderPair->getLeftDir(),
firstFolderPair->getRightDir(),
firstFolderPair->getAltCompConfig(),
firstFolderPair->getAltSyncConfig(),
firstFolderPair->getAltFilterConfig());
//add additional pairs
guiCfg.mainCfg.additionalPairs.clear();
std::transform(additionalFolderPairs.begin(), additionalFolderPairs.end(),
std::back_inserter(guiCfg.mainCfg.additionalPairs), getEnhancedPair);
//sync preview
guiCfg.highlightSyncAction = m_bpButtonViewTypeSyncAction->isActive();
return guiCfg;
}
const Zstring& MainDialog::lastRunConfigName()
{
static Zstring instance = zen::getConfigDir() + Zstr("LastRun.ffs_gui");
return instance;
}
void MainDialog::updateGuiDelayedIf(bool condition)
{
const int delay = 400;
if (condition)
{
gridview::refresh(*m_gridMainL, *m_gridMainC, *m_gridMainR);
m_gridMainL->Update();
m_gridMainC->Update();
m_gridMainR->Update();
wxMilliSleep(delay); //some delay to show the changed GUI before removing rows from sight
}
updateGui();
}
void MainDialog::OnShowExcluded(wxCommandEvent& event)
{
//toggle showing filtered rows
currentCfg.hideExcludedItems = !currentCfg.hideExcludedItems;
//make sure, checkbox and value are in sync
m_checkBoxHideExcluded->SetValue(currentCfg.hideExcludedItems);
updateGui();
}
void MainDialog::OnConfigureFilter(wxCommandEvent& event)
{
if (showFilterDialog(this,
true, //is main filter dialog
currentCfg.mainCfg.globalFilter) == ReturnSmallDlg::BUTTON_OKAY)
{
updateGlobalFilterButton(); //refresh global filter icon
applyFilterConfig(); //re-apply filter
}
//event.Skip()
}
void MainDialog::OnGlobalFilterContext(wxMouseEvent& event)
{
auto clearFilter = [&]
{
currentCfg.mainCfg.globalFilter = FilterConfig();
updateGlobalFilterButton(); //refresh global filter icon
applyFilterConfig(); //re-apply filter
};
auto copyFilter = [&] { filterCfgOnClipboard = make_unique<FilterConfig>(currentCfg.mainCfg.globalFilter); };
auto pasteFilter = [&]
{
if (filterCfgOnClipboard)
{
currentCfg.mainCfg.globalFilter = *filterCfgOnClipboard;
updateGlobalFilterButton(); //refresh global filter icon
applyFilterConfig(); //re-apply filter
}
};
ContextMenu menu;
menu.addItem( _("Clear filter settings"), clearFilter, nullptr, !isNullFilter(currentCfg.mainCfg.globalFilter));
menu.addSeparator();
menu.addItem( _("Copy"), copyFilter, nullptr, !isNullFilter(currentCfg.mainCfg.globalFilter));
menu.addItem( _("Paste"), pasteFilter, nullptr, filterCfgOnClipboard.get() != nullptr);
menu.popup(*this);
}
void MainDialog::OnToggleViewType(wxCommandEvent& event)
{
setViewTypeSyncAction(!m_bpButtonViewTypeSyncAction->isActive()); //toggle view
}
void MainDialog::OnToggleViewButton(wxCommandEvent& event)
{
if (auto button = dynamic_cast<ToggleButton*>(event.GetEventObject()))
{
button->toggle();
updateGui();
}
else
assert(false);
}
inline
wxBitmap buttonPressed(const std::string& name)
{
wxBitmap background = getResourceImage(L"buttonPressed");
return mirrorIfRtl(
layOver(getResourceImage(utfCvrtTo<wxString>(name)), background));
}
inline
wxBitmap buttonReleased(const std::string& name)
{
wxImage output = getResourceImage(utfCvrtTo<wxString>(name)).ConvertToImage().ConvertToGreyscale(1.0/3, 1.0/3, 1.0/3); //treat all channels equally!
//zen::moveImage(output, 1, 0); //move image right one pixel
brighten(output, 80);
return mirrorIfRtl(output);
}
void MainDialog::initViewFilterButtons()
{
m_bpButtonViewTypeSyncAction->init(getResourceImage(L"viewtype_sync_action"), getResourceImage(L"viewtype_cmp_result"));
//tooltip is updated dynamically in setViewTypeSyncAction()
auto initButton = [](ToggleButton& btn, const char* imgName, const wxString& tooltip) { btn.init(buttonPressed(imgName), buttonReleased(imgName)); btn.SetToolTip(tooltip); };
//compare result buttons
initButton(*m_bpButtonShowLeftOnly, "cat_left_only", _("Show files that exist on left side only"));
initButton(*m_bpButtonShowRightOnly, "cat_right_only", _("Show files that exist on right side only"));
initButton(*m_bpButtonShowLeftNewer, "cat_left_newer", _("Show files that are newer on left"));
initButton(*m_bpButtonShowRightNewer, "cat_right_newer", _("Show files that are newer on right"));
initButton(*m_bpButtonShowEqual, "cat_equal", _("Show files that are equal"));
initButton(*m_bpButtonShowDifferent, "cat_different", _("Show files that are different"));
initButton(*m_bpButtonShowConflict, "cat_conflict", _("Show conflicts"));
//sync preview buttons
initButton(*m_bpButtonShowCreateLeft, "so_create_left", _("Show files that will be created on the left side"));
initButton(*m_bpButtonShowCreateRight, "so_create_right", _("Show files that will be created on the right side"));
initButton(*m_bpButtonShowDeleteLeft, "so_delete_left", _("Show files that will be deleted on the left side"));
initButton(*m_bpButtonShowDeleteRight, "so_delete_right", _("Show files that will be deleted on the right side"));
initButton(*m_bpButtonShowUpdateLeft, "so_update_left", _("Show files that will be overwritten on left side"));
initButton(*m_bpButtonShowUpdateRight, "so_update_right", _("Show files that will be overwritten on right side"));
initButton(*m_bpButtonShowDoNothing, "so_none", _("Show files that won't be copied"));
}
void MainDialog::setViewFilterDefault()
{
auto setButton = [](ToggleButton* tb, bool value) { tb->setActive(value); };
const auto& def = globalCfg.gui.viewFilterDefault;
setButton(m_bpButtonShowLeftOnly, def.leftOnly);
setButton(m_bpButtonShowRightOnly, def.rightOnly);
setButton(m_bpButtonShowLeftNewer, def.leftNewer);
setButton(m_bpButtonShowRightNewer, def.rightNewer);
setButton(m_bpButtonShowEqual, def.equal);
setButton(m_bpButtonShowDifferent, def.different);
setButton(m_bpButtonShowConflict, def.conflict);
setButton(m_bpButtonShowCreateLeft, def.createLeft);
setButton(m_bpButtonShowCreateRight,def.createRight);
setButton(m_bpButtonShowUpdateLeft, def.updateLeft);
setButton(m_bpButtonShowUpdateRight,def.updateRight);
setButton(m_bpButtonShowDeleteLeft, def.deleteLeft);
setButton(m_bpButtonShowDeleteRight,def.deleteRight);
setButton(m_bpButtonShowDoNothing, def.doNothing);
}
void MainDialog::OnViewButtonRightClick(wxMouseEvent& event)
{
auto setButtonDefault = [](const ToggleButton* tb, bool& defaultValue)
{
if (tb->IsShown())
defaultValue = tb->isActive();
};
auto setDefault = [&]
{
auto& def = globalCfg.gui.viewFilterDefault;
setButtonDefault(m_bpButtonShowLeftOnly, def.leftOnly);
setButtonDefault(m_bpButtonShowRightOnly, def.rightOnly);
setButtonDefault(m_bpButtonShowLeftNewer, def.leftNewer);
setButtonDefault(m_bpButtonShowRightNewer, def.rightNewer);
setButtonDefault(m_bpButtonShowEqual, def.equal);
setButtonDefault(m_bpButtonShowDifferent, def.different);
setButtonDefault(m_bpButtonShowConflict, def.conflict);
setButtonDefault(m_bpButtonShowCreateLeft, def.createLeft);
setButtonDefault(m_bpButtonShowCreateRight, def.createRight);
setButtonDefault(m_bpButtonShowUpdateLeft, def.updateLeft);
setButtonDefault(m_bpButtonShowUpdateRight, def.updateRight);
setButtonDefault(m_bpButtonShowDeleteLeft, def.deleteLeft);
setButtonDefault(m_bpButtonShowDeleteRight, def.deleteRight);
setButtonDefault(m_bpButtonShowDoNothing, def.doNothing);
};
ContextMenu menu;
menu.addItem( _("Set as default"), setDefault);
menu.popup(*this);
}
void MainDialog::updateGlobalFilterButton()
{
//global filter: test for Null-filter
if (!isNullFilter(currentCfg.mainCfg.globalFilter))
{
setImage(*m_bpButtonFilter, getResourceImage(L"filter"));
m_bpButtonFilter->SetToolTip(_("Filter is active") + L" (F10)");
}
else
{
setImage(*m_bpButtonFilter, greyScale(getResourceImage(L"filter")));
m_bpButtonFilter->SetToolTip(_("No filter selected")+ L" (F10)");
}
}
void MainDialog::OnCompare(wxCommandEvent& event)
{
//PERF_START;
//wxBusyCursor dummy; -> redundant: progress already shown in progress dialog!
wxWindow* oldFocus = wxWindow::FindFocus();
ZEN_ON_SCOPE_EXIT(if (oldFocus) oldFocus->SetFocus();); //e.g. keep focus on main grid after pressing F5
int scrollPosX = 0;
int scrollPosY = 0;
m_gridMainL->GetViewStart(&scrollPosX, &scrollPosY); //preserve current scroll position
ZEN_ON_SCOPE_EXIT(
m_gridMainL->Scroll(scrollPosX, scrollPosY); //
m_gridMainR->Scroll(scrollPosX, scrollPosY); //restore
m_gridMainC->Scroll(-1, scrollPosY); ) //
clearGrid(); //avoid memory peak by clearing old data first
disableAllElements(true); //CompareStatusHandler will internally process Window messages, so avoid unexpected callbacks!
auto app = wxTheApp; //fix lambda/wxWigets/VC fuck up
ZEN_ON_SCOPE_EXIT(app->Yield(); enableAllElements()); //ui update before enabling buttons again: prevent strange behaviour of delayed button clicks
try
{
//class handling status display and error messages
CompareStatusHandler statusHandler(*this);
const std::vector<zen::FolderPairCfg> cmpConfig = zen::extractCompareCfg(getConfig().mainCfg);
//GUI mode: place directory locks on directories isolated(!) during both comparison and synchronization
std::unique_ptr<LockHolder> dirLocks;
//COMPARE DIRECTORIES
compare(globalCfg.fileTimeTolerance,
globalCfg.optDialogs,
true, //allow pw prompt
globalCfg.runWithBackgroundPriority,
globalCfg.createLockFile,
dirLocks,
cmpConfig,
folderCmp,
statusHandler); //throw GuiAbortProcess
}
catch (GuiAbortProcess&)
{
flashStatusInformation(_("Operation aborted"));
// if (m_buttonCompare->IsShownOnScreen()) m_buttonCompare->SetFocus();
updateGui(); //refresh grid in ANY case! (also on abort)
return;
}
gridDataView->setData(folderCmp); //update view on data
treeDataView->setData(folderCmp); //
updateGui();
// if (m_buttonSync->IsShownOnScreen()) m_buttonSync->SetFocus();
gridview::clearSelection(*m_gridMainL, *m_gridMainC, *m_gridMainR);
m_gridNavi->clearSelection();
//play (optional) sound notification after sync has completed (GUI and batch mode)
//const Zstring soundFile = zen::getResourceDir() + Zstr("Compare_Complete.wav");
//if (fileExists(soundFile))
// wxSound::Play(toWx(soundFile), wxSOUND_ASYNC);
//add to folder history after successful comparison only
folderHistoryLeft ->addItem(toZ(m_directoryLeft ->GetValue()));
folderHistoryRight->addItem(toZ(m_directoryRight->GetValue()));
//prepare status information
if (allElementsEqual(folderCmp))
flashStatusInformation(_("All folders are in sync"));
}
void MainDialog::updateTopButtonImages()
{
auto updateButton = [&](wxBitmapButton& btn, const wxBitmap& bmp, const wxString& variantName, bool makeGrey)
{
wxImage labelImage = createImageFromText(btn.GetLabel(), btn.GetFont(), makeGrey ? wxColor(128, 128, 128) : wxSystemSettings::GetColour(wxSYS_COLOUR_BTNTEXT));
wxImage variantImage = createImageFromText(variantName, wxFont(wxNORMAL_FONT->GetPointSize(), wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxBOLD), wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT));
wxImage descrImage = stackImages(labelImage, variantImage, ImageStackLayout::VERTICAL, ImageStackAlignment::CENTER);
const wxImage& iconImage = makeGrey ? greyScale(bmp.ConvertToImage()) : bmp.ConvertToImage();
wxImage dynImage = btn.GetLayoutDirection() != wxLayout_RightToLeft ?
stackImages(iconImage, descrImage, ImageStackLayout::HORIZONTAL, ImageStackAlignment::CENTER, 5) :
stackImages(descrImage, iconImage, ImageStackLayout::HORIZONTAL, ImageStackAlignment::CENTER, 5);
//SetMinSize() instead of SetSize() is needed here for wxWindows layout determination to work corretly
wxSize minSize = dynImage.GetSize() + wxSize(10, 10); //add border space
minSize.x = std::max(minSize.x, 180);
btn.SetMinSize(minSize);
btn.SetBitmapLabel(wxBitmap(dynImage));
//SetLabel() calls confuse wxBitmapButton in the disabled state and it won't show the image! workaround:
btn.SetBitmapDisabled(wxBitmap(dynImage.ConvertToDisabled()));
};
updateButton(*m_buttonCompare, getResourceImage(L"compare"), getConfig().mainCfg.getCompVariantName(), false);
updateButton(*m_buttonSync, getResourceImage(L"sync"), getConfig().mainCfg.getSyncVariantName(), folderCmp.empty());
m_panelTopButtons->Layout();
}
void MainDialog::updateGui()
{
updateGridViewData(); //update gridDataView and write status information
updateStatistics();
updateUnsavedCfgStatus();
updateTopButtonImages();
auiMgr.Update(); //fix small display distortion, if view filter panel is empty
}
void MainDialog::clearGrid()
{
folderCmp.clear();
gridDataView->setData(folderCmp);
treeDataView->setData(folderCmp);
updateGui();
}
void MainDialog::updateStatistics()
{
//update preview of item count and bytes to be transferred:
const SyncStatistics st(folderCmp);
setText(*m_staticTextData, filesizeToShortString(st.getDataToProcess()));
if (st.getDataToProcess() == 0)
m_bitmapData->SetBitmap(greyScale(getResourceImage(L"data")));
else
m_bitmapData->SetBitmap(getResourceImage(L"data"));
auto setValue = [](wxStaticText& txtControl, int value, wxStaticBitmap& bmpControl, const wchar_t* bmpName)
{
setText(txtControl, toGuiString(value));
if (value == 0)
bmpControl.SetBitmap(greyScale(mirrorIfRtl(getResourceImage(bmpName))));
else
bmpControl.SetBitmap(mirrorIfRtl(getResourceImage(bmpName)));
};
setValue(*m_staticTextCreateLeft, st.getCreate<LEFT_SIDE >(), *m_bitmapCreateLeft, L"so_create_left_small");
setValue(*m_staticTextUpdateLeft, st.getUpdate<LEFT_SIDE >(), *m_bitmapUpdateLeft, L"so_update_left_small");
setValue(*m_staticTextDeleteLeft, st.getDelete<LEFT_SIDE >(), *m_bitmapDeleteLeft, L"so_delete_left_small");
setValue(*m_staticTextCreateRight, st.getCreate<RIGHT_SIDE>(), *m_bitmapCreateRight, L"so_create_right_small");
setValue(*m_staticTextUpdateRight, st.getUpdate<RIGHT_SIDE>(), *m_bitmapUpdateRight, L"so_update_right_small");
setValue(*m_staticTextDeleteRight, st.getDelete<RIGHT_SIDE>(), *m_bitmapDeleteRight, L"so_delete_right_small");
m_panelStatistics->Layout();
m_panelStatistics->Refresh(); //fix small mess up on RTL layout
}
void MainDialog::OnSyncSettings(wxCommandEvent& event)
{
ExecWhenFinishedCfg ewfCfg = { ¤tCfg.mainCfg.onCompletion,
&globalCfg.gui.onCompletionHistory,
globalCfg.gui.onCompletionHistoryMax
};
if (showSyncConfigDlg(this,
currentCfg.mainCfg.cmpConfig.compareVar,
currentCfg.mainCfg.syncCfg,
¤tCfg.handleError,
&ewfCfg) == ReturnSyncConfig::BUTTON_OKAY) //optional input parameter
{
applySyncConfig();
}
}
void MainDialog::applyCompareConfig(bool switchMiddleGrid)
{
clearGrid(); //+ GUI update
//convenience: change sync view
if (switchMiddleGrid)
switch (currentCfg.mainCfg.cmpConfig.compareVar)
{
case CMP_BY_TIME_SIZE:
setViewTypeSyncAction(true);
break;
case CMP_BY_CONTENT:
setViewTypeSyncAction(false);
break;
}
}
void MainDialog::OnCmpSettings(wxCommandEvent& event)
{
//show window right next to the compare-config button
//wxPoint windowPos = m_bpButtonCmpConfig->GetScreenPosition();
//windowPos.x += m_bpButtonCmpConfig->GetSize().GetWidth() + 5;
CompConfig cmpConfigNew = currentCfg.mainCfg.cmpConfig;
if (zen::showCompareCfgDialog(this, cmpConfigNew) == ReturnSmallDlg::BUTTON_OKAY &&
//check if settings were changed at all
cmpConfigNew != currentCfg.mainCfg.cmpConfig)
{
currentCfg.mainCfg.cmpConfig = cmpConfigNew;
applyCompareConfig(true); //true: switchMiddleGrid
}
}
void MainDialog::OnStartSync(wxCommandEvent& event)
{
if (folderCmp.empty())
{
//quick sync: simulate button click on "compare"
wxCommandEvent dummy2(wxEVT_COMMAND_BUTTON_CLICKED);
if (wxEvtHandler* evtHandler = m_buttonCompare->GetEventHandler())
evtHandler->ProcessEvent(dummy2); //synchronous call
if (folderCmp.empty()) //check if user aborted or error occurred, ect...
return;
}
//show sync preview/confirmation dialog
if (globalCfg.optDialogs.confirmSyncStart)
{
bool dontShowAgain = false;
if (zen::showSyncPreviewDlg(this,
getConfig().mainCfg.getSyncVariantName(),
zen::SyncStatistics(folderCmp),
dontShowAgain) != ReturnSmallDlg::BUTTON_OKAY)
return;
globalCfg.optDialogs.confirmSyncStart = !dontShowAgain;
}
try
{
//PERF_START;
const Zstring activeCfgFilename = activeConfigFiles.size() == 1 && activeConfigFiles[0] != lastRunConfigName() ? activeConfigFiles[0] : Zstring();
const auto& guiCfg = getConfig();
disableAllElements(false); //SyncStatusHandler will internally process Window messages, so avoid unexpected callbacks!
ZEN_ON_SCOPE_EXIT(enableAllElements());
//class handling status updates and error messages
SyncStatusHandler statusHandler(this, //throw GuiAbortProcess
globalCfg.lastSyncsLogFileSizeMax,
currentCfg.handleError,
xmlAccess::extractJobName(activeCfgFilename),
guiCfg.mainCfg.onCompletion,
globalCfg.gui.onCompletionHistory);
//wxBusyCursor dummy; -> redundant: progress already shown in progress dialog!
//GUI mode: place directory locks on directories isolated(!) during both comparison and synchronization
std::unique_ptr<LockHolder> dirLocks;
if (globalCfg.createLockFile)
{
std::set<Zstring, LessFilename> dirnamesExisting;
for (auto it = begin(folderCmp); it != end(folderCmp); ++it)
{
if (it->isExisting<LEFT_SIDE>()) //do NOT check directory existence again!
dirnamesExisting.insert(it->getBaseDirPf<LEFT_SIDE >());
if (it->isExisting<RIGHT_SIDE>())
dirnamesExisting.insert(it->getBaseDirPf<RIGHT_SIDE>());
}
dirLocks = make_unique<LockHolder>(dirnamesExisting, globalCfg.optDialogs.warningDirectoryLockFailed, statusHandler);
}
//START SYNCHRONIZATION
const std::vector<zen::FolderPairSyncCfg> syncProcessCfg = zen::extractSyncCfg(guiCfg.mainCfg);
if (syncProcessCfg.size() != folderCmp.size())
throw std::logic_error("Programming Error: Contract violation! " + std::string(__FILE__) + ":" + numberTo<std::string>(__LINE__));
//should never happen: sync button is deactivated if they are not in sync
synchronize(localTime(),
globalCfg.optDialogs,
globalCfg.verifyFileCopy,
globalCfg.copyLockedFiles,
globalCfg.copyFilePermissions,
globalCfg.transactionalFileCopy,
globalCfg.runWithBackgroundPriority,
syncProcessCfg,
folderCmp,
statusHandler);
}
catch (GuiAbortProcess&)
{
//do NOT disable the sync button: user might want to try to sync the REMAINING rows
} //enableSynchronization(false);
//remove empty rows: just a beautification, invalid rows shouldn't cause issues
gridDataView->removeInvalidRows();
updateGui();
}
void MainDialog::onGridDoubleClickL(GridClickEvent& event)
{
onGridDoubleClickRim(event.row_, true);
}
void MainDialog::onGridDoubleClickR(GridClickEvent& event)
{
onGridDoubleClickRim(event.row_, false);
}
void MainDialog::onGridDoubleClickRim(size_t row, bool leftSide)
{
if (!globalCfg.gui.externelApplications.empty())
{
std::vector<FileSystemObject*> selection;
if (FileSystemObject* fsObj = gridDataView->getObject(row)) //selection must be a list of BOUND pointers!
selection.push_back(fsObj);
openExternalApplication(globalCfg.gui.externelApplications[0].second, selection, leftSide);
}
}
void MainDialog::onGridLabelLeftClick(bool onLeft, ColumnTypeRim type)
{
auto sortInfo = gridDataView->getSortInfo();
bool sortAscending = GridView::getDefaultSortDirection(type);
if (sortInfo && sortInfo->onLeft_ == onLeft && sortInfo->type_ == type)
sortAscending = !sortInfo->ascending_;
gridDataView->sortView(type, onLeft, sortAscending);
gridview::clearSelection(*m_gridMainL, *m_gridMainC, *m_gridMainR);
updateGui(); //refresh gridDataView
}
void MainDialog::onGridLabelLeftClickL(GridClickEvent& event)
{
onGridLabelLeftClick(true, static_cast<ColumnTypeRim>(event.colType_));
}
void MainDialog::onGridLabelLeftClickR(GridClickEvent& event)
{
onGridLabelLeftClick(false, static_cast<ColumnTypeRim>(event.colType_));
}
void MainDialog::onGridLabelLeftClickC(GridClickEvent& event)
{
//sorting middle grid is more or less useless: therefore let's toggle view instead!
setViewTypeSyncAction(!m_bpButtonViewTypeSyncAction->isActive()); //toggle view
}
void MainDialog::OnSwapSides(wxCommandEvent& event)
{
//swap directory names: first pair
firstFolderPair->setValues(firstFolderPair->getRightDir(), // swap directories
firstFolderPair->getLeftDir(), //
firstFolderPair->getAltCompConfig(),
firstFolderPair->getAltSyncConfig(),
firstFolderPair->getAltFilterConfig());
//additional pairs
for (auto it = additionalFolderPairs.begin(); it != additionalFolderPairs.end(); ++it)
{
FolderPairPanel* panel = *it;
panel->setValues(panel->getRightDir(), // swap directories
panel->getLeftDir(), //
panel->getAltCompConfig(),
panel->getAltSyncConfig(),
panel->getAltFilterConfig());
}
//swap view filter
bool tmp = m_bpButtonShowLeftOnly->isActive();
m_bpButtonShowLeftOnly->setActive(m_bpButtonShowRightOnly->isActive());
m_bpButtonShowRightOnly->setActive(tmp);
tmp = m_bpButtonShowLeftNewer->isActive();
m_bpButtonShowLeftNewer->setActive(m_bpButtonShowRightNewer->isActive());
m_bpButtonShowRightNewer->setActive(tmp);
/* for sync preview and "mirror" variant swapping may create strange effect:
tmp = m_bpButtonShowCreateLeft->isActive();
m_bpButtonShowCreateLeft->setActive(m_bpButtonShowCreateRight->isActive());
m_bpButtonShowCreateRight->setActive(tmp);
tmp = m_bpButtonShowDeleteLeft->isActive();
m_bpButtonShowDeleteLeft->setActive(m_bpButtonShowDeleteRight->isActive());
m_bpButtonShowDeleteRight->setActive(tmp);
tmp = m_bpButtonShowUpdateLeft->isActive();
m_bpButtonShowUpdateLeft->setActive(m_bpButtonShowUpdateRight->isActive());
m_bpButtonShowUpdateRight->setActive(tmp);
*/
//swap grid information
zen::swapGrids(getConfig().mainCfg, folderCmp);
updateGui();
}
void MainDialog::updateGridViewData()
{
size_t filesOnLeftView = 0;
size_t foldersOnLeftView = 0;
size_t filesOnRightView = 0;
size_t foldersOnRightView = 0;
zen::UInt64 filesizeLeftView;
zen::UInt64 filesizeRightView;
//disable all buttons per default
m_bpButtonShowLeftOnly ->Show(false);
m_bpButtonShowRightOnly ->Show(false);
m_bpButtonShowLeftNewer ->Show(false);
m_bpButtonShowRightNewer->Show(false);
m_bpButtonShowDifferent ->Show(false);
m_bpButtonShowEqual ->Show(false);
m_bpButtonShowConflict ->Show(false);
m_bpButtonShowCreateLeft ->Show(false);
m_bpButtonShowCreateRight->Show(false);
m_bpButtonShowDeleteLeft ->Show(false);
m_bpButtonShowDeleteRight->Show(false);
m_bpButtonShowUpdateLeft ->Show(false);
m_bpButtonShowUpdateRight->Show(false);
m_bpButtonShowDoNothing ->Show(false);
if (m_bpButtonViewTypeSyncAction->isActive())
{
const GridView::StatusSyncPreview result = gridDataView->updateSyncPreview(currentCfg.hideExcludedItems,
m_bpButtonShowCreateLeft ->isActive(),
m_bpButtonShowCreateRight->isActive(),
m_bpButtonShowDeleteLeft ->isActive(),
m_bpButtonShowDeleteRight->isActive(),
m_bpButtonShowUpdateLeft ->isActive(),
m_bpButtonShowUpdateRight->isActive(),
m_bpButtonShowDoNothing ->isActive(),
m_bpButtonShowEqual ->isActive(),
m_bpButtonShowConflict ->isActive());
filesOnLeftView = result.filesOnLeftView;
foldersOnLeftView = result.foldersOnLeftView;
filesOnRightView = result.filesOnRightView;
foldersOnRightView = result.foldersOnRightView;
filesizeLeftView = result.filesizeLeftView;
filesizeRightView = result.filesizeRightView;
//sync preview buttons
m_bpButtonShowCreateLeft ->Show(result.existsSyncCreateLeft);
m_bpButtonShowCreateRight ->Show(result.existsSyncCreateRight);
m_bpButtonShowDeleteLeft ->Show(result.existsSyncDeleteLeft);
m_bpButtonShowDeleteRight ->Show(result.existsSyncDeleteRight);
m_bpButtonShowUpdateLeft ->Show(result.existsSyncDirLeft);
m_bpButtonShowUpdateRight ->Show(result.existsSyncDirRight);
m_bpButtonShowDoNothing ->Show(result.existsSyncDirNone);
m_bpButtonShowEqual ->Show(result.existsSyncEqual);
m_bpButtonShowConflict ->Show(result.existsConflict);
const bool anyViewFilterButtonShown = m_bpButtonShowCreateLeft ->IsShown() ||
m_bpButtonShowCreateRight->IsShown() ||
m_bpButtonShowDeleteLeft ->IsShown() ||
m_bpButtonShowDeleteRight->IsShown() ||
m_bpButtonShowUpdateLeft ->IsShown() ||
m_bpButtonShowUpdateRight->IsShown() ||
m_bpButtonShowDoNothing ->IsShown() ||
m_bpButtonShowEqual ->IsShown() ||
m_bpButtonShowConflict ->IsShown();
m_bpButtonViewTypeSyncAction->Show(anyViewFilterButtonShown);
if (anyViewFilterButtonShown)
{
m_panelViewFilter->Show();
m_panelViewFilter->Layout();
}
else
m_panelViewFilter->Hide();
}
else
{
const GridView::StatusCmpResult result = gridDataView->updateCmpResult(currentCfg.hideExcludedItems,
m_bpButtonShowLeftOnly ->isActive(),
m_bpButtonShowRightOnly ->isActive(),
m_bpButtonShowLeftNewer ->isActive(),
m_bpButtonShowRightNewer->isActive(),
m_bpButtonShowDifferent ->isActive(),
m_bpButtonShowEqual ->isActive(),
m_bpButtonShowConflict ->isActive());
filesOnLeftView = result.filesOnLeftView;
foldersOnLeftView = result.foldersOnLeftView;
filesOnRightView = result.filesOnRightView;
foldersOnRightView = result.foldersOnRightView;
filesizeLeftView = result.filesizeLeftView;
filesizeRightView = result.filesizeRightView;
//comparison result view buttons
m_bpButtonShowLeftOnly ->Show(result.existsLeftOnly);
m_bpButtonShowRightOnly ->Show(result.existsRightOnly);
m_bpButtonShowLeftNewer ->Show(result.existsLeftNewer);
m_bpButtonShowRightNewer->Show(result.existsRightNewer);
m_bpButtonShowDifferent ->Show(result.existsDifferent);
m_bpButtonShowEqual ->Show(result.existsEqual);
m_bpButtonShowConflict ->Show(result.existsConflict);
const bool anyViewFilterButtonShown = m_bpButtonShowLeftOnly ->IsShown() ||
m_bpButtonShowRightOnly ->IsShown() ||
m_bpButtonShowLeftNewer ->IsShown() ||
m_bpButtonShowRightNewer->IsShown() ||
m_bpButtonShowDifferent ->IsShown() ||
m_bpButtonShowEqual ->IsShown() ||
m_bpButtonShowConflict ->IsShown();
m_bpButtonViewTypeSyncAction->Show(anyViewFilterButtonShown);
if (anyViewFilterButtonShown)
{
m_panelViewFilter->Show();
m_panelViewFilter->Layout();
}
else
m_panelViewFilter->Hide();
}
//all three grids retrieve their data directly via gridDataView
gridview::refresh(*m_gridMainL, *m_gridMainC, *m_gridMainR);
//navigation tree
if (m_bpButtonViewTypeSyncAction->isActive())
treeDataView->updateSyncPreview(currentCfg.hideExcludedItems,
m_bpButtonShowCreateLeft ->isActive(),
m_bpButtonShowCreateRight->isActive(),
m_bpButtonShowDeleteLeft ->isActive(),
m_bpButtonShowDeleteRight->isActive(),
m_bpButtonShowUpdateLeft ->isActive(),
m_bpButtonShowUpdateRight->isActive(),
m_bpButtonShowDoNothing ->isActive(),
m_bpButtonShowEqual ->isActive(),
m_bpButtonShowConflict ->isActive());
else
treeDataView->updateCmpResult(currentCfg.hideExcludedItems,
m_bpButtonShowLeftOnly ->isActive(),
m_bpButtonShowRightOnly ->isActive(),
m_bpButtonShowLeftNewer ->isActive(),
m_bpButtonShowRightNewer->isActive(),
m_bpButtonShowDifferent ->isActive(),
m_bpButtonShowEqual ->isActive(),
m_bpButtonShowConflict ->isActive());
m_gridNavi->Refresh();
//update status bar information
setStatusBarFileStatistics(filesOnLeftView,
foldersOnLeftView,
filesOnRightView,
foldersOnRightView,
filesizeLeftView,
filesizeRightView);
}
void MainDialog::applyFilterConfig()
{
applyFiltering(folderCmp, getConfig().mainCfg);
updateGui();
//updateGuiDelayedIf(currentCfg.hideExcludedItems); //show update GUI before removing rows
}
void MainDialog::applySyncConfig()
{
zen::redetermineSyncDirection(getConfig().mainCfg, folderCmp,
[&](const std::wstring& warning)
{
bool& warningActive = globalCfg.optDialogs.warningDatabaseError;
if (warningActive)
{
bool dontWarnAgain = false;
if (showWarningDlg(this,
ReturnWarningDlg::BUTTON_IGNORE, warning, dontWarnAgain) == ReturnWarningDlg::BUTTON_IGNORE)
warningActive = !dontWarnAgain;
}
});
updateGui();
}
void MainDialog::showFindPanel() //CTRL + F or F3 with empty search phrase
{
auiMgr.GetPane(m_panelSearch).Show();
auiMgr.Update();
m_textCtrlSearchTxt->SelectAll();
wxWindow* focus = wxWindow::FindFocus(); //restore when closing panel!
if (!isComponentOf(focus, m_panelSearch))
focusWindowAfterSearch = focus == &m_gridMainR->getMainWin() ? focus : &m_gridMainL->getMainWin();
//don't save pointer to arbitrary window: it might not exist anymore when hideFindPanel() uses it!!! (e.g. some folder pair panel)
m_textCtrlSearchTxt->SetFocus();
}
void MainDialog::hideFindPanel()
{
auiMgr.GetPane(m_panelSearch).Hide();
auiMgr.Update();
if (focusWindowAfterSearch)
{
focusWindowAfterSearch->SetFocus();
focusWindowAfterSearch = nullptr;
}
}
void MainDialog::startFindNext() //F3 or ENTER in m_textCtrlSearchTxt
{
const wxString& searchString = m_textCtrlSearchTxt->GetValue();
if (searchString.empty())
showFindPanel();
else
{
Grid* grid1 = m_gridMainL;
Grid* grid2 = m_gridMainR;
wxWindow* focus = wxWindow::FindFocus();
if ((isComponentOf(focus, m_panelSearch) ? focusWindowAfterSearch : focus) == &m_gridMainR->getMainWin())
std::swap(grid1, grid2); //select side to start search at grid cursor position
wxBeginBusyCursor(wxHOURGLASS_CURSOR);
const std::pair<const Grid*, ptrdiff_t> result = findGridMatch(*grid1, *grid2, searchString,
m_checkBoxMatchCase->GetValue()); //parameter owned by GUI, *not* globalCfg structure! => we should better implement a getGlocalCfg()!
wxEndBusyCursor();
if (Grid* grid = const_cast<Grid*>(result.first)) //grid wasn't const when passing to findAndSelectNext(), so this is safe
{
assert(result.second >= 0);
gridview::setScrollMaster(*grid);
grid->setGridCursor(result.second);
focusWindowAfterSearch = &grid->getMainWin();
if (!isComponentOf(wxWindow::FindFocus(), m_panelSearch))
grid->getMainWin().SetFocus();
}
else
{
showFindPanel();
wxMessageBox(replaceCpy(_("Cannot find %x"), L"%x", L"\"" + searchString + L"\"", false), _("Find"), wxOK, this);
}
}
}
void MainDialog::OnSearchGridEnter(wxCommandEvent& event)
{
startFindNext();
}
void MainDialog::OnHideSearchPanel(wxCommandEvent& event)
{
hideFindPanel();
}
void MainDialog::OnSearchPanelKeyPressed(wxKeyEvent& event)
{
switch (event.GetKeyCode())
{
case WXK_RETURN:
case WXK_NUMPAD_ENTER: //catches ENTER keys while focus is on *any* part of m_panelSearch! Seems to obsolete OnHideSearchPanel()!
startFindNext();
return;
case WXK_ESCAPE:
hideFindPanel();
return;
}
event.Skip();
}
void MainDialog::OnAddFolderPair(wxCommandEvent& event)
{
wxWindowUpdateLocker dummy(this); //avoid display distortion
std::vector<FolderPairEnh> newPairs;
newPairs.push_back(getConfig().mainCfg.firstPair);
//clear first pair
const FolderPairEnh cfgEmpty;
firstFolderPair->setValues(cfgEmpty.leftDirectory,
cfgEmpty.rightDirectory,
cfgEmpty.altCmpConfig,
cfgEmpty.altSyncConfig,
cfgEmpty.localFilter);
//keep sequence to update GUI as last step
addFolderPair(newPairs, true); //add pair in front of additonal pairs
}
void MainDialog::OnRemoveTopFolderPair(wxCommandEvent& event)
{
if (!additionalFolderPairs.empty())
{
wxWindowUpdateLocker dummy(this); //avoid display distortion
//get settings from second folder pair
const FolderPairEnh cfgSecond = getEnhancedPair(additionalFolderPairs[0]);
//reset first pair
firstFolderPair->setValues(cfgSecond.leftDirectory,
cfgSecond.rightDirectory,
cfgSecond.altCmpConfig,
cfgSecond.altSyncConfig,
cfgSecond.localFilter);
removeAddFolderPair(0); //remove second folder pair (first of additional folder pairs)
}
}
void MainDialog::OnRemoveFolderPair(wxCommandEvent& event)
{
wxWindowUpdateLocker dummy(this); //avoid display distortion
const wxObject* const eventObj = event.GetEventObject(); //find folder pair originating the event
for (auto it = additionalFolderPairs.begin(); it != additionalFolderPairs.end(); ++it)
if (eventObj == (*it)->m_bpButtonRemovePair)
{
removeAddFolderPair(it - additionalFolderPairs.begin());
break;
}
}
void MainDialog::updateGuiForFolderPair()
{
wxWindowUpdateLocker dummy(this);
//adapt delete top folder pair button
m_bpButtonRemovePair->Show(!additionalFolderPairs.empty());
m_panelTopLeft->Layout();
//adapt local filter and sync cfg for first folder pair
const bool showLocalCfgFirstPair = !additionalFolderPairs.empty() ||
firstFolderPair->getAltCompConfig().get() != nullptr ||
firstFolderPair->getAltSyncConfig().get() != nullptr ||
!isNullFilter(firstFolderPair->getAltFilterConfig());
m_bpButtonAltCompCfg ->Show(showLocalCfgFirstPair);
m_bpButtonAltSyncCfg ->Show(showLocalCfgFirstPair);
m_bpButtonLocalFilter->Show(showLocalCfgFirstPair);
setImage(*m_bpButtonSwapSides, getResourceImage(showLocalCfgFirstPair ? L"swap_slim" : L"swap"));
m_panelTopMiddle->Layout(); //both required to update button size for calculations below!!!
m_panelDirectoryPairs->Layout(); // -> updates size of stretched m_panelTopLeft!
int addPairMinimalHeight = 0;
int addPairOptimalHeight = 0;
if (!additionalFolderPairs.empty())
{
const int pairHeight = additionalFolderPairs[0]->GetSize().GetHeight();
addPairMinimalHeight = std::min<double>(1.5, additionalFolderPairs.size()) * pairHeight; //have 1.5 * height indicate that more folders are there
addPairOptimalHeight = std::min<double>(globalCfg.gui.maxFolderPairsVisible - 1 + 0.5, //subtract first/main folder pair and add 0.5 to indicate additional folders
additionalFolderPairs.size()) * pairHeight;
addPairOptimalHeight = std::max(addPairOptimalHeight, addPairMinimalHeight); //implicitly handle corrupted values for "maxFolderPairsVisible"
}
const int firstPairHeight = std::max(m_panelDirectoryPairs->ClientToWindowSize(m_panelTopLeft ->GetSize()).GetHeight(), //include m_panelDirectoryPairs window borders!
m_panelDirectoryPairs->ClientToWindowSize(m_panelTopMiddle->GetSize()).GetHeight()); //
//########################################################################################################################
//wxAUI hack: set minimum height to desired value, then call wxAuiPaneInfo::Fixed() to apply it
auiMgr.GetPane(m_panelDirectoryPairs).MinSize(-1, firstPairHeight + addPairOptimalHeight);
auiMgr.GetPane(m_panelDirectoryPairs).Fixed();
auiMgr.Update();
//now make resizable again
auiMgr.GetPane(m_panelDirectoryPairs).Resizable();
auiMgr.Update();
//########################################################################################################################
//make sure user cannot fully shrink additional folder pairs
auiMgr.GetPane(m_panelDirectoryPairs).MinSize(-1, firstPairHeight + addPairMinimalHeight);
auiMgr.Update();
m_scrolledWindowFolderPairs->Fit(); //adjust scrolled window size
//m_scrolledWindowFolderPairs->Layout(); //adjust stuff inside scrolled window
m_panelDirectoryPairs->Layout();
}
void MainDialog::addFolderPair(const std::vector<FolderPairEnh>& newPairs, bool addFront)
{
wxWindowUpdateLocker dummy(m_panelDirectoryPairs); //avoid display distortion
//wxWindowUpdateLocker dummy2(m_panelGrids); //
std::vector<FolderPairPanel*> newEntries;
std::for_each(newPairs.begin(), newPairs.end(),
[&](const FolderPairEnh& enhPair)
{
//add new folder pair
FolderPairPanel* newPair = new FolderPairPanel(m_scrolledWindowFolderPairs, *this);
//init dropdown history
newPair->m_directoryLeft ->init(folderHistoryLeft);
newPair->m_directoryRight->init(folderHistoryRight);
//set width of left folder panel
const int width = m_panelTopLeft->GetSize().GetWidth();
newPair->m_panelLeft->SetMinSize(wxSize(width, -1));
if (addFront)
{
bSizerAddFolderPairs->Insert(0, newPair, 0, wxEXPAND);
additionalFolderPairs.insert(additionalFolderPairs.begin(), newPair);
}
else
{
bSizerAddFolderPairs->Add(newPair, 0, wxEXPAND);
additionalFolderPairs.push_back(newPair);
}
newEntries.push_back(newPair);
//register events
newPair->m_bpButtonRemovePair->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(MainDialog::OnRemoveFolderPair), nullptr, this);
});
updateGuiForFolderPair();
//wxComboBox screws up miserably if width/height is smaller than the magic number 4! Problem occurs when trying to set tooltip
//so we have to update window sizes before setting configuration:
for (auto it = newPairs.begin(); it != newPairs.end(); ++it)//set alternate configuration
newEntries[it - newPairs.begin()]->setValues(it->leftDirectory,
it->rightDirectory,
it->altCmpConfig,
it->altSyncConfig,
it->localFilter);
clearGrid(); //+ GUI update
}
void MainDialog::removeAddFolderPair(size_t pos)
{
wxWindowUpdateLocker dummy(m_panelDirectoryPairs); //avoid display distortion
//wxWindowUpdateLocker dummy2(m_panelGrids); //
if (pos < additionalFolderPairs.size())
{
//remove folder pairs from window
FolderPairPanel* panel = additionalFolderPairs[pos];
//const int pairHeight = panel->GetSize().GetHeight();
bSizerAddFolderPairs->Detach(panel); //Remove() does not work on Window*, so do it manually
additionalFolderPairs.erase(additionalFolderPairs.begin() + pos); //remove element from vector
//more (non-portable) wxWidgets bullshit: on OS X wxWindow::Destroy() screws up and calls "operator delete" directly rather than
//the deferred deletion it is expected to do (and which is implemented correctly on Windows and Linux)
//http://bb10.com/python-wxpython-devel/2012-09/msg00004.html
//=> since we're in a mouse button callback of a sub-component of "panel" we need to delay deletion ourselves:
processAsync2([] {}, [panel] { panel->Destroy(); });
//set size of scrolled window
//const size_t additionalRows = additionalFolderPairs.size();
//if (additionalRows <= globalCfg.gui.addFolderPairCountMax) //up to "addFolderPairCountMax" additional pairs shall be shown
// m_scrolledWindowFolderPairs->SetMinSize(wxSize(-1, pairHeight * static_cast<int>(additionalRows)));
//update controls
//m_scrolledWindowFolderPairs->Fit(); //adjust scrolled window size
//m_scrolledWindowFolderPairs->Layout(); //adjust stuff inside scrolled window
//bSizer1->Layout();
}
updateGuiForFolderPair();
clearGrid(); //+ GUI update
}
void MainDialog::clearAddFolderPairs()
{
wxWindowUpdateLocker dummy(m_panelDirectoryPairs); //avoid display distortion
//wxWindowUpdateLocker dummy2(m_panelGrids); //
additionalFolderPairs.clear();
bSizerAddFolderPairs->Clear(true);
updateGuiForFolderPair();
//m_scrolledWindowFolderPairs->SetMinSize(wxSize(-1, 0));
//bSizer1->Layout();
}
//########################################################################################################
//menu events
void MainDialog::OnMenuGlobalSettings(wxCommandEvent& event)
{
zen::showGlobalSettingsDlg(this, globalCfg);
}
void MainDialog::OnMenuExportFileList(wxCommandEvent& event)
{
//get a filename
wxFileDialog filePicker(this, //creating this on freestore leads to memleak!
wxEmptyString,
wxEmptyString,
L"FileList.csv", //default file name
_("Comma-separated values") + L" (*.csv)|*.csv" + L"|" +_("All files") + L" (*.*)|*",
wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if (filePicker.ShowModal() != wxID_OK)
return;
wxBusyCursor dummy;
const Zstring filename = utfCvrtTo<Zstring>(filePicker.GetPath());
//http://en.wikipedia.org/wiki/Comma-separated_values
const lconv* localInfo = ::localeconv(); //always bound according to doc
const bool haveCommaAsDecimalSep = std::string(localInfo->decimal_point) == ",";
const char CSV_SEP = haveCommaAsDecimalSep ? ';' : ',';
auto fmtValue = [&](const wxString& val) -> Utf8String
{
Utf8String&& tmp = utfCvrtTo<Utf8String>(val);
if (contains(tmp, CSV_SEP))
return '\"' + tmp + '\"';
else
return tmp;
};
Utf8String header; //perf: wxString doesn't model exponential growth and so is out, std::string doesn't give performance guarantee!
header += BYTE_ORDER_MARK_UTF8;
//base folders
header += fmtValue(_("Folder pairs")) + '\n' ;
std::for_each(begin(folderCmp), end(folderCmp),
[&](BaseDirPair& baseDirObj)
{
header += utfCvrtTo<Utf8String>(baseDirObj.getBaseDirPf<LEFT_SIDE >()) + CSV_SEP;
header += utfCvrtTo<Utf8String>(baseDirObj.getBaseDirPf<RIGHT_SIDE>()) + '\n';
});
header += '\n';
//write header
auto provLeft = m_gridMainL->getDataProvider();
auto provMiddle = m_gridMainC->getDataProvider();
auto provRight = m_gridMainR->getDataProvider();
auto colAttrLeft = m_gridMainL->getColumnConfig();
auto colAttrMiddle = m_gridMainC->getColumnConfig();
auto colAttrRight = m_gridMainR->getColumnConfig();
vector_remove_if(colAttrLeft , [](const Grid::ColumnAttribute& ca) { return !ca.visible_; });
vector_remove_if(colAttrMiddle, [](const Grid::ColumnAttribute& ca) { return !ca.visible_ || static_cast<ColumnTypeMiddle>(ca.type_) == COL_TYPE_CHECKBOX; });
vector_remove_if(colAttrRight , [](const Grid::ColumnAttribute& ca) { return !ca.visible_; });
if (provLeft && provMiddle && provRight)
{
std::for_each(colAttrLeft.begin(), colAttrLeft.end(),
[&](const Grid::ColumnAttribute& ca)
{
header += fmtValue(provLeft->getColumnLabel(ca.type_));
header += CSV_SEP;
});
std::for_each(colAttrMiddle.begin(), colAttrMiddle.end(),
[&](const Grid::ColumnAttribute& ca)
{
header += fmtValue(provMiddle->getColumnLabel(ca.type_));
header += CSV_SEP;
});
if (!colAttrRight.empty())
{
std::for_each(colAttrRight.begin(), colAttrRight.end() - 1,
[&](const Grid::ColumnAttribute& ca)
{
header += fmtValue(provRight->getColumnLabel(ca.type_));
header += CSV_SEP;
});
header += fmtValue(provRight->getColumnLabel(colAttrRight.back().type_));
}
header += '\n';
try
{
//write file
FileOutput fileOut(filename, zen::FileOutput::ACC_OVERWRITE); //throw FileError
replace(header, '\n', LINE_BREAK);
fileOut.write(&*header.begin(), header.size()); //throw FileError
//main grid: write rows one after the other instead of creating one big string: memory allocation might fail; think 1 million rows!
/*
performance test case "export 600.000 rows" to CSV:
aproach 1. assemble single temporary string, then write file: 4.6s
aproach 2. write to buffered file output directly for each row: 6.4s
*/
const size_t rowCount = m_gridMainL->getRowCount();
for (size_t row = 0; row < rowCount; ++row)
{
Utf8String tmp;
std::for_each(colAttrLeft.begin(), colAttrLeft.end(),
[&](const Grid::ColumnAttribute& ca)
{
tmp += fmtValue(provLeft->getValue(row, ca.type_));
tmp += CSV_SEP;
});
std::for_each(colAttrMiddle.begin(), colAttrMiddle.end(),
[&](const Grid::ColumnAttribute& ca)
{
tmp += fmtValue(provMiddle->getValue(row, ca.type_));
tmp += CSV_SEP;
});
std::for_each(colAttrRight.begin(), colAttrRight.end(),
[&](const Grid::ColumnAttribute& ca)
{
tmp += fmtValue(provRight->getValue(row, ca.type_));
tmp += CSV_SEP;
});
tmp += '\n';
replace(tmp, '\n', LINE_BREAK);
fileOut.write(&*tmp.begin(), tmp.size()); //throw FileError
}
flashStatusInformation(_("File list exported"));
}
catch (const FileError& e)
{
wxMessageBox(e.toString(), L"FreeFileSync - " + _("Error"), wxOK | wxICON_ERROR, this);
}
}
}
void MainDialog::OnMenuCheckVersion(wxCommandEvent& event)
{
zen::checkForUpdateNow(this);
}
void MainDialog::OnMenuCheckVersionAutomatically(wxCommandEvent& event)
{
globalCfg.gui.lastUpdateCheck = globalCfg.gui.lastUpdateCheck == -1 ? 0 : -1;
m_menuItemCheckVersionAuto->Check(globalCfg.gui.lastUpdateCheck != -1);
zen::checkForUpdatePeriodically(this, globalCfg.gui.lastUpdateCheck, [&] { flashStatusInformation(_("Searching for program updates...")); });
}
void MainDialog::OnRegularUpdateCheck(wxIdleEvent& event)
{
//execute just once per startup!
Disconnect(wxEVT_IDLE, wxIdleEventHandler(MainDialog::OnRegularUpdateCheck), nullptr, this);
if (manualProgramUpdateRequired())
zen::checkForUpdatePeriodically(this, globalCfg.gui.lastUpdateCheck, [&] { flashStatusInformation(_("Searching for program updates...")); });
}
void MainDialog::OnLayoutWindowAsync(wxIdleEvent& event)
{
//execute just once per startup!
Disconnect(wxEVT_IDLE, wxIdleEventHandler(MainDialog::OnLayoutWindowAsync), nullptr, this);
wxWindowUpdateLocker dummy(this); //avoid display distortion
//adjust folder pair distortion on startup
std::for_each(additionalFolderPairs.begin(), additionalFolderPairs.end(),
[](FolderPairPanel* panel) { panel->Layout(); });
m_panelTopButtons->Layout();
Layout(); //strangely this layout call works if called in next idle event only
auiMgr.Update(); //fix view filter distortion
}
void MainDialog::OnMenuAbout(wxCommandEvent& event)
{
zen::showAboutDialog(this);
}
void MainDialog::OnShowHelp(wxCommandEvent& event)
{
zen::displayHelpEntry(this);
}
//#########################################################################################################
//language selection
void MainDialog::switchProgramLanguage(int langID)
{
//create new dialog with respect to new language
xmlAccess::XmlGlobalSettings newGlobalCfg = getGlobalCfgBeforeExit();
newGlobalCfg.programLanguage = langID;
//show new dialog, then delete old one
MainDialog::create(getConfig(), activeConfigFiles, &newGlobalCfg, false);
//we don't use Close():
//1. we don't want to show the prompt to save current config in OnClose()
//2. after getGlobalCfgBeforeExit() the old main dialog is invalid so we want to force deletion
Destroy();
}
void MainDialog::OnMenuLanguageSwitch(wxCommandEvent& event)
{
std::map<MenuItemID, LanguageID>::const_iterator it = languageMenuItemMap.find(event.GetId());
if (it != languageMenuItemMap.end())
switchProgramLanguage(it->second);
}
//#########################################################################################################
void MainDialog::setViewTypeSyncAction(bool value)
{
//if (m_bpButtonViewTypeSyncAction->isActive() == value) return; support polling -> what about initialization?
m_bpButtonViewTypeSyncAction->setActive(value);
m_bpButtonViewTypeSyncAction->SetToolTip((value ? _("Action") : _("Category")) + L" (F9)");
//toggle display of sync preview in middle grid
gridview::highlightSyncAction(*m_gridMainC, value);
updateGui();
}
|