File: f.file.cc

package info (click to toggle)
fotoxx 24.70-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 21,888 kB
  • sloc: cpp: 78,255; makefile: 116; xml: 52
file content (4711 lines) | stat: -rw-r--r-- 175,352 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
/********************************************************************************

   Fotocx - edit photos and manage collections

   Copyright 2007-2024 Michael Cornelison
   source code URL: https://kornelix.net
   contact: mkornelix@gmail.com

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version. See https://www.gnu.org/licenses

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

*********************************************************************************

   Fotocx image edit - file menu and file functions

   m_new_session           start a new parallel session of Fotocx
   m_open_file             file open dialog
   m_cycle2files           cycle 2 previous image files
   m_cycle3files           cycle 3 previous image files
   m_view360               view a 360 degree panorama image
   m_rename                rename current image file or clicked thumbnail
   m_permissions           show and change file permissions
   m_change_alpha          change image file alpha channel
   f_open                  open and display an image file
   f_open_saved            open the last image file saved
   f_remove                remove file and fix index, gallery, thumbs, albums
   f_preload               preload image files ahead of need
   x_prev_next             open prev/next file in current or prev/next gallery
   m_prev                  menu function - open previous
   m_next                  menu function - open next
   m_prev_next             menu button function - open previous or next file
   m_zoom_menu             menu button function - zoom image/thumb (F/G view)
   m_blank_image           create a new monocolor image
   create_blank_file       callable function to create a new monocolor image
   play_gif                play current GIF file animation

   m_copy_move             copy or move an image file to a new location
   m_copyto_desktop        copy an image file to the desktop
   m_copyto_clip           copy clicked file or current file to the clipboard
   m_delete_trash          delete or trash an image file
   m_convert_adobe         convert Adobe file into one or more jpeg files
   m_wallpaper             set current image file as wallpaper

   m_print_image           print an image file
   m_print_calibrated      print an image file with calibrated colors
   m_calibrate_printer     printer color calibration tool
   m_quit                  menu quit
   quitxx                  callable quit
   m_uninstall             uninstall fotocx
   m_help                  help menu: user guide, change log, about

   m_file_save             save a (modified) image file to disk
   m_file_save_replace     save file (replace) for KB shortcut
   m_file_save_version     save file (new version) for KB shortcut
   f_save                  save an image file to disk (replace, new version, new file)
   f_save_as               dialog to save an image file with a designated file name

   f_realpath              get real path for filename having symlinks
   file_rootname           get root file name /.../filename
   file_basename           get base file name /.../filename.ext
   file_all_versions       get base file and all versions /.../filename.vNN.ext
   file_new_version        get next available version /.../filename.vNN.ext
   file_newest_version     get newest file version or base file name if none
   file_prior_version      get prior version or base file name for given file

   find_imagefiles         find all image files under a given folder path

   regfile                 test if file exists, is regular file
   dirfile                 test if file exists, is a directory/folder
   hasperm                 test if file exists, has read or write permission

   set_permissions         dialog to show and set file permissions
   conv_permissions        conv. permission formats: external <> mode_t

*********************************************************************************/

#define EX extern                                                                //  disable extern declarations
#include "fotocx.h"                                                              //  (variables in fotocx.h are refs)

using namespace zfuncs;


/********************************************************************************/

//  start a new parallel session of fotocx
//  new window is slightly down and right from old window
//  args = optional command line args
//  current file is appended if it exists

void m_new_session(GtkWidget *, ch *)
{
   ch       *pp;
   int      cc;

   F1_help_topic = "new session"; 
   Plog(1,"m_new_session \n");

   if (curr_file) {
      cc = strlen(curr_file);
      pp = (ch *) zmalloc(cc+100,"new-session");
      repl_1str(curr_file,pp+1,cc+99,"\"","\\\"");                               //  replace embedded " with \" 
      pp[0] = '"';
      cc = strlen(pp);                                                           //  add " at both ends
      pp[cc] = '"';
      pp[cc+1] = 0;
      new_session(pp);
      zfree(pp);
   }

   else new_session(0);
   return;
}


//  callable new session function

void new_session(ch *args)
{
   int      cc, xx, yy, ww, hh;
   ch       progexe[300];
                                                                                 //  do before new session:
   zdialog_inputs("save");                                                       //  save dialog inputs
   zdialog_geometry("save");                                                     //  save dialogs position/size
   gallery_memory("save");                                                       //  save recent gallery positions
   save_params();                                                                //  save state for next session

   gtk_window_get_position(MWIN,&xx,&yy);                                        //  get window position and size
   gtk_window_get_size(MWIN,&ww,&hh);
   xx += 100;                                                                    //  shift down and right
   yy += 100;

   cc = readlink("/proc/self/exe",progexe,300);                                  //  get own program path
   if (cc <= 0) {
      zmessageACK(Mwin,"cannot get /proc/self/exe");
      return;
   }
   progexe[cc] = 0;
   
   if (! args) args = "";

   zshell("log ack","%s -c %d %d %d %d %s &",progexe,xx,yy,ww,hh,args);
   return;
}


/********************************************************************************/

//  find and open an image file using a file open dialog

void m_open_file(GtkWidget *, ch *)
{
   int      err;

   F1_help_topic = "open image file";
   Plog(1,"m_open_file \n");

   err = f_open(0);
   if (err) return;

   viewmode('F');                                                                //  file view mode
   return;
}


/********************************************************************************/

//  open the previous file opened (not the same as toolbar [prev] button)
//  repeated use will alternate the two most recent files

void m_cycle2files(GtkWidget *, ch *)
{
   FILE     *fid;
   ch       *file, buff[XFCC];
   int      Nth = 0, err;
   float    gzoom;

   F1_help_topic = "cycle 2 files";

   Plog(1,"m_cycle2files \n");

   viewmode('F');
   if (! Cstate) return;
   gzoom = Cstate->fzoom;

   fid = fopen(recentfiles_file,"r");
   if (! fid) return;

   file = fgets_trim(buff,XFCC,fid,1);                                           //  skip over first most recent file

   while (true)
   {
      file = fgets_trim(buff,XFCC,fid,1);                                        //  find next most recent file
      if (! file) break;
      err = f_open(file,Nth,0,0,0);
      if (! err) break;
   }

   fclose(fid);

   Cstate->fzoom = gzoom;                                                        //  keep same image scale
   Fpaint2();
   return;
}


/********************************************************************************/

//  open the 2nd previous file opened
//  repeated use will alternate the 3 most recent files

void m_cycle3files(GtkWidget *, ch *) 
{
   FILE     *fid;
   ch       *file, buff[XFCC];
   int      Nth = 0, err;
   float    gzoom;

   F1_help_topic = "cycle 3 files";

   Plog(1,"m_cycle3files \n");

   viewmode('F');
   if (! Cstate) return;
   gzoom = Cstate->fzoom;

   fid = fopen(recentfiles_file,"r");
   if (! fid) return;

   file = fgets_trim(buff,XFCC,fid,1);                                           //  skip over 2 most recent files
   file = fgets_trim(buff,XFCC,fid,1);

   while (true)
   {
      file = fgets_trim(buff,XFCC,fid,1);                                        //  find next most recent file
      if (! file) break;
      err = f_open(file,Nth,0,0,0);
      if (! err) break;
   }

   fclose(fid);

   Cstate->fzoom = gzoom;                                                        //  keep same image scale
   Fpaint2();
   return;
}


/********************************************************************************/

//   view a 360 degree panorama image
//   center of view direction can be any angle 0-360 degrees
//   image width is assumed to correspond to a 360 degree view

namespace view360 
{
   void   show();
   void * show_thread(void *arg);
   void   mousefunc();
   void   KB_func(int key);
   void   quit();

   PXB      *filepxb, *viewpxb;
   PIXBUF   *viewpixbuf;
   ch       *filename = 0;
   int      Frecalc;
   int      fww, fhh;                                                            //  file dimensions
   int      dww, dhh;                                                            //  window dimensions
   int      pdww, pdhh;
   int      cx, cy;
   float    *Fx, *Fy, zoom;
   zdialog  *zd;
}


//  menu function

void m_view360(GtkWidget *, ch *)
{
   using namespace view360;
   
   F1_help_topic = "view 360° pano";

   Plog(1,"m_view360 \n");

   if (clicked_file) {                                                           //  use clicked file if present
      filename = clicked_file;
      clicked_file = 0;
   }
   else if (curr_file)                                                           //  else use current file
      filename = zstrdup(curr_file,"view360");
   else return;

   filepxb = PXB_load(filename,1);
   zfree(filename);

   if (! filepxb) return;
   
   zd = zmessage_post(Mwin,"20/20",10,
                "Mouse drag: pan image 360° \n"
                "L/R mouse click: zoom in/out \n"
                "Escape: quit panorama view");

   Vmenu_block(1);                                                               //  block menus   
   Fview360 = 1;                                                                 //  flag for main window KBpress() 

   fww = filepxb->ww;
   fhh = filepxb->hh;
   cx = fww/2;                                                                   //  initial view center = middle
   cy = fhh/2;
   zoom = 1.0;                                                                   //  initial zoom
   Fx = Fy = 0;                                                                  //  no allocated constants
   pdww = pdhh = 0;
   Frecalc = 1;
   
   viewmode('F');
   gdk_window_freeze_updates(gdkwin);
   takeMouse(mousefunc,0);
   show();

   return;
}


//  show current view region on window

void view360::show()
{
   using namespace view360;

   int      ii, px, py, dx, dy;
   float    sx, sy, R, C, Tx, Ty;

   if (! Fview360) return;

   dww = gdk_window_get_width(gdkwin);                                           //  drawing window size
   dhh = gdk_window_get_height(gdkwin);
   if (dww < 20 || dhh < 20) return;                                             //  too small
   
   if (dww != pdww || dhh != pdhh) {
      pdww = dww;
      pdhh = dhh;
      if (Fx) zfree(Fx);
      if (Fy) zfree(Fy);
      Fx = (float *) zmalloc(dww * dhh * sizeof(float),"view360");
      Fy = (float *) zmalloc(dww * dhh * sizeof(float),"view360");
      Frecalc = 1;
   }

   viewpxb = PXB_make(dww,dhh,3);
   viewpixbuf = viewpxb->pixbuf;
   gdk_pixbuf_fill(viewpixbuf,0);

   if (Frecalc)
   {
      Frecalc = 0;

      for (py = 0; py < dhh; py++)                                               //  loop window pixels
      for (px = 0; px < dww; px++)
      {
         dx = px - dww/2;                                                        //  distance from center
         dy = py - dhh/2;
         dx = dx / zoom;                                                         //  scale for zoom
         dy = dy / zoom;   

         ii = py * dww + px;

         sx = 6.28 * dx / fww;                                                   //  scale (dx,dy) so that fww/4
         sy = 6.28 * dy / fww;                                                   //    (90 deg.) is PI/2

         if (sx > 1.0 || sx < -1.0 || sy > 0.7 || sy < -0.7) {                   //  limit +-90 and +-63 deg. view
            Fx[ii] = Fy[ii] = 0;
            continue;
         }

         R = sqrtf(sx*sx + sy*sy);                                               //  conv. (dx,dy) in rectilinear proj.
         C = atanf(R);                                                           //     to spherical coordinates
         Tx = atanf(sx);
         Ty = asinf(sy/R * sinf(C));
         if (R == 0.0) Tx = Ty = 0;                                              //  avoid Ty = nan
         
         sx = 0.25 * fww * Tx;                                                   //  conv. spherical coordinate (Ty,Tx) 
         sy = 0.25 * fww * Ty * cosf(Tx);                                        //    to flat coordinates (sx,sy)

         Fx[ii] = sx;
         Fy[ii] = sy;
      }
   }
   
   do_wthreads(show_thread,NSMP);

   cairo_t *cr = draw_context_create(gdkwin,draw_context);
   gdk_cairo_set_source_pixbuf(cr,viewpxb->pixbuf,0,0);
   cairo_paint(cr);
   draw_context_destroy(draw_context);

   PXB_free(viewpxb);
   return;
}


//  thread function to generate the image

void * view360::show_thread(void *arg)
{
   using namespace view360;

   int      index = *((int *) (arg));
   int      ii, stat, px, py;
   float    sx, sy;
   uint8    pixs[4], *pixss, *pixp;
   
   for (py = index; py < dhh; py += NSMP)                                        //  loop window pixels
   for (px = 0; px < dww; px++)
   {
      ii = py * dww + px;
      sx = Fx[ii];
      sy = Fy[ii];
      if (sx == 0 && sy == 0) continue;
      if (sx == NAN || sy == NAN) continue;

      sx += cx;                                                                  //  add back center
      sy += cy;

      if (sy < 0) continue;                                                      //  off the image
      if (sy >= fhh) continue;

      if (sx < 0) sx = fww + sx;                                                 //  handle x wrap-around
      if (sx >= fww) sx = sx - fww;
      
      pixp = PXBpix(viewpxb,px,py);                                              //  dest. pixel

      stat = vpixel(filepxb,sx,sy,pixs);                                         //  source pixel interpolated
      if (stat) memcpy(pixp,pixs,3);                                             //  fails at image left/right edge
      else {
         pixss = PXBpix(filepxb,int(sx),int(sy));                                //  use no interpolation
         memcpy(pixp,pixss,3);
      }
   }

   return 0;
}


//  mouse function - move center of view with mouse drag

void view360::mousefunc()
{
   using namespace view360;
   
   int      Fshow = 0;
   
   if (Mxdrag || Mydrag) {                                                       //  change center of view
      cx += 2 * Mwdragx;                                                         //  horizontal center
      if (cx < 0) cx = fww + cx;
      if (cx >= fww) cx = cx - fww;
//    cy += Mwdragy;                                                             //  vertical center
      Mxdrag = Mydrag = 0;
      Fshow = 1;
   }
   
   if (LMclick) {                                                                //  zoom-in
      LMclick = 0;
      zoom = zoom * 1.414;
      if (zoom > 1.99) zoom = 2;
      Fshow = 1;
      Frecalc = 1;
   }
   
   if (RMclick) {                                                                //  zoom-out
      RMclick = 0;
      zoom = zoom / 1.414;
      if (zoom < 0.3) zoom = 0.3;
      Fshow = 1;
      Frecalc = 1;
   }

   if (Fshow) {
      if (zd) zdialog_free(zd);
      zd = 0;
      show();
   }

   return;
}


//  keyboard function

void view360::KB_func(int key)
{
   using namespace view360;

   int         ii;   
   
   if (zd) zdialog_free(zd);
   zd = 0;   

   if (key == GDK_KEY_Escape) quit();
   
   for (ii = 0; ii < Nkbsu; ii++) {                                              //  test if KB key is "Quit" shortcut
      if (toupper(key) == kbsutab[ii].key[0]) {
         if (strmatchcase(kbsutab[ii].menu,"Quit")) quit();
         else break;
      }
   }

   if (key == GDK_KEY_Left) {                                                    //  left/right arrow keys pan image
      cx -= 20;
      if (cx < 0) cx = fww + cx;
   }

   if (key == GDK_KEY_Right) {
      cx += 20;
      if (cx >= fww) cx = cx - fww;
   }

   show();
   return;
}


//  quit and free resources

void view360::quit()
{
   if (! Fview360) return;
   freeMouse();
   PXB_free(filepxb);
   PXB_free(viewpxb);
   if (Fx) zfree(Fx);
   if (Fy) zfree(Fy);
   Fview360 = 0;
   Vmenu_block(0);
   gdk_window_thaw_updates(gdkwin);
   Fpaint2();
}


/********************************************************************************/

//  rename menu function
//  activate rename dialog, stuff data from current or clicked file
//  dialog remains active when new file is opened

ch     rename_old[200] = "";                                                     //  base names only
ch     rename_new[200] = "";
ch     rename_prev[200] = "";
ch     *rename_file = 0;

void m_rename(GtkWidget *, ch *menu)
{
   int rename_dialog_event(zdialog *zd, ch *event);

   ch     *pdir, *pfile, *pext;

   F1_help_topic = "rename";

   Plog(1,"m_rename \n");

   if (rename_file) zfree(rename_file);
   rename_file = 0;

   if (clicked_file) {                                                           //  use clicked file if present
      rename_file = clicked_file;
      clicked_file = 0;
   }

   else if (curr_file)                                                           //  else current file
      rename_file = zstrdup(curr_file,"rename");

   else {
      zmessageACK(Mwin,"no current file");
      return;
   }

   if (FGM != 'F' && FGM != 'G') viewmode('F');

/***
       ______________________________________
      |         Rename Image File            |
      |                                      |
      | Old Name  [_______________________]  |
      | New Name  [_______________________]  |
      |           [previous name] [Add 1]    |
      |                                      |
      | [x] keep this dialog open            |
      |                                      |
      |                          [Apply] [X] |
      |______________________________________|

***/

   if (! zd_rename)                                                              //  restart dialog
   {
      zd_rename = zdialog_new("Rename Image File",Mwin,"Apply"," X ",null);
      zdialog *zd = zd_rename;

      zdialog_add_widget(zd,"hbox","hb1","dialog",0,"space=3");
      zdialog_add_widget(zd,"vbox","vb1","hb1",0,"homog|space=5");
      zdialog_add_widget(zd,"vbox","vb2","hb1",0,"homog|expand");

      zdialog_add_widget(zd,"label","Lold","vb1","Old Name");
      zdialog_add_widget(zd,"label","Lnew","vb1","New Name");
      zdialog_add_widget(zd,"label","space","vb1");

      zdialog_add_widget(zd,"hbox","hb2","vb2");
      zdialog_add_widget(zd,"label","oldname","hb2");
      zdialog_add_widget(zd,"label","space","hb2",0,"expand");

      zdialog_add_widget(zd,"zentry","newname","vb2",0,"size=20");
      zdialog_add_widget(zd,"hbox","hb3","vb2",0,"space=3");
      zdialog_add_widget(zd,"button","prev","hb3","previous name");
      zdialog_add_widget(zd,"button","Badd1","hb3","Add 1","space=8");

      zdialog_add_widget(zd,"hbox","hb4","dialog",0,"space=3");
      zdialog_add_widget(zd,"check","keepopen","hb4","keep this dialog open","space=3");

      zdialog_load_inputs(zd);
      zdialog_run(zd,rename_dialog_event,"parent");                              //  run dialog
   }

   zdialog *zd = zd_rename;
   parsefile(rename_file,&pdir,&pfile,&pext);
   strncpy0(rename_old,pfile,199);
   strncpy0(rename_new,pfile,199);
   zdialog_stuff(zd,"oldname",rename_old);                                       //  current file name
   zdialog_stuff(zd,"newname",rename_new);                                       //  entered file name (same)

   return;
}


//  dialog event and completion callback function

int rename_dialog_event(zdialog *zd, ch *event)
{
   ch       *pp, *pdir, *pfile, *pext, suffix[16];
   ch       *newfile = 0, *nextfile = 0, namever[200];
   int      nseq, digits, ccp, ccn, ccx, err, Fkeep;
   
   if (strmatch(event,"prev"))                                                   //  previous name >> new name
   {
      if (! *rename_prev) return 1;
      if (! rename_file) return 1;

      pp = strrchr(rename_prev,'.');
      if (pp && strlen(pp) == 4 && pp[1] == 'v'                                  //  look for file version .vNN
         && pp[2] >= '0' && pp[2] <= '9'                                         //    and remove if found
         && pp[3] >= '0' && pp[3] <= '9') *pp = 0;
      zdialog_stuff(zd,"newname",rename_prev);                                   //  stuff prev rename name into dialog

      parsefile(rename_file,&pdir,&pfile,&pext);                                 //  curr. file to be renamed
      pp = strrchr(pfile,'.');                                                   //  look for file version .vNN
      if (pp && strlen(pp) == 4 && pp[1] == 'v'
         && pp[2] >= '0' && pp[2] <= '9'
         && pp[3] >= '0' && pp[3] <= '9') 
      {
         *namever = 0;                                                           //  prev rename name + curr file version
         strncatv(namever,200,rename_prev,pp,null);
         zdialog_stuff(zd,"newname",namever);                                    //  stuff into dialog
      }
   }     

   if (strmatch(event,"Badd1"))                                                  //  increment sequence number
   {
      zdialog_fetch(zd,"newname",rename_new,188);                                //  get entered filename
      pp = strrchr(rename_new,'.');                                              //  find .ext
      if (pp && strlen(pp) < 8) {
         if (strmatchN(pp-4,".v",2) &&                                           //  find .vNN.ext
            (pp[2] >= '0' && pp[2] <= '9') && 
            (pp[3] >= '0' && pp[3] <= '9')) pp -= 4;
         strncpy0(suffix,pp,16);                                                 //  save .ext or .vNN.ext
      }
      else {
         pp = rename_new + strlen(rename_new);
         *suffix = 0;
      }

      digits = 0;
      while (pp[-1] >= '0' && pp[-1] <= '9') {
         pp--;                                                                   //  look for NNN in filenameNNN
         digits++;
      }
      nseq = 1;
      if (digits) nseq += atoi(pp);                                              //  NNN + 1
      if (nseq > 9999) nseq = 1;
      if (digits < 1) digits = 1;
      if (nseq > 9 && digits < 2) digits = 2;
      if (nseq > 99 && digits < 3) digits = 3;
      if (nseq > 999 && digits < 4) digits = 4;
      sprintf(pp,"%0*d",digits,nseq);                                            //  replace NNN with NNN + 1
      strncat(rename_new,suffix,199);                                            //  append .ext or .vNN.ext
      zdialog_stuff(zd,"newname",rename_new);
   }
   
   if (zd->zstat == 0) goto CLEANUP;                                             //  not finished
   if (zd->zstat != 1) goto KILL;                                                //  canceled

   zd->zstat = 0;                                                                //  apply - keep dialog active
   
   if (! rename_file) goto CLEANUP;

   parsefile(rename_file,&pdir,&pfile,&pext);                                    //  existing /folders/file.ext

   zdialog_fetch(zd,"newname",rename_new,194);                                   //  new file name from user

   ccp = strlen(pdir);                                                           //  length of /folders/
   ccn = strlen(rename_new);                                                     //  length of file
   if (pext) ccx = strlen(pext);                                                 //  length of .ext
   else ccx = 0;

   newfile = (ch *) zmalloc(ccp + ccn + ccx + 1,"rename");                       //  put it all together
   strncpy(newfile,rename_file,ccp);                                             //   /folders.../newfilename.ext
   strcpy(newfile+ccp,rename_new);
   if (ccx) strcpy(newfile+ccp+ccn,pext);

   if (regfile(newfile)) {                                                       //  check if new name exists
      zmessageACK(Mwin,"output file exists");
      zfree(newfile);
      newfile = 0;
      goto CLEANUP;
   }

   if (FGM == 'F')
      nextfile = gallery(0,"get",curr_file_posn+1);                              //  save next file, before rename
   else nextfile = 0;

   err = rename(rename_file,newfile);                                            //  rename the file
   if (err) {
      zmessageACK(Mwin,"file error: %s",strerror(errno));
      goto KILL;
   }
   
   album_purge_replace("ALL",rename_file,newfile);                               //  replace name in albums

   load_filemeta(newfile);                                                       //  add new file to image index
   update_image_index(newfile);
   delete_image_index(rename_file);                                              //  delete old file in image index

   delete_thumbfile(rename_file);                                                //  remove old thumbnail
   update_thumbfile(newfile);                                                    //  add new thumbnail 

   add_recent_file(newfile);                                                     //  first in recent files list
   
   strncpy0(rename_prev,rename_new,199);                                         //  save new name to previous name

   if (curr_file && strmatch(rename_file,curr_file))                             //  current file exists no more
      free_resources();
   
   if (navi::gallerytype == FOLDER) {                                            //  refresh gallery list
      gallery(0,"init",0);
      gallery(0,"sort",-2);                                                      //  recall sort and position
      gallery(0,"paint",-1);
   }
   
   zdialog_fetch(zd,"keepopen",Fkeep);
   if (Fkeep) {                                                                  //  keep dialog open
      if (FGM == 'F' && nextfile) {
         f_open(nextfile);                                                       //  will call m_rename()
         gtk_window_present(MWIN);                                               //  keep focus on main window
      }
      if (newfile) zfree(newfile);
      newfile = 0;
      goto CLEANUP;
   }
   else {                                                                        //  close dialog
      f_open(newfile);                                                           //  open renamed file
      goto KILL;
   }

KILL:
   zdialog_free(zd);                                                             //  kill dialog
   zd_rename = 0;

CLEANUP:
   if (newfile) zfree(newfile);
   if (nextfile) zfree(nextfile);
   return 1;
}


/********************************************************************************/

//  show and change file permissions

ch  *permissions_file = 0;

void m_permissions(GtkWidget *, ch *menu)
{
   int permissions_dialog_event(zdialog *zd, ch *event);

   ch       permissions[100];
   ch       *pp;
   STATB    statB;

   F1_help_topic = "permissions";

   Plog(1,"m_permissions \n");

   if (permissions_file) zfree(permissions_file);
   permissions_file = 0;

   if (clicked_file) {                                                           //  use clicked file if present
      permissions_file = clicked_file;
      clicked_file = 0;
   }

   else if (curr_file)                                                           //  else current file
      permissions_file = zstrdup(curr_file,"permissions");

   else {
      zmessageACK(Mwin,"no current file");
      return;
   }

   if (FGM != 'F' && FGM != 'G') viewmode('F');

/***
       ______________________________________
      |       File Permissions               |
      |                                      |
      | File: [____________________________] |        file name
      |                                      |  
      | owner [read+write |v]                |
      | group [read only  |v]                |        combo box entries: read+write, read only, no access
      | other [no access  |v]                |
      |                                      |
      | [x] keep this dialog open            |
      |                                      |
      |                          [Apply] [X] |
      |______________________________________|

***/

   if (! zd_permissions)                                                         //  restart dialog
   {
      zd_permissions = zdialog_new("File Permissions",Mwin,"Apply"," X ",null);
      zdialog *zd = zd_permissions;
      
      zdialog_add_widget(zd,"hbox","hbfile","dialog",0,"space=3");
      zdialog_add_widget(zd,"label","labfile","hbfile","File:","space=3");
      zdialog_add_widget(zd,"label","filename","hbfile",0,"space=3");
      
      zdialog_add_widget(zd,"hbox","hbperm","dialog",0,"space=2");
      zdialog_add_widget(zd,"label","space","hbperm",0,"space=3");
      zdialog_add_widget(zd,"vbox","vb1","hbperm",0,"homog");
      zdialog_add_widget(zd,"label","space","hbperm",0,"space=6");
      zdialog_add_widget(zd,"vbox","vb2","hbperm",0,"homog");
      
      zdialog_add_widget(zd,"label","labown","vb1","owner","space=3");
      zdialog_add_widget(zd,"combo","permown","vb2",0,"space=3");
      zdialog_stuff(zd,"permown","read+write");
      zdialog_stuff(zd,"permown","read only");
      zdialog_stuff(zd,"permown","no access");

      zdialog_add_widget(zd,"label","labgrp","vb1","group","space=3");
      zdialog_add_widget(zd,"combo","permgrp","vb2",0,"space=3");
      zdialog_stuff(zd,"permgrp","read+write");
      zdialog_stuff(zd,"permgrp","read only");
      zdialog_stuff(zd,"permgrp","no access");

      zdialog_add_widget(zd,"label","laboth","vb1","other","space=3");
      zdialog_add_widget(zd,"combo","permoth","vb2",0,"space=3");
      zdialog_stuff(zd,"permoth","read+write");
      zdialog_stuff(zd,"permoth","read only");
      zdialog_stuff(zd,"permoth","no access");

      zdialog_add_widget(zd,"hbox","hbkeep","dialog",0,"space=3");
      zdialog_add_widget(zd,"check","keepopen","hbkeep","keep this dialog open","space=3");

      zdialog_resize(zd,280,0);
      zdialog_run(zd,permissions_dialog_event,"parent");                         //  run dialog
   }

   zdialog *zd = zd_permissions;
   
   pp = strrchr(permissions_file,'/');                                           //  stuff file name into dialog
   if (pp) pp++;
   else pp = permissions_file;
   zdialog_stuff(zd,"filename",pp);
   
   stat(permissions_file,&statB);                                                //  stuff curr. permissions
   conv_permissions(statB.st_mode,permissions);

   pp = substring(permissions,',',1);
   if (pp) zdialog_stuff(zd,"permown",pp);

   pp = substring(permissions,',',2);
   if (pp) zdialog_stuff(zd,"permgrp",pp);

   pp = substring(permissions,',',3);
   if (pp) zdialog_stuff(zd,"permoth",pp);

   return;
}


//  dialog event and completion callback function

int permissions_dialog_event(zdialog *zd, ch *event)
{
   int         Fkeep;
   mode_t      mode;
   ch          permown[20], permgrp[20], permoth[20];
   ch          permissions[100];
   
   if (zd->zstat == 0) return 1;                                                 //  wait for dialog finished
   if (zd->zstat != 1) goto KILL;                                                //  cancel 
   
   zdialog_fetch(zd,"permown",permown,20);                                       //  [apply]
   zdialog_fetch(zd,"permgrp",permgrp,20);                                       //  construct permissions string
   zdialog_fetch(zd,"permoth",permoth,20);                                       //  e.g. "read+write, read only, no access"
   snprintf(permissions,100,"%s, %s, %s",permown,permgrp,permoth);

   conv_permissions(permissions,mode);                                           //  convert to mode_t
   chmod(permissions_file,mode);                                                 //  set file permissions

   zdialog_fetch(zd,"keepopen",Fkeep);
   if (! Fkeep) goto KILL;
   zd->zstat = 0;                                                                //  keep dialog active
   gtk_window_present(MWIN);                                                     //  keep focus on main window 
   return 1;

KILL:
   if (permissions_file) zfree(permissions_file);                                //  free memory
   permissions_file = 0;
   zdialog_free(zd);                                                             //  kill dialog
   zd_permissions = 0;
   return 1;
}


/********************************************************************************

  Add or remove alpha channel.
  Add: alpha channel is added with value 255.
  Remove: RGB pixels are reduced according to alpha channel value:
    RGBout = RGBin * (alpha/255)
    Transparent margins (e.g. panorama images) will become black.

***/


void m_change_alpha(GtkWidget *, ch *)
{
   int change_alpha_dialog_event(zdialog *zd, ch *event);
   
   int      ftype;
   ch       *pp;
   zdialog  *zd;
   
   F1_help_topic = "change alpha";
   Plog(1,"m_change_alpha \n");
   
   if (! curr_file) {
      zmessageACK(Mwin,"no current file");
      return;
   }
   
   viewmode('F');

   ftype = image_file_type(curr_file);
   if (ftype != IMAGE) return;

   pp = strrchr(curr_file,'.');
   if (pp && strstr(".jpg .JPG .jpeg .JPEG",pp)) {
      zmessageACK(Mwin,"JPEG images have no alpha channel");
      return;
   }

   E0pxm = PXM_load(curr_file,1);                                                //  reload file with full bit depth
   if (! E0pxm) return;

/***
          ___________________________________
         |      Change Alpha Channel         |
         |                                   |
         | File: [_________________________] |
         | alpha channel: (not) present      |
         |                                   |
         |                [Add] [Remove] [X] |
         |___________________________________|

***/

   zd = zdialog_new("Change Alpha Channel",Mwin,"Add","Remove"," X ",null);
   if (! zd) return;
   
   zdialog_add_widget(zd,"hbox","hbfile","dialog",0,"space=3");
   zdialog_add_widget(zd,"label","labfile","hbfile","File:","space=3");
   zdialog_add_widget(zd,"label","filename","hbfile",0,"space=3");

   zdialog_add_widget(zd,"hbox","hbalpha","dialog",0,"space=3");
   zdialog_add_widget(zd,"label","labalpha","hbalpha","alpha channel:","space=3");
   zdialog_add_widget(zd,"label","labpresent","hbalpha","(not) present","space=3");
   
   pp = strrchr(curr_file,'/');                                                  //  stuff file name into dialog
   if (pp) pp++;
   else pp = curr_file;
   zdialog_stuff(zd,"filename",pp);

   if (E0pxm->nc == 4)
      zdialog_stuff(zd,"labpresent","present");
   else
      zdialog_stuff(zd,"labpresent","not present");

   zdialog_resize(zd,300,0);
   zdialog_run(zd,change_alpha_dialog_event,"parent");

   return;
}


//  dialog event and completion function

int change_alpha_dialog_event(zdialog *zd, ch *event)
{
   if (! zd->zstat) return 1;                                                    //  wait for completion
   
   if (zd->zstat == 1)                                                           //  [add] 
   {
      zd->zstat = 0;                                                             //  keep dialog alive

      E0pxm = PXM_load(curr_file,1);                                             //  reload file with full bit depth
      if (! E0pxm) return 1;
   
      if (E0pxm->nc == 4) return 1;                                              //  have alpha channel, do nothing

      PXM_addalpha(E0pxm);                                                       //  add alpha channel, value = 255
      
      f_save(curr_file,curr_file_type,curr_file_bpc,0,1);                        //  replace file on disk
      f_open(curr_file);                                                         //  refresh in memory

      zdialog_stuff(zd,"labpresent","present");                                  //  update dialog status
      return 1;
   }

   if (zd->zstat == 2)                                                           //  [remove]
   {
      zd->zstat = 0;                                                             //  keep dialog alive

      E0pxm = PXM_load(curr_file,1);                                             //  reload file with full bit depth
      if (! E0pxm) return 1;

      if (E0pxm->nc != 4) return 1;                                              //  no alpha channel, do nothing
      
      PXM_applyalpha(E0pxm);                                                     //  apply and remove alpha channel

      f_save(curr_file,curr_file_type,curr_file_bpc,0,1);                        //  replace file on disk
      f_open(curr_file);                                                         //  refresh in memory

      zdialog_stuff(zd,"labpresent","not present");                              //  update dialog status
      return 1;
   }
   
   zdialog_free(zd);                                                             //  [OK] or [x]

   if (E0pxm) PXM_free(E0pxm);                                                   //  free memory
   E0pxm = 0;

   return 1;
}


/********************************************************************************/

//  Open a file and initialize Fpxb pixbuf. New current file.
//
//  Nth:    if Nth matches file position in current gallery, curr_file_posn
//          is set to Nth, otherwise it is searched and set correctly.
//          (a file can be present multiple times in an album gallery).
//  Fkeep:  edit undo/redo stack is not purged, and current edits are kept
//          after opening the new file (used by file_save()).
//  Fack:   failure will cause a popup ACK dialog.
//  fzoom:  keep current zoom level and position, otherwise fit window.
//
//  Following are set: curr_file_type, curr_file_bpc, curr_file_size.
//  Returns: 0 = OK, +N = error.
//  errors: 1  reentry
//          2  unsaved changes in prior file
//          3  file not found or user cancel
//          4  unsupported file type or PXB_load() failure

int f_open(ch *filespec, int Nth, int Fkeep, int Fack, int fzoom)
{
   PXB            *tempxb = 0;
   int            fposn, retcode = 0;
   FTYPE          ftype;
   static int     Freent = 0;
   ch             *pp, *file;
   int            Funsaved = 0, choice;
   ch             *modmess = "There are unsaved changes.";

   if (Freent++) {                                                               //  stop re-entry
      Plog(0,"f_open() re-entry \n");
      goto ret1;
   }

   poptext_killnow();                                                            //  kill pending popup message
   
   if (curr_file && filespec && strmatch(filespec,curr_file)){                   //  re-open current file                  24.40
      Plog(1,"f_open(), re-open current file \n");
      Fpaintnow();      
      Freent = 0;
      return 0;
   }

   if (CEF && CEF->Fmods && ! CEF->Fsaved) Funsaved = 1;                         //  active edits unsaved                  24.40
   if (URS_pos > 0 && URS_saved[URS_pos] == 0) Funsaved = 1;                     //  completed edits unsaved
   if (Fmetamod) Funsaved = 1;                                                   //  metadata edits unsaved
   if (Funsaved) {
      choice = zdialog_choose(Mwin,"parent",modmess,"Keep","Discard",0);         //  ask user
      if (choice == 1) goto ret2;
   }

   if (CEF && CEF->zd)                                                           //  cancel pending edit
      zdialog_send_event(CEF->zd,"cancel");

   if (CEF) {                                                                    //  cannot
      zmessageACK(Mwin,"finish or cancel pending edit");
      goto ret2;
   }

   sa_clear();                                                                   //  clear area if any
   
   file = 0;

   if (filespec)
      file = zstrdup(filespec,"f-open");                                         //  use passed filespec
   else {
      pp = curr_file;                                                            //  use file open dialog
      if (! pp && navi::gallerytype == FOLDER) pp = navi::galleryname;
      file = zgetfile("Open Image File",MWIN,"file",pp);
   }

   if (! file) goto ret3;

   if (! regfile(file)) {                                                        //  check file exists
      if (Fack) zmessage_post(Mwin,"20/20",4,"file not found: %s",file);
      zfree(file);
      goto ret3;
   }

   ftype = image_file_type(file);                                                //  reject thumbnail
   if (ftype == THUMB) {
      if (Fack) zmessageACK(Mwin,"thumbnail file");
      goto ret4;
   }

   if (ftype != IMAGE && ftype != RAW && ftype != VIDEO) {                       //  must be supported image file type
      if (Fack) {
         Plog(0,"%s\n",file);
         zmessageACK(Mwin,"unknown file type");
      }
      zfree(file);
      goto ret4;
   }

   tempxb = PXB_load(file,1);                                                    //  load image as PXB pixbuf

   if (! tempxb) {                                                               //  PXB_load() messages user
      zfree(file);
      goto ret4;
   }

   free_resources(Fkeep);                                                        //  free resources for prior image file

   curr_file = file;                                                             //  new current file

   Fpxb = tempxb;                                                                //  pixmap for current image

   strcpy(curr_file_type,f_load_type);                                           //  set curr_file_xxx from f_load_xxx
   curr_file_bpc = f_load_bpc;
   curr_file_size = f_load_size;

   load_filemeta(curr_file);                                                     //  load metadata used by fotocx
   
   Fmeta_edithist = 0;                                                           //  no edit history data loaded
   
   Fupright = Flevel = 0;                                                        //  file not uprighted or levelled 
   if (ftype == RAW) Fupright = 1;                                               //  assume RAW loaders do upright

   fposn = file_position(file,Nth);                                              //  file position in gallery list
   if (fposn < 0) {                                                              //  not there
      gallery(curr_file,"init",0);                                               //  generate new gallery list
      gallery(0,"sort",-2);                                                      //  recall sort and position 
      gallery(curr_file,"paint",0);                                              //  position at curr. file
      fposn = file_position(curr_file,0);                                        //  position and count in gallery list
   }
   curr_file_posn = fposn;                                                       //  keep track of file position

   if (! fzoom) {                                                                //  discard zoom state
      Fzoom = 0;                                                                 //  zoom level = fit window
      zoomx = zoomy = 0;                                                         //  no zoom center
   }

   add_recent_file(curr_file);                                                   //  most recent file opened

   if (zd_rename) m_rename(0,0);                                                 //  update active rename dialog
   if (zd_permissions) m_permissions(0,0);                                       //    "  permissions dialog
   if (zd_copymove) m_copy_move(0,0);                                            //    "  copy/move dialog
   if (zd_deltrash) m_delete_trash(0,0);                                         //    "  delete/trash dialog
   if (zd_metaview) meta_view(0);                                                //    "  metadata view window
   if (zd_editmeta) m_meta_edit_main(0,0);                                       //    "  edit metadata dialog
   if (zd_editanymeta) m_meta_edit_any(0,0);                                     //    "  edit any metadata dialog
   if (zd_deletemeta) m_meta_delete(0,0);                                        //    "  delete metadata dialog
   if (Fcaps) meta_show_caps(1);                                                 //  show captions on current image

   if (CEF && CEF->menufunc) CEF->menufunc(0,0);                                 //  restart edit function
   
   if (ftype == VIDEO)                                                           //  offer to play video file
      zmessage_post(Mwin,"20/30",3,"VIDEO  press P to play");
   
   pp = strrchr(curr_file,'.');                                                  //  offer to play animated GIF file
   if (pp && strstr(".gif .GIF",pp))
      zmessage_post(Mwin,"20/30",3,"GIF  press P to play");

   if (FGM == 'F') {
      Fpaintnow();                                                               //  force repaint
      set_mwin_title();                                                          //  set win title from curr_file info
   }

   if (FGM == 'G') gallery(0,"paint",-1);                                        //  paint gallery
   goto ret0; 

   ret4: retcode++;
   ret3: retcode++;
   ret2: retcode++;
   ret1: retcode++;
   ret0:
   Freent = 0;

   return retcode;
}


/********************************************************************************/

//  Open a file that was just saved. Used by file_save().
//  The edit undo/redo stack is not purged and current edits are kept.
//  Following are set:
//    curr_file  *_folder  *_file_posn  *_file_type  *_file_bpc  *_file_size
//  Returns: 0 = OK, +N = error.

int f_open_saved()
{
   int      Nth = -1, fposn;
   
   if (! f_save_file) return 1;

   if (E0pxm) {                                                                  //  edits were made
      PXB_free(Fpxb);                                                            //  new window image
      Fpxb = PXM_PXB_copy(E0pxm);
   }
   
   zstrcopy(curr_file,f_save_file,"f_open_saved");                               //  curr. file = last saved file

   fposn = file_position(curr_file,Nth);                                         //  file position in gallery list
   if (fposn < 0) {                                                              //  not there
      gallery(curr_file,"init",0);                                               //  generate new gallery list
      gallery(0,"sort",-2);                                                      //  recall sort and position
      gallery(curr_file,"paint",-1);                                             //  position at current file
      fposn = file_position(curr_file,0);                                        //  position and count in gallery list
   }
   curr_file_posn = fposn;                                                       //  keep track of file position

   strcpy(curr_file_type,f_save_type);                                           //  set curr_file_xxx from f_save_xxx
   curr_file_bpc = f_save_bpc;
   curr_file_size = f_save_size;

   zoomx = zoomy = 0;                                                            //  no zoom center
   if (FGM == 'F') set_mwin_title();                                             //  set win title from curr_file info

   if (zd_metaview) meta_view(0);                                                //  update meta view window
   return 0;
}


/********************************************************************************

   Remove a file and clean up index, thumbnails, gallery, curr_file.
   Albums must be handled separately via album_purge_replace().
   'opt' is "delete" or "trash".
   trash logic: Move target file to ~/Desktop/ first, then move to trash.
                Gnome trash fails for files on mounted volumes.
   Returns 0 if OK, else error code.

****/

int f_remove(ch *file, ch *opt)
{
   int      err, Nth;
   ch       *cfile = 0;
   ch       trashfile[400] = "~/Desktop/"; 
   ch       *pp;
   GFile    *gfile;
   GError   *gerror = 0;
   int      gstat;
   
   if (*opt == 'd')                                                              //  delete
   {
      err = remove(file);
      if (err && errno != ENOENT) {                                              //  OK if already deleted
         zmessageACK(Mwin,"delete %s \n %s",file,strerror(errno));
         return err;
      }
   }
   
   if (*opt == 't')                                                              //  trash
   {
      strcpy(trashfile,getenv("HOME"));                                          //  copy to desktop, then Gnome trash
      strcat(trashfile,"/Desktop/");
      pp = strrchr(file,'/');                                                    //  get base file name, filename.jpg
      if (pp) pp++;
      else pp = file;
      strncatv(trashfile,400,pp,0);                                              //  ~/Desktop/filename.jpg
      
      err = cp_copy(file,trashfile);                                             //  copy target file to desktop
      if (err) {
         zmessageACK(Mwin,"copy to Desktop failed: %s",strerror(errno));
         return 1;
      }
      
      gfile = g_file_new_for_path(trashfile);
      gstat = g_file_trash(gfile,0,&gerror);
      g_object_unref(gfile);
      if (! gstat) {
         zmessageACK(Mwin,"move to trash failed: %s",gerror->message);
         return 2;
      }
      
      err = remove(file);                                                        //  delete file
      if (err && errno != ENOENT) {                                              //  OK if already deleted
         zmessageACK(Mwin,"delete %s \n %s",file,strerror(errno));
         return err;
      }
   }

   delete_image_index(file);                                                     //  delete file in image index
   delete_thumbfile(file);                                                       //  delete thumbnail file and cache

   Nth = file_position(file,0);                                                  //  find in gallery list
   if (Nth >= 0) gallery(0,"delete",Nth);                                        //  delete from gallery list
   
   if (curr_file && strmatch(file,curr_file)) {                                  //  current file was removed
      free_resources();
      cfile = gallery(0,"getR",curr_file_posn);                                  //  new current file = next 
      if (cfile) f_open(cfile);
      else {
         Nth = curr_file_posn - 1;
         if (Nth >= navi::Gfolders && Nth < navi::Gfiles) {                      //  no next, try previous
            cfile = gallery(0,"getR",curr_file_posn - 1); 
            if (cfile) f_open(cfile);
         }
      }
   }
   
   return 0;
}


/********************************************************************************/

//  Function to preload image files hopefully ahead of need.
//  Usage: f_preload(next)
//    next = -1 / +1  to read previous / next image file in curr. gallery
//    preload_file will be non-zero if and when preload_pxb is available.

void f_preload(int next, int Flast)
{
   int      fd;
   ch       *file;

   if (! curr_file) return;

   file = prev_next_file(next,Flast);
   if (! file) return;

   if (strmatch(file,curr_file)) return;

   fd = open(file,O_RDONLY);
   if (fd >= 0) {
      posix_fadvise(fd,0,0,POSIX_FADV_WILLNEED);                                 //  preload file in kernel cache
      close(fd);
   }

   return;
}


/********************************************************************************/

//  Open previous or next file in current gallery list, 
//  or jump to previous or next gallery when at the limits.
//  index is -1 / +1 for prev / next file.
//  Fjump: jump to last file version, jump to prev/next folder.

void x_prev_next(int index, int Fjump)
{
   using namespace navi;

   ch              *newfile = 0, *newgallery = 0;
   int             err, Nth = 0;
   static int      xbusy = 0, jumpswitch = 0;
   static zdialog  *zd = 0;

   ch     *mess1 = "Previous gallery";
   ch     *mess2 = "Next gallery";
   ch     *mess3 = "Start of gallery";
   ch     *mess4 = "End of gallery";
   
   if (! curr_file) return;
   if (FGM != 'F' && FGM != 'G') return;

   if (zd && zdialog_valid2(zd,"post")) zdialog_free(zd);                        //  clear prior popup message
   zd = 0;
   
   if (xbusy) return;                                                            //  avoid "function busy"
   xbusy = 1;
   
   newfile = prev_next_file(index,Fjump);                                        //  get prev/next file (last version)
   if (newfile) {
      Nth = curr_file_posn + index;                                              //  albums can have repeat files
      err = f_open(newfile,Nth,0,1,1);                                           //  open image or RAW file 
      if (! err) f_preload(index,Fjump);                                         //  preload next image
      goto returnx;
   }
   
   if (Fjump) {
      if (index == -1) zd = zmessage_post(Mwin,"5/5",3,mess1,0);                 //  notify jump to prev/next gallery
      if (index == +1) zd = zmessage_post(Mwin,"5/5",3,mess2,0);
   }
   else {
      if (index == -1) zd = zmessage_post(Mwin,"5/5",3,mess3,0);                 //  notify gallery start/end
      if (index == +1) zd = zmessage_post(Mwin,"5/5",3,mess4,0);
      jumpswitch = 0;
   }

   if (Fjump && jumpswitch) {                                                    //  jump to prev/next gallery
      jumpswitch = 0;
      newgallery = prev_next_gallery(index);
      if (! newgallery) goto returnx;
      gallery(newgallery,"init",0);                                              //  load gallery
      zfree(newgallery);
      gallery(0,"sort",-2);                                                      //  preserve sort
      if (Gfiles - Gfolders > 0) {                                               //  at least one image file present
         if (index == +1) Nth = Gfolders;                                        //  get first or last image file
         if (index == -1) Nth = Gfiles - 1;
         newfile = gallery(0,"getR",Nth);
         err = f_open(newfile,Nth,0,1,0);                                        //  open image or RAW file
         if (! err) gallery(newfile,"paint",Nth);
         if (! err) f_preload(index,Fjump);                                      //  preload next image
         goto returnx;
      }
      else {                                                                     //  no image files in gallery
         gallery(0,"paint",0);
         viewmode('G');
         free_resources();
      }
   }

   else if (Fjump) jumpswitch = 1;                                               //  hesitate once, jump next time
   
returnx:
   zmainloop();                                                                  //  refresh window (holding arrow key)
   xbusy = 0;
   return;
}


void m_prev(GtkWidget *, ch *menu)
{
   Plog(1,"m_prev \n");
   if (menu) x_prev_next(-1,1);                                                  //  jump option
   else x_prev_next(-1,0);                                                       //  search from curr_file -1
   return;                                                                       //    to first file
}


void m_next(GtkWidget *, ch *menu)
{
   Plog(1,"m_next \n");
   if (menu) x_prev_next(+1,1);                                                  //  jump option 
   else x_prev_next(+1,0);                                                       //  search from curr_file +1
   return;                                                                       //    to last file
}


void m_prev_next(GtkWidget *, ch *menu)                                          //  left/right mouse click >>
{                                                                                //    previous/next image file
   int button = zfuncs::vmenuclickbutton;
   if (button == 1) m_prev(0,0);
   else m_next(0,0);
   return;
}


/********************************************************************************/

//  zoom in/out - left/right mouse click on zoom button or F-view image

void m_zoom_menu(GtkWidget *, ch *menu)                                          //  left/right mouse click
{
   F1_help_topic = "zoom";

   int button = zfuncs::vmenuclickbutton;

   if (FGM == 'G') {                                                             //  G view, larger/smaller thumbnails
      if (button == 1) navi::menufuncx(0,"Zoom+");
      else navi::menufuncx(0,"Zoom-");
   }
   
   if (FGM == 'F') {                                                             //  F view, zoom image in/out
      if (button == 1) m_zoom(0,"Zoom+");
      else m_zoom(0,"Zoom-");
   }
   
   return;
}


/********************************************************************************/

//  create a new blank image file with desired background color

void m_blank_image(GtkWidget *, ch *pname)
{
   ch          color[20], fname[100], fext[8], *filespec;
   int         zstat, err, cc, ww, hh, RGB[3];
   zdialog     *zd;
   ch          *pp;
   ch          *curr_folder = 0;

   F1_help_topic = "blank image";

   Plog(1,"m_blank_image \n");

   if (navi::gallerytype == FOLDER) curr_folder = navi::galleryname;
   else curr_folder = topfolders[0];
   if (! curr_folder) {
      Plog(0,"no top image folders defined \n");                                 //  should not happen
      return;
   }

   viewmode('F');

/***
       __________________________________________________
      |           Create Blank Image                     |
      |                                                  |
      | file name [___________________________] [.jpg|v] |
      | width [____]  height [____] (pixels)             |
      | color [____]                                     |
      |                                                  |
      |                                         [OK] [X] |
      |__________________________________________________|

***/


   zd = zdialog_new("Create Blank Image",Mwin,"OK"," X ",null);
   zdialog_add_widget(zd,"hbox","hbf","dialog",0,"space=1");
   zdialog_add_widget(zd,"label","labf","hbf","file name","space=3");
   zdialog_add_widget(zd,"zentry","file","hbf",0,"space=3|expand");
   zdialog_add_widget(zd,"combo","ext","hbf",".jpg","space=3|size=3");
   zdialog_add_widget(zd,"hbox","hbz","dialog",0,"space=1");
   zdialog_add_widget(zd,"label","labw","hbz","Width","space=5");
   zdialog_add_widget(zd,"zspin","width","hbz","100|30000|1|1600");
   zdialog_add_widget(zd,"label","space","hbz",0,"space=5");
   zdialog_add_widget(zd,"label","labh","hbz","Height","space=5");
   zdialog_add_widget(zd,"zspin","height","hbz","100|16000|1|1000");
   zdialog_add_widget(zd,"label","labp","hbz","(pixels)","space=3");
   zdialog_add_widget(zd,"hbox","hbc","dialog",0,"space=1");
   zdialog_add_widget(zd,"label","labc","hbc","Color","space=5");
   zdialog_add_widget(zd,"colorbutt","color","hbc","200|200|200");

   zdialog_stuff(zd,"ext",".jpg");
   zdialog_stuff(zd,"ext",".png");
   
   zdialog_load_inputs(zd);

   zdialog_set_modal(zd);
   
   zdialog_run(zd,0,"save");                                                     //  run dialog
   zstat = zdialog_wait(zd);                                                     //  wait for completion

   if (zstat != 1) {                                                             //  cancel
      zdialog_free(zd);
      return;
   }

   zdialog_fetch(zd,"file",fname,92);                                            //  get new file name
   strTrim2(fname);
   if (*fname <= ' ') {
      zmessageACK(zd->dialog,"supply a file name");
      zdialog_free(zd);
      m_blank_image(0,0);                                                        //  retry
      return;
   }

   zdialog_fetch(zd,"ext",fext,8);                                               //  add extension
   strcat(fname,fext);
   
   cc = strlen(fname);
   filespec = zstrdup(curr_folder,"blank-image",cc+4);                           //  make full filespec
   strcat(filespec,"/");
   strcat(filespec,fname);

   zdialog_fetch(zd,"width",ww);                                                 //  get image dimensions
   zdialog_fetch(zd,"height",hh);

   RGB[0] = RGB[1] = RGB[2] = 255;
   zdialog_fetch(zd,"color",color,19);                                           //  get image color
   pp = substring(color,"|",1);
   if (pp) RGB[0] = atoi(pp);
   pp = substring(color,"|",2);
   if (pp) RGB[1] = atoi(pp);
   pp = substring(color,"|",3);
   if (pp) RGB[2] = atoi(pp);

   zdialog_free(zd);

   err = create_blank_file(filespec,ww,hh,RGB);
   if (! err) f_open(filespec);                                                  //  make it the current file
   zfree(filespec);
   return;
}


//  function to create a new blank image file
//  file extension must be one of: .jpg .tif .png
//  RGB args are in the range 0 - 255
//  if file exists it is overwritten
//  returns 0 if OK, 1 if file exists, +N if error

int create_blank_file(ch *file, int ww, int hh, int RGB[3])
{
   ch             *pp;
   ch             *fext;
   int            cstat;
   PXB            *tempxb;
   GError         *gerror = 0;
   uint8          *pixel;

   if (regfile(file)) {
      zmessageACK(Mwin,"output file exists");                                    //  file already exists
      return 1;
   }

   pp = strrchr(file,'.');                                                       //  get file .ext
   if (! pp || strlen(pp) > 4) return 1;

   if (strmatch(pp,".jpg")) fext = "jpeg";                                       //  validate and set pixbuf arg.
   else if (strmatch(pp,".png")) fext = "png";
   else return 2;

   tempxb = PXB_make(ww,hh,3);                                                   //  create pixbuf image

   for (int py = 0; py < hh; py++)                                               //  fill with color
   for (int px = 0; px < ww; px++)
   {
      pixel = PXBpix(tempxb,px,py);
      pixel[0] = RGB[0];
      pixel[1] = RGB[1];
      pixel[2] = RGB[2];
   }

   cstat = gdk_pixbuf_save(tempxb->pixbuf,file,fext,&gerror,null);
   if (! cstat) {
      zmessageACK(Mwin,"error: %s",gerror->message);
      PXB_free(tempxb);
      return 3;
   }

   PXB_free(tempxb);
   return 0;
}


/********************************************************************************/

//  animate given GIF file if possible

void play_gif(ch *file)
{
   int gif_animations_dialog_event(zdialog *, ch *event);

   FILE        *fid;
   ch          *file2;
   ch          command[300], buff[20] = "", *pp = 0;
   zdialog     *zd;
   GtkWidget   *image;
   GdkPixbufAnimation *animation;
   
   file2 = zescape_quotes(file);
   snprintf(command,300,"exiftool -s3 -framecount \"%s\"",file2);
   zfree(file2);
   fid = popen(command,"r");
   if (fid) {
      pp = fgets(buff,20,fid);
      pclose(fid);
   }
   if (! pp || atoi(pp) < 2) return;

   zd = zdialog_new("GIF animation",Mwin,null);
   zdialog_add_widget(zd,"image","gif","dialog");
   image = zdialog_gtkwidget(zd,"gif");
   animation = gdk_pixbuf_animation_new_from_file(curr_file,0);
   gtk_image_set_from_animation(GTK_IMAGE(image),animation);
   zdialog_run(zd,gif_animations_dialog_event,"desktop");
   zdialog_can_focus(zd,0);  

   return;
}


//  dialog event and completion function

int gif_animations_dialog_event(zdialog *zd, ch *event)
{
   if (zd->zstat) zdialog_free(zd); 
   return 1;
}


/********************************************************************************/

//  copy or move an image file to a new location

namespace   copymove_names
{
   ch       *sorcfile = 0;                                                       //  source file full name
   ch       *destname = 0;                                                       //  destination file base name
   ch       *destfile = 0;                                                       //  destination file full name
   ch       *nextfile = 0;                                                       //  next file in source gallery
   ch       *prevfile = 0;
}


//  menu function 

void m_copy_move(GtkWidget *, ch *)
{
   using namespace copymove_names;

   int copymove_dialog_event(zdialog *zd, ch *event);

   ch     *title = "Copy or Move Image File";
   ch     *pp;

   F1_help_topic = "copy/move";

   Plog(1,"m_copy_move \n");

   if (sorcfile) zfree(sorcfile);
   sorcfile = 0;

   if (clicked_file) {                                                           //  use clicked file if present
      sorcfile = clicked_file;
      clicked_file = 0;
   }
   else if (curr_file)                                                           //  else use current file
      sorcfile = zstrdup(curr_file,"copy_move");
   else return;

   if (FGM != 'F' && FGM != 'G') return;

/***
          ________________________________________________________
         |               Copy or Move Image File                  |
         |                                                        |
         | Image File: [________________________________________] |              sorcname       file base name
         | New Location: [_____________________________] [browse] |              copymove_loc   destination folder
         | New File Name: [______________________________] [prev] |              destname       file base name
         |                                                        |
         | (o) copy (duplicate file)  (o) move (delete original)  |
         | [x] keep this dialog open                              |
         | [x] move to next input file                            |
         |                                            [Apply] [X] |
         |________________________________________________________|
***/

   if (! zd_copymove)                                                            //  globally visible dialog
   {
      zd_copymove = zdialog_new(title,Mwin,"Apply"," X ",null);
      zdialog *zd = zd_copymove;

      zdialog_add_widget(zd,"hbox","hb1","dialog",0,"space=3");
      zdialog_add_widget(zd,"label","labf","hb1","Image File:","space=5");
      zdialog_add_widget(zd,"label","sorcname","hb1");                           //  sorcname not editable

      zdialog_add_widget(zd,"hbox","hb2","dialog",0,"space=2");
      zdialog_add_widget(zd,"label","labl","hb2","New Location:","space=5");
      zdialog_add_widget(zd,"zentry","copymove_loc","hb2",0,"expand");
      zdialog_add_widget(zd,"button","Browse","hb2","Browse","space=5");
      
      zdialog_add_widget(zd,"hbox","hb3","dialog",0,"space=2");
      zdialog_add_widget(zd,"label","labl","hb3","New File Name:","space=5");
      zdialog_add_widget(zd,"zentry","destname","hb3",0,"expand");
      zdialog_add_widget(zd,"button","Prev","hb3","Prev","space=5");
      
      zdialog_add_widget(zd,"hbox","hb4","dialog",0,"space=3");
      zdialog_add_widget(zd,"radio","copy","hb4","copy (duplicate file)","space=5");
      zdialog_add_widget(zd,"radio","move","hb4","move (delete original)","space=5");

      zdialog_add_widget(zd,"hbox","hb5","dialog");
      zdialog_add_widget(zd,"check","keepopen","hb5","keep this dialog open","space=3");

      zdialog_add_widget(zd,"hbox","hb6","dialog");
      zdialog_add_widget(zd,"check","next","hb6","move to next input file","space=3");
      
      zdialog_stuff(zd,"copy",1);
      zdialog_stuff(zd,"move",0);
      zdialog_stuff(zd,"keepopen",0);
      zdialog_stuff(zd,"next",0);

      zdialog_load_inputs(zd);                                                   //  default prior inputs
      zdialog_resize(zd,400,0);
      zdialog_run(zd,copymove_dialog_event,"parent");                            //  run dialog
   }

   zdialog *zd = zd_copymove;
   
   zdialog_stuff(zd,"sorcname","");                                              //  clear dialog
   zdialog_stuff(zd,"copymove_loc","");
   zdialog_stuff(zd,"destname","");
   
   if (sorcfile) {
      if (FGM == 'G') f_open(sorcfile);                                          //  show or highlight gallery
      pp = strrchr(sorcfile,'/');
      if (pp) {
         zdialog_stuff(zd,"sorcname",pp+1);                                      //  use given source file
         zdialog_stuff(zd,"destname",pp+1);                                      //  initz. dest file name from source
      }
   }
   
   if (! sorcfile || ! pp) {                                                     //  should not happen
      zmessageACK(Mwin,"invalid source file: %s",sorcfile);
      zdialog_free(zd);
      zd_copymove = 0;
      return;
   }

   if (copymove_loc) zdialog_stuff(zd,"copymove_loc",copymove_loc);              //  last used copy-to location

   return;
}


//  dialog event and completion callback function

int copymove_dialog_event(zdialog *zd, ch *event)
{
   using namespace copymove_names;

   int          Fcopy, Fmove, Fnext;
   ch           *pp, *pext;
   ch           copyloc[XFCC];
   int          cc, err, Fkeep, Nth;
   
   if (strmatch(event,"Browse")) {                                               //  browse for new location
      pp = zgetfile("Select folder",MWIN,"folder",copymove_loc);
      if (! pp) return 1;
      if (copymove_loc) zfree(copymove_loc);                                     //  save new copymove location
      copymove_loc = pp;
      zdialog_stuff(zd,"copymove_loc",copymove_loc);
      return 1;
   }
   
   if (strmatch(event,"Prev"))                                                   //  use previous name
      if (prevfile) zdialog_stuff(zd,"destname",prevfile);
   
   if (zd->zstat == 0) return 1;                                                 //  wait for dialog finished

   if (zd->zstat != 1) {                                                         //  cancel
      zdialog_free(zd);                                                          //  kill dialog
      zd_copymove = 0;
      return 1;
   }

   zd->zstat = 0;                                                                //  [apply] - keep dialog active

   if (image_file_type(sorcfile) != IMAGE) {
      zmessageACK(Mwin,"invalid source file: %s",sorcfile);                      //  validate source file
      return 1;
   }

   zdialog_fetch(zd,"copy",Fcopy);                                               //  get options
   zdialog_fetch(zd,"move",Fmove);
   zdialog_fetch(zd,"next",Fnext);

   if (Fcopy + Fmove != 1) return 1;                                             //  one of copy/move must be set

   zdialog_fetch(zd,"copymove_loc",copyloc,XFCC);                                //  get move-to location from dialog
   if (! dirfile(copyloc)) {                                                     //  check for valid folder
      zmessageACK(Mwin,"new location is not a folder");
      return 1;
   }

   zstrcopy(copymove_loc,copyloc,"copy_move");                                   //  save new copymove location

   if (destname) zfree(destname);
   destname = (ch *) zmalloc(200,"copy_move");                                   //  get dest file name
   zdialog_fetch(zd,"destname",destname,190);

   if (*destname <= ' ' || strchr(destname,'/')) {
      zmessageACK(Mwin,"new file name is invalid");
      return 1;
   }
   
   pext = strrchr(destname,'.');                                                 //  find dest file .ext
   if (! pext || strlen(pext) > 8) 
      pext = destname + strlen(destname);                                        //  try to skip over '.' in file name
   if (strlen(pext) > 3 && pext[1] == 'v') 
      pext = destname + strlen(destname);                                        //  try to skip over version number

   *pext = 0;
   pp = strrchr(sorcfile,'.');
   if (pp && strlen(pp) < 9) strcpy(pext,pp);                                    //  copy source file .ext to dest file

   cc = strlen(copymove_loc) + strlen(destname) + 2;                             //  new file = copymove_loc/destname.ext
   if (destfile) zfree(destfile);
   destfile = (ch *) zmalloc(cc,"copy_move");
   *destfile = 0;
   strncatv(destfile,cc,copymove_loc,"/",destname,0);

   if (strmatch(sorcfile,destfile)) {                                            //  block copy to self
      zmessageACK(Mwin,"cannot copy a file to itself");
      return 1;
   }

   if (regfile(destfile)) {                                                      //  if new file exists
      int yn = zmessageYN(Mwin,"output file exists, overwrite?");                //    optionally overwrite file
      if (! yn) return 1;
   }

   err = cp_copy(sorcfile,destfile);                                             //  copy source file to destination
   if (err) {
      zmessageACK(Mwin,strerror(err));
      return 1;
   }
   
   if (prevfile) zfree(prevfile);                                                //  save last dest file name 
   pp = strrchr(destfile,'/');
   prevfile = zstrdup(pp+1,"copy_move");
   
   load_filemeta(destfile);                                                      //  update image index for new file
   update_image_index(destfile);
   add_recent_file(destfile);                                                    //  add to recent files list

   if (nextfile) zfree(nextfile);                                                //  find next file in gallery, if any
   nextfile = 0;
   Nth = file_position(sorcfile,0);                                              //  source file position in gallery
   if (Nth >= 0) nextfile = gallery(0,"get",Nth+1);

   if (Fmove)                                                                    //  move - delete source file
   {
      album_purge_replace("ALL",sorcfile,destfile);                              //  replace in albums where present
                                                                                 //    (must precede f_remove)
      err = f_remove(sorcfile,"delete");                                         //  delete file/index/thumb/gallery
      if (err) {
         zmessageACK(Mwin,"delete failed: \n %s",strerror(errno));
         return 1;
      }
      
      if (curr_file && strmatch(curr_file,sorcfile)) {                           //  current file deleted
         zfree(curr_file);
         curr_file = 0;
      }
   }

   if (sorcfile) zfree(sorcfile);                                                //  initz. no source file
   sorcfile = 0;
   zdialog_stuff(zd,"sorcname","");
   zdialog_stuff(zd,"destname","");

   if (Fnext && nextfile) {                                                      //  next file in gallery
      sorcfile = nextfile;
      nextfile = 0;
      f_open(sorcfile);                                                          //  show file or highlight thumb
      pp = strrchr(sorcfile,'/');
      if (pp) {
         zdialog_stuff(zd,"sorcname",pp+1);                                      //  next source and dest file name
         zdialog_stuff(zd,"destname",pp+1);
      }
   }

   else if (curr_file) f_open(curr_file);                                        //  restore curr. metadata
   
   else viewmode('G');

   if (FGM == 'G' && navi::gallerytype == FOLDER) {                              //  refresh gallery
      gallery(0,"init",0);
      gallery(0,"sort",-2);                                                      //  recall sort and position
      gallery(0,"paint",-1);
   }
   
   zdialog_fetch(zd,"keepopen",Fkeep);
   if (! Fkeep) {
      zdialog_free(zd);                                                          //  kill dialog
      zd_copymove = 0;
   }
   else gtk_window_present(MWIN);                                                //  keep focus on main window

   return 1;
}


/********************************************************************************/

//  copy selected image file to the desktop

void m_copyto_desktop(GtkWidget *, ch *)
{
   ch       *file, *pp, newfile[XFCC];
   int      err;
   
   F1_help_topic = "copy to desktop";

   Plog(1,"m_copyto_desktop \n");

   if (FGM != 'F' && FGM != 'G') return;
   
   file = clicked_file;
   if (! file) file = curr_file;
   if (! file) return;
   
   snprintf(newfile,XFCC,"%s/%s",getenv("HOME"),desktopname);                    //  locale specific desktop name
   pp = strrchr(file,'/');
   if (! pp) return;
   strncatv(newfile,XFCC,pp,0);                                                  //  new desktop file name
   
   if (regfile(newfile)) {                                                       //  check if file exists
      int yn = zmessageYN(Mwin,"output file exists, overwrite?");                //  confirm overwrite
      if (! yn) goto cleanup;
   }
   
   if (curr_file && strmatch(file,curr_file)                                     //  current file is copied
                  && image_file_type(file) == IMAGE)
      f_save(newfile,curr_file_type,curr_file_bpc,0,1);                          //  preserve edits
   
   else {
      err = cp_copy(file,newfile);                                               //  copy other file
      if (err) {
         zmessageACK(Mwin,strerror(err));
         goto cleanup;
      }
      load_filemeta(newfile);                                                    //  update image index
      update_image_index(newfile);
   }

cleanup:
   if (clicked_file) zfree(clicked_file);
   clicked_file = 0;
   return;
}


/********************************************************************************/

//  copy selected image file to the clipboard

void m_copyto_clip(GtkWidget *, ch *)
{
   int file_copytoclipboard(ch *file);
   
   ch       tempfile[200];
   int      err;
   
   F1_help_topic = "copy to clipboard";

   Plog(1,"m_copyto_clip \n");

   if (FGM != 'F' && FGM != 'G') return;

   if (clicked_file) {
      file_copytoclipboard(clicked_file);                                        //  get file behind thumbnail
      zfree(clicked_file);
      clicked_file = 0;
      return;
   }

   if (! curr_file) {
      zmessageACK(Mwin,"no current file");
      return;
   }
   
   if (image_file_type(curr_file) != IMAGE) {                                    //  non-image file
      file_copytoclipboard(curr_file);
      return;
   }
   
   snprintf(tempfile,200,"%s/clipboard.jpg",temp_folder);                        //  may be edited and unsaved
   err = f_save(tempfile,"jpg",8,0,1);
   if (err) return;
   file_copytoclipboard(tempfile);
   remove(tempfile);

   return;
}


//  copy an image file to the clipboard (as pixbuf)
//  any prior clipboard image is replaced
//  supports copy/paste to other apps (not used within fotocx)
//  returns 1 if OK, else 0

int file_copytoclipboard(ch *file)
{
   GtkClipboard   *clipboard;
   PIXBUF         *pixbuf;
   GError         *gerror = 0;

   pixbuf = gdk_pixbuf_new_from_file(file,&gerror);
   if (! pixbuf) return 0;

   clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
   if (! clipboard) return 0;
   gtk_clipboard_clear(clipboard);
   gtk_clipboard_set_image(clipboard,pixbuf);
   gtk_clipboard_set_can_store(clipboard,0,0);
   gtk_clipboard_store(clipboard);                                               //  persistence after exit does not work
// GdkWindow *gdkw = gtk_widget_get_window(Mwin);
// gdk_display_store_clipboard(zfuncs::display,gdkw,0,null,0);
   g_object_unref(pixbuf);
   return 1;
}


/********************************************************************************/

//  Delete or Trash an image file.
//  Use the Linux standard trash function.
//  If not available, show diagnostic and do nothing.

ch  *deltrash_file = 0;

void m_delete_trash(GtkWidget *, ch *)                                           //  combined delete/trash function
{
   int delete_trash_dialog_event(zdialog *zd, ch *event);

   ch   *title = "Delete/Trash Image File";
   
   F1_help_topic = "delete/trash";

   Plog(1,"m_delete_trash \n");

   if (FGM != 'F' && FGM != 'G') return;

   if (deltrash_file) zfree(deltrash_file);
   deltrash_file = 0;
   
   if (clicked_file) {                                                           //  use clicked file if present 
      deltrash_file = clicked_file;
      clicked_file = 0;
   }

   else if (curr_file)                                                           //  else current file
      deltrash_file = zstrdup(curr_file,"delete-trash");

/***
          ______________________________________
         |        Delete/Trash Image File       |
         |                                      |
         | File: [____________________________] |
         |                                      |
         | [x] keep this dialog open            |
         |                                      |
         |                 [Delete] [Trash] [X] |
         |______________________________________|

***/

   if (! zd_deltrash)                                                            //  start dialog if not already
   {
      zd_deltrash = zdialog_new(title,Mwin,"Delete","Trash"," X ",null);
      zdialog *zd = zd_deltrash;

      zdialog_add_widget(zd,"hbox","hb1","dialog",0,"space=3");
      zdialog_add_widget(zd,"label","labf","hb1","File:","space=3");
      zdialog_add_widget(zd,"label","file","hb1",0,"space=3");
      zdialog_add_widget(zd,"hbox","hb2","dialog",0,"space=3");
      zdialog_add_widget(zd,"check","keepopen","hb2","keep this dialog open","space=3");

      zdialog_resize(zd,300,0);
      zdialog_load_inputs(zd);
      zdialog_run(zd,delete_trash_dialog_event,"parent");                        //  run dialog
   }
   
   if (deltrash_file) 
   {
      ch *pp = strrchr(deltrash_file,'/');
      if (pp) pp++;
      else pp = deltrash_file;
      zdialog_stuff(zd_deltrash,"file",pp);
      if (FGM == 'G') f_open(deltrash_file);                                     //  show or highlight gallery
   }
   else zdialog_stuff(zd_deltrash,"file","");
   
   return;
}


//  dialog event and completion callback function

int delete_trash_dialog_event(zdialog *zd, ch *event)
{
   int         err = 0, yn = 0;
   int         ftype, Fkeep;
   STATB       statB;
   ch          *opt = 0;
   ch          *pp;

   if (zd->zstat == 0) return 1;                                                 //  wait for dialog finished
   if (zd->zstat == 1) goto PREP;                                                //  [delete] button
   if (zd->zstat == 2) goto PREP;                                                //  [trash] button
   goto EXIT;                                                                    //  cancel

PREP:

   if (! deltrash_file) goto EXIT;                                               //  no file to delete or trash

   if (! regfile(deltrash_file,&statB)) {                                        //  check file exists
      zmessageACK(Mwin,strerror(errno));
      goto EXIT;
   }

   ftype = image_file_type(deltrash_file);
   if (ftype != IMAGE && ftype != RAW && ftype != VIDEO) {                       //  must be image or RAW or VIDEO 
      zmessageACK(Mwin,"not a known image file");
      goto EXIT;
   }

   if (! hasperm(deltrash_file,'w')) {                                           //  check permission
      if (zd->zstat == 1)
         yn = zmessageYN(Mwin,"Delete read-only file?");
      if (zd->zstat == 2)
         yn = zmessageYN(Mwin,"Trash read-only file?");
      if (! yn) goto NEXT;                                                       //  keep file

      statB.st_mode |= S_IWUSR;                                                  //  make writable
      err = chmod(deltrash_file,statB.st_mode);
      if (err) {
         zmessageACK(Mwin,strerror(errno));
         goto EXIT;
      }
   }

   album_purge_replace("ALL",deltrash_file,0);                                   //  remove from albums if present

   if (zd->zstat == 1) opt = "delete";                                           //  [delete] button
   if (zd->zstat == 2) opt = "trash";                                            //  [trash] button

   err = f_remove(deltrash_file,opt);                                            //  remove file/index/thumb/gallery
   if (err) goto EXIT;

   if (FGM == 'F') {                                                             //  F window
      zdialog_fetch(zd,"keepopen",Fkeep);
      if (! Fkeep) goto EXIT;
      zd->zstat = 0;                                                             //  keep dialog active
      gtk_window_present(MWIN);                                                  //  keep focus on main window
      return 1;
   }

NEXT:                                                                            //  step to next file

   if (FGM == 'G') {                                                             //  gallery view
      gallery(0,"init",0);                                                       //  refresh for removed file
      gallery(0,"sort",-2);                                                      //  recall sort and position 
      gallery(0,"paint",-1);                                                     //  paint
   }

   if (FGM == 'F') m_next(0,0);                                                  //  file view mode, open next image
   
   zdialog_fetch(zd,"keepopen",Fkeep);                                           //  keep going if wanted
   if (! Fkeep) goto EXIT;

   zd->zstat = 0;                                                                //  keep dialog active
   gtk_window_present(MWIN);                                                     //  keep focus on main window

   zdialog_stuff(zd_deltrash,"file","");                                         //  set no next file in dialog
   if (deltrash_file) zfree(deltrash_file);
   deltrash_file = 0;

   if (! curr_file) goto EXIT;                                                   //  no current file

   deltrash_file = zstrdup(curr_file,"delete-trash");                            //  default delete new current file
   pp = strrchr(deltrash_file,'/');
   if (pp) pp++;
   else pp = deltrash_file;
   zdialog_stuff(zd_deltrash,"file",pp);

   if (FGM == 'G') f_open(deltrash_file);                                        //  show or highlight gallery
   return 1;

EXIT:

   if (deltrash_file) zfree(deltrash_file);                                      //  free memory
   deltrash_file = 0;
   zdialog_free(zd);                                                             //  quit dialog
   zd_deltrash = 0;
   return 1;
}


/********************************************************************************/

//  Select an Adobe document file and convert all pages into jpeg image files.
//  The image files are named InputFileName-N.jpg where N is the page number.
//  File types recognized:
//       .pdf              portable document format
//       .ps  .eps         postscript
//       .psd              photoshop image file

void m_convert_adobe(GtkWidget *, ch *)
{
   ch       *pp, *infile = 0, *outfile = 0;
   ch       *f1, *f2;
   zdialog  *zd = 0;
   int      err;

   F1_help_topic = "convert adobe";

   Plog(1,"convert adobe \n");

   pp = 0;
   if (navi::gallerytype == FOLDER) pp = navi::galleryname;
   infile = zgetfile("Open Adobe File",MWIN,"file",pp);
   if (! infile) goto returnx;

   pp = strrchr(infile,'.');
   if (! strcasestr(".pdf .ps .eps .psd",pp)) {
      zmessageACK(Mwin,"not an Adobe file (.pdf .ps .eps .psd)");
      goto returnx;
   }
   
   if (strmatchcase(".psd",pp)) goto photoshop;                                  //  photoshop image
   
   err = zshell(0,"which gs >/dev/null 2>&1");                                   //  check ghostscript installed
   if (err) {
      zmessageACK(Mwin,"ghostscript must be installed");
      goto returnx;
   }

   outfile = zstrdup(infile,"convert adobe",12);                                 //  file.pdf  >>  file-%d.jpg
   pp = strrchr(outfile,'.');
   if (! pp) goto returnx;
   strcpy(pp,"-%d.jpg");                                                         //  file-1.jpg, file-2.jpg, ...
   
   f1 = zescape_quotes(infile); 
   f2 = zescape_quotes(outfile);
   err = zshell("ack","gs -q -sDEVICE=jpeg -r300 -dFitPage "                     //  300 dpi 
                      "-o \"%s\" \"%s\" ", f2, f1);
   zfree(f1);
   zfree(f2);

   if (err) goto returnx;
   
   strcpy(pp,"-1.jpg");                                                          //  open 1st output file
   f_open(outfile);
   viewmode('G');                                                                //  show gallery at file position
   goto returnx;

photoshop:

   err = zshell(0,"which convert >/dev/null 2>&1");                              //  check imagemagick installed
   if (err) {
      zmessageACK(Mwin,"imagemagick must be installed");
      goto returnx;
   }

   outfile = zstrdup(infile,"convert adobe",8);                                  //  file.psd  >>  file.jpg
   pp = strrchr(outfile,'.');
   if (! pp) goto returnx;
   strcpy(pp,".jpg");                                                            //  output file:  file.jpg

   f1 = zescape_quotes(infile);
   f2 = zescape_quotes(outfile);
   err = zshell("ack","convert \"%s\" \"%s\" ",f1,f2);
   zfree(f1);
   zfree(f2);

   if (err) goto returnx;
   
   f_open(outfile);
   viewmode('G');                                                                //  show gallery at file position

returnx:

   if (zd) zdialog_free(zd);
   if (infile) zfree(infile);
   if (outfile) zfree(outfile);
   return;
}


/********************************************************************************/

//  set current file as desktop wallpaper (GNOME only) (fails for Ubuntu 24.04) 

void m_wallpaper(GtkWidget *, ch *)
{
   ch *  key = "gsettings set org.gnome.desktop.background";
   ch *  id = "picture-uri";
   ch *  cf;

   F1_help_topic = "set wallpaper";

   Plog(1,"m_wallpaper \n");

   if (! curr_file) {
      zmessageACK(Mwin,"no current file");
      return;
   }

   cf = zescape_quotes(curr_file);                                               //  replace " with \"
   zshell("log ack","%s %s \"file://%s\" ",key,id,cf);
   zfree(cf);

   return;
}


/********************************************************************************/

//  print image file

void m_print_image(GtkWidget *, ch *)                                            //  use GTK print
{
   int print_addgrid(PXB *Ppxb);

   int      pstat, yn;
   ch       printfile[200];
   PXB      *Ppxb = 0;
   GError   *gerror = 0;

   F1_help_topic = "print image";

   Plog(1,"m_print_image \n");

   if (FGM != 'F' && FGM != 'G') return;

   if (clicked_file) Ppxb = PXB_load(clicked_file,1);                            //  clicked thumbnail
   else if (E0pxm) Ppxb = PXM_PXB_copy(E0pxm);                                   //  current edited file
   else if (curr_file) Ppxb = PXB_load(curr_file,1);                             //  current file
   clicked_file = 0;
   if (! Ppxb) return;
   
   if (sa_stat == sa_stat_fini) {                                                //  ask if print select area              24.50
      yn = zmessageYN(Mwin,"print select area(s) only?");
      if (yn) {
         select_copysave(0,"copy");                                              //  copy select area to file
         snprintf(printfile,200,"%s/copied_area.png",saved_areas_folder);
         Ppxb = PXB_load(printfile,1);
         if (! Ppxb) return;
      }
   }

   print_addgrid(Ppxb);                                                          //  add grid lines if wanted
   
   snprintf(printfile,200,"%s/printfile.bmp",temp_folder);

   pstat = gdk_pixbuf_save(Ppxb->pixbuf,printfile,"png",&gerror,null);           //  .png for non-print of transp. areas   24.50
   if (! pstat) {
      zmessageACK(Mwin,"error: %s",gerror->message);
      PXB_free(Ppxb);
      return;
   }

   print_image_file(Mwin,printfile);

   PXB_free(Ppxb);
   return;
}


//  add grid lines to print image if wanted

int print_addgrid(PXB *Ppxb)
{
   uint8    *pix;
   int      px, py, ww, hh;
   int      startx, starty, stepx, stepy;

   if (! gridsettings[GON]) return 0;                                            //  grid lines off

   ww = Ppxb->ww;
   hh = Ppxb->hh;

   stepx = gridsettings[GXS];                                                    //  space between grid lines
   stepy = gridsettings[GYS];

   stepx = stepx / Mscale;                                                       //  window scale to image scale
   stepy = stepy / Mscale;

   if (gridsettings[GXC])                                                        //  if line counts specified,
      stepx = ww / (1 + gridsettings[GXC]);                                      //    set spacing accordingly
   if (gridsettings[GYC])
      stepy = hh / ( 1 + gridsettings[GYC]);

   startx = stepx * gridsettings[GXF] / 100;                                     //  variable offsets
   if (startx < 0) startx += stepx;

   starty = stepy * gridsettings[GYF] / 100;
   if (starty < 0) starty += stepy;

   if (gridsettings[GX]) {                                                       //  x-grid enabled
      for (px = startx; px < ww-6; px += stepx)
      for (py = 0; py < hh; py++)
      {
         pix = PXBpix(Ppxb,px,py);                                               //  wwwbbb  fat grid lines
         memset(pix,255,9);                                                      //  wwwbbb
         memset(pix+9,0,9);                                                      //  wwwbbb
      }                                                                          //  ......
   }

   if (gridsettings[GY]) {                                                       //  y-grid enabled
      for (py = starty; py < hh-6; py += stepy)
      for (px = 0; px < ww-3; px += 3)
      {
         pix = PXBpix(Ppxb,px,py);                                               //  www...
         memset(pix,255,9);                                                      //  www...
         pix = PXBpix(Ppxb,px,py+1);                                             //  www...
         memset(pix,255,9);                                                      //  bbb...
         pix = PXBpix(Ppxb,px,py+2);                                             //  bbb...
         memset(pix,255,9);                                                      //  bbb...
         pix = PXBpix(Ppxb,px,py+3);
         memset(pix,0,9);
         pix = PXBpix(Ppxb,px,py+4);
         memset(pix,0,9);
         pix = PXBpix(Ppxb,px,py+5);
         memset(pix,0,9);
      }
   }

   return 1;
}


//  print calibrated image
//  menu function calling print_calibrated() in f.tools.cc

namespace calibprint
{
   int   dialog_event(zdialog *zd, ch *event);
   void  printchart();
   void  scanchart();
   void  fixchart();
   void  processchart();

//  parameters for RGB step size of 23: 0 23 46 69 ... 253 (253 --> 255)
//  NC    colors per RGB dimension (12) (counting both 0 and 255)                //  step size from 16 to 23
//  CS    color step size (23)
//  TS    tile size in pixels (70)
//  ROWS  chart rows (50)               ROWS x COLS must be >= NC*NC*NC
//  COLS  chart columns (35)

   #define NC 12
   #define CS 23
   #define TS 70
   #define ROWS 50
   #define COLS 35

   #define NC2 (NC*NC)
   #define NC3 (NC*NC*NC)

   int   RGBvals[NC];
   int   Ntiles = NC3;
   int   chartww = COLS * TS;             //  chart image size
   int   charthh = ROWS * TS;
   int   margin = 80;                     //  chart margins
   ch    printchartfile[200];
   ch    scanchartfile[200];
}


//  Print the current image file with adjusted colors
//  Also called from the file menu function m_print_calibrated()

void m_print_calibrated(GtkWidget *, ch *)
{
   using namespace calibprint;

   zdialog  *zd;
   int      zstat;
   ch       *title = "Color map file to use";
   ch       mapfile[200];
   FILE     *fid;
   PIXBUF   *pixbuf;
   GError   *gerror = 0;
   uint8    *pixels, *pix1;
   ch       *pp, *pp2, printfile[200];
   int      ww, hh, rs, nc, px, py, nn, err;
   int      R1, G1, B1, R2, G2, B2;
   int      RGB[NC][NC][NC][3], ERR[NC][NC][NC][3];
   int      rr1, rr2, gg1, gg2, bb1, bb2;
   int      rx, gx, bx;
   int      ii, Dr, Dg, Db;
   float    W[8], w, Wsum, D, Dmax, F;
   float    Er, Eg, Eb;

   Plog(1,"m_print_calibrated \n");

   F1_help_topic = "print calibrated";

   viewmode('F');                                                                //  file view mode

   if (! curr_file) {
      zmessageACK(Mwin,"Select the image file to print.");
      return;
   }

   for (int ii = 0; ii < NC; ii++)                                               //  construct RGBvals table
      RGBvals[ii] = CS * ii;
   RGBvals[NC-1] = 255;                                                          //  set last value = 255

   zd = zdialog_new(title,Mwin,"Browse","Proceed"," X ",null);                   //  show current color map file
   zdialog_add_widget(zd,"hbox","hbmap","dialog");                               //    and allow user to choose another
   zdialog_add_widget(zd,"label","labmap","hbmap",0,"space=3");
   zdialog_stuff(zd,"labmap",colormapfile);
   zdialog_resize(zd,250,0);
   zdialog_run(zd,0,"parent");
   zstat = zdialog_wait(zd);
   zdialog_free(zd);

   if (zstat == 1) {                                                             //  [browse]
      snprintf(mapfile,200,"%s/%s",printer_color_folder,colormapfile);
      pp = zgetfile("Color Map File",MWIN,"file",mapfile,1);
      if (! pp) return;
      pp2 = strrchr(pp,'/');
      zstrcopy(colormapfile,pp2+1,"print calibrated");
      zfree(pp);
   }

   else if (zstat != 2) return;                                                  //  not proceed: cancel

   snprintf(mapfile,200,"%s/%s",printer_color_folder,colormapfile);
   fid = fopen(mapfile,"r");                                                     //  read color map file
   if (! fid) return;

   for (R1 = 0; R1 < NC; R1++)
   for (G1 = 0; G1 < NC; G1++)
   for (B1 = 0; B1 < NC; B1++)
   {
      nn = fscanf(fid,"RGB: %d %d %d   ERR: %d %d %d ",
           &RGB[R1][G1][B1][0], &RGB[R1][G1][B1][1], &RGB[R1][G1][B1][2],
           &ERR[R1][G1][B1][0], &ERR[R1][G1][B1][1], &ERR[R1][G1][B1][2]);
      if (nn != 6) {
         zmessageACK(Mwin,"file format error");
         fclose(fid);
         return;
      }
   }

   fclose(fid);

   pixbuf = gdk_pixbuf_copy(Fpxb->pixbuf);                                       //  get image pixbuf to convert
   if (! pixbuf) {
      if (gerror) zmessageACK(Mwin,gerror->message);
      return;
   }

   Funcbusy(+1);

   ww = gdk_pixbuf_get_width(pixbuf);
   hh = gdk_pixbuf_get_height(pixbuf);
   pixels = gdk_pixbuf_get_pixels(pixbuf);
   rs = gdk_pixbuf_get_rowstride(pixbuf);
   nc = gdk_pixbuf_get_n_channels(pixbuf);

   poptext_window(MWIN,"converting colors...",300,200,0,-1);

   for (py = 0; py < hh; py++)
   for (px = 0; px < ww; px++)
   {
      zmainloop(10);                                                             //  keep GTK alive

      pix1 = pixels + py * rs + px * nc;
      R1 = pix1[0];                                                              //  image RGB values
      G1 = pix1[1];
      B1 = pix1[2];

      rr1 = R1/CS;                                                               //  get color map values surrounding RGB
      rr2 = rr1 + 1;
      if (rr2 > NC-1) {                                                          //  if > last entry, use last entry
         rr1--;
         rr2--;
      }

      gg1 = G1/CS;
      gg2 = gg1 + 1;
      if (gg2 > NC-1) {
         gg1--;
         gg2--;
      }

      bb1 = B1/CS;
      bb2 = bb1 + 1;
      if (bb2 > NC-1) {
         bb1--;
         bb2--;
      }

      ii = 0;
      Wsum = 0;
      Dmax = CS;

      for (rx = rr1; rx <= rr2; rx++)                                            //  loop 8 enclosing error map nodes
      for (gx = gg1; gx <= gg2; gx++)
      for (bx = bb1; bx <= bb2; bx++)
      {
         Dr = R1 - RGBvals[rx];                                                  //  RGB distance from enclosing node
         Dg = G1 - RGBvals[gx];
         Db = B1 - RGBvals[bx];
         D = sqrtf(Dr*Dr + Dg*Dg + Db*Db);
         if (D > Dmax) W[ii] = 0;
         else W[ii] = (Dmax - D) / Dmax;                                         //  weight of node
         Wsum += W[ii];                                                          //  sum of weights
         ii++;
      }

      ii = 0;
      Er = Eg = Eb = 0;

      for (rx = rr1; rx <= rr2; rx++)                                            //  loop 8 enclosing error map nodes
      for (gx = gg1; gx <= gg2; gx++)
      for (bx = bb1; bx <= bb2; bx++)
      {
         w = W[ii] / Wsum;
         Er += w * ERR[rx][gx][bx][0];                                           //  weighted sum of map node errors
         Eg += w * ERR[rx][gx][bx][1];
         Eb += w * ERR[rx][gx][bx][2];
         ii++;
      }

      F = 1.0;                                                                   //  use 100% of calculated error
      R2 = R1 - F * Er;                                                          //  adjusted RGB = image RGB - error
      G2 = G1 - F * Eg;
      B2 = B1 - F * Eb;

      RGBfix(R2,G2,B2);

      pix1[0] = R2;
      pix1[1] = G2;
      pix1[2] = B2;
   }

   poptext_killnow();

   Funcbusy(-1);

   snprintf(printfile,200,"%s/printfile.png",temp_folder);                       //  save revised pixbuf to print file
   gdk_pixbuf_save(pixbuf,printfile,"png",&gerror,"compression","1",null);
   if (gerror) {
      zmessageACK(Mwin,gerror->message);
      return;
   }

   g_object_unref(pixbuf);

   err = f_open(printfile);                                                      //  open print file
   if (err) return;

   zmessageACK(Mwin,"Image colors are converted for printing.");
   print_image_file(Mwin,printfile);

   return;
}


/********************************************************************************/

//  printer color calibration tool

void m_calibrate_printer(GtkWidget *, ch *menu)
{
   using namespace calibprint;

   zdialog     *zd;
   ch          *title = "Calibrate Printer";

   F1_help_topic = "calibrate printer";

   Plog(1,"m_calibrate_printer \n");

   viewmode('F');                                                                //  file view mode

   for (int ii = 0; ii < NC; ii++)                                               //  construct RGBvals table
      RGBvals[ii] = CS * ii;
   RGBvals[NC-1] = 255;                                                          //  set last value = 255

/***
       ______________________________________
      |         Calibrate Printer            |
      |                                      |
      |  (o) print color chart               |
      |  (o) scan and save color chart       |
      |  (o) align and trim color chart      |
      |  (o) open and process color chart    |
      |                                      |
      |                        [Proceed] [X] |
      |______________________________________|

***/

   zd = zdialog_new(title,Mwin,"Proceed"," X ",null);

   zdialog_add_widget(zd,"radio","printchart","dialog","print color chart");
   zdialog_add_widget(zd,"radio","scanchart","dialog","scan and save color chart");
   zdialog_add_widget(zd,"radio","fixchart","dialog","align and trim color chart");
   zdialog_add_widget(zd,"radio","processchart","dialog","open and process color chart");

   zdialog_stuff(zd,"printchart",1);
   zdialog_stuff(zd,"scanchart",0);
   zdialog_stuff(zd,"fixchart",0);
   zdialog_stuff(zd,"processchart",0);

   zdialog_resize(zd,250,0);
   zdialog_run(zd,dialog_event,"parent");
   return;
}


//  dialog event and completion function

int calibprint::dialog_event(zdialog *zd, ch *event)
{
   using namespace calibprint;

   int      nn;

   if (! zd->zstat) return 1;                                                    //  wait for proceed or cancel

   if (zd->zstat != 1) {                                                         //  cancel
      zdialog_free(zd);
      return 1;
   }

   zdialog_fetch(zd,"printchart",nn);
   if (nn) {
      printchart();
      return 1;
   }

   zdialog_fetch(zd,"scanchart",nn);
   if (nn) {
      scanchart();
      return 1;
   }

   zdialog_fetch(zd,"fixchart",nn);
   if (nn) {
      fixchart();
      return 1;
   }

   zdialog_fetch(zd,"processchart",nn);
   if (nn) {
      processchart();
      return 1;
   }

   zd->zstat = 0;                                                                //  keep dialog active
   return 1;
}


//  generate and print the color chart

void calibprint::printchart()
{
   using namespace calibprint;

   int      ii, cc, fww, fhh, rx, gx, bx;
   int      row, col, px, py;
   int      chartrs;
   uint8    *chartpixels, *pix1;
   PIXBUF   *chartpxb;
   GError   *gerror = 0;

   fww = chartww + 2 * margin;
   fhh = charthh + 2 * margin;

   chartpxb = gdk_pixbuf_new(GDKRGB,0,8,fww,fhh);                                //  make chart image
   if (! chartpxb) {
      zmessageACK(Mwin,"cannot create pixbuf");
      return;
   }

   chartpixels = gdk_pixbuf_get_pixels(chartpxb);                                //  clear to white
   chartrs = gdk_pixbuf_get_rowstride(chartpxb);
   cc = fhh * chartrs;
   memset(chartpixels,255,cc);

   for (py = 0; py < charthh; py++)                                              //  fill chart tiles with colors
   for (px = 0; px < chartww; px++)
   {
      row = py / TS;
      col = px / TS;
      ii = row * COLS + col;
      if (ii >= Ntiles) break;                                                   //  last chart positions may be unused
      rx = ii / NC2;
      gx = (ii - NC2 * rx) / NC;                                                 //  RGB index values for tile ii
      bx = ii - NC2 * rx - NC * gx;
      pix1 = chartpixels + (py + margin) * chartrs + (px + margin) * 3;
      pix1[0] = RGBvals[rx];
      pix1[1] = RGBvals[gx];
      pix1[2] = RGBvals[bx];
   }

   for (py = margin-10; py < fhh-margin+10; py++)                                //  add green margin around tiles
   for (px = margin-10; px < fww-margin+10; px++)                                //    for easier de-skew and trim
   {
      if (py > margin-1 && py < fhh-margin &&
          px > margin-1 && px < fww-margin) continue;
      pix1 = chartpixels + py * chartrs + px * 3;
      pix1[0] = pix1[2] = 0;
      pix1[1] = 255;
   }

   snprintf(printchartfile,200,"%s/printchart.png",printer_color_folder);
   gdk_pixbuf_save(chartpxb,printchartfile,"png",&gerror,null);
   if (gerror) {
      zmessageACK(Mwin,gerror->message);
      return;
   }

   g_object_unref(chartpxb);

   zmessageACK(Mwin,"Print chart in vertical orientation without margins.");
   print_image_file(Mwin,printchartfile);                                        //  print the chart

   return;
}


//  scan the color chart

void calibprint::scanchart()
{
   using namespace calibprint;

   zmessageACK(Mwin,"Scan the printed color chart. \n"
                    "The darkest row is at the top. \n"
                    "Save in %s/",printer_color_folder);
   return;
}


//  edit and fix the color chart

void calibprint::fixchart()
{
   using namespace calibprint;

   ch       *pp;

   zmessageACK(Mwin,"Open and edit the scanned color chart file. \n"
                    "Remove any skew or rotation from scanning. \n"
                    "(Use the Fix Perspective function for this). \n"
                    "Cut off the thin green margin ACCURATELY.");

   pp = zgetfile("scanned color chart file",MWIN,"file",printer_color_folder,1);
   if (! pp) return;
   strncpy0(scanchartfile,pp,200);
   f_open(scanchartfile);
   return;
}


//  process the scanned and fixed color chart

void calibprint::processchart()
{
   using namespace calibprint;

   PIXBUF   *chartpxb;
   GError   *gerror = 0;
   uint8    *chartpixels, *pix1;
   FILE     *fid;
   ch       mapfile[200], *pp, *pp2;
   int      chartrs, chartnc, px, py;
   int      ii, nn, row, col, rx, gx, bx;
   int      xlo, xhi, ylo, yhi;
   float    fww, fhh;
   int      Rsum, Gsum, Bsum, Rout, Gout, Bout;
   int      r1, r2, ry, g1, g2, gy, b1, b2, by;
   int      ERR1[NC][NC][NC][3], ERR2[NC][NC][NC][3];

   zmessageACK(Mwin,"Open the trimmed color chart file");

   pp = zgetfile("trimmed color chart file",MWIN,"file",printer_color_folder,1);
   if (! pp) return;
   strncpy0(scanchartfile,pp,200);

   chartpxb = gdk_pixbuf_new_from_file(scanchartfile,&gerror);                   //  scanned chart without margins
   if (! chartpxb) {
      if (gerror) zmessageACK(Mwin,gerror->message);
      return;
   }

   chartww = gdk_pixbuf_get_width(chartpxb);
   charthh = gdk_pixbuf_get_height(chartpxb);
   chartpixels = gdk_pixbuf_get_pixels(chartpxb);
   chartrs = gdk_pixbuf_get_rowstride(chartpxb);
   chartnc = gdk_pixbuf_get_n_channels(chartpxb);
   fww = 1.0 * chartww / COLS;
   fhh = 1.0 * charthh / ROWS;

   for (row = 0; row < ROWS; row++)                                              //  loop each tile
   for (col = 0; col < COLS; col++)
   {
      ii = row * COLS + col;
      if (ii >= Ntiles) break;

      ylo = row * fhh;                                                           //  tile position within chart image
      yhi = ylo + fhh;
      xlo = col * fww;
      xhi = xlo + fww;

      Rsum = Gsum = Bsum = nn = 0;

      for (py = ylo+fhh/5; py < yhi-fhh/5; py++)                                 //  get tile pixels less 20% margins
      for (px = xlo+fww/5; px < xhi-fww/5; px++)
      {
         pix1 = chartpixels + py * chartrs + px * chartnc;
         Rsum += pix1[0];
         Gsum += pix1[1];
         Bsum += pix1[2];
         nn++;
      }

      Rout = Rsum / nn;                                                          //  average tile RGB values
      Gout = Gsum / nn;
      Bout = Bsum / nn;

      rx = ii / NC2;
      gx = (ii - NC2 * rx) / NC;
      bx = ii - NC2 * rx - NC * gx;

      ERR1[rx][gx][bx][0] = Rout - RGBvals[rx];                                  //  error = (scammed RGB) - (printed RGB)
      ERR1[rx][gx][bx][1] = Gout - RGBvals[gx];
      ERR1[rx][gx][bx][2] = Bout - RGBvals[bx];
   }

   g_object_unref(chartpxb);

   //  anneal the error values to reduce randomness

   for (int pass = 1; pass <= 4; pass++)                                         //  4 passes
   {
      for (rx = 0; rx < NC; rx++)                                                //  use neighbors in 3 channels
      for (gx = 0; gx < NC; gx++)
      for (bx = 0; bx < NC; bx++)
      {
         r1 = rx-1;
         r2 = rx+1;
         g1 = gx-1;
         g2 = gx+1;
         b1 = bx-1;
         b2 = bx+1;

         if (r1 < 0) r1 = 0;
         if (r2 > NC-1) r2 = NC-1;
         if (g1 < 0) g1 = 0;
         if (g2 > NC-1) g2 = NC-1;
         if (b1 < 0) b1 = 0;
         if (b2 > NC-1) b2 = NC-1;

         Rsum = Gsum = Bsum = nn = 0;

         for (ry = r1; ry <= r2; ry++)
         for (gy = g1; gy <= g2; gy++)
         for (by = b1; by <= b2; by++)
         {
            Rsum += ERR1[ry][gy][by][0];
            Gsum += ERR1[ry][gy][by][1];
            Bsum += ERR1[ry][gy][by][2];
            nn++;
         }

         ERR2[rx][gx][bx][0] = Rsum / nn;
         ERR2[rx][gx][bx][1] = Gsum / nn;
         ERR2[rx][gx][bx][2] = Bsum / nn;
      }

      for (rx = 0; rx < NC; rx++)
      for (gx = 0; gx < NC; gx++)
      for (bx = 0; bx < NC; bx++)
      {
         ERR1[rx][gx][bx][0] = ERR2[rx][gx][bx][0];
         ERR1[rx][gx][bx][1] = ERR2[rx][gx][bx][1];
         ERR1[rx][gx][bx][2] = ERR2[rx][gx][bx][2];
      }

      for (rx = 1; rx < NC-1; rx++)                                              //  use neighbors in same channel
      for (gx = 0; gx < NC; gx++)
      for (bx = 0; bx < NC; bx++)
         ERR2[rx][gx][bx][0] = 0.5 * (ERR1[rx-1][gx][bx][0] + ERR1[rx+1][gx][bx][0]);

      for (rx = 0; rx < NC; rx++)
      for (gx = 1; gx < NC-1; gx++)
      for (bx = 0; bx < NC; bx++)
         ERR2[rx][gx][bx][1] = 0.5 * (ERR1[rx][gx-1][bx][1] + ERR1[rx][gx+1][bx][1]);

      for (rx = 0; rx < NC; rx++)
      for (gx = 0; gx < NC; gx++)
      for (bx = 1; bx < NC-1; bx++)
         ERR2[rx][gx][bx][2] = 0.5 * (ERR1[rx][gx][bx-1][2] + ERR1[rx][gx][bx+1][2]);

      for (rx = 0; rx < NC; rx++)
      for (gx = 0; gx < NC; gx++)
      for (bx = 0; bx < NC; bx++)
      {
         ERR1[rx][gx][bx][0] = ERR2[rx][gx][bx][0];
         ERR1[rx][gx][bx][1] = ERR2[rx][gx][bx][1];
         ERR1[rx][gx][bx][2] = ERR2[rx][gx][bx][2];
      }
   }                                                                             //  pass loop

   //  save finished color map to user-selected file

   zmessageACK(Mwin,"Set the name for the output calibration file \n"
                    "[your calibration name].dat");

   snprintf(mapfile,200,"%s/%s",printer_color_folder,colormapfile);
   pp = zgetfile("Color Map File",MWIN,"save",mapfile,1);
   if (! pp) return;
   pp2 = strrchr(pp,'/');
   zstrcopy(colormapfile,pp2+1,"calibrate printer");
   save_params();
   zfree(pp);

   snprintf(mapfile,200,"%s/%s",printer_color_folder,colormapfile);
   fid = fopen(mapfile,"w");
   if (! fid) return;

   for (rx = 0; rx < NC; rx++)
   for (gx = 0; gx < NC; gx++)
   for (bx = 0; bx < NC; bx++)
   {
      fprintf(fid,"RGB: %3d %3d %3d   ERR: %4d %4d %4d \n",
          RGBvals[rx], RGBvals[gx], RGBvals[bx],
          ERR2[rx][gx][bx][0], ERR2[rx][gx][bx][1], ERR2[rx][gx][bx][2]);
   }

   fclose(fid);

   return;
}


/********************************************************************************/

//  Quit menu function
//  Click on window [x] button (delete event) also comes here.
//  User can bail out if unsaved edit, open dialog, or running function.

void m_quit(GtkWidget *, ch *)
{
   int      yn, nn, ii;
   int      Funsaved = 0, choice;
   ch       *modmess = "There are unsaved changes.";

   Plog(1,"m_quit \n");

   if (CEF && CEF->Fmods && ! CEF->Fsaved) Funsaved = 1;                         //  active edits unsaved
   if (URS_pos > 0 && URS_saved[URS_pos] == 0) Funsaved = 1;                     //  completed edits unsaved
   if (Fmetamod) Funsaved = 1;                                                   //  metadata edits unsaved
   if (Funsaved) {
      choice = zdialog_choose(Mwin,"parent",modmess,"Keep","Discard",0);         //  ask user
      if (choice == 1) return;
   }
   
   if (Nfuncbusy) {                                                              //  something is still running
      yn = zmessageYN(Mwin,"Kill busy function?");
      if (! yn) return;
      Fescape = 1;                                                               //  tell it to exit
      for (ii = 0; ii < 20; ii++) {                                              //  allow 2 secs.
         if (Nfuncbusy) zmainsleep(0.1);
         else break;
      }
      if (ii == 20) Plog(0,"busy function will be killed \n");                   //  still running
   }

   if (zfuncs::zdialog_count) {                                                  //  24.20
      yn = zmessageYN(Mwin,"Kill active dialog?");                               //  allow user bailout
      if (! yn) return;
   }
   
   if (! Faskquit) goto quitxx;                                                  //  no "ask to quit" option
   nn = zdialog_choose2(Mwin,"parent","Quit Fotocx?","Yes","No",0);              //  get button or KB key input
   if (nn == 1) goto quitxx;                                                     //  [Yes] button
   if (nn == 2 || nn == -1) return;                                              //  [No] or [x] button

   nn = toupper(nn);
   if (nn == "No"[0]) return;                                                    //  KB input matches [No] button
   if (nn == "Yes"[0]) goto quitxx;                                              //  KB input matches [Yes] button

quitxx:
   Plog(1,"Quit Fotocx\n");
   quitxx();                                                                     //  does not return
}


//  used also for main window destroy event
//  does not return

void quitxx()
{
   Fshutdown = 1;
   Fescape = 1;                                                                  //  stop long-running funcs
   gtk_window_get_position(MWIN,&mwgeom[0],&mwgeom[1]);                          //  save main window position and size
   gtk_window_get_size(MWIN,&mwgeom[2],&mwgeom[3]);                              //    for next session
   zdialog_inputs("save");                                                       //  save dialog inputs
   zdialog_geometry("save");                                                     //  save dialogs position/size
   gallery_memory("save");                                                       //  save recent gallery positions
   free_resources();                                                             //  free memory
   showz_docfile(0,0,"quit");                                                    //  close userguide window
   zshell(0,"rm -R -f %s",temp_folder);                                          //  delete temp files
   save_params();                                                                //  save state for next session
   fflush(null);                                                                 //  flush stdout, stderr
   zexit(0,"Fotocx exit");
}


/********************************************************************************/

//  uninstall fotocx from either /usr/bin etc. or $HOME/.local/bin etc.

void m_uninstall(GtkWidget *, ch *)                                              //  24.30
{
   ch    *pp, baseloc[300];
   int   cc;

   F1_help_topic = "help menu";
   
   Plog(1,"m_uninstall \n");
   
   cc = readlink("/proc/self/exe",baseloc,300);                                  //  get own program path
   if (cc <= 0) {                                                                //  [baseloc]/bin/fotocx
      zmessageACK(Mwin,"cannot get /proc/self/exe");
      return;
   }
   baseloc[cc] = 0;
   
   pp = strstr(baseloc,"/bin/");
   if (pp) *(pp+1) = 0;

   zmessageACK(Mwin,
         "Delete fotocx program files: \n"
         "  $ find %s -path \"*fotocx*\" -type l,f,d -delete \n\n"
         "Delete fotocx user data: \n"
         "  $ rm -f -d -R %s", baseloc, get_zhomedir());

   return;
}


/********************************************************************************/

//  help menu function

void m_help(GtkWidget *, ch *menu)
{
   Plog(1,"m_help \n");
   
   F1_help_topic = "help menu";
   
   if (! *menu) {
      showz_docfile(Mwin,"userguide","help menu");
      return;
   }

   if (strmatch(menu,"User Guide"))
      showz_docfile(Mwin,"userguide",0);

   if (strmatch(menu,"Video Tutorial"))
      zshell("log ack","xdg-open https://youtu.be/F5Kwnr4TrwM");                 //  24.40

   if (strmatch(menu,"Outboard Programs"))
      check_outboards(1);
   
   if (strmatch(menu,"Log File"))
      if (! isatty(fileno(stdin)))
         showz_logfile(Mwin);
      
   if (strmatch(menu,"Command Params"))
      showz_docfile(Mwin,"userguide","command parameters");

   if (strmatch(menu,"Change Log"))
      showz_textfile("doc","changelog",Mwin);

   if (strmatch(menu,"Copyright"))
      showz_textfile("doc","copyright",Mwin);

   if (strmatch(menu,"Licenses")) 
      showz_textfile("doc","licenses",Mwin);

   if (strmatch(menu,"Privacy"))
      showz_docfile(Mwin,"userguide","privacy");

   if (strmatch(menu,"About"))
      zabout(Mwin);
   
   if (strmatch(menu,"Home Page"))
      zshell("log ack","xdg-open https://kornelix.net");                         //  24.40

   if (strmatch(menu,"Uninstall"))
      m_uninstall(0,0);

   return;
}


/********************************************************************************/

//  save (modified) image file to disk

void m_file_save(GtkWidget *, ch *menu)
{
   int  file_save_dialog_event(zdialog *zd, ch *event);

   ch             *pp;
   zdialog        *zd;

   F1_help_topic = "file save";

   Plog(1,"m_file_save \n");

   if (FGM != 'F' && FGM != 'G') return;

   if (! curr_file) {
      zmessageACK(Mwin,"no current file");
      if (zd_filesave) zdialog_free(zd_filesave);
      zd_filesave = 0;
      return;
   }
   
   if (strmatch(curr_file_type,"other"))                                         //  if unsupported type, use jpg
      strcpy(curr_file_type,"jpg");

/***
          _______________________________________________
         |        Save Image File                        |
         |                                               |
         |   filename.jpg                                |
         |                                               |
         |  [new version] save as new file version       |
         |  [new file ...] save as new file name or type |
         |  [replace file] replace file (OVERWRITE)      |
         |                                               |
         |                                           [X] |
         |_______________________________________________|

***/

   if (! zd_filesave)
   {
      zd = zdialog_new("Save Image File",Mwin," X ",null);
      zd_filesave = zd;

      zdialog_add_widget(zd,"hbox","hbf","dialog",0,"space=3");
      zdialog_add_widget(zd,"label","filename","hbf",0,"space=10");

      zdialog_add_widget(zd,"hbox","hb0","dialog");
      zdialog_add_widget(zd,"vbox","vb1","hb0",0,"space=3|homog");
      zdialog_add_widget(zd,"vbox","vb2","hb0",0,"space=5|homog");

      zdialog_add_widget(zd,"button","newvers","vb1","new version");
      zdialog_add_widget(zd,"button","newfile","vb1","new file ...");
      zdialog_add_widget(zd,"button","replace","vb1","replace file");

      zdialog_add_widget(zd,"hbox","hb1","vb2");
      zdialog_add_widget(zd,"hbox","hb2","vb2");
      zdialog_add_widget(zd,"hbox","hb3","vb2");

      zdialog_add_widget(zd,"label","labvers","hb1","save as new file version");
      zdialog_add_widget(zd,"label","labfile","hb2","save as new file name or type");
      zdialog_add_widget(zd,"icon","warning","hb3","warning.png","size=30");
      zdialog_add_widget(zd,"label","labrepl","hb3","replace old file (OVERWRITE)","space=3");
   }

   zd = zd_filesave;

   pp = strrchr(curr_file,'/');
   if (pp) zdialog_stuff(zd,"filename",pp+1);

   zdialog_run(zd,file_save_dialog_event,"mouse");
   return;
}


//  dialog event and completion function

int file_save_dialog_event(zdialog *zd, ch *event)
{
   ch       *RP = 0, *newfilename = 0;
   ch       temp[8];
   int      err;
   
   if (zd->zstat) goto retx;                                                     //  cancel
   if (! zstrstr("newvers newfile replace",event)) return 1;                     //  ignore other events

   if (strmatch(event,"newvers"))                                                //  save as new version
   {
      RP = f_realpath(curr_file);                                                //  use real path
      if (! RP) {
         zmessageACK(Mwin,"file not found: %s",curr_file);
         goto retx;
      }
      
      newfilename = file_new_version(RP);                                        //  get next avail. file version name
      if (! newfilename) goto retx;
      
      if (strmatch(curr_file_type,"RAW"))                                        //  if RAW file, save as 16-bit TIFF
         err = f_save(newfilename,"tif",16,0,1);
      else if (strcasestr("jp2 heic avif webp",curr_file_type))                  //  save these types as jpg 
         err = f_save(newfilename,"jpg",8,0,1);
      else if (strcasestr("pdf ps eps",curr_file_type))                          //  if pdf/ps/eps, save as jpg
         err = f_save(newfilename,"jpg",8,0,1);
      else 
         err = f_save(newfilename,curr_file_type,curr_file_bpc,0,1);             //  save with same file type

      if (! err) f_open_saved();                                                 //  open saved file with edit hist
      goto retx;
   }

   if (strmatch(event,"replace"))                                                //  replace current file
   {
      if (strcasestr("RAW jp2 heic avif webp pdf ps eps",curr_file_type)) { 
         strToUpper(temp,curr_file_type);
         zmessageACK(Mwin,"cannot replace %s file",temp);
         goto retx;
      }

      RP = f_realpath(curr_file);                                                //  use real path
      if (! RP) {
         zmessageACK(Mwin,"file not found: %s",curr_file);
         goto retx;
      }

      err = f_save(RP,curr_file_type,curr_file_bpc,0,1);                         //  save with current edits
      if (! err) f_open_saved();                                                 //  open saved file with edit hist
      goto retx;
   }

   if (strmatch(event,"newfile"))
      err = f_save_as();                                                         //  save-as file chooser dialog

retx:
   if (RP) zfree(RP);
   if (newfilename) zfree(newfilename);
   zdialog_free(zd);                                                             //  kill dialog
   zd_filesave = 0;
   return 1;
}


//  menu entry for KB shortcut Save File (replace)

void m_file_save_replace(GtkWidget *, ch *menu)
{
   int      err;
   ch       *RP;

   Plog(1,"m_file_save_replace \n");

   RP = f_realpath(curr_file);                                                   //  use real path
   if (! RP) {
      zmessageACK(Mwin,"file not found: %s",curr_file);
      return;
   }

   err = f_save(RP,curr_file_type,curr_file_bpc,0,1);                            //  save file
   if (! err) f_open_saved();                                                    //  open saved file with edit hist
   zfree(RP); 
   return;
}


//  menu entry for KB shortcut Save File Version

void m_file_save_version(GtkWidget *, ch *menu)
{
   ch       *newfilename = 0, *RP = 0;
   ch       newfiletype[8];
   int      err;

   Plog(1,"m_file_save_version \n");

   RP = f_realpath(curr_file);                                                   //  use real path
   if (! RP) {
      zmessageACK(Mwin,"file not found: %s",curr_file);
      return;
   }

   strncpy0(newfiletype,curr_file_type,6);
   newfilename = file_new_version(RP);                                           //  get next avail. file version name
   if (! newfilename) goto retx;
   err = f_save(newfilename,newfiletype,curr_file_bpc,0,1);                      //  save file
   if (! err) f_open_saved();                                                    //  open saved file with edit hist

retx:
   if (RP) zfree(RP);
   if (newfilename) zfree(newfilename);
   return;
}


/********************************************************************************/

//  Save current image to specified file (same or new).
//  Update image index file and thumbnail file.
//  Set f_save_type, f_save_bpc, f_save_size
//  Returns 0 if OK, else +N.
//  If Fack is true, failure will cause a popup ACK dialog.

int f_save(ch *outfile, ch *outype, int outbpc, int qual, int Fack)
{
   ch       *metakey[5], *metadata[5];
   ch       *ppv[1], *tempfile, *pext, *outfile2;
   int      nkeys, err, cc1, cc2, cc3, ii;
   int      Fmod, Fcopy, Ftransp, Fnewfile;
   int      px, py;
   STATB    statB;

   ch       *warnalpha = "Transparency map will be lost.\n"
                         "save to TIFF or PNG file to retain.";
   
   if (! curr_file) return 1;

   if (strmatch(outype,"RAW")) {                                                 //  disallow saving as RAW type
      zmessageACK(Mwin,"cannot save as RAW type");
      return 1;
   }

   Fmod = 0;
   if (! qual) qual = jpeg_def_quality;                                          //  use default jpeg compression

   if (CEF) {                                                                    //  edit function active
      if (CEF->Fmods) Fmod = 1;                                                  //  active edits pending
      if (CEF->zd) zdialog_send_event(CEF->zd,"done");                           //  tell it to finish
      if (CEF) return 1;                                                         //  failed (HDR etc.)
   }
   
   if (URS_pos > 0 && URS_saved[URS_pos] == 0) Fmod = 1;                         //  completed edits not yet saved
   
   if (strmatch(outfile,curr_file)) Fnewfile = 0;                                //  replace current file
   else Fnewfile = 1;                                                            //  new file (name/.ext/location)
   
   if (! Fnewfile) {
      err = access(outfile,W_OK);                                                //  test file can be written by me
      if (err) {
         zmessageACK(Mwin,"%s: %s","no write permission",outfile);
         return 1;
      }
   }

   outfile2 = f_realpath(outfile);                                               //  resolve symlinks in file path
   if (! outfile2) {
      zmessageACK(Mwin,"f_save(), file not found: %s",outfile);
      return 2;
   }
   
   tempfile = zstrdup(outfile2,"f_save",8);                                      //  add space for new extension 
   zfree(outfile2);
   outfile2 = tempfile;
   
   if (Fnewfile) {                                                               //  if new file, force .ext
      pext = strrchr(outfile2,'/');                                              //    to one of: .jpg .png .tif
      if (pext) pext = strrchr(pext,'.');
      if (! pext) pext = outfile2 + strlen(outfile2);
      pext[0] = '.';
      strcpy(pext+1,outype);
   }

   if (! Fnewfile && ! Fmod) {                                                   //  no edit changes to file
      Fcopy = 1;                                                                 //  direct copy to output file?
      if (E0pxm) Fcopy = 0;                                                      //  no, non-edit change (upright)
      if (curr_file_bpc != outbpc) Fcopy = 0;                                    //  no, BPC change
      if (qual < jpeg_def_quality) Fcopy = 0;                                    //  no, higher compression wanted
      if (Fcopy) {
         err = cp_copy(curr_file,outfile2);                                      //  copy unchanged file to output
         if (! err) goto updateindex;
         zmessageACK(Mwin,strerror(err));
         zfree(outfile2);
         return 1;
      }
   }
   
   if (! E0pxm) {
      E0pxm = PXM_load(curr_file,1);                                             //  no prior edits, load image file
      if (! E0pxm) {
         zfree(outfile2);
         return 1;
      }
   }

   tempfile = zstrdup(outfile2,"f_save",20);                                     //  temp file in same folder
   strcat(tempfile,"-temp.");
   strcat(tempfile,outype);
   
   if (E0pxm->nc == 4 && ! strstr("tif png",outype))                             //  alpha channel will be lost
   {
      Ftransp = 0;
      for (py = 2; py < E0pxm->hh-2; py += 2)                                    //  ignore extreme edges
      for (px = 2; px < E0pxm->ww-2; px += 2)
         if (PXMpix(E0pxm,px,py)[3] < 250) {
            Ftransp = 1;
            goto breakout;
         }
   breakout:                                                                     //  warn transparency lost
      if (Ftransp) {
         ii = zdialog_choose(Mwin,"mouse",warnalpha,"save anyway"," X ",null);
         if (ii != 1) {
            remove(tempfile);                                                    //  user canceled
            zfree(tempfile);
            zfree(outfile2);
            return 0;
         }
      }
   }

   if (! strstr("tif png",outype)) outbpc = 8;                                   //  force bpc 8 if 16 not supported
   
   err = PXM_save(E0pxm,tempfile,outbpc,qual,Fack);
   if (err) {
      remove(tempfile);                                                          //  failure, clean up
      zfree(tempfile);
      zfree(outfile2);
      return 1;
   }
   
   cc1 = 0;                                                                      //  meta_edithist[] text cc

   if (Fmeta_edithist) cc1 = meta_edithist_cc0;                                  //  meta_edithist at file open
   else {
      metakey[0] = (ch *) meta_edithist_key;
      meta_get1(curr_file,metakey,ppv,1);                                        //  get edits made before 
      if (ppv[0]) {                                                              //    this file was opened
         strncpy0(meta_edithist,ppv[0],metadataXcc-2);
         zfree(ppv[0]);
         cc1 = strlen(meta_edithist);
         meta_edithist_cc0 = cc1;                                                //  edit hist cc when file was opened
      }                                                                          //  (not updated for new edits) 
      Fmeta_edithist = 1;                                                        //  history is loaded
   }

   for (ii = 1; ii <= URS_pos; ii++)                                             //  append edits from undo/redo stack
   {                                                                             //  (omit index 0 = initial image)
      cc2 = strlen(URS_menu[ii]);
      cc3 = strlen(URS_parms[ii]);
      if (cc1 + 7 + cc2 + cc3 + 5 > metadataXcc) break;                          //  no more room
      strcpy(meta_edithist+cc1,Frelease);
      cc1 += strlen(Frelease);                                                   //  append "Fotocx-nn.n: Menu: parms|"
      strcpy(meta_edithist+cc1,": ");
      cc1 += 2;
      strcpy(meta_edithist+cc1,URS_menu[ii]);
      cc1 += cc2;
      if (cc3) {
         strcpy(meta_edithist+cc1,": ");
         cc1 += 2;
         strcpy(meta_edithist+cc1,URS_parms[ii]);
         cc1 += cc3;
      }
      meta_edithist[cc1++] = '|';
   }

   if (CEF && CEF->Fmods)                                                        //  append active edit function 
   {
      cc2 = strlen(CEF->menuname);
      cc3 = strlen(CEF->edit_hist);
      if (cc1 + 7 + cc2 + cc3 + 5 < metadataXcc) {
         strcpy(meta_edithist+cc1,"Fotocx:");
         cc1 += 7;                                                               //  append "Fotocx:Menu:parms|"
         strcpy(meta_edithist+cc1,CEF->menuname);
         if (cc3) {
            cc1 += cc2;
            strcpy(meta_edithist+cc1,": ");
            cc1 += 2;
            strcpy(meta_edithist+cc1,CEF->edit_hist);
            cc1 += cc3;
         }
         meta_edithist[cc1++] = '|';
      }
   }
   
   meta_edithist[cc1] = 0;
   
   nkeys = 0;

   if (Fupright) {                                                               //  image was uprighted
      Fupright = 0;
      metakey[nkeys] = meta_orientation_key;                                     //  orientation = upright
      metadata[nkeys] = "1";                                                     //  meta_put() exiftool: -n added
      nkeys++;
   }
   
   if (Flevel) {                                                                 //  image was levelled 
      Flevel = 0;
      metakey[nkeys] = meta_rollangle_key;                                       //  rollangle = 0
      metadata[nkeys] = "0";
      nkeys++;
   }

   if (cc1) {                                                                    //  prior and/or curr. edit history
      metakey[nkeys] = meta_edithist_key;                                        //  add to metadata
      metadata[nkeys] = meta_edithist;
      nkeys++;
   }

   err = meta_copy(curr_file,tempfile,metakey,metadata,nkeys);                   //  copy all metadata to
   if (err) {                                                                    //    temp file with above revisions 
      if (Fack) zmessageACK(Mwin,"Unable to copy metadata");                     //  bugfix: do this even if nkeys=0       26.1
      else Plog(1,"Unable to copy metadata \n");
   }
   
   err = rename(tempfile,outfile2);                                              //  rename temp file to output file
   if (err) {
      if (Fack) zmessageACK(Mwin,strerror(err));
      remove(tempfile);                                                          //  delete temp file
      zfree(tempfile);
      zfree(outfile2);
      return 2;                                                                  //  could not save
   }
   
   zfree(tempfile);                                                              //  free memory

   for (ii = 0; ii <= URS_pos; ii++)                                             //  mark all prior edits as saved
      URS_saved[ii] = 1;
   
   if (CEF && Fmod) CEF->Fsaved = 1;                                             //  current edit is saved 

updateindex:

   update_thumbfile(outfile2);                                                   //  refresh thumbnail file

   load_filemeta(outfile2);                                                      //  load output file metadata

   if (Fmod) {
      set_meta_wwhh(E0pxm->ww,E0pxm->hh);                                        //  set meta_wwhh in memory
      save_filemeta(outfile2);                                                   //  includes update_image_index() 
   }
   else update_image_index(outfile2);                                            //  add to image index

   if (samefolder(outfile2,navi::galleryname)) {                                 //  if saving into current gallery
      gallery(curr_file,"init",0);                                               //  update curr. gallery list
      gallery(0,"sort",-2);                                                      //  recall sort and position
      set_mwin_title();                                                          //  update posn, count in title
   }

   add_recent_file(outfile2);                                                    //  first in recent files list

   zstrcopy(f_save_file,outfile2,"f_save");                                      //  for f_open_saved()

   err = stat(curr_file,&statB);                                                 //  get current file permissions
   chmod(outfile2,statB.st_mode);                                                //  set permissions for output file

   stat(outfile2,&statB);                                                        //  set output file size, type, bit depth
   f_save_size = statB.st_size;
   strcpy(f_save_type,outype);
   f_save_bpc = outbpc;
   
   if (strmatch(curr_file,outfile2))                                             //  curr. file is being overwritten
      if (zd_metaview) meta_view(0);                                             //  view meta dialog active

   if (CEF && CEF->menufunc)
      CEF->menufunc(0,0);                                                        //  restart edit function

   zfree(outfile2);
   return 0;
}


/********************************************************************************/

//  save (modified) image to new file name or type
//  confirm if overwrite of existing file
//  returns 0 if OK, 1 if cancel or error

GtkWidget      *saveas_fchooser;

int f_save_as()
{
   int  f_save_as_dialog_event(zdialog *zd, ch *event);

   zdialog        *zd;
   ch             *save_folder = 0;
   ch             *type;
   ch             *newfile, *fname;
   ch             *outfile = 0, *outfile2 = 0, *pp, *pext;
   ch             permissions[100];
   int            ii, zstat, err, bpc;
   int            jpgqual = jpeg_def_quality;
   int            mkcurr = 0;
   STATB          statB;
   mode_t         mode;

/***
       _____________________________________________________
      |   Save as New File Name or Type                     |
      |   ________________________________________________  |
      |  |                                                | |
      |  |       file chooser dialog                      | |
      |  |                                                | |
      |  |                                                | |
      |  |                                                | |
      |  |                                                | |
      |  |                                                | |
      |  |________________________________________________| |
      |                                                     |
      |  (o) tif  (o) png  (o) jpg  [90] jpg quality        |                    //  sep. file type and color depth
      |  color depth: (o) 8-bit  (o) 16-bit                 |
      |  [x] open the new file (will become current file)   |
      |  permissions: [__________________________] [change] |
      |                                                     |
      |                                          [Save] [X] |
      |_____________________________________________________|

***/

   zd = zdialog_new("Save as new file name or type",Mwin,"Save"," X ",null);

   zdialog_add_widget(zd,"hbox","hbfc","dialog",0,"expand");
   saveas_fchooser = gtk_file_chooser_widget_new(GTK_FILE_CHOOSER_ACTION_SAVE);
   gtk_container_add(GTK_CONTAINER(zdialog_gtkwidget(zd,"hbfc")),saveas_fchooser);

   zdialog_add_widget(zd,"vbox","space","dialog",0,"space=3");

   zdialog_add_widget(zd,"hbox","hbft","dialog");
   zdialog_add_widget(zd,"radio","tif","hbft","tif","space=4");
   zdialog_add_widget(zd,"radio","png","hbft","png","space=4");
   zdialog_add_widget(zd,"radio","jpg","hbft","jpg","space=2");
   zdialog_add_widget(zd,"zspin","jpgqual","hbft","10|100|1|90","size=3");
   zdialog_add_widget(zd,"label","labqual","hbft","jpg quality","space=6");

   zdialog_add_widget(zd,"hbox","hbcd","hbft");
   zdialog_add_widget(zd,"label","space","hbcd","","space=8");
   zdialog_add_widget(zd,"label","labdepth","hbcd","color depth:","space=3");
   zdialog_add_widget(zd,"radio","8-bit","hbcd","8-bit","space=4");
   zdialog_add_widget(zd,"radio","16-bit","hbcd","16-bit","space=4");

   zdialog_add_widget(zd,"hbox","hbmc","dialog");
   zdialog_add_widget(zd,"check","mkcurr","hbmc",0,"space=8");
   zdialog_add_widget(zd,"label","labmc","hbmc","open the new file ");
   zdialog_add_widget(zd,"label","labmc","hbmc","(will become current file)");

   zdialog_add_widget(zd,"hbox","hbperm","dialog");
   zdialog_add_widget(zd,"label","labperm","hbperm","permissions:","space=8");
   zdialog_add_widget(zd,"label","permissions","hbperm");
   zdialog_add_widget(zd,"button","change","hbperm","Change","space=8");

   save_folder = f_realpath(curr_file);                                          //  use real path
   if (! save_folder) save_folder = zstrdup(curr_file,"file-save");
   pp = strrchr(save_folder,'/');
   if (pp) *pp = 0;
   gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(saveas_fchooser),save_folder);
   zfree(save_folder);

   newfile = zstrdup(curr_file,"file-save");
   fname = strrchr(newfile,'/') + 1;
   gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(saveas_fchooser),fname);
   zfree(newfile);

   zdialog_stuff(zd,"tif",0);                                                    //  no file type selected
   zdialog_stuff(zd,"png",0);
   zdialog_stuff(zd,"jpg",0);
   zdialog_stuff(zd,"8-bit",0);
   zdialog_stuff(zd,"16-bit",0);

   zdialog_stuff(zd,"jpgqual",jpeg_def_quality);                                 //  default jpeg quality, user setting

   if (strmatch(curr_file_type,"tif")) {                                         //  if curr. file type is tif,
      zdialog_stuff(zd,"tif",1);                                                 //    set corresp. type and bit depth
      if (curr_file_bpc == 16)
         zdialog_stuff(zd,"16-bit",1);
      else zdialog_stuff(zd,"8-bit",1);
   }

   else if (strmatch(curr_file_type,"png")) {                                    //  same for png
      zdialog_stuff(zd,"png",1);
      if (curr_file_bpc == 16)
         zdialog_stuff(zd,"16-bit",1);
      else zdialog_stuff(zd,"8-bit",1);
   }

   else {                                                                        //  same for jpg
      zdialog_stuff(zd,"jpg",1);
      zdialog_stuff(zd,"8-bit",1);
   }

   zdialog_stuff(zd,"mkcurr",1);                                                 //  "make current" is default

   err = stat(curr_file,&statB);                                                 //  current file permissions
   conv_permissions(statB.st_mode,permissions);                                  //   >> default new file permissions
   zdialog_stuff(zd,"permissions",permissions);

   zdialog_resize(zd,700,500);
   zdialog_run(zd,f_save_as_dialog_event,"parent");

zdialog_wait:

   zstat = zdialog_wait(zd);
   if (zstat != 1) {                                                             //  user cancel
      zdialog_free(zd);
      return 1;
   }

   outfile2 = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(saveas_fchooser));
   if (! outfile2) {
      zd->zstat = 0;
      goto zdialog_wait;
   }
   
   zstrcopy(outfile,outfile2,"f_save_as",12);                                    //  add space for possible .vNN and .ext
   g_free(outfile2);

   type = "";
   bpc = -1;
   
   zdialog_fetch(zd,"tif",ii);                                                   //  get selected file type
   if (ii) type = "tif";

   zdialog_fetch(zd,"png",ii);
   if (ii) type = "png";

   zdialog_fetch(zd,"jpg",ii);
   if (ii) type = "jpg";
   
   zdialog_fetch(zd,"8-bit",ii);                                                 //  get selected color depth
   if (ii) bpc = 8;
   
   zdialog_fetch(zd,"16-bit",ii);
   if (ii) bpc = 16;
   
   if (! strstr("tif png jpg",type)) goto zdialog_wait;                          //  should not happen
   if (bpc != 8 && bpc != 16) goto zdialog_wait;
   if (strmatch(type,"jpg") && bpc != 8) goto zdialog_wait;

   zdialog_fetch(zd,"jpgqual",jpgqual);                                          //  jpeg compression level

   pext = strrchr(outfile,'/');                                                  //  locate file .ext
   if (pext) pext = strrchr(pext,'.');

   if (pext) {                                                                   //  validate .ext OK for type
      if (strmatch(type,"jpg") && ! strcasestr(".jpg .jpeg",pext)) *pext = 0;
      if (strmatch(type,"tif") && ! strcasestr(".tif .tiff",pext)) *pext = 0;
      if (strmatch(type,"png") && ! strcasestr(".png",pext)) *pext = 0;
   }

   if (! pext || ! *pext) {
      pext = outfile + strlen(outfile);                                          //  wrong or missing, add new .ext
      *pext = '.';                                                               //  NO replace .JPG with .jpg etc.
      strcpy(pext+1,type);
   }

   zdialog_fetch(zd,"mkcurr",mkcurr);                                            //  get make current option 

   if (regfile(outfile)) {                                                       //  check if file exists
      int yn = zmessageYN(Mwin,"Overwrite file? \n %s",outfile);                 //  confirm overwrite
      if (! yn) {
         zd->zstat = 0;
         goto zdialog_wait;
      }
   }
   
   zdialog_fetch(zd,"permissions",permissions,100);                              //  get permissions from dialog
   conv_permissions(permissions,mode);

   zdialog_free(zd);                                                             //  zdialog_free(zd);

   err = f_save(outfile,type,bpc,jpgqual,1);                                     //  save the file
   if (err) {
      zfree(outfile);
      return 1;
   }
   
   chmod(outfile,mode);                                                          //  set permissions
   
   if (samefolder(outfile,navi::galleryname)) {                                  //  if saving into current gallery
      gallery(outfile,"init",0);                                                 //    refresh gallery list
      gallery(0,"sort",-2);                                                      //    recall sort and position 
      curr_file_posn = file_position(curr_file,curr_file_posn);                  //    update curr. file position
      set_mwin_title();                                                          //    update window title (file count)
   }

   if (mkcurr) f_open_saved();                                                   //  open saved file with edit hist

   zfree(outfile);
   return 0;
}


//  dialog event and completion function

int f_save_as_dialog_event(zdialog *zd, ch *event)
{
   int      ii, err;
   ch       *filespec, *filename, *pp;
   ch       oldperms[100], newperms[100];
   ch       ext[4];
   
   if (zd->zstat) return 1;                                                      //  [save] or cancel

   if (strmatch(event,"jpgqual")) {                                              //  if jpg quality edited, set jpg .ext
      zdialog_stuff(zd,"jpg",1);
      event = "jpg";
   }

   if (zstrstr("tif png jpg",event)) {                                           //  file type selection
      zdialog_stuff(zd,"tif",0);                                                 //  turn off all types
      zdialog_stuff(zd,"png",0);
      zdialog_stuff(zd,"jpg",0);
      zdialog_stuff(zd,event,1);                                                 //  turn on selected type
   }
   
   if (zstrstr("8-bit 16-bit",event)) {                                          //  color depth selection
      zdialog_stuff(zd,"8-bit",0);                                               //  turn off all depths
      zdialog_stuff(zd,"16-bit",0);
      zdialog_stuff(zd,event,1);                                                 //  turn on selected depth
   }
   
   zdialog_fetch(zd,"jpg",ii);                                                   //  if jpg, force 8-bit
   if (ii) {
      zdialog_stuff(zd,"16-bit",0);
      zdialog_stuff(zd,"8-bit",1);
   }
   
   zdialog_fetch(zd,"tif",ii);                                                   //  get chosen file type "tif" ...
   if (ii) strcpy(ext,"tif");                                                    //  set corresp. extension ".tif" ...
   zdialog_fetch(zd,"png",ii);
   if (ii) strcpy(ext,"png");
   zdialog_fetch(zd,"jpg",ii);
   if (ii) strcpy(ext,"jpg");

   filespec = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(saveas_fchooser));
   if (! filespec) return 1;
   filename = strrchr(filespec,'/');                                             //  revise file .ext in chooser dialog
   if (! filename) return 1;
   filename = zstrdup(filename+1,"file-save",6);
   pp = strrchr(filename,'.');
   if (! pp || strlen(pp) > 5) pp = filename + strlen(filename);
   *pp = '.';
   strcpy(pp+1,ext);
   gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(saveas_fchooser),filename);
   zfree(filename);
   g_free(filespec);
   
   if (strmatch(event,"change")) {                                               //  change saved file permissions
      zdialog_fetch(zd,"permissions",oldperms,100);
      err = set_permissions(zd->dialog,"",oldperms,newperms);
      if (! err) zdialog_stuff(zd,"permissions",newperms);
   }

   return 1;
}


/********************************************************************************/

//  get real path for filename possibly having symlinks
//  all folders in input filename path must exist
//  final file name need not exist (f_save() caller)
//  returns real path or null if error
//  returned path is subject for zfree()

ch * f_realpath(ch * infile)
{
   int      cc;
   ch       *pp, *RP, *outfile;
   ch       tempfile[XFCC];
   
   RP = realpath(infile,null);                                                   //  try full file path
   if (RP) {
      outfile = zstrdup(RP,"realpath");                                          //  OK
      free(RP);
      return outfile;
   }

   strcpy(tempfile,infile);                                                      //  fail, try folders only 
   pp = strrchr(tempfile + 2,'/');
   if (! pp) return 0;
   *pp = 0;
   RP = realpath(tempfile,null);
   *pp = '/';
   if (! RP) return 0;                                                           //  fail

   cc = strlen(pp);                                                              //  return folders/file
   outfile = zstrdup(RP,"realpath",cc+2);
   strcat(outfile,pp);
   free(RP);
   return outfile;
}


/********************************************************************************/

//  get the root name of an image file, without version and extension
//     /.../filename.V03.jpg  -->  /.../filename
//  returned root name has extra length to add .vNN.exxxxt
//  returned root name is subject for zfree()

ch * file_rootname(ch *file)
{
   ch    *rootname, *pp1, *pp2;
   
   rootname = zstrdup(file,"rootname",16);
   pp1 = strrchr(rootname,'/');                                                  //  find file .ext
   if (! pp1) pp1 = rootname;
   pp2 = strrchr(pp1,'.');                                                       //  pp2 --> .ext or ending null
   if (! pp2) pp2 = pp1 + strlen(pp1);

   if (pp2[-4] == '.' && pp2[-3] == 'v' &&                                       //  look for .vNN.ext
       pp2[-2] >= '0' && pp2[-2] <= '9' &&
       pp2[-1] >= '0' && pp2[-1] <= '9') pp2 -= 4;                               //  pp2 -->  .ext or .vNN.ext
   *pp2 = 0;                                                                     //  pp2 -->  new ending null

   return rootname;
}


/********************************************************************************/

//  return base name for given file = original file name /.../filename.ext
//  returns null if base file does not exist.
//  returned base name has extra length to add .vNN.exxxxt
//  returned base name is subject for zfree()

ch * file_basename(ch *file)
{
   ch       *rootname, **flist, *pp = 0;
   int      ii, cc, nf;
   
   flist = file_all_versions(file,nf);                                           //  get base file and all versions
   if (! nf) return 0;

   rootname = file_rootname(file);
   cc = strlen(rootname);
   zfree(rootname);
   
   for (ii = 0; ii < nf; ii++) 
   {
      pp = flist[ii];
      if (strmatchN(pp+cc,".v",2)) continue;
      if (pp[cc] == '.') break;
   }
   
   if (ii < nf) pp = zstrdup(pp,"basename",16);
   else pp = 0;
   
   for (ii = 0; ii < nf; ii++)
      zfree(flist[ii]);
   zfree(flist);
   
   return pp;
}


/********************************************************************************/

//  Get all versions of a given file name in sequence, including base file.
//  Returned list of file names is subject for zfree()
//  (each returned flist[*] member and flist itself)
//  returns null if nothing found

ch ** file_all_versions(ch *file, int &NF)
{
   int  file_comp_versions(ch *f1, ch *f2);

   ch       **flist1, **flist2, *rootname;
   ch       *pext, *pvers;
   int      ii, jj, err, cc1, cc2;
   
   rootname = file_rootname(file);                                               //  /.../fname.vNN.ext  -->  /.../fname
   if (! rootname) return 0;

   cc1 = strlen(rootname);                                                       //  file cc without .vNN.ext
   strcpy(rootname + cc1,".*");
   err = zfind(rootname,flist1,NF);                                              //  find /.../fname.*
   zfree(rootname);
   if (err || NF < 1) return 0;

   flist2 = (ch **) zmalloc(NF * sizeof(ch *),"file-vers");                      //  scan for valid versions

   for (ii = jj = 0; ii < NF; ii++)                                              //  validate fname.ext or fname.vNN.ext
   {
      if (image_file_type(flist1[ii]) > VIDEO) continue;                         //  not image file

      pext = strrchr(flist1[ii],'.');                                            //  get file .ext
      if (! pext) continue;
      cc2 = pext - flist1[ii];                                                   //  file cc without .ext
      if (cc2 > cc1) {                                                           //  version present?  .vNN.ext
         cc2 -= 4;
         pvers = flist1[ii] + cc2;
         if (strncmp(pvers,".v01",4) < 0) continue;                              //  not valid version
         if (strncmp(pvers,".v99",4) > 0) continue;
      }

      flist2[jj++] = flist1[ii];                                                 //  valid version, add to list
   }

   zfree(flist1);
   NF = jj;

   if (NF == 0) {
      zfree(flist2);
      return 0;
   }
   
   if (NF == 1) return flist2;

   if (NF > 99) {                                                                //  screen out problem file
      zmessageACK(Mwin,"file: %s \n exceed 99 versions",file);
      zfree(flist2);
      return 0;
   }

   HeapSort(flist2,NF,file_comp_versions);                                       //  sort in base, version order 
   return flist2;
}


int file_comp_versions(ch *f1, ch *f2)
{
   f1 = strrchr(f1,'.');                                                         //  find .ext in file f1
   if (! f1) return -1;                                                          //  f1 has no .ext
   f2 = strrchr(f2,'.');
   if (! f2) return +1;                                                          //  f2 has no .ext
   f1 -= 4;                                                                      //  point to '.v' in filename.vNN.ext
   if (! strmatchN(f1,".v",2)) return -1;                                        //  f1 not a version
   f2 -= 4;
   if (! strmatchN(f2,".v",2)) return +1;                                        //  f2 not a version
   return strcmp(f1,f2);                                                         //  compare versions
}


/********************************************************************************/

//  Get next available version  /.../filename.vNN.ext  for given file.
//  Returns  "/.../filename.v01.ext"  if no versions are found.
//  Returns null if bad file name or 99 versions already exist.
//  Returned file name is subject for zfree().

ch * file_new_version(ch *file)
{
   ch       *retname, *pp, pext[8];
   ch       **flist = 0;
   int      ii, cc, NF = 0, vers;
   
   pp = (ch *) strrchr(file,'/');                                                //  find .ext for file
   if (! pp) return 0;
   pp = strrchr(pp,'.');
   if (pp) strncpy0(pext,pp,8);
   else strcpy(pext,".jpg");
   
   if (strcasestr(".jp2 .heic .avif .webp",pext))                                //  replace these types with .jpg
      strcpy(pext,".jpg");
   
   flist = file_all_versions(file,NF);                                           //  get base file and all versions
   if (! NF) {                                                                   //  nothing exists
      retname = file_rootname(file);                                             //  get /.../filename
      retname = zstrdup(retname,"new-version",12);
      cc = strlen(retname);
      strcpy(retname+cc,".v01");                                                 //  return /.../filename.v01.ext
      strcpy(retname+cc+4,pext);
      return retname;
   }
   
   retname = zstrdup(flist[NF-1],"new-version",12);                              //  get last version found

   for (ii = 0; ii < NF; ii++)                                                   //  free memory
      zfree(flist[ii]);
   zfree(flist);

   pp = strrchr(retname,'/');                                                    //  find .ext
   if (! pp) return 0;
   pp = strrchr(pp,'.');
   if (! pp) {                                                                   //  none
      strcat(retname,"v.01.jpg");                                                //  return /.../filename.v01.jpg
      return retname;
   }
   
   if (strmatchN(pp-4,".v",2)) {                                                 //  find /.../filename.vNN.ext
      if (pp[-2] >= '0' && pp[-2] <= '9' &&                                      //                        |
          pp[-1] >= '0' && pp[-1] <= '9')                                        //                        pp
      {
         vers = 10 * (pp[-2] - '0') + pp[-1] - '0';
         if (vers >= 99) {
            zmessageACK(Mwin,"file: %s \n exceed 99 versions",file);
            return 0;
         }
         vers++;                                                                 //  add 1 to .vNN, leave same .ext
         pp[-2] = vers/10 + '0';
         pp[-1] = vers - 10 * (vers/10) + '0';
         return retname;                                                         //  return /.../filename.vNN.ext
      }
   }

   strncpy0(pext,pp,8);                                                          //  keep .ext
   strcpy(pp,".v01");                                                            //  return /.../filename.v01.ext
   strcpy(pp+4,pext);
   return retname;
}


/********************************************************************************/

//  Get the newest version  /.../filename.vNN.ext  for the given file.
//  Returns unversioned file  /.../filename.ext  if found by itself.
//  Returns null if bad file name.
//  Returned file name is subject for zfree().

ch * file_newest_version(ch *file)
{
   ch       *retname;
   ch       **flist;
   int      ii, NF;
   
   flist = file_all_versions(file,NF);                                           //  get base file and all versions
   if (! NF) return 0;

   retname = zstrdup(flist[NF-1],"newest-version",12);                           //  get last version found

   for (ii = 0; ii < NF; ii++)                                                   //  free memory
      zfree(flist[ii]);
   zfree(flist);

   return retname;
}


/********************************************************************************/

//  Get the prior version  /.../filename.vNN.ext  for the given file.
//  Returns unversioned file  /.../filename.ext  if no prior .vNN found.
//  Returns null if bad file name or no prior version.

ch * file_prior_version(ch *file)
{
   ch       *retname;
   ch       **flist;
   int      ii, NF;
   
   flist = file_all_versions(file,NF);                                           //  get base file and all versions
   if (! NF) return 0;
   
   for (ii = 0; ii < NF; ii++)                                                   //  find input file in list
      if (strmatch(file,flist[ii])) break;
   
   if (ii == 0) return 0;                                                        //  input is base file (no prior)
   if (ii == NF) return 0;                                                       //  should not happen

   retname = zstrdup(flist[ii-1],"prior-version");                               //  prior file in list

   for (ii = 0; ii < NF; ii++)                                                   //  free memory
      zfree(flist[ii]);
   zfree(flist);

   return retname;
}


/********************************************************************************

   Find all image files within given path.

   int find_imagefiles(ch *folder, int flags, ch **&flist, int &NF)

      folder      folder path to search
      flags       sum of the following:
                     1  include image files (+RAW +video)
                     2  include thumbnails
                     4  include hidden files 
                     8  include folders
                    16  recurse folders
                    32  omit symlinks
      NF          count of files returned
      flist       list of files returned

   Returns 0 if OK, +N if error (errno is set).
   flist and flist[*] are subjects for zfree().

*********************************************************************************/

namespace find_imagefiles_names
{
   ch    **fif_filelist;                  //  list of filespecs returned
   int   fif_max;                         //  filelist slots allocated
   int   fif_count;                       //  filelist slots filled
}


int find_imagefiles(ch *folder, int flags, ch **&flist, int &NF, int Finit) 
{
   using namespace find_imagefiles_names;

   int         globflags, Fimages, Fthumbs, Fdirs, Frecurse, Fnolinks;
   int         err1, err2, cc;
   FTYPE       ftype;
   ch          *file, *mfolder, **templist;
   glob_t      globdata;
   STATB       statB;
   
   if (Finit) {                                                                  //  initial call
      spinlock(1);                                                               //  prevent reentrance
      fif_max = fif_count = 0;
   }

   globflags = GLOB_NOSORT;
   Fimages = Fthumbs = Fdirs = Frecurse = Fnolinks = 0;
   
   if (flags & 1) Fimages = 1;
   if (flags & 2) Fthumbs = 1;
   if (flags & 4) globflags += GLOB_PERIOD;
   if (flags & 8) Fdirs = 1;
   if (flags & 16) Frecurse = 1;
   if (flags & 32) Fnolinks = 1;
   
   if (Fdirs && ! Fimages && ! Fthumbs)
      globflags += GLOB_ONLYDIR;

   globdata.gl_pathc = 0;                                                        //  glob() setup
   globdata.gl_offs = 0;
   globdata.gl_pathc = 0;

   NF = 0;                                                                       //  empty output
   flist = 0;

   mfolder = zstrdup(folder,"find-files",4);                                     //  append /* to input folder
   strcat(mfolder,"/*");

   err1 = glob(mfolder,globflags,null,&globdata);                                //  find all files in folder
   if (err1) {
      if (err1 == GLOB_NOMATCH) err1 = 0;
      else if (err1 == GLOB_ABORTED) err1 = 1;
      else if (err1 == GLOB_NOSPACE) err1 = 2;
      else err1 = 3;
      goto fif_return;
   }

   for (uint ii = 0; ii < globdata.gl_pathc; ii++)                               //  loop found files
   {
      file = globdata.gl_pathv[ii];

      if (Fnolinks) {                                                            //  detect and omit symlinks
         err1 = lstat(file,&statB);
         if (err1) continue;
         if (S_ISLNK(statB.st_mode)) continue;
      }
      
      if (Frecurse && dirfile(file)) {                                           //  folder
         err1 = find_imagefiles(file,flags,flist,NF,0);                          //  process member files
         if (err1) goto fif_return;
      }
      
      ftype = image_file_type(file);
      if (ftype == OTHER) continue;                                              //  unknown file type
      
      if (ftype == FDIR && ! Fdirs) continue;
      if (ftype == THUMB && ! Fthumbs) continue;
      if (ftype == IMAGE || ftype == RAW || ftype == VIDEO)
         if (! Fimages) continue;
      
      if (fif_count == fif_max) {                                                //  output list is full
         if (fif_max == 0) {
            fif_max = 1000;                                                      //  initial space, 1000 files
            cc = fif_max * sizeof(ch *);
            fif_filelist = (ch **) zmalloc(cc,"find-files");
         }
         else {
            templist = fif_filelist;                                             //  expand by 2x each time needed
            cc = fif_max * sizeof(ch *);
            fif_filelist = (ch **) zmalloc(cc+cc,"find-files");
            memcpy(fif_filelist,templist,cc);
            memset(fif_filelist+fif_max,0,cc);
            zfree(templist);
            fif_max *= 2;
         }
      }

      fif_filelist[fif_count] = zstrdup(file,"find-files");                      //  add file to output list
      fif_count += 1;
   }

   err1 = 0;

fif_return:

   err2 = errno;                                                                 //  preserve Linux errno

   globfree(&globdata);                                                          //  free memory
   zfree(mfolder);

   if (Finit) {                                                                  //  user call
      NF = fif_count;
      if (NF) flist = fif_filelist;
      spinlock(0);                                                               //  unlock
   }
   
   errno = err2;                                                                 //  return err1 and preserve errno
   return err1;
}


/********************************************************************************/

//  test if a file exists, is a regular file

int regfile(ch *file, struct stat *statb)
{
   STATB    statB;
   int      err;

   err = stat(file,&statB);
   if (err) return 0;
   if (! S_ISREG(statB.st_mode)) return 0;
   if (statb) *statb = statB;
   return 1;
}


//  test if a file exists, is a directory/folder

int dirfile(ch *file, struct stat *statb)
{
   STATB    statB;
   int      err;
   
   err = stat(file,&statB);
   if (err) return 0;
   if (! S_ISDIR(statB.st_mode)) return 0;
   if (statb) *statb = statB;
   return 1;
}


//  test if file exists, is a regular file, and read or write permission
//  rw: 'r' or read or 'w' for write or ' ' for file exists only
//  returns 0 if file does not exist, is not a regular file, or access is not permitted
//  returns 1 if all is OK

int hasperm(ch *file, ch rw)
{
   STATB    statB;
   
   if (! regfile(file,&statB)) return 0;
   if (rw == 'r' && ! (S_IRUSR & statB.st_mode)) return 0;
   if (rw == 'w' && ! (S_IWUSR & statB.st_mode)) return 0;
   return 1;
}


/********************************************************************************/

//  Show a permissions setting, edit and return changed permissions.
//  'fname' is a file name or permission category, e.g. 'default'
//  Permissions are strings: "read+write", "read only", "no access".
//  'p1' and 'p2' are input and output permissions strings, which are
//    any combination of three of the above strings, comma separated,
//     which define the access permissions for user, group, other.
//  p1 and p2 are char[100] strings to allow for fat translations.
//  Returns 1 if user cancel or error, 0 if changes were made OK.

int set_permissions(GtkWidget *parent, ch *fname, ch *p1, ch *p2)
{
   ch             operm[50], gperm[50], wperm[50];
   ch             *pp;
   zdialog        *zd;
   int            zstat;

/***
          ________________________________
         |           permissions          |
         |                                |
         |  owner    [read+write |v]      |
         |  group    [read only  |v]      |
         |  other    [no access  |v]      |
         |                                |
         |                    [Apply] [X] |
         |________________________________|

***/

   zd = zdialog_new("Permissions",parent,"Apply"," X ",null);
   zdialog_add_widget(zd,"hbox","space","dialog",0,"space=5");
   zdialog_add_widget(zd,"hbox","hb1","dialog");
   zdialog_add_widget(zd,"vbox","vb1","hb1",0,"homog|space=5");
   zdialog_add_widget(zd,"vbox","vb2","hb1",0,"homog|space=5");
   zdialog_add_widget(zd,"label","labowner","vb1","owner");
   zdialog_add_widget(zd,"label","labgroup","vb1","group");
   zdialog_add_widget(zd,"label","labother","vb1","other");
   zdialog_add_widget(zd,"combo","ownerperm","vb2");
   zdialog_add_widget(zd,"combo","groupperm","vb2");
   zdialog_add_widget(zd,"combo","otherperm","vb2");
   
   zdialog_stuff(zd,"ownerperm","read+write");                                   //  initz. combo boxes
   zdialog_stuff(zd,"ownerperm","read only");
   zdialog_stuff(zd,"ownerperm","no access");
   
   zdialog_stuff(zd,"groupperm","read+write");
   zdialog_stuff(zd,"groupperm","read only");
   zdialog_stuff(zd,"groupperm","no access");
   
   zdialog_stuff(zd,"otherperm","read+write");
   zdialog_stuff(zd,"otherperm","read only");
   zdialog_stuff(zd,"otherperm","no access");
   
   pp = substring(p1,',',1);                                                     //  initz. dialog from input permissions
   if (pp) zdialog_stuff(zd,"ownerperm",pp);

   pp = substring(p1,',',2);
   if (pp) zdialog_stuff(zd,"groupperm",pp);

   pp = substring(p1,',',3);
   if (pp) zdialog_stuff(zd,"otherperm",pp);
   
   zdialog_run(zd,0,0);                                                          //  run dialog

   zstat = zdialog_wait(zd);                                                     //  wait for completion
   if (zstat != 1) {
      zdialog_free(zd);                                                          //  cancel
      return 1;                                                                  //  error return
   }
   
   *p2 = 0;

   zdialog_fetch(zd,"ownerperm",operm,50);                                       //  get permissions from dialog
   zdialog_fetch(zd,"groupperm",gperm,50);
   zdialog_fetch(zd,"otherperm",wperm,50);
   
   snprintf(p2,100,"%s, %s, %s",operm,gperm,wperm);                              //  output permissions
   
   zdialog_free(zd);
   return 0;                                                                     //  normal return
}


//  convert between permission formats
//  string:  "read+write, read only, no access"
//  mode_t:   bitmap of permissions, e.g. 0640

int conv_permissions(ch *perms, mode_t &mode)                                    //  string permissions to mode_t
{
   int      err = 0;
   ch       *pp;

   mode = 0;

   pp = substring(perms,',',1);
   if (pp) {
      if (strmatch(pp,"read+write")) mode += S_IRUSR + S_IWUSR;
      else if (strmatch(pp,"read only")) mode += S_IRUSR;
      else if (strmatch(pp,"no access")); 
      else err = 1;
   }
   else err = 1;
   
   pp = substring(perms,',',2);
   if (pp) {
      if (strmatch(pp,"read+write")) mode += S_IRGRP + S_IWGRP;
      else if (strmatch(pp,"read only")) mode += S_IRGRP;
      else if (strmatch(pp,"no access")); 
      else err = 1;
   }
   else err = 1;
   
   pp = substring(perms,',',3);
   if (pp) {
      if (strmatch(pp,"read+write")) mode += S_IROTH + S_IWOTH;
      else if (strmatch(pp,"read only")) mode += S_IROTH;
      else if (strmatch(pp,"no access")); 
      else err = 1;
   }
   else err = 1;
   
   return err;
}


int conv_permissions(mode_t mode, ch *perms)                                     //  mode_t to string permissions 
{
   int      err = 0;

   *perms = 0;

   if (mode & S_IRUSR && mode & S_IWUSR) strcat(perms,"read+write");
   else if (mode & S_IRUSR) strcat(perms,"read only");
   else strcat(perms,"no access");
   strcat(perms,", ");

   if (mode & S_IRGRP && mode & S_IWGRP) strcat(perms,"read+write");
   else if (mode & S_IRGRP) strcat(perms,"read only");
   else strcat(perms,"no access");
   strcat(perms,", ");

   if (mode & S_IROTH && mode & S_IWOTH) strcat(perms,"read+write");
   else if (mode & S_IROTH) strcat(perms,"read only");
   else strcat(perms,"no access");
   
   return err;
}