File: wxlayer.cpp

package info (click to toggle)
golly 3.3-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 20,176 kB
  • sloc: cpp: 72,638; ansic: 25,919; python: 7,921; sh: 4,245; objc: 3,721; java: 2,781; xml: 1,362; makefile: 530; javascript: 279; perl: 69
file content (3502 lines) | stat: -rw-r--r-- 123,908 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
// This file is part of Golly.
// See docs/License.html for the copyright notice.

#include "wx/wxprec.h"      // for compilers that support precompilation
#ifndef WX_PRECOMP
    #include "wx/wx.h"      // for all others include the necessary headers
#endif

#if wxUSE_TOOLTIPS
    #include "wx/tooltip.h" // for wxToolTip
#endif
#include "wx/rawbmp.h"      // for wxAlphaPixelData
#include "wx/filename.h"    // for wxFileName
#include "wx/colordlg.h"    // for wxColourDialog
#include "wx/tglbtn.h"      // for wxToggleButton

#include "bigint.h"
#include "lifealgo.h"
#include "qlifealgo.h"
#include "hlifealgo.h"
#include "viewport.h"
#include "util.h"          // for linereader

#include "wxgolly.h"       // for wxGetApp, mainptr, viewptr, bigview, statusptr
#include "wxmain.h"        // for mainptr->...
#include "wxedit.h"        // for ShiftEditBar
#include "wxselect.h"      // for Selection
#include "wxview.h"        // for viewptr->...
#include "wxstatus.h"      // for statusptr->...
#include "wxutils.h"       // for Warning, FillRect, CreatePaleBitmap, etc
#include "wxrender.h"      // for DrawOneIcon
#include "wxprefs.h"       // for initrule, swapcolors, userrules, rulesdir, etc
#include "wxscript.h"      // for inscript
#include "wxundo.h"        // for UndoRedo, etc
#include "wxalgos.h"       // for algo_type, initalgo, algoinfo, CreateNewUniverse, etc
#include "wxlayer.h"

#ifdef _MSC_VER
   #pragma warning(disable:4702)   // disable "unreachable code" warnings from MSVC
#endif
#include <map>                     // for std::map
#ifdef _MSC_VER
   #pragma warning(default:4702)   // enable "unreachable code" warnings
#endif

#ifdef __WXMAC__
    // we need to convert filepath to decomposed UTF8 so fopen will work
    #define OPENFILE(filepath) fopen(filepath.fn_str(),"r")
#else
    #define OPENFILE(filepath) fopen(filepath.mb_str(wxConvLocal),"r")
#endif

// -----------------------------------------------------------------------------

const int layerbarht = 32;       // height of layer bar

int numlayers = 0;               // number of existing layers
int numclones = 0;               // number of cloned layers
int currindex = -1;              // index of current layer

Layer* currlayer = NULL;         // pointer to current layer
Layer* layer[MAX_LAYERS];        // array of layers

bool cloneavail[MAX_LAYERS];     // for setting unique cloneid
bool cloning = false;            // adding a cloned layer?
bool duplicating = false;        // adding a duplicated layer?

algo_type oldalgo;               // algorithm in old layer
wxString oldrule;                // rule in old layer
int oldmag;                      // scale in old layer
bigint oldx;                     // X position in old layer
bigint oldy;                     // Y position in old layer
wxCursor* oldcurs;               // cursor mode in old layer

// ids for bitmap buttons in layer bar
enum {
    LAYER_0 = 0,                  // LAYER_0 must be first id
    LAYER_LAST = LAYER_0 + MAX_LAYERS - 1,
    ADD_LAYER,
    CLONE_LAYER,
    DUPLICATE_LAYER,
    DELETE_LAYER,
    STACK_LAYERS,
    TILE_LAYERS,
    NUM_BUTTONS                   // must be last
};

// bitmaps for layer bar buttons
#include "bitmaps/add.xpm"
#include "bitmaps/clone.xpm"
#include "bitmaps/duplicate.xpm"
#include "bitmaps/delete.xpm"
#include "bitmaps/stack.xpm"
#include "bitmaps/stack_down.xpm"
#include "bitmaps/tile.xpm"
#include "bitmaps/tile_down.xpm"

// -----------------------------------------------------------------------------

// Define layer bar window:

// derive from wxPanel so we get current theme's background color on Windows
class LayerBar : public wxPanel
{
public:
    LayerBar(wxWindow* parent, wxCoord xorg, wxCoord yorg, int wd, int ht);
    ~LayerBar() {}
    
    // add a button to layer bar
    void AddButton(int id, const wxString& tip);
    
    // add a horizontal gap between buttons
    void AddSeparator();
    
    // enable/disable button
    void EnableButton(int id, bool enable);
    
    // set state of a toggle button
    void SelectButton(int id, bool select);
    
    // might need to expand/shrink width of layer buttons
    void ResizeLayerButtons();
    
    // detect press and release of button
    void OnButtonDown(wxMouseEvent& event);
    void OnButtonUp(wxMouseEvent& event);
    void OnKillFocus(wxFocusEvent& event);
    
private:
    // any class wishing to process wxWidgets events must use this macro
    DECLARE_EVENT_TABLE()
    
    // event handlers
    void OnPaint(wxPaintEvent& event);
    void OnSize(wxSizeEvent& event);
    void OnMouseDown(wxMouseEvent& event);
    void OnButton(wxCommandEvent& event);
    
    // bitmaps for normal or down state
    wxBitmap normbutt[NUM_BUTTONS];
    wxBitmap downbutt[NUM_BUTTONS];
    
#ifdef __WXMSW__
    // on Windows we need bitmaps for disabled buttons
    wxBitmap disnormbutt[NUM_BUTTONS];
    wxBitmap disdownbutt[NUM_BUTTONS];
#endif
    
    // positioning data used by AddButton and AddSeparator
    int ypos, xpos, smallgap, biggap;
    
    int downid;          // id of currently pressed layer button
    int currbuttwd;      // current width of each layer button
};

BEGIN_EVENT_TABLE(LayerBar, wxPanel)
EVT_PAINT            (           LayerBar::OnPaint)
EVT_SIZE             (           LayerBar::OnSize)
EVT_LEFT_DOWN        (           LayerBar::OnMouseDown)
EVT_BUTTON           (wxID_ANY,  LayerBar::OnButton)
EVT_TOGGLEBUTTON     (wxID_ANY,  LayerBar::OnButton)
END_EVENT_TABLE()

static LayerBar* layerbarptr = NULL;      // global pointer to layer bar

// layer bar buttons must be global to use Connect/Disconnect on Windows;
// note that bitmapbutt[0..MAX_LAYERS-1] are not used, but it simplifies
// our logic to have those dummy indices
static wxBitmapButton* bitmapbutt[NUM_BUTTONS] = {NULL};
static wxToggleButton* togglebutt[MAX_LAYERS] = {NULL};

// width and height of toggle buttons
const int MAX_TOGGLE_WD = 128;
const int MIN_TOGGLE_WD = 48;
#if defined(__WXMSW__)
    const int TOGGLE_HT = 22;
#elif defined(__WXGTK__)
    const int TOGGLE_HT = 24;
#elif defined(__WXOSX_COCOA__) && !wxCHECK_VERSION(3,0,0)
    const int TOGGLE_HT = 24;
#else
    const int TOGGLE_HT = 20;
#endif

// width and height of bitmap buttons
#if defined(__WXOSX_COCOA__) && wxCHECK_VERSION(3,0,0)
    const int BUTTON_WD = 24;
    const int BUTTON_HT = 24;
#elif defined(__WXOSX_COCOA__) || defined(__WXGTK__)
    const int BUTTON_WD = 28;
    const int BUTTON_HT = 28;
#else
    const int BUTTON_WD = 24;
    const int BUTTON_HT = 24;
#endif

const wxString SWITCH_LAYER = _("Switch to this layer");

// -----------------------------------------------------------------------------

LayerBar::LayerBar(wxWindow* parent, wxCoord xorg, wxCoord yorg, int wd, int ht)
: wxPanel(parent, wxID_ANY, wxPoint(xorg,yorg), wxSize(wd,ht),
#ifdef __WXMSW__
            // need this to avoid buttons flashing on Windows
            wxNO_FULL_REPAINT_ON_RESIZE
#else
            // better for Mac and Linux
            wxFULL_REPAINT_ON_RESIZE
#endif
            )
{
#ifdef __WXGTK__
    // avoid erasing background on GTK+
    SetBackgroundStyle(wxBG_STYLE_CUSTOM);
#endif
    
    // init bitmaps for normal state
    normbutt[ADD_LAYER] =         XPM_BITMAP(add);
    normbutt[ADD_LAYER] =         XPM_BITMAP(add);
    normbutt[CLONE_LAYER] =       XPM_BITMAP(clone);
    normbutt[DUPLICATE_LAYER] =   XPM_BITMAP(duplicate);
    normbutt[DELETE_LAYER] =      XPM_BITMAP(delete);
    normbutt[STACK_LAYERS] =      XPM_BITMAP(stack);
    normbutt[TILE_LAYERS] =       XPM_BITMAP(tile);
    
    // some bitmap buttons also have a down state
    downbutt[STACK_LAYERS] = XPM_BITMAP(stack_down);
    downbutt[TILE_LAYERS] =  XPM_BITMAP(tile_down);
    
#ifdef __WXMSW__
    // create bitmaps for disabled buttons
    CreatePaleBitmap(normbutt[ADD_LAYER],        disnormbutt[ADD_LAYER]);
    CreatePaleBitmap(normbutt[CLONE_LAYER],      disnormbutt[CLONE_LAYER]);
    CreatePaleBitmap(normbutt[DUPLICATE_LAYER],  disnormbutt[DUPLICATE_LAYER]);
    CreatePaleBitmap(normbutt[DELETE_LAYER],     disnormbutt[DELETE_LAYER]);
    CreatePaleBitmap(normbutt[STACK_LAYERS],     disnormbutt[STACK_LAYERS]);
    CreatePaleBitmap(normbutt[TILE_LAYERS],      disnormbutt[TILE_LAYERS]);
    
    // create bitmaps for disabled buttons in down state
    CreatePaleBitmap(downbutt[STACK_LAYERS],     disdownbutt[STACK_LAYERS]);
    CreatePaleBitmap(downbutt[TILE_LAYERS],      disdownbutt[TILE_LAYERS]);
#endif
    
    // init position variables used by AddButton and AddSeparator
    biggap = 16;
#ifdef __WXGTK__
    // buttons are a different size in wxGTK
    xpos = 2;
    ypos = 2;
    smallgap = 6;
#else
    xpos = 4;
    ypos = (32 - BUTTON_HT) / 2;
    smallgap = 4;
#endif
    
    downid = -1;         // no layer button down as yet
    
    currbuttwd = MAX_TOGGLE_WD;
}

// -----------------------------------------------------------------------------

void LayerBar::OnPaint(wxPaintEvent& WXUNUSED(event))
{
    wxPaintDC dc(this);
    
    int wd, ht;
    GetClientSize(&wd, &ht);
    if (wd < 1 || ht < 1 || !showlayer) return;
    
#ifdef __WXMSW__
    // needed on Windows
    dc.Clear();
#endif
    
    wxRect r = wxRect(0, 0, wd, ht);
    
#ifdef __WXMAC__
    wxBrush brush(wxColor(202,202,202));
    FillRect(dc, r, brush);
#endif
    
    if (!showedit) {
        // draw gray border line at bottom edge
#if defined(__WXMSW__)
        dc.SetPen(*wxGREY_PEN);
#elif defined(__WXMAC__)
        wxPen linepen(wxColor(140,140,140));
        dc.SetPen(linepen);
#else
        dc.SetPen(*wxLIGHT_GREY_PEN);
#endif
        dc.DrawLine(0, r.GetBottom(), r.width, r.GetBottom());
        dc.SetPen(wxNullPen);
    }
}

// -----------------------------------------------------------------------------

void LayerBar::OnSize(wxSizeEvent& event)
{
    ResizeLayerButtons();
    event.Skip();
}

// -----------------------------------------------------------------------------

void LayerBar::ResizeLayerButtons()
{
    // might need to expand/shrink width of layer button(s)
    if (layerbarptr) {
        int wd, ht;
        GetClientSize(&wd, &ht);
        
        wxRect r1 = togglebutt[0]->GetRect();
        int x = r1.GetLeft();
        int y = r1.GetTop();
        const int rgap = 4;
        int viswidth = wd - x - rgap;
        int oldbuttwd = currbuttwd;
        
        if (numlayers*currbuttwd <= viswidth) {
            // all layer buttons are visible so try to expand widths
            while (currbuttwd < MAX_TOGGLE_WD && numlayers*(currbuttwd+1) <= viswidth) {
                currbuttwd++;
            }
        } else {
            // try to reduce widths until all layer buttons are visible
            while (currbuttwd > MIN_TOGGLE_WD && numlayers*currbuttwd > viswidth) {
                currbuttwd--;
            }
        }
        
        if (currbuttwd != oldbuttwd && currbuttwd >= 0) {
            for (int i = 0; i < MAX_LAYERS; i++) {
                togglebutt[i]->SetSize(x, y, currbuttwd, TOGGLE_HT);
#if defined(__WXOSX_COCOA__) && wxCHECK_VERSION(3,0,0)
                // ensure there is a gap between buttons
                togglebutt[i]->SetSize(x, y, currbuttwd-4, TOGGLE_HT);
#else
                togglebutt[i]->SetSize(x, y, currbuttwd, TOGGLE_HT);
#endif
                x += currbuttwd;
            }
        }
    }
}

// -----------------------------------------------------------------------------

void LayerBar::OnMouseDown(wxMouseEvent& WXUNUSED(event))
{
    // this is NOT called if user clicks a layer bar button;
    // on Windows we need to reset keyboard focus to viewport window
    viewptr->SetFocus();
    
    mainptr->showbanner = false;
    statusptr->ClearMessage();
}

// -----------------------------------------------------------------------------

void LayerBar::OnButton(wxCommandEvent& event)
{
#ifdef __WXMAC__
    // close any open tool tip window (fixes wxMac bug?)
    wxToolTip::RemoveToolTips();
#endif
    
    mainptr->showbanner = false;
    statusptr->ClearMessage();
    
    int id = event.GetId();
    
#ifdef __WXMSW__
    // disconnect focus handler and reset focus to viewptr;
    // we must do latter before button becomes disabled
    if (id < MAX_LAYERS) {
        togglebutt[id]->Disconnect(id, wxEVT_KILL_FOCUS,
                                   wxFocusEventHandler(LayerBar::OnKillFocus));
    } else {
        bitmapbutt[id]->Disconnect(id, wxEVT_KILL_FOCUS,
                                   wxFocusEventHandler(LayerBar::OnKillFocus));
    }
    viewptr->SetFocus();
#endif
    
    switch (id) {
        case ADD_LAYER:         AddLayer(); break;
        case CLONE_LAYER:       CloneLayer(); break;
        case DUPLICATE_LAYER:   DuplicateLayer(); break;
        case DELETE_LAYER:      DeleteLayer(); break;
        case STACK_LAYERS:      ToggleStackLayers(); break;
        case TILE_LAYERS:       ToggleTileLayers(); break;
        default:
            // id < MAX_LAYERS
            if (id == currindex) {
                // make sure toggle button stays in selected state
                togglebutt[id]->SetValue(true);
            } else {
                SetLayer(id);
                if (inscript) {
                    // update window title, viewport and status bar
                    inscript = false;
                    mainptr->SetWindowTitle(wxEmptyString);
                    mainptr->UpdatePatternAndStatus();
                    inscript = true;
                }
            }
    }
    
    // avoid weird bug on Mac where viewport can lose keyboard focus after
    // the user hits DELETE_LAYER button *and* the "All controls" option
    // is ticked in System Prefs > Keyboard & Mouse > Keyboard Shortcuts
    viewptr->SetFocus();
}

// -----------------------------------------------------------------------------

void LayerBar::OnKillFocus(wxFocusEvent& event)
{
    int id = event.GetId();
    if (id < MAX_LAYERS) {
        togglebutt[id]->SetFocus();   // don't let button lose focus
    } else {
        bitmapbutt[id]->SetFocus();   // don't let button lose focus
    }
}

// -----------------------------------------------------------------------------

void LayerBar::OnButtonDown(wxMouseEvent& event)
{
    // a layer bar button has been pressed
    int id = event.GetId();
    
    // connect a handler that keeps focus with the pressed button
    if (id < MAX_LAYERS) {
        togglebutt[id]->Connect(id, wxEVT_KILL_FOCUS,
                                wxFocusEventHandler(LayerBar::OnKillFocus));
    } else {
        bitmapbutt[id]->Connect(id, wxEVT_KILL_FOCUS,
                                wxFocusEventHandler(LayerBar::OnKillFocus));
    }
    
    event.Skip();
}

// -----------------------------------------------------------------------------

void LayerBar::OnButtonUp(wxMouseEvent& event)
{
    // a layer bar button has been released
    wxPoint pt;
    int wd, ht;
    int id = event.GetId();
    
    if (id < MAX_LAYERS) {
        pt = togglebutt[id]->ScreenToClient( wxGetMousePosition() );
        togglebutt[id]->GetClientSize(&wd, &ht);
        // disconnect kill-focus handler
        togglebutt[id]->Disconnect(id, wxEVT_KILL_FOCUS,
                                   wxFocusEventHandler(LayerBar::OnKillFocus));
    } else {
        pt = bitmapbutt[id]->ScreenToClient( wxGetMousePosition() );
        bitmapbutt[id]->GetClientSize(&wd, &ht);
        // disconnect kill-focus handler
        bitmapbutt[id]->Disconnect(id, wxEVT_KILL_FOCUS,
                                   wxFocusEventHandler(LayerBar::OnKillFocus));
    }
    
    viewptr->SetFocus();
    
    wxRect r(0, 0, wd, ht);
    if ( r.Contains(pt) ) {
        // call OnButton
        wxCommandEvent buttevt(wxEVT_COMMAND_BUTTON_CLICKED, id);
        if (id < MAX_LAYERS) {
            buttevt.SetEventObject(togglebutt[id]);
            togglebutt[id]->GetEventHandler()->ProcessEvent(buttevt);
        } else {
            buttevt.SetEventObject(bitmapbutt[id]);
            bitmapbutt[id]->GetEventHandler()->ProcessEvent(buttevt);
        }
    }
}

// -----------------------------------------------------------------------------

void LayerBar::AddButton(int id, const wxString& tip)
{
    if (id < MAX_LAYERS) {
        // create toggle button
        int y = (layerbarht - TOGGLE_HT) / 2;
        togglebutt[id] = new wxToggleButton(this, id, wxT("?"),
                                            wxPoint(xpos, y),
#if defined(__WXOSX_COCOA__) && wxCHECK_VERSION(3,0,0)
                                            wxSize(MIN_TOGGLE_WD, TOGGLE_HT), wxBORDER_SIMPLE
#else
                                            wxSize(MIN_TOGGLE_WD, TOGGLE_HT)
#endif
                                            );
        if (togglebutt[id] == NULL) {
            Fatal(_("Failed to create layer bar bitmap button!"));
        } else {
#if defined(__WXGTK__) || defined(__WXOSX_COCOA__)
            // use smaller font on Linux and OS X Cocoa
            togglebutt[id]->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
            
            // we need to create size using MIN_TOGGLE_WD above and resize now
            // using MAX_TOGGLE_WD, otherwise we can't shrink size later
            // (possibly only needed by wxMac)
#if defined(__WXOSX_COCOA__) && wxCHECK_VERSION(3,0,0)
            // ensure there is a gap between buttons
            togglebutt[id]->SetSize(xpos, y, MAX_TOGGLE_WD-4, TOGGLE_HT);
#else
            togglebutt[id]->SetSize(xpos, y, MAX_TOGGLE_WD, TOGGLE_HT);
#endif
            
            xpos += MAX_TOGGLE_WD;
            
            togglebutt[id]->SetToolTip(SWITCH_LAYER);
            
#ifdef __WXMSW__
            // fix problem with layer bar buttons when generating/inscript
            // due to focus being changed to viewptr
            togglebutt[id]->Connect(id, wxEVT_LEFT_DOWN,
                                    wxMouseEventHandler(LayerBar::OnButtonDown));
            togglebutt[id]->Connect(id, wxEVT_LEFT_UP,
                                    wxMouseEventHandler(LayerBar::OnButtonUp));
#endif
        }
        
    } else {
        // create bitmap button
        bitmapbutt[id] = new wxBitmapButton(this, id, normbutt[id], wxPoint(xpos,ypos),
#if defined(__WXOSX_COCOA__) && wxCHECK_VERSION(3,0,0)
                                            wxSize(BUTTON_WD, BUTTON_HT), wxBORDER_SIMPLE
#else
                                            wxSize(BUTTON_WD, BUTTON_HT)
#endif
                                            );
        if (bitmapbutt[id] == NULL) {
            Fatal(_("Failed to create layer bar bitmap button!"));
        } else {
            xpos += BUTTON_WD + smallgap;
            
            bitmapbutt[id]->SetToolTip(tip);
            
#ifdef __WXMSW__
            // fix problem with layer bar buttons when generating/inscript
            // due to focus being changed to viewptr
            bitmapbutt[id]->Connect(id, wxEVT_LEFT_DOWN,
                                    wxMouseEventHandler(LayerBar::OnButtonDown));
            bitmapbutt[id]->Connect(id, wxEVT_LEFT_UP,
                                    wxMouseEventHandler(LayerBar::OnButtonUp));
#endif
        }
    }
}

// -----------------------------------------------------------------------------

void LayerBar::AddSeparator()
{
    xpos += biggap - smallgap;
}

// -----------------------------------------------------------------------------

void LayerBar::EnableButton(int id, bool enable)
{
    if (id < MAX_LAYERS) {
        // toggle button
        if (enable == togglebutt[id]->IsEnabled()) return;
        
        togglebutt[id]->Enable(enable);
        
    } else {
        // bitmap button
        if (enable == bitmapbutt[id]->IsEnabled()) return;
        
#ifdef __WXMSW__
        if (id == STACK_LAYERS && stacklayers) {
            bitmapbutt[id]->SetBitmapDisabled(disdownbutt[id]);
            
        } else if (id == TILE_LAYERS && tilelayers) {
            bitmapbutt[id]->SetBitmapDisabled(disdownbutt[id]);
            
        } else {
            bitmapbutt[id]->SetBitmapDisabled(disnormbutt[id]);
        }
#endif
        
        bitmapbutt[id]->Enable(enable);
    }
}

// -----------------------------------------------------------------------------

void LayerBar::SelectButton(int id, bool select)
{
    if (id < MAX_LAYERS) {
        // toggle button
        if (select) {
            if (downid >= LAYER_0) {
                // deselect old layer button
                togglebutt[downid]->SetValue(false);      
                togglebutt[downid]->SetToolTip(SWITCH_LAYER);
            }
            downid = id;
            togglebutt[id]->SetToolTip(_("Current layer"));
        }
        togglebutt[id]->SetValue(select);
        
    } else {
        // bitmap button
        if (select) {
            bitmapbutt[id]->SetBitmapLabel(downbutt[id]);
        } else {
            bitmapbutt[id]->SetBitmapLabel(normbutt[id]);
        }
        if (showlayer) bitmapbutt[id]->Refresh(false);
    }
}

// -----------------------------------------------------------------------------

void CreateLayerBar(wxWindow* parent)
{
    int wd, ht;
    parent->GetClientSize(&wd, &ht);
    
    layerbarptr = new LayerBar(parent, 0, 0, wd, layerbarht);
    if (layerbarptr == NULL) Fatal(_("Failed to create layer bar!"));
    
    // create bitmap buttons
    layerbarptr->AddButton(ADD_LAYER,         _("Add new layer"));
    layerbarptr->AddButton(CLONE_LAYER,       _("Clone current layer"));
    layerbarptr->AddButton(DUPLICATE_LAYER,   _("Duplicate current layer"));
    layerbarptr->AddButton(DELETE_LAYER,      _("Delete current layer"));
    layerbarptr->AddSeparator();
    layerbarptr->AddButton(STACK_LAYERS,      _("Stack layers"));
    layerbarptr->AddButton(TILE_LAYERS,       _("Tile layers"));
    layerbarptr->AddSeparator();
    
    // create a toggle button for each layer
    for (int i = 0; i < MAX_LAYERS; i++) {
        layerbarptr->AddButton(i, wxEmptyString);
    }
    
    // hide all toggle buttons except for layer 0
    for (int i = 1; i < MAX_LAYERS; i++) togglebutt[i]->Show(false);
    
    // select STACK_LAYERS or TILE_LAYERS if necessary
    if (stacklayers) layerbarptr->SelectButton(STACK_LAYERS, true);
    if (tilelayers) layerbarptr->SelectButton(TILE_LAYERS, true);
    
    // select LAYER_0 button
    layerbarptr->SelectButton(LAYER_0, true);
    
    layerbarptr->Show(showlayer);
}

// -----------------------------------------------------------------------------

int LayerBarHeight() {
    return (showlayer ? layerbarht : 0);
}

// -----------------------------------------------------------------------------

void ResizeLayerBar(int wd)
{
    if (layerbarptr && showlayer) {
        layerbarptr->SetSize(wd, layerbarht);
    }
}

// -----------------------------------------------------------------------------

void UpdateLayerBar()
{
    if (layerbarptr && showlayer && !mainptr->IsIconized()) {
        bool active = !viewptr->waitingforclick;
        
        layerbarptr->EnableButton(ADD_LAYER,         active && !inscript && numlayers < MAX_LAYERS);
        layerbarptr->EnableButton(CLONE_LAYER,       active && !inscript && numlayers < MAX_LAYERS);
        layerbarptr->EnableButton(DUPLICATE_LAYER,   active && !inscript && numlayers < MAX_LAYERS);
        layerbarptr->EnableButton(DELETE_LAYER,      active && !inscript && numlayers > 1);
        layerbarptr->EnableButton(STACK_LAYERS,      active);
        layerbarptr->EnableButton(TILE_LAYERS,       active);
        for (int i = 0; i < numlayers; i++) {
            layerbarptr->EnableButton(i, active && CanSwitchLayer(i));
        }
        
        // no need to redraw entire bar here if it only contains buttons
        // layerbarptr->Refresh(false);
    }
}

// -----------------------------------------------------------------------------

void UpdateLayerButton(int index, const wxString& name)
{
    // assume caller has replaced any "&" with "&&"
    togglebutt[index]->SetLabel(name);
}

// -----------------------------------------------------------------------------

void RedrawLayerBar()
{
    if (layerbarptr && showlayer && !mainptr->IsIconized()) {
        layerbarptr->Refresh(false);
        #ifdef __WXGTK__
            // avoid bug that can cause buttons to lose their bitmaps
            layerbarptr->Update();
        #endif
    }
}

// -----------------------------------------------------------------------------

void ToggleLayerBar()
{
    showlayer = !showlayer;
    
    if (showlayer) {
        ShiftEditBar(layerbarht);     // move edit bar down
    } else {
        // hide layer bar
        ShiftEditBar(-layerbarht);    // move edit bar up
    }
    
    mainptr->ResizeBigView();
    layerbarptr->Show(showlayer);    // needed on Windows
    mainptr->UpdateMenuItems();
}

// -----------------------------------------------------------------------------

void CalculateTileRects(int bigwd, int bight)
{
    // set tilerect in each layer
    wxRect r;
    bool portrait = (bigwd <= bight);
    int rows, cols;
    
    // try to avoid the aspect ratio of each tile becoming too large
    switch (numlayers) {
        case 4: rows = 2; cols = 2; break;
        case 9: rows = 3; cols = 3; break;
            
        case 3: case 5: case 7:
            rows = portrait ? numlayers / 2 + 1 : 2;
            cols = portrait ? 2 : numlayers / 2 + 1;
            break;
            
        case 6: case 8: case 10:
            rows = portrait ? numlayers / 2 : 2;
            cols = portrait ? 2 : numlayers / 2;
            break;
            
        default:
            // numlayers == 2 or > 10
            rows = portrait ? numlayers : 1;
            cols = portrait ? 1 : numlayers;
    }
    
    int tilewd = bigwd / cols;
    int tileht = bight / rows;
    if ( float(tilewd) > float(tileht) * 2.5 ) {
        rows = 1;
        cols = numlayers;
        tileht = bight;
        tilewd = bigwd / numlayers;
    } else if ( float(tileht) > float(tilewd) * 2.5 ) {
        cols = 1;
        rows = numlayers;
        tilewd = bigwd;
        tileht = bight / numlayers;
    }
    
    for ( int i = 0; i < rows; i++ ) {
        for ( int j = 0; j < cols; j++ ) {
            r.x = j * tilewd;
            r.y = i * tileht;
            r.width = tilewd;
            r.height = tileht;
            if (i == rows - 1) {
                // may need to increase height of bottom-edge tile
                r.height += bight - (rows * tileht);
            }
            if (j == cols - 1) {
                // may need to increase width of right-edge tile
                r.width += bigwd - (cols * tilewd);
            }
            int index = i * cols + j;
            if (index == numlayers) {
                // numlayers == 3,5,7
                layer[index - 1]->tilerect.width += r.width;
            } else {
                layer[index]->tilerect = r;
            }
        }
    }
    
    if (tileborder > 0) {
        // make tilerects smaller to allow for equal-width tile borders
        for ( int i = 0; i < rows; i++ ) {
            for ( int j = 0; j < cols; j++ ) {
                int index = i * cols + j;
                if (index == numlayers) {
                    // numlayers == 3,5,7
                    layer[index - 1]->tilerect.width -= tileborder;
                } else {
                    layer[index]->tilerect.x += tileborder;
                    layer[index]->tilerect.y += tileborder;
                    layer[index]->tilerect.width -= tileborder;
                    layer[index]->tilerect.height -= tileborder;
                    if (j == cols - 1) layer[index]->tilerect.width -= tileborder;
                    if (i == rows - 1) layer[index]->tilerect.height -= tileborder;
                }
            }
        }
    }
}

// -----------------------------------------------------------------------------

void ResizeTiles(int bigwd, int bight)
{
    // set tilerect for each layer so they tile bigview's client area
    CalculateTileRects(bigwd, bight);
    
    // set size of each tile window
    for ( int i = 0; i < numlayers; i++ ) {
        if (layer[i]->tilerect.width < 0) layer[i]->tilerect.width = 0;
        if (layer[i]->tilerect.height < 0) layer[i]->tilerect.height = 0;
        layer[i]->tilewin->SetSize( layer[i]->tilerect );
    }
    
    // set viewport size for each tile; this is currently the same as the
    // tilerect size because tile windows are created with wxNO_BORDER
    for ( int i = 0; i < numlayers; i++ ) {
        int wd, ht;
        layer[i]->tilewin->GetClientSize(&wd, &ht);
        // wd or ht might be < 1 on Windows
        if (wd < 1) wd = 1;
        if (ht < 1) ht = 1;
        layer[i]->view->resize(wd, ht);
    }
}

// -----------------------------------------------------------------------------

void ResizeLayers(int wd, int ht)
{
    // this is called whenever the size of the bigview window changes;
    // wd and ht are the dimensions of bigview's client area
    if (tilelayers && numlayers > 1) {
        ResizeTiles(wd, ht);
    } else {
        // resize viewport in each layer to bigview's client area
        for (int i = 0; i < numlayers; i++) {
            layer[i]->view->resize(wd, ht);
        }
    }
}

// -----------------------------------------------------------------------------

void CreateTiles()
{
    // create tile windows
    for ( int i = 0; i < numlayers; i++ ) {
        layer[i]->tilewin = new PatternView(bigview,
            // correct size will be set below by ResizeTiles
            0, 0, 0, 0,
            wxNO_BORDER | wxFULL_REPAINT_ON_RESIZE | wxWANTS_CHARS);
        if (layer[i]->tilewin == NULL) Fatal(_("Failed to create tile window!"));
        
        // set tileindex >= 0; this must always match the layer index, so we'll need to
        // destroy and recreate all tiles whenever a tile is added, deleted or moved
        layer[i]->tilewin->tileindex = i;
        
#if wxUSE_DRAG_AND_DROP
        // let user drop file onto any tile (but file will be loaded into current tile)
        layer[i]->tilewin->SetDropTarget(mainptr->NewDropTarget());
#endif
    }
    
    // init tilerects, tile window sizes and their viewport sizes
    int wd, ht;
    bigview->GetClientSize(&wd, &ht);
    // wd or ht might be < 1 on Windows
    if (wd < 1) wd = 1;
    if (ht < 1) ht = 1;
    ResizeTiles(wd, ht);
    
    // change viewptr to tile window for current layer
    viewptr = currlayer->tilewin;
    if (mainptr->infront) viewptr->SetFocus();
}

// -----------------------------------------------------------------------------

void DestroyTiles()
{
    // reset viewptr to main viewport window
    viewptr = bigview;
    if (mainptr->infront) viewptr->SetFocus();
    
    // destroy all tile windows
    for ( int i = 0; i < numlayers; i++ ) {
        delete layer[i]->tilewin;
    }
    
    // resize viewport in each layer to bigview's client area
    int wd, ht;
    bigview->GetClientSize(&wd, &ht);
    // wd or ht might be < 1 on Windows
    if (wd < 1) wd = 1;
    if (ht < 1) ht = 1;
    for ( int i = 0; i < numlayers; i++ ) {
        layer[i]->view->resize(wd, ht);
    }
}

// -----------------------------------------------------------------------------

void SyncClones()
{
    if (numclones == 0) return;
    
    if (currlayer->cloneid > 0) {
        // make sure clone algo and most other settings are synchronized
        for ( int i = 0; i < numlayers; i++ ) {
            Layer* cloneptr = layer[i];
            if (cloneptr != currlayer && cloneptr->cloneid == currlayer->cloneid) {
                // universe might have been re-created, or algorithm changed
                cloneptr->algo = currlayer->algo;
                cloneptr->algtype = currlayer->algtype;
                cloneptr->rule = currlayer->rule;
                
                // no need to sync undo/redo history
                // cloneptr->undoredo = currlayer->undoredo;
                
                // along with view, don't sync these settings
                // cloneptr->autofit = currlayer->autofit;
                // cloneptr->hyperspeed = currlayer->hyperspeed;
                // cloneptr->showhashinfo = currlayer->showhashinfo;
                // cloneptr->drawingstate = currlayer->drawingstate;
                // cloneptr->curs = currlayer->curs;
                // cloneptr->originx = currlayer->originx;
                // cloneptr->originy = currlayer->originy;
                // cloneptr->currname = currlayer->currname;
                
                // sync various flags
                cloneptr->dirty = currlayer->dirty;
                cloneptr->savedirty = currlayer->savedirty;
                cloneptr->stayclean = currlayer->stayclean;
                
                // sync step size
                cloneptr->currbase = currlayer->currbase;
                cloneptr->currexpo = currlayer->currexpo;
                
                // sync selection info
                cloneptr->currsel = currlayer->currsel;
                cloneptr->savesel = currlayer->savesel;
                
                // sync the stuff needed to reset pattern
                cloneptr->startalgo = currlayer->startalgo;
                cloneptr->savestart = currlayer->savestart;
                cloneptr->startdirty = currlayer->startdirty;
                cloneptr->startrule = currlayer->startrule;
                cloneptr->startgen = currlayer->startgen;
                cloneptr->currfile = currlayer->currfile;
                cloneptr->startsel = currlayer->startsel;
                // clone can have different starting name, pos, scale, step
                // cloneptr->startname = currlayer->startname;
                // cloneptr->startx = currlayer->startx;
                // cloneptr->starty = currlayer->starty;
                // cloneptr->startmag = currlayer->startmag;
                // cloneptr->startbase = currlayer->startbase;
                // cloneptr->startexpo = currlayer->startexpo;
                
                // sync timeline settings
                cloneptr->currframe = currlayer->currframe;
                cloneptr->autoplay = currlayer->autoplay;
                cloneptr->tlspeed = currlayer->tlspeed;
            }
        }
    }
}

// -----------------------------------------------------------------------------

void SaveLayerSettings()
{
    // set oldalgo and oldrule for use in CurrentLayerChanged
    oldalgo = currlayer->algtype;
    oldrule = wxString(currlayer->algo->getrule(), wxConvLocal);
    
    // we're about to change layer so remember current rule
    // in case we switch back to this layer
    currlayer->rule = oldrule;
    
    // synchronize clone info (do AFTER setting currlayer->rule)
    SyncClones();
    
    if (syncviews) {
        // save scale and location for use in CurrentLayerChanged
        oldmag = currlayer->view->getmag();
        oldx = currlayer->view->x;
        oldy = currlayer->view->y;
    }
    
    if (synccursors) {
        // save cursor mode for use in CurrentLayerChanged
        oldcurs = currlayer->curs;
    }
}

// -----------------------------------------------------------------------------

bool RestoreRule(const wxString& rule)
{
    const char* err = currlayer->algo->setrule( rule.mb_str(wxConvLocal) );
    if (err) {
        // this can happen if a .rule file was deleted
        // or it was edited and some sort of error introduced, so best to
        // use algo's default rule (which should never fail)
        currlayer->algo->setrule( currlayer->algo->DefaultRule() );
        wxString msg = _("The rule \"") + rule;
        msg += _("\" is no longer valid!\nUsing the default rule instead.");
        Warning(msg);
        return false;
    }
    return true;
}

// -----------------------------------------------------------------------------

void CurrentLayerChanged()
{
    // currlayer has changed since SaveLayerSettings was called;
    // update rule if the new currlayer uses a different algorithm or rule
    if ( currlayer->algtype != oldalgo || !currlayer->rule.IsSameAs(oldrule,false) ) {
        RestoreRule(currlayer->rule);
    }
    
    if (syncviews) currlayer->view->setpositionmag(oldx, oldy, oldmag);
    if (synccursors) currlayer->curs = oldcurs;
    
    // select current layer button (also deselects old button)
    layerbarptr->SelectButton(currindex, true);
    
    if (tilelayers && numlayers > 1) {
        // switch to new tile
        viewptr = currlayer->tilewin;
        if (mainptr->infront) viewptr->SetFocus();
    }
    
    if (allowundo) {
        // update Undo/Redo items so they show the correct action
        currlayer->undoredo->UpdateUndoRedoItems();
    } else {
        // undo/redo is disabled so clear history;
        // this also removes action from Undo/Redo items
        currlayer->undoredo->ClearUndoRedo();
    }
    
    mainptr->SetStepExponent(currlayer->currexpo);
    // SetStepExponent calls SetGenIncrement
    mainptr->SetWindowTitle(currlayer->currname);
    
    mainptr->UpdateUserInterface();
    mainptr->UpdatePatternAndStatus();
    bigview->UpdateScrollBars();
}

// -----------------------------------------------------------------------------

void UpdateLayerNames()
{
    // update names in all layer items at end of Layer menu
    for (int i = 0; i < numlayers; i++)
        mainptr->UpdateLayerItem(i);
}

// -----------------------------------------------------------------------------

static wxBitmap** CopyIcons(wxBitmap** srcicons, int maxstate)
{
    wxBitmap** iconptr = (wxBitmap**) malloc(256 * sizeof(wxBitmap*));
    if (iconptr) {
        for (int i = 0; i < 256; i++) iconptr[i] = NULL;
        for (int i = 0; i <= maxstate; i++) {
            if (srcicons && srcicons[i]) {
                wxRect rect(0, 0, srcicons[i]->GetWidth(), srcicons[i]->GetHeight());
                iconptr[i] = new wxBitmap(srcicons[i]->GetSubBitmap(rect));
            }
        }
    }
    return iconptr;
}

// -----------------------------------------------------------------------------

static void CopyBuiltinIcons(wxBitmap** i7x7, wxBitmap** i15x15, wxBitmap** i31x31)
{
    int maxstate = currlayer->algo->NumCellStates() - 1;

    if (currlayer->icons7x7) FreeIconBitmaps(currlayer->icons7x7);
    if (currlayer->icons15x15) FreeIconBitmaps(currlayer->icons15x15);
    if (currlayer->icons31x31) FreeIconBitmaps(currlayer->icons31x31);

    currlayer->icons7x7 = CopyIcons(i7x7, maxstate);
    currlayer->icons15x15 = CopyIcons(i15x15, maxstate);
    currlayer->icons31x31 = CopyIcons(i31x31, maxstate);
}

// -----------------------------------------------------------------------------

static unsigned char* CreateIconAtlas(wxBitmap** srcicons, int iconsize)
{
    bool multicolor = currlayer->multicoloricons;
    
    unsigned char deadr = currlayer->cellr[0];
    unsigned char deadg = currlayer->cellg[0];
    unsigned char deadb = currlayer->cellb[0];
    if (swapcolors) {
        deadr = 255 - deadr;
        deadg = 255 - deadg;
        deadb = 255 - deadb;
    }

    // allocate enough memory for texture atlas to store RGBA pixels for a row of icons
    // (note that we use calloc so all alpha bytes are initially 0)
    int rowbytes = currlayer->numicons * iconsize * 4;
    unsigned char* atlasptr = (unsigned char*) calloc(rowbytes * iconsize, 1);
    
    if (atlasptr) {
        for (int state = 1; state <= currlayer->numicons; state++) {
            if (srcicons && srcicons[state]) {
                int wd = srcicons[state]->GetWidth();       // should be iconsize - 1
                int ht = srcicons[state]->GetHeight();      // ditto
                
                wxAlphaPixelData icondata(*srcicons[state]);
                if (icondata) {
                    wxAlphaPixelData::Iterator iconpxl(icondata);
                    
                    unsigned char liver = currlayer->cellr[state];
                    unsigned char liveg = currlayer->cellg[state];
                    unsigned char liveb = currlayer->cellb[state];
                    if (swapcolors) {
                        liver = 255 - liver;
                        liveg = 255 - liveg;
                        liveb = 255 - liveb;
                    }
                    
                    // start at top left byte of icon
                    int tpos = (state-1) * iconsize * 4;
                    for (int row = 0; row < ht; row++) {
                        wxAlphaPixelData::Iterator iconrow = iconpxl;
                        int rowstart = tpos;
                        for (int col = 0; col < wd; col++) {
                            unsigned char r = iconpxl.Red();
                            unsigned char g = iconpxl.Green();
                            unsigned char b = iconpxl.Blue();
                            if (r || g || b) {
                                // non-black pixel
                                if (multicolor) {
                                    // use non-black pixel in multi-colored icon
                                    if (swapcolors) {
                                        atlasptr[tpos]   = 255 - r;
                                        atlasptr[tpos+1] = 255 - g;
                                        atlasptr[tpos+2] = 255 - b;
                                    } else {
                                        atlasptr[tpos]   = r;
                                        atlasptr[tpos+1] = g;
                                        atlasptr[tpos+2] = b;
                                    }
                                } else {
                                    // grayscale icon (r = g = b)
                                    if (r == 255) {
                                        // replace white pixel with live cell color
                                        atlasptr[tpos]   = liver;
                                        atlasptr[tpos+1] = liveg;
                                        atlasptr[tpos+2] = liveb;
                                    } else {
                                        // replace gray pixel with appropriate shade between
                                        // live and dead cell colors
                                        float frac = (float)r / 255.0;
                                        atlasptr[tpos]   = (int)(deadr + frac * (liver - deadr) + 0.5);
                                        atlasptr[tpos+1] = (int)(deadg + frac * (liveg - deadg) + 0.5);
                                        atlasptr[tpos+2] = (int)(deadb + frac * (liveb - deadb) + 0.5);
                                    }
                                }
                                atlasptr[tpos+3] = 255;     // alpha channel is opaque
                            }
                            // move to next pixel
                            tpos += 4;
                            iconpxl++;
                        }
                        // move to next row
                        tpos = rowstart + rowbytes;
                        iconpxl = iconrow;
                        iconpxl.OffsetY(icondata, 1);
                    }
                }
            }
        }
    }
    return atlasptr;
}

// -----------------------------------------------------------------------------

Layer* CreateTemporaryLayer()
{
    Layer* templayer = new Layer();
    if (templayer == NULL) Warning(_("Failed to create temporary layer!"));
    return templayer;
}

// -----------------------------------------------------------------------------

void AddLayer()
{
    if (numlayers >= MAX_LAYERS) return;
    
    // we need to test mainptr here because AddLayer is called from main window's ctor
    if (mainptr && mainptr->generating) {
        mainptr->command_pending = true;
        mainptr->cmdevent.SetId(ID_ADD_LAYER);
        mainptr->Stop();
        return;
    }
    
    if (numlayers == 0) {
        // creating the very first layer
        currindex = 0;
    } else {
        if (tilelayers && numlayers > 1) DestroyTiles();
        
        SaveLayerSettings();
        
        // insert new layer after currindex
        currindex++;
        if (currindex < numlayers) {
            // shift right one or more layers
            for (int i = numlayers; i > currindex; i--)
                layer[i] = layer[i-1];
        }
    }
    
    Layer* oldlayer = NULL;
    if (cloning || duplicating) oldlayer = currlayer;
    
    currlayer = new Layer();
    if (currlayer == NULL) Fatal(_("Failed to create new layer!"));
    layer[currindex] = currlayer;
    
    if (cloning || duplicating) {
        // copy old layer's colors to new layer
        currlayer->fromrgb = oldlayer->fromrgb;
        currlayer->torgb = oldlayer->torgb;
        currlayer->multicoloricons = oldlayer->multicoloricons;
        currlayer->numicons = oldlayer->numicons;
        for (int n = 0; n <= currlayer->numicons; n++) {
            currlayer->cellr[n] = oldlayer->cellr[n];
            currlayer->cellg[n] = oldlayer->cellg[n];
            currlayer->cellb[n] = oldlayer->cellb[n];
        }
        if (cloning) {
            // use same icon pointers
            currlayer->icons7x7 = oldlayer->icons7x7;
            currlayer->icons15x15 = oldlayer->icons15x15;
            currlayer->icons31x31 = oldlayer->icons31x31;
            // use same atlas
            currlayer->atlas7x7 = oldlayer->atlas7x7;
            currlayer->atlas15x15 = oldlayer->atlas15x15;
            currlayer->atlas31x31 = oldlayer->atlas31x31;
        } else {
            // duplicate icons from old layer
            currlayer->icons7x7 = CopyIcons(oldlayer->icons7x7, currlayer->numicons);
            currlayer->icons15x15 = CopyIcons(oldlayer->icons15x15, currlayer->numicons);
            currlayer->icons31x31 = CopyIcons(oldlayer->icons31x31, currlayer->numicons);
            // create icon texture atlases
            currlayer->atlas7x7 = CreateIconAtlas(oldlayer->icons7x7, 8);
            currlayer->atlas15x15 = CreateIconAtlas(oldlayer->icons15x15, 16);
            currlayer->atlas31x31 = CreateIconAtlas(oldlayer->icons31x31, 32);
        }
    } else {
        // set new layer's colors+icons to default colors+icons for current algo+rule
        UpdateLayerColors();
    }
    
    numlayers++;
    
    if (numlayers > 1) {
        // add toggle button at end of layer bar
        layerbarptr->ResizeLayerButtons();
        togglebutt[numlayers-1]->Show(true);
        
        // add another item at end of Layer menu
        mainptr->AppendLayerItem();
        
        UpdateLayerNames();
        
        if (tilelayers && numlayers > 1) CreateTiles();
        
        CurrentLayerChanged();
    }
}

// -----------------------------------------------------------------------------

void CloneLayer()
{
    if (numlayers >= MAX_LAYERS) return;
    
    if (mainptr->generating) {
        mainptr->command_pending = true;
        mainptr->cmdevent.SetId(ID_CLONE);
        mainptr->Stop();
        return;
    }
    
    cloning = true;
    AddLayer();
    cloning = false;
}

// -----------------------------------------------------------------------------

void DuplicateLayer()
{
    if (numlayers >= MAX_LAYERS) return;
    
    if (mainptr->generating) {
        mainptr->command_pending = true;
        mainptr->cmdevent.SetId(ID_DUPLICATE);
        mainptr->Stop();
        return;
    }
    
    duplicating = true;
    AddLayer();
    duplicating = false;
}

// -----------------------------------------------------------------------------

void DeleteLayer()
{
    if (numlayers <= 1) return;
    
    if (mainptr->generating) {
        mainptr->command_pending = true;
        mainptr->cmdevent.SetId(ID_DEL_LAYER);
        mainptr->Stop();
        return;
    }
    
    // note that we don't need to ask to delete a clone
    if (askondelete && currlayer->dirty && currlayer->cloneid == 0 && !mainptr->SaveCurrentLayer()) return;
    
    // numlayers > 1
    if (tilelayers) DestroyTiles();
    
    SaveLayerSettings();
    
    delete currlayer;
    numlayers--;
    
    if (currindex < numlayers) {
        // shift left one or more layers
        for (int i = currindex; i < numlayers; i++)
            layer[i] = layer[i+1];
    }
    if (currindex > 0) currindex--;
    currlayer = layer[currindex];
    
    // remove toggle button at end of layer bar
    togglebutt[numlayers]->Show(false);
    layerbarptr->ResizeLayerButtons();
    
    // remove item from end of Layer menu
    mainptr->RemoveLayerItem();
    
    UpdateLayerNames();
    
    if (tilelayers && numlayers > 1) CreateTiles();
    
    CurrentLayerChanged();
}

// -----------------------------------------------------------------------------

void DeleteOtherLayers()
{
    if (inscript || numlayers <= 1) return;
    
    if (askondelete) {
        // keep track of which unique clones have been seen;
        // we add 1 below to allow for cloneseen[0] (always false)
        const int maxseen = MAX_LAYERS/2 + 1;
        bool cloneseen[maxseen];
        for (int i = 0; i < maxseen; i++) cloneseen[i] = false;
        
        // for each dirty layer, except current layer and all of its clones,
        // ask user if they want to save changes
        int cid = layer[currindex]->cloneid;
        if (cid > 0) cloneseen[cid] = true;
        int oldindex = currindex;
        for (int i = 0; i < numlayers; i++) {
            // only ask once for each unique clone (cloneid == 0 for non-clone)
            cid = layer[i]->cloneid;
            if (i != oldindex && !cloneseen[cid]) {
                if (cid > 0) cloneseen[cid] = true;
                if (layer[i]->dirty) {
                    // temporarily turn off generating flag for SetLayer
                    bool oldgen = mainptr->generating;
                    mainptr->generating = false;
                    SetLayer(i);
                    if (!mainptr->SaveCurrentLayer()) {
                        // user hit Cancel so restore current layer and generating flag
                        SetLayer(oldindex);
                        mainptr->generating = oldgen;
                        mainptr->UpdateUserInterface();
                        return;
                    }
                    SetLayer(oldindex);
                    mainptr->generating = oldgen;
                }
            }
        }
    }
    
    // numlayers > 1
    if (tilelayers) DestroyTiles();
    
    SyncClones();
    
    // delete all layers except current layer;
    // we need to do this carefully because ~Layer() requires numlayers
    // and the layer array to be correct when deleting a cloned layer
    int i = numlayers;
    while (numlayers > 1) {
        i--;
        if (i != currindex) {
            delete layer[i];     // ~Layer() is called
            numlayers--;
            
            // may need to shift the current layer left one place
            if (i < numlayers) layer[i] = layer[i+1];
            
            // remove toggle button at end of layer bar
            togglebutt[numlayers]->Show(false);
            
            // remove item from end of Layer menu
            mainptr->RemoveLayerItem();
        }
    }
    
    layerbarptr->ResizeLayerButtons();
    
    currindex = 0;
    // currlayer doesn't change
    
    // update the only layer item
    mainptr->UpdateLayerItem(0);
    
    // update window title (may need to remove "=" prefix)
    mainptr->SetWindowTitle(wxEmptyString);
    
    // select LAYER_0 button (also deselects old button)
    layerbarptr->SelectButton(LAYER_0, true);
    
    mainptr->UpdateMenuItems();
    mainptr->UpdatePatternAndStatus();
}

// -----------------------------------------------------------------------------

void SetLayer(int index)
{
    if (currindex == index) return;
    if (index < 0 || index >= numlayers) return;
    
    if (inscript) {
        // always allow a script to switch layers
    } else if (mainptr->generating) {
        mainptr->command_pending = true;
        mainptr->cmdevent.SetId(ID_LAYER0 + index);
        mainptr->Stop();
        return;
    }
    
    SaveLayerSettings();
    currindex = index;
    currlayer = layer[currindex];
    CurrentLayerChanged();
}

// -----------------------------------------------------------------------------

bool CanSwitchLayer(int WXUNUSED(index))
{
    if (inscript) {
        // user can only switch layers if script has set the appropriate option
        return canswitch;
    } else {
        // user can switch to any layer
        return true;
    }
}

// -----------------------------------------------------------------------------

void SwitchToClickedTile(int index)
{
    if (inscript && !CanSwitchLayer(index)) {
        // statusptr->ErrorMessage does nothing if inscript is true
        Warning(_("You cannot switch to another layer while this script is running."));
        return;
    }
    
    // switch current layer to clicked tile
    SetLayer(index);
    
    if (inscript) {
        // update window title, viewport and status bar
        inscript = false;
        mainptr->SetWindowTitle(wxEmptyString);
        mainptr->UpdatePatternAndStatus();
        inscript = true;
    }
}

// -----------------------------------------------------------------------------

void MoveLayer(int fromindex, int toindex)
{
    if (fromindex == toindex) return;
    if (fromindex < 0 || fromindex >= numlayers) return;
    if (toindex < 0 || toindex >= numlayers) return;
    
    SaveLayerSettings();
    
    if (fromindex > toindex) {
        Layer* savelayer = layer[fromindex];
        for (int i = fromindex; i > toindex; i--) layer[i] = layer[i - 1];
        layer[toindex] = savelayer;
    } else {
        // fromindex < toindex
        Layer* savelayer = layer[fromindex];
        for (int i = fromindex; i < toindex; i++) layer[i] = layer[i + 1];
        layer[toindex] = savelayer;
    }
    
    currindex = toindex;
    currlayer = layer[currindex];
    
    UpdateLayerNames();
    
    if (tilelayers && numlayers > 1) {
        DestroyTiles();
        CreateTiles();
    }
    
    CurrentLayerChanged();
}

// -----------------------------------------------------------------------------

void MoveLayerDialog()
{
    if (inscript || numlayers <= 1) return;
    
    if (mainptr->generating) {
        mainptr->command_pending = true;
        mainptr->cmdevent.SetId(ID_MOVE_LAYER);
        mainptr->Stop();
        return;
    }
    
    wxString msg = _("Move the current layer to a new position:");
    if (currindex > 0) {
        msg += _("\n(enter 0 to make it the first layer)");
    }
    
    int newindex;
    if ( GetInteger(_("Move Layer"), msg,
                    currindex, 0, numlayers - 1, &newindex) ) {
        MoveLayer(currindex, newindex);
    }
}

// -----------------------------------------------------------------------------

void NameLayerDialog()
{
    if (inscript) return;
    
    if (mainptr->generating) {
        mainptr->command_pending = true;
        mainptr->cmdevent.SetId(ID_NAME_LAYER);
        mainptr->Stop();
        return;
    }
    
    wxString oldname = currlayer->currname;
    wxString newname;
    if ( GetString(_("Name Layer"), _("Enter a new name for the current layer:"), oldname, newname) &&
        !newname.IsEmpty() && oldname != newname ) {
        
        // inscript is false so no need to call SavePendingChanges
        // if (allowundo) SavePendingChanges();
        
        // show new name in main window's title bar;
        // also sets currlayer->currname and updates menu item
        mainptr->SetWindowTitle(newname);
        
        if (allowundo) {
            // note that currfile and savestart/dirty flags don't change here
            currlayer->undoredo->RememberNameChange(oldname, currlayer->currfile,
                                                    currlayer->savestart, currlayer->dirty);
        }
    }
}

// -----------------------------------------------------------------------------

void MarkLayerDirty()
{
    // need to save starting pattern
    currlayer->savestart = true;
    
    // if script has reset dirty flag then don't change it; this makes sense
    // for scripts that call new() and then construct a pattern
    if (currlayer->stayclean) return;
    
    if (!currlayer->dirty) {
        currlayer->dirty = true;
        
        // pass in currname so UpdateLayerItem(currindex) gets called
        mainptr->SetWindowTitle(currlayer->currname);
        
        if (currlayer->cloneid > 0) {
            // synchronize other clones
            for ( int i = 0; i < numlayers; i++ ) {
                Layer* cloneptr = layer[i];
                if (cloneptr != currlayer && cloneptr->cloneid == currlayer->cloneid) {
                    // set dirty flag and display asterisk in layer item
                    cloneptr->dirty = true;
                    mainptr->UpdateLayerItem(i);
                }
            }
        }
    }
}

// -----------------------------------------------------------------------------

void MarkLayerClean(const wxString& title)
{
    currlayer->dirty = false;
    
    // if script is resetting dirty flag -- eg. via new() -- then don't allow
    // dirty flag to be set true for the remainder of the script; this is
    // nicer for scripts that construct a pattern (ie. running such a script
    // is equivalent to loading a pattern file)
    if (inscript) currlayer->stayclean = true;
    
    if (title.IsEmpty()) {
        // pass in currname so UpdateLayerItem(currindex) gets called
        mainptr->SetWindowTitle(currlayer->currname);
    } else {
        // set currlayer->currname to title and call UpdateLayerItem(currindex)
        mainptr->SetWindowTitle(title);
    }
    
    if (currlayer->cloneid > 0) {
        // synchronize other clones
        for ( int i = 0; i < numlayers; i++ ) {
            Layer* cloneptr = layer[i];
            if (cloneptr != currlayer && cloneptr->cloneid == currlayer->cloneid) {
                // reset dirty flag
                cloneptr->dirty = false;
                if (inscript) cloneptr->stayclean = true;
                
                // always allow clones to have different names
                // cloneptr->currname = currlayer->currname;
                
                // remove asterisk from layer item
                mainptr->UpdateLayerItem(i);
            }
        }
    }
}

// -----------------------------------------------------------------------------

void ToggleSyncViews()
{
    syncviews = !syncviews;
    
    mainptr->UpdateUserInterface();
    mainptr->UpdatePatternAndStatus();
}

// -----------------------------------------------------------------------------

void ToggleSyncCursors()
{
    synccursors = !synccursors;
    
    mainptr->UpdateUserInterface();
    mainptr->UpdatePatternAndStatus();
}

// -----------------------------------------------------------------------------

void ToggleStackLayers()
{
    stacklayers = !stacklayers;
    if (stacklayers && tilelayers) {
        tilelayers = false;
        layerbarptr->SelectButton(TILE_LAYERS, false);
        if (numlayers > 1) DestroyTiles();
    }
    layerbarptr->SelectButton(STACK_LAYERS, stacklayers);
    
    mainptr->UpdateUserInterface();
    if (inscript) {
        // always update viewport and status bar
        inscript = false;
        mainptr->UpdatePatternAndStatus();
        inscript = true;
    } else {
        mainptr->UpdatePatternAndStatus();
    }
}

// -----------------------------------------------------------------------------

void ToggleTileLayers()
{
    tilelayers = !tilelayers;
    if (tilelayers && stacklayers) {
        stacklayers = false;
        layerbarptr->SelectButton(STACK_LAYERS, false);
    }
    layerbarptr->SelectButton(TILE_LAYERS, tilelayers);
    
    if (tilelayers) {
        if (numlayers > 1) CreateTiles();
    } else {
        if (numlayers > 1) DestroyTiles();
    }
    
    mainptr->UpdateUserInterface();
    if (inscript) {
        // always update viewport and status bar
        inscript = false;
        mainptr->UpdatePatternAndStatus();
        inscript = true;
    } else {
        mainptr->UpdatePatternAndStatus();
    }
}

// -----------------------------------------------------------------------------

void CreateColorGradient()
{
    int maxstate = currlayer->algo->NumCellStates() - 1;
    unsigned char r1 = currlayer->fromrgb.Red();
    unsigned char g1 = currlayer->fromrgb.Green();
    unsigned char b1 = currlayer->fromrgb.Blue();
    unsigned char r2 = currlayer->torgb.Red();
    unsigned char g2 = currlayer->torgb.Green();
    unsigned char b2 = currlayer->torgb.Blue();
    
    // set cell colors for states 1..maxstate using a color gradient
    // starting with r1,g1,b1 and ending with r2,g2,b2
    currlayer->cellr[1] = r1;
    currlayer->cellg[1] = g1;
    currlayer->cellb[1] = b1;
    if (maxstate > 2) {
        int N = maxstate - 1;
        double rfrac = (double)(r2 - r1) / (double)N;
        double gfrac = (double)(g2 - g1) / (double)N;
        double bfrac = (double)(b2 - b1) / (double)N;
        for (int n = 1; n < N; n++) {
            currlayer->cellr[n+1] = (int)(r1 + n * rfrac + 0.5);
            currlayer->cellg[n+1] = (int)(g1 + n * gfrac + 0.5);
            currlayer->cellb[n+1] = (int)(b1 + n * bfrac + 0.5);
        }
    }
    if (maxstate > 1) {
        currlayer->cellr[maxstate] = r2;
        currlayer->cellg[maxstate] = g2;
        currlayer->cellb[maxstate] = b2;
    }
}

// -----------------------------------------------------------------------------

static FILE* FindRuleFile(const wxString& rulename)
{
    const wxString extn = wxT(".rule");
    wxString path;
    
    // first look for rulename.rule in userrules
    path = userrules + rulename;
    path += extn;
    FILE* f = OPENFILE(path);
    if (f) return f;
    
    // now look for rulename.rule in rulesdir
    path = rulesdir + rulename;
    path += extn;
    return OPENFILE(path);
}

// -----------------------------------------------------------------------------

static void CheckRuleHeader(char* linebuf, const wxString& rulename)
{
    // check that 1st line of rulename.rule file contains "@RULE rulename"
    // where rulename must match the file name exactly (to avoid problems on
    // case-sensitive file systems)
    if (strncmp(linebuf, "@RULE ", 6) != 0) {
        wxString msg = _("The first line in ");
        msg += rulename;
        msg += _(".rule does not start with @RULE.");
        Warning(msg);
    } else if (strcmp(linebuf+6, (const char*)rulename.mb_str(wxConvLocal)) != 0) {
        wxString ruleinfile = wxString(linebuf+6, wxConvLocal);
        wxString msg = _("The specified rule (");
        msg += rulename;
        msg += _(") does not match the rule name in the .rule file (");
        msg += ruleinfile;
        msg += _(").\n\nThis will cause problems if you save or copy patterns");
        msg += _(" and try to use them on a case-sensitive file system.");
        Warning(msg);
    }
}

// -----------------------------------------------------------------------------

static void ParseColors(linereader& reader, char* linebuf, int MAXLINELEN,
                        int* linenum, bool* eof)
{
    // parse @COLORS section in currently open .rule file
    int state, r, g, b, r1, g1, b1, r2, g2, b2;
    int maxstate = currlayer->algo->NumCellStates() - 1;
    
    while (reader.fgets(linebuf, MAXLINELEN) != 0) {
        *linenum = *linenum + 1;
        if (linebuf[0] == '#' || linebuf[0] == 0) {
            // skip comment or empty line
        } else if (sscanf(linebuf, "%d%d%d%d%d%d", &r1, &g1, &b1, &r2, &g2, &b2) == 6) {
            // assume line is like this:
            // 255 0 0 0 0 255    use a gradient from red to blue
            currlayer->fromrgb.Set(r1, g1, b1);
            currlayer->torgb.Set(r2, g2, b2);
            CreateColorGradient();
        } else if (sscanf(linebuf, "%d%d%d%d", &state, &r, &g, &b) == 4) {
            // assume line is like this:
            // 1 0 128 255        state 1 is light blue
            if (state >= 0 && state <= maxstate) {
                currlayer->cellr[state] = r;
                currlayer->cellg[state] = g;
                currlayer->cellb[state] = b;
            }
        } else if (linebuf[0] == '@') {
            // found next section, so stop parsing
            *eof = false;
            return;
        }
        // ignore unexpected syntax (better for upward compatibility)
    }
    *eof = true;
}

// -----------------------------------------------------------------------------

static void DeleteXPMData(char** xpmdata, int numstrings)
{
    if (xpmdata) {
        for (int i = 0; i < numstrings; i++)
            if (xpmdata[i]) free(xpmdata[i]);
        free(xpmdata);
    }
}

// -----------------------------------------------------------------------------

static void CreateIcons(const char** xpmdata, int size)
{
    int maxstates = currlayer->algo->NumCellStates();
    
    // we only need to call FreeIconBitmaps if .rule file has duplicate XPM data
    // (unlikely but best to play it safe)
    if (size == 7) {
        if (currlayer->icons7x7) FreeIconBitmaps(currlayer->icons7x7);
        currlayer->icons7x7 = CreateIconBitmaps(xpmdata, maxstates);

    } else if (size == 15) {
        if (currlayer->icons15x15) FreeIconBitmaps(currlayer->icons15x15);
        currlayer->icons15x15 = CreateIconBitmaps(xpmdata, maxstates);

    } else if (size == 31) {
        if (currlayer->icons31x31) FreeIconBitmaps(currlayer->icons31x31);
        currlayer->icons31x31 = CreateIconBitmaps(xpmdata, maxstates);
    }
}

// -----------------------------------------------------------------------------

static void ParseIcons(const wxString& rulename, linereader& reader, char* linebuf, int MAXLINELEN,
                       int* linenum, bool* eof)
{
    // parse @ICONS section in currently open .rule file
    char** xpmdata = NULL;
    int xpmstarted = 0, xpmstrings = 0, maxstrings = 0;
    int wd = 0, ht = 0, numcolors = 0, chars_per_pixel = 0;
    
    std::map<std::string,int> colormap;

    while (true) {
        if (reader.fgets(linebuf, MAXLINELEN) == 0) {
            *eof = true;
            break;
        }
        *linenum = *linenum + 1;
        if (linebuf[0] == '#' || linebuf[0] == '/' || linebuf[0] == 0) {
            // skip comment or empty line
        } else if (linebuf[0] == '"') {
            if (xpmstarted) {
                // we have a "..." string containing XPM data
                if (xpmstrings == 0) {
                    if (sscanf(linebuf, "\"%d%d%d%d\"", &wd, &ht, &numcolors, &chars_per_pixel) == 4 &&
                        wd > 0 && ht > 0 && numcolors > 0 && chars_per_pixel > 0 && ht % wd == 0) {
                        if (wd != 7 && wd != 15 && wd != 31) {
                            // this version of Golly doesn't support the supplied icon size
                            // so silently ignore the rest of this XPM data
                            xpmstarted = 0;
                            continue;
                        }
                        maxstrings = 1 + numcolors + ht;
                        // create and initialize xpmdata
                        xpmdata = (char**) malloc(maxstrings * sizeof(char*));
                        if (xpmdata) {
                            for (int i = 0; i < maxstrings; i++) xpmdata[i] = NULL;
                        } else {
                            Warning(_("Failed to allocate memory for XPM icon data!"));
                            *eof = true;
                            return;
                        }
                    } else {
                        wxString msg;
                        msg.Printf(_("The XPM header string on line %d in "), *linenum);
                        msg += rulename;
                        msg += _(".rule is incorrect");
                        if (wd > 0 && ht > 0 && ht % wd != 0)
                            msg += _(" (height must be a multiple of width).");
                        else if (chars_per_pixel < 1 || chars_per_pixel > 2)
                            msg += _(" (chars_per_pixel must be 1 or 2).");
                        else
                            msg += _(" (4 positive integers are required).");
                        Warning(msg);
                        *eof = true;
                        return;
                    }
                }
                
                // copy data inside "..." to next string in xpmdata
                int len = strlen(linebuf);
                while (linebuf[len] != '"') len--;
                len--;
                if (xpmstrings > 0 && xpmstrings <= numcolors) {
                    // build colormap so we can validate chars in pixel data
                    std::string pixel;
                    char ch1, ch2, ch3;
                    bool badline = false;
                    if (chars_per_pixel == 1) {
                        badline = sscanf(linebuf+1, "%c%c", &ch1, &ch2) != 2 || ch2 != ' ';
                        pixel += ch1;
                    } else {
                        badline = sscanf(linebuf+1, "%c%c%c", &ch1, &ch2, &ch3) != 3 || ch3 != ' ';
                        pixel += ch1;
                        pixel += ch2;
                    }
                    if (badline) {
                        DeleteXPMData(xpmdata, maxstrings);
                        wxString msg;
                        msg.Printf(_("The XPM color info on line %d in "), *linenum);
                        msg += rulename;
                        msg += _(".rule is incorrect.");
                        Warning(msg);
                        *eof = true;
                        return;
                    }
                    colormap[pixel] = xpmstrings;
                } else if (xpmstrings > numcolors) {
                    // check length of string containing pixel data
                    if (len != wd * chars_per_pixel) {
                        DeleteXPMData(xpmdata, maxstrings);
                        wxString msg;
                        msg.Printf(_("The XPM data string on line %d in "), *linenum);
                        msg += rulename;
                        msg += _(".rule has the wrong length.");
                        Warning(msg);
                        *eof = true;
                        return;
                    }
                    // now check that chars in pixel data are valid (ie. in colormap)
                    for (int i = 1; i <= len; i += chars_per_pixel) {
                        std::string pixel;
                        pixel += linebuf[i];
                        if (chars_per_pixel > 1)
                            pixel += linebuf[i+1];
                        if (colormap.find(pixel) == colormap.end()) {
                            DeleteXPMData(xpmdata, maxstrings);
                            wxString msg;
                            msg.Printf(_("The XPM data string on line %d in "), *linenum);
                            msg += rulename;
                            msg += _(".rule has an unknown pixel: ");
                            msg += wxString(pixel.c_str(), wxConvLocal);
                            Warning(msg);
                            *eof = true;
                            return;
                        }
                    }
                }
                char* str = (char*) malloc(len+1);
                if (str) {
                    strncpy(str, linebuf+1, len);
                    str[len] = 0;
                    xpmdata[xpmstrings] = str;
                } else {
                    DeleteXPMData(xpmdata, maxstrings);
                    Warning(_("Failed to allocate memory for XPM string!"));
                    *eof = true;
                    return;
                }
                
                xpmstrings++;
                if (xpmstrings == maxstrings) {
                    // we've got all the data for this icon size
                    CreateIcons((const char**)xpmdata, wd);
                    DeleteXPMData(xpmdata, maxstrings);
                    xpmdata = NULL;
                    xpmstarted = 0;
                    colormap.clear();
                }
            }
        } else if (strcmp(linebuf, "XPM") == 0) {
            // start parsing XPM data on following lines
            if (xpmstarted) break;  // handle error below
            xpmstarted = *linenum;
            xpmstrings = 0;
        } else if (strcmp(linebuf, "circles") == 0) {
            // use circular icons
            CopyBuiltinIcons(circles7x7, circles15x15, circles31x31);
        } else if (strcmp(linebuf, "diamonds") == 0) {
            // use diamond-shaped icons
            CopyBuiltinIcons(diamonds7x7, diamonds15x15, diamonds31x31);
        } else if (strcmp(linebuf, "hexagons") == 0) {
            // use hexagonal icons
            CopyBuiltinIcons(hexagons7x7, hexagons15x15, hexagons31x31);
        } else if (strcmp(linebuf, "triangles") == 0) {
            // use triangular icons
            if (currlayer->algo->NumCellStates() != 4) {
                wxString msg;
                msg.Printf(_("The triangular icons specified on line %d in "), *linenum);
                msg += rulename;
                msg += _(".rule can only be used with a 4-state rule.");
                Warning(msg);
                // don't return 
            } else {
                CopyBuiltinIcons(triangles7x7, triangles15x15, triangles31x31);
            }
        } else if (linebuf[0] == '@') {
            // found next section, so stop parsing
            *eof = false;
            break;
        }
        // ignore unexpected syntax (better for upward compatibility)
    }
    
    if (xpmstarted) {
        // XPM data was incomplete
        DeleteXPMData(xpmdata, maxstrings);
        wxString msg;
        msg.Printf(_("The XPM icon data starting on line %d in "), xpmstarted);
        msg += rulename;
        msg += _(".rule does not have enough strings.");
        Warning(msg);
        *eof = true;
        return;
    }
    
    // create scaled bitmaps if size(s) not supplied
    if (!currlayer->icons7x7) {
        if (currlayer->icons15x15) {
            // scale down 15x15 bitmaps
            currlayer->icons7x7 = ScaleIconBitmaps(currlayer->icons15x15, 7);
        } else if (currlayer->icons31x31) {
            // scale down 31x31 bitmaps
            currlayer->icons7x7 = ScaleIconBitmaps(currlayer->icons31x31, 7);
        }
    }
    if (!currlayer->icons15x15) {
        if (currlayer->icons31x31) {
            // scale down 31x31 bitmaps
            currlayer->icons15x15 = ScaleIconBitmaps(currlayer->icons31x31, 15);
        } else if (currlayer->icons7x7) {
            // scale up 7x7 bitmaps
            currlayer->icons15x15 = ScaleIconBitmaps(currlayer->icons7x7, 15);
        }
    }
    if (!currlayer->icons31x31) {
        if (currlayer->icons15x15) {
            // scale up 15x15 bitmaps
            currlayer->icons31x31 = ScaleIconBitmaps(currlayer->icons15x15, 31);
        } else if (currlayer->icons7x7) {
            // scale up 7x7 bitmaps
            currlayer->icons31x31 = ScaleIconBitmaps(currlayer->icons7x7, 31);
        }
    }
}

// -----------------------------------------------------------------------------

static void LoadRuleInfo(FILE* rulefile, const wxString& rulename,
                         bool* loadedcolors, bool* loadedicons)
{
    // load any color and/or icon info from the currently open .rule file
    const int MAXLINELEN = 4095;
    char linebuf[MAXLINELEN + 1];
    int linenum = 0;
    bool eof = false;
    bool skipget = false;

    // the linereader class handles all line endings (CR, CR+LF, LF)
    linereader reader(rulefile);
    
    while (true) {
        if (skipget) {
            // ParseColors/ParseIcons has stopped at next section
            // (ie. linebuf contains @...) so skip fgets call
            skipget = false;
        } else {
            if (reader.fgets(linebuf, MAXLINELEN) == 0) break;
            linenum++;
            if (linenum == 1) CheckRuleHeader(linebuf, rulename);
        }
        // look for @COLORS or @ICONS section
        if (strcmp(linebuf, "@COLORS") == 0 && !*loadedcolors) {
            *loadedcolors = true;
            ParseColors(reader, linebuf, MAXLINELEN, &linenum, &eof);
            if (eof) break;
            // otherwise linebuf contains @... so skip next fgets call
            skipget = true;
        } else if (strcmp(linebuf, "@ICONS") == 0 && !*loadedicons) {
            *loadedicons = true;
            ParseIcons(rulename, reader, linebuf, MAXLINELEN, &linenum, &eof);
            if (eof) break;
            // otherwise linebuf contains @... so skip next fgets call
            skipget = true;
        }
    }
    
    reader.close();     // closes rulefile
}

// -----------------------------------------------------------------------------

static FILE* FindColorFile(const wxString& rule, const wxString& dir)
{
    const wxString extn = wxT(".colors");
    wxString path;
    
    // first look for rule.colors in given directory
    path = dir + rule;
    path += extn;
    FILE* f = OPENFILE(path);
    if (f) return f;
    
    // if rule has the form foo-* then look for foo.colors in dir;
    // this allows related rules to share a single .colors file
    wxString prefix = rule.BeforeLast('-');
    if (!prefix.IsEmpty()) {
        path = dir + prefix;
        path += extn;
        f = OPENFILE(path);
        if (f) return f;
    }
    
    return NULL;
}

// -----------------------------------------------------------------------------

static bool LoadRuleColors(const wxString& rule, int maxstate)
{
    // if rule.colors file exists in userrules or rulesdir then
    // change colors according to info in file
    FILE* f = FindColorFile(rule, userrules);
    if (!f) f = FindColorFile(rule, rulesdir);
    if (f) {
        // the linereader class handles all line endings (CR, CR+LF, LF)
        linereader reader(f);
        // not needed here, but useful if we ever return early due to error
        // reader.setcloseonfree();
        const int MAXLINELEN = 512;
        char buf[MAXLINELEN + 1];
        while (reader.fgets(buf, MAXLINELEN) != 0) {
            if (buf[0] == '#' || buf[0] == 0) {
                // skip comment or empty line
            } else {
                // look for "color" or "gradient" keyword at start of line
                char* keyword = buf;
                char* value;
                while (*keyword == ' ') keyword++;
                value = keyword;
                while (*value >= 'a' && *value <= 'z') value++;
                while (*value == ' ' || *value == '=') value++;
                if (strncmp(keyword, "color", 5) == 0) {
                    int state, r, g, b;
                    if (sscanf(value, "%d%d%d%d", &state, &r, &g, &b) == 4) {
                        if (state >= 0 && state <= maxstate) {
                            currlayer->cellr[state] = r;
                            currlayer->cellg[state] = g;
                            currlayer->cellb[state] = b;
                        }
                    };
                } else if (strncmp(keyword, "gradient", 8) == 0) {
                    int r1, g1, b1, r2, g2, b2;
                    if (sscanf(value, "%d%d%d%d%d%d", &r1, &g1, &b1, &r2, &g2, &b2) == 6) {
                        currlayer->fromrgb.Set(r1, g1, b1);
                        currlayer->torgb.Set(r2, g2, b2);
                        CreateColorGradient();
                    };
                }
            }
        }
        reader.close();
        return true;
    }
    return false;
}

// -----------------------------------------------------------------------------

static void DeleteIcons(Layer* layer)
{
    // delete given layer's existing icons
    if (layer->icons7x7) {
        for (int i = 0; i < 256; i++) delete layer->icons7x7[i];
        free(layer->icons7x7);
        layer->icons7x7 = NULL;
    }
    if (layer->icons15x15) {
        for (int i = 0; i < 256; i++) delete layer->icons15x15[i];
        free(layer->icons15x15);
        layer->icons15x15 = NULL;
    }
    if (layer->icons31x31) {
        for (int i = 0; i < 256; i++) delete layer->icons31x31[i];
        free(layer->icons31x31);
        layer->icons31x31 = NULL;
    }

    // also delete icon texture atlases
    if (layer->atlas7x7) {
        free(layer->atlas7x7);
        layer->atlas7x7 = NULL;
    }
    if (layer->atlas15x15) {
        free(layer->atlas15x15);
        layer->atlas15x15 = NULL;
    }
    if (layer->atlas31x31) {
        free(layer->atlas31x31);
        layer->atlas31x31 = NULL;
    }
}

// -----------------------------------------------------------------------------

static bool FindIconFile(const wxString& rule, const wxString& dir, wxString& path)
{
    const wxString extn = wxT(".icons");
    
    // first look for rule.icons in given directory
    path = dir + rule;
    path += extn;
    if (wxFileName::FileExists(path)) return true;
    
    // if rule has the form foo-* then look for foo.icons in dir;
    // this allows related rules to share a single .icons file
    wxString prefix = rule.BeforeLast('-');
    if (!prefix.IsEmpty()) {
        path = dir + prefix;
        path += extn;
        if (wxFileName::FileExists(path)) return true;
    }
    
    return false;
}

// -----------------------------------------------------------------------------

static bool LoadRuleIcons(const wxString& rule, int maxstate)
{
    // if rule.icons file exists in userrules or rulesdir then
    // load icons for current layer
    wxString path;
    return (FindIconFile(rule, userrules, path) ||
            FindIconFile(rule, rulesdir, path)) &&
            LoadIconFile(path, maxstate, &currlayer->icons7x7,
                                         &currlayer->icons15x15,
                                         &currlayer->icons31x31);
}

// -----------------------------------------------------------------------------

static void UseDefaultIcons(int maxstate)
{
    // icons weren't specified so use default icons
    if (currlayer->algo->getgridtype() == lifealgo::HEX_GRID) {
        // use hexagonal icons
        currlayer->icons7x7 = CopyIcons(hexagons7x7, maxstate);
        currlayer->icons15x15 = CopyIcons(hexagons15x15, maxstate);
        currlayer->icons31x31 = CopyIcons(hexagons31x31, maxstate);
    } else if (currlayer->algo->getgridtype() == lifealgo::VN_GRID) {
        // use diamond-shaped icons for 4-neighbor von Neumann neighborhood
        currlayer->icons7x7 = CopyIcons(diamonds7x7, maxstate);
        currlayer->icons15x15 = CopyIcons(diamonds15x15, maxstate);
        currlayer->icons31x31 = CopyIcons(diamonds31x31, maxstate);
    } else {
        // otherwise use default icons from current algo
        AlgoData* ad = algoinfo[currlayer->algtype];
        currlayer->icons7x7 = CopyIcons(ad->icons7x7, maxstate);
        currlayer->icons15x15 = CopyIcons(ad->icons15x15, maxstate);
        currlayer->icons31x31 = CopyIcons(ad->icons31x31, maxstate);
    }
}

// -----------------------------------------------------------------------------

static bool MultiColorBitmaps(wxBitmap** iconmaps, int maxstate)
{
    // return true if any icon contains at least one color that isn't a shade of gray
    for (int n = 1; n <= maxstate; n++) {
        wxBitmap* icon = iconmaps[n];
        if (icon) {
            int wd = icon->GetWidth();
            int ht = icon->GetHeight();
            wxAlphaPixelData icondata(*icon);
            if (icondata) {
                wxAlphaPixelData::Iterator iconpxl(icondata);
                for (int i = 0; i < ht; i++) {
                    wxAlphaPixelData::Iterator iconrow = iconpxl;
                    for (int j = 0; j < wd; j++) {
                        unsigned char r = iconpxl.Red();
                        unsigned char g = iconpxl.Green();
                        unsigned char b = iconpxl.Blue();
                        if (r != g || g != b) return true;
                        iconpxl++;
                    }
                    // move to next row
                    iconpxl = iconrow;
                    iconpxl.OffsetY(icondata, 1);
                }
            }
        }
    }
    return false;   // all icons are grayscale
}

// -----------------------------------------------------------------------------

static void SetAverageColor(int state, wxBitmap* icon)
{
    // set non-icon color to average color of non-black pixels in given icon
    if (icon) {
        int wd = icon->GetWidth();
        int ht = icon->GetHeight();
        
        wxAlphaPixelData icondata(*icon);
        if (icondata) {
            wxAlphaPixelData::Iterator iconpxl(icondata);
            
            int nbcount = 0;  // # of non-black pixels
            int totalr = 0;
            int totalg = 0;
            int totalb = 0;
            
            for (int i = 0; i < ht; i++) {
                wxAlphaPixelData::Iterator iconrow = iconpxl;
                for (int j = 0; j < wd; j++) {
                    if (iconpxl.Red() || iconpxl.Green() || iconpxl.Blue()) {
                        // non-black pixel
                        totalr += iconpxl.Red();
                        totalg += iconpxl.Green();
                        totalb += iconpxl.Blue();
                        nbcount++;
                    }
                    iconpxl++;
                }
                // move to next row of icon bitmap
                iconpxl = iconrow;
                iconpxl.OffsetY(icondata, 1);
            }
            
            if (nbcount>0) {
                currlayer->cellr[state] = int(totalr / nbcount);
                currlayer->cellg[state] = int(totalg / nbcount);
                currlayer->cellb[state] = int(totalb / nbcount);
            }
            else { // avoid div0
                currlayer->cellr[state] = 0;
                currlayer->cellg[state] = 0;
                currlayer->cellb[state] = 0;
            }
        }
    }
}

// -----------------------------------------------------------------------------

void UpdateCurrentColors()
{
    // set current layer's colors and icons according to current algo and rule
    AlgoData* ad = algoinfo[currlayer->algtype];
    int maxstate = currlayer->algo->NumCellStates() - 1;
    
    // copy default colors from current algo
    currlayer->fromrgb = ad->fromrgb;
    currlayer->torgb = ad->torgb;
    if (ad->gradient) {
        CreateColorGradient();
        // state 0 is not part of the gradient
        currlayer->cellr[0] = ad->algor[0];
        currlayer->cellg[0] = ad->algog[0];
        currlayer->cellb[0] = ad->algob[0];
    } else {
        for (int n = 0; n <= maxstate; n++) {
            currlayer->cellr[n] = ad->algor[n];
            currlayer->cellg[n] = ad->algog[n];
            currlayer->cellb[n] = ad->algob[n];
        }
    }
    
    wxString rulename = wxString(currlayer->algo->getrule(), wxConvLocal);
    // replace any '\' and '/' chars with underscores;
    // ie. given 12/34/6 we look for 12_34_6.rule
    rulename.Replace(wxT("\\"), wxT("_"));
    rulename.Replace(wxT("/"), wxT("_"));
    
    // strip off any suffix like ":T100,200" used to specify a bounded grid
    if (rulename.Find(':') >= 0) rulename = rulename.BeforeFirst(':');

    // deallocate current layer's old icons
    DeleteIcons(currlayer);

    // this flag will change if any icon uses a non-grayscale color
    currlayer->multicoloricons = false;

    bool loadedcolors = false;
    bool loadedicons = false;
    
    // look for rulename.rule first
    FILE* rulefile = FindRuleFile(rulename);
    if (rulefile) {
        LoadRuleInfo(rulefile, rulename, &loadedcolors, &loadedicons);
        
        if (!loadedcolors || !loadedicons) {
            // if rulename has the form foo-* then look for foo-shared.rule
            // and load its colors and/or icons
            wxString prefix = rulename.BeforeLast('-');
            if (!prefix.IsEmpty() && !rulename.EndsWith(wxT("-shared"))) {
                rulename = prefix + wxT("-shared");
                rulefile = FindRuleFile(rulename);
                if (rulefile) LoadRuleInfo(rulefile, rulename, &loadedcolors, &loadedicons);
            }
        }
        
        if (!loadedicons) UseDefaultIcons(maxstate);
        
        // use the smallest icons to check if they are multi-color
        if (currlayer->icons7x7 && MultiColorBitmaps(currlayer->icons7x7, maxstate))
            currlayer->multicoloricons = true;
        
        // if the icons are multi-color then we don't call SetAverageColor as we do below
        // (better if the .rule file sets the appropriate non-icon colors)
        
    } else {
        // no rulename.rule so look for deprecated rulename.colors and/or rulename.icons
        loadedcolors = LoadRuleColors(rulename, maxstate);
        loadedicons = LoadRuleIcons(rulename, maxstate);
        if (!loadedicons) UseDefaultIcons(maxstate);
            
        // if rulename.colors wasn't supplied and icons are multi-color then we set
        // non-icon colors to the average of the non-black pixels in each icon
        // (note that we use the 7x7 icons because they are faster to scan)
        wxBitmap** iconmaps = currlayer->icons7x7;
        if (!loadedcolors && iconmaps && currlayer->multicoloricons) {
            for (int n = 1; n <= maxstate; n++) {
                SetAverageColor(n, iconmaps[n]);
            }
            // if extra 15x15 icon was supplied then use it to set state 0 color
            iconmaps = currlayer->icons15x15;
            if (iconmaps && iconmaps[0]) {
                wxAlphaPixelData icondata(*iconmaps[0]);
                if (icondata) {
                    wxAlphaPixelData::Iterator iconpxl(icondata);
                    // iconpxl is the top left pixel
                    currlayer->cellr[0] = iconpxl.Red();
                    currlayer->cellg[0] = iconpxl.Green();
                    currlayer->cellb[0] = iconpxl.Blue();
                }
            }
        }
    }    

    // create icon texture atlases (used for rendering)
    currlayer->numicons = maxstate;
    currlayer->atlas7x7 = CreateIconAtlas(currlayer->icons7x7, 8);
    currlayer->atlas15x15 = CreateIconAtlas(currlayer->icons15x15, 16);
    currlayer->atlas31x31 = CreateIconAtlas(currlayer->icons31x31, 32);
    
    if (swapcolors) {
        // invert cell colors in current layer
        for (int n = 0; n <= maxstate; n++) {
            currlayer->cellr[n] = 255 - currlayer->cellr[n];
            currlayer->cellg[n] = 255 - currlayer->cellg[n];
            currlayer->cellb[n] = 255 - currlayer->cellb[n];
        }
    }
}

// -----------------------------------------------------------------------------

void UpdateCloneColors()
{
    if (currlayer->cloneid > 0) {
        for (int i = 0; i < numlayers; i++) {
            Layer* cloneptr = layer[i];
            if (cloneptr != currlayer && cloneptr->cloneid == currlayer->cloneid) {
                cloneptr->fromrgb = currlayer->fromrgb;
                cloneptr->torgb = currlayer->torgb;
                cloneptr->multicoloricons = currlayer->multicoloricons;
                cloneptr->numicons = currlayer->numicons;
                for (int n = 0; n <= currlayer->numicons; n++) {
                    cloneptr->cellr[n] = currlayer->cellr[n];
                    cloneptr->cellg[n] = currlayer->cellg[n];
                    cloneptr->cellb[n] = currlayer->cellb[n];
                }
                
                // use same icon pointers
                cloneptr->icons7x7 = currlayer->icons7x7;
                cloneptr->icons15x15 = currlayer->icons15x15;
                cloneptr->icons31x31 = currlayer->icons31x31;
                
                // use same atlas
                cloneptr->atlas7x7 = currlayer->atlas7x7;
                cloneptr->atlas15x15 = currlayer->atlas15x15;
                cloneptr->atlas31x31 = currlayer->atlas31x31;
            }
        }
    }
}

// -----------------------------------------------------------------------------

void UpdateLayerColors()
{
    UpdateCurrentColors();
    
    // above has created icon texture data so don't call UpdateIconColors here
    
    // if current layer has clones then update their colors
    UpdateCloneColors();
}

// -----------------------------------------------------------------------------

void UpdateIconColors()
{
    // delete current icon texture atlases
    if (currlayer->atlas7x7) {
        free(currlayer->atlas7x7);
    }
    if (currlayer->atlas15x15) {
        free(currlayer->atlas15x15);
    }
    if (currlayer->atlas31x31) {
        free(currlayer->atlas31x31);
    }
    
    // re-create icon texture atlases
    currlayer->atlas7x7 = CreateIconAtlas(currlayer->icons7x7, 8);
    currlayer->atlas15x15 = CreateIconAtlas(currlayer->icons15x15, 16);
    currlayer->atlas31x31 = CreateIconAtlas(currlayer->icons31x31, 32);
}

// -----------------------------------------------------------------------------

void InvertIconColors(unsigned char* atlasptr, int iconsize, int numicons)
{
    if (atlasptr) {
        int numbytes = numicons * iconsize * iconsize * 4;
        int i = 0;
        while (i < numbytes) {
            if (atlasptr[i+3] == 0) {
                // ignore transparent pixel
            } else {
                // invert pixel color
                atlasptr[i]   = 255 - atlasptr[i];
                atlasptr[i+1] = 255 - atlasptr[i+1];
                atlasptr[i+2] = 255 - atlasptr[i+2];
            }
            i += 4;
        }
    }
}

// -----------------------------------------------------------------------------

void InvertCellColors()
{
    bool clone_inverted[MAX_LAYERS] = {false};
    
    // swapcolors has changed so invert cell colors in all layers
    for (int i = 0; i < numlayers; i++) {
        Layer* layerptr = layer[i];
        
        // do NOT use layerptr->algo->... here -- it might not be correct
        // for a non-current layer (but we can use layerptr->algtype)
        int maxstate = algoinfo[layerptr->algtype]->maxstates - 1;
        for (int n = 0; n <= maxstate; n++) {
            layerptr->cellr[n] = 255 - layerptr->cellr[n];
            layerptr->cellg[n] = 255 - layerptr->cellg[n];
            layerptr->cellb[n] = 255 - layerptr->cellb[n];
        }
        
        // clones share icon texture data so we must be careful to only invert them once
        if (layerptr->cloneid == 0 || !clone_inverted[layerptr->cloneid]) {
            // invert colors in icon texture atlases
            // (do NOT use maxstate here -- might be > layerptr->numicons)
            InvertIconColors(layerptr->atlas7x7, 8, layerptr->numicons);
            InvertIconColors(layerptr->atlas15x15, 16, layerptr->numicons);
            InvertIconColors(layerptr->atlas31x31, 32, layerptr->numicons);
            if (layerptr->cloneid > 0) clone_inverted[layerptr->cloneid] = true;
        }
    }
}

// -----------------------------------------------------------------------------

Layer* GetLayer(int index)
{
    if (index < 0 || index >= numlayers) {
        Warning(_("Bad index in GetLayer!"));
        return NULL;
    } else {
        return layer[index];
    }
}

// -----------------------------------------------------------------------------

int GetUniqueCloneID()
{
    // find first available index (> 0) to use as cloneid
    for (int i = 1; i < MAX_LAYERS; i++) {
        if (cloneavail[i]) {
            cloneavail[i] = false;
            return i;
        }
    }
    // bug if we get here
    Warning(_("Bug in GetUniqueCloneID!"));
    return 1;
}

// -----------------------------------------------------------------------------

Layer::Layer()
{
    if (!cloning) {
        // use a unique temporary file for saving starting patterns
        tempstart = wxFileName::CreateTempFileName(tempdir + wxT("golly_start_"));
    }
    
    dirty = false;                // user has not modified pattern
    savedirty = false;            // in case script created layer
    stayclean = inscript;         // if true then keep the dirty flag false
                                  // for the duration of the script
    savestart = false;            // no need to save starting pattern
    currfile.Clear();             // no pattern file has been loaded
    startgen = 0;                 // initial starting generation
    currname = _("untitled");     // initial window title
    originx = 0;                  // no X origin offset
    originy = 0;                  // no Y origin offset
    
    icons7x7 = NULL;              // no 7x7 icons
    icons15x15 = NULL;            // no 15x15 icons
    icons31x31 = NULL;            // no 31x31 icons

    atlas7x7 = NULL;              // no texture atlas for 7x7 icons
    atlas15x15 = NULL;            // no texture atlas for 15x15 icons
    atlas31x31 = NULL;            // no texture atlas for 31x31 icons
    
    currframe = 0;                // first frame in timeline
    autoplay = 0;                 // not playing
    tlspeed = 0;                  // default speed for autoplay
    
    // create viewport; the initial size is not important because it will soon change
    view = new viewport(100,100);
    if (view == NULL) Fatal(_("Failed to create viewport!"));
    
    if (numlayers == 0) {
        // creating very first layer (can't be a clone)
        cloneid = 0;
        
        // initialize cloneavail array (cloneavail[0] is never used)
        cloneavail[0] = false;
        for (int i = 1; i < MAX_LAYERS; i++) cloneavail[i] = true;
        
        // set some options using initial values stored in prefs file
        algtype = initalgo;
        hyperspeed = inithyperspeed;
        showhashinfo = initshowhashinfo;
        autofit = initautofit;
        
        // initial base step and exponent
        currbase = algoinfo[algtype]->defbase;
        currexpo = 0;
        
        // create empty universe
        algo = CreateNewUniverse(algtype);
        
        // set rule using initrule stored in prefs file
        const char* err = algo->setrule(initrule);
        if (err) {
            // user might have edited rule in prefs file, or deleted .rule file
            algo->setrule( algo->DefaultRule() );
        }
        
        // don't need to remember rule here (SaveLayerSettings will do it)
        rule = wxEmptyString;
        
        // initialize undo/redo history
        undoredo = new UndoRedo();
        if (undoredo == NULL) Fatal(_("Failed to create new undo/redo object!"));
        
        // set cursor in case newcurs/opencurs are set to "No Change"
        curs = curs_pencil;
        drawingstate = 1;
        
    } else {
        // adding a new layer after currlayer (see AddLayer)
        
        // inherit current universe type and other settings
        algtype = currlayer->algtype;
        hyperspeed = currlayer->hyperspeed;
        showhashinfo = currlayer->showhashinfo;
        autofit = currlayer->autofit;
        
        // initial base step and exponent
        currbase = algoinfo[algtype]->defbase;
        currexpo = 0;
        
        if (cloning) {
            if (currlayer->cloneid == 0) {
                // first time this universe is being cloned so need a unique cloneid
                cloneid = GetUniqueCloneID();
                currlayer->cloneid = cloneid;    // current layer also becomes a clone
                numclones += 2;
            } else {
                // we're cloning an existing clone
                cloneid = currlayer->cloneid;
                numclones++;
            }
            
            // clones share the same universe and undo/redo history
            algo = currlayer->algo;
            undoredo = currlayer->undoredo;
            
            // clones also share the same timeline
            currframe = currlayer->currframe;
            autoplay = currlayer->autoplay;
            tlspeed = currlayer->tlspeed;
            
            // clones use same name for starting file
            tempstart = currlayer->tempstart;
            
        } else {
            // this layer isn't a clone
            cloneid = 0;
            
            // create empty universe
            algo = CreateNewUniverse(algtype);
            
            // use current rule
            const char* err = algo->setrule(currlayer->algo->getrule());
            if (err) {
                // .rule file might have been deleted
                algo->setrule( algo->DefaultRule() );
            }
            
            // initialize undo/redo history
            undoredo = new UndoRedo();
            if (undoredo == NULL) Fatal(_("Failed to create new undo/redo object!"));
        }
        
        // inherit current rule
        rule = wxString(currlayer->algo->getrule(), wxConvLocal);
        
        // inherit current viewport's size, scale and location
        view->resize( currlayer->view->getwidth(), currlayer->view->getheight() );
        view->setpositionmag( currlayer->view->x, currlayer->view->y,
                             currlayer->view->getmag() );
        
        // inherit current cursor and drawing state
        curs = currlayer->curs;
        drawingstate = currlayer->drawingstate;
        
        if (cloning || duplicating) {
            // duplicate all the other current settings
            currname = currlayer->currname;
            dirty = currlayer->dirty;
            savedirty = currlayer->savedirty;
            stayclean = currlayer->stayclean;
            currbase = currlayer->currbase;
            currexpo = currlayer->currexpo;
            autofit = currlayer->autofit;
            hyperspeed = currlayer->hyperspeed;
            showhashinfo = currlayer->showhashinfo;
            originx = currlayer->originx;
            originy = currlayer->originy;
            
            // duplicate selection info
            currsel = currlayer->currsel;
            savesel = currlayer->savesel;
            
            // duplicate the stuff needed to reset pattern
            currfile = currlayer->currfile;
            savestart = currlayer->savestart;
            startalgo = currlayer->startalgo;
            startdirty = currlayer->startdirty;
            startrule = currlayer->startrule;
            startx = currlayer->startx;
            starty = currlayer->starty;
            startbase = currlayer->startbase;
            startexpo = currlayer->startexpo;
            startmag = currlayer->startmag;
            startgen = currlayer->startgen;
            startsel = currlayer->startsel;
            if (cloning) {
                // if clone is created after pattern has been generated
                // then we don't want a reset to change its name
                startname = currlayer->currname;
            } else {
                startname = currlayer->startname;
            }
        }
        
        if (duplicating) {
            // first set same gen count
            algo->setGeneration( currlayer->algo->getGeneration() );
            
            // duplicate pattern
            if ( !currlayer->algo->isEmpty() ) {
                bigint top, left, bottom, right;
                currlayer->algo->findedges(&top, &left, &bottom, &right);
                if ( viewptr->OutsideLimits(top, left, bottom, right) ) {
                    Warning(_("Pattern is too big to duplicate."));
                } else {
                    viewptr->CopyRect(top.toint(), left.toint(), bottom.toint(), right.toint(),
                                      currlayer->algo, algo, false, _("Duplicating layer"));
                }
            }
            
            // tempstart file must remain unique in duplicate layer
            if ( wxFileExists(currlayer->tempstart) ) {
                if ( !wxCopyFile(currlayer->tempstart, tempstart, true) ) {
                    Warning(_("Could not copy tempstart file!"));
                }
            }
            if (currlayer->currfile == currlayer->tempstart) {
                currfile = tempstart;
            }
            
            if (allowundo) {
                // duplicate current undo/redo history in new layer
                undoredo->DuplicateHistory(currlayer, this);
            }
        }
    }
}

// -----------------------------------------------------------------------------

Layer::~Layer()
{
    // delete stuff allocated in ctor
    delete view;
    
    if (cloneid > 0) {
        // this layer is a clone, so count how many layers have the same cloneid
        int clonecount = 0;
        for (int i = 0; i < numlayers; i++) {
            if (layer[i]->cloneid == cloneid) clonecount++;
            
            // tell undo/redo which clone is being deleted
            if (this == layer[i]) undoredo->DeletingClone(i);
        }     
        if (clonecount > 2) {
            // only delete this clone
            numclones--;
        } else {
            // first make this cloneid available for the next clone
            cloneavail[cloneid] = true;
            // reset the other cloneid to 0 (should only be one such clone)
            for (int i = 0; i < numlayers; i++) {
                // careful -- layer[i] might be this layer
                if (this != layer[i] && layer[i]->cloneid == cloneid)
                    layer[i]->cloneid = 0;
            }
            numclones -= 2;
        }
        
    } else {
        // this layer is not a clone, so delete universe and undo/redo history
        delete algo;
        delete undoredo;
        
        // delete tempstart file if it exists
        if (wxFileExists(tempstart)) wxRemoveFile(tempstart);
        
        // delete any icons
        DeleteIcons(this);
    }
}

// -----------------------------------------------------------------------------

// define a window for displaying cell colors/icons:

const int CELLSIZE = 16;      // wd and ht of each cell
const int NUMCOLS = 32;       // number of columns
const int NUMROWS = 8;        // number of rows

class CellPanel : public wxPanel
{
public:
    CellPanel(wxWindow* parent, wxWindowID id)
    : wxPanel(parent, id, wxPoint(0,0),
              wxSize(NUMCOLS*CELLSIZE+1,NUMROWS*CELLSIZE+1)) { }
    
    wxStaticText* statebox;    // for showing state of cell under cursor
    wxStaticText* rgbbox;      // for showing color of cell under cursor
    
private:
    void OnEraseBackground(wxEraseEvent& event);
    void OnPaint(wxPaintEvent& event);
    void OnMouseDown(wxMouseEvent& event);
    void OnMouseMotion(wxMouseEvent& event);
    void OnMouseExit(wxMouseEvent& event);
    
    DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(CellPanel, wxPanel)
EVT_ERASE_BACKGROUND (CellPanel::OnEraseBackground)
EVT_PAINT            (CellPanel::OnPaint)
EVT_LEFT_DOWN        (CellPanel::OnMouseDown)
EVT_LEFT_DCLICK      (CellPanel::OnMouseDown)
EVT_MOTION           (CellPanel::OnMouseMotion)
EVT_ENTER_WINDOW     (CellPanel::OnMouseMotion)
EVT_LEAVE_WINDOW     (CellPanel::OnMouseExit)
END_EVENT_TABLE()

// -----------------------------------------------------------------------------

void CellPanel::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
{
    // do nothing
}

// -----------------------------------------------------------------------------

void CellPanel::OnPaint(wxPaintEvent& WXUNUSED(event))
{
    wxPaintDC dc(this);
    
    dc.SetPen(*wxBLACK_PEN);
    
#ifdef __WXMSW__
    // we have to use theme background color on Windows
    wxBrush bgbrush(GetBackgroundColour());
#else
    wxBrush bgbrush(*wxTRANSPARENT_BRUSH);
#endif
    
    // draw cell boxes
    wxBitmap** iconmaps = currlayer->icons15x15;
    wxRect r = wxRect(0, 0, CELLSIZE+1, CELLSIZE+1);
    int col = 0;
    for (int state = 0; state < 256; state++) {
        if (state < currlayer->algo->NumCellStates()) {
            if (showicons && iconmaps && iconmaps[state]) {
                dc.SetBrush(*wxTRANSPARENT_BRUSH);
                dc.DrawRectangle(r);
                dc.SetBrush(wxNullBrush);               
                DrawOneIcon(dc, r.x + 1, r.y + 1, iconmaps[state],
                            currlayer->cellr[0],
                            currlayer->cellg[0],
                            currlayer->cellb[0],
                            currlayer->cellr[state],
                            currlayer->cellg[state],
                            currlayer->cellb[state],
                            currlayer->multicoloricons);
            } else {
                wxColor color(currlayer->cellr[state],
                              currlayer->cellg[state],
                              currlayer->cellb[state]);
                dc.SetBrush(wxBrush(color));
                dc.DrawRectangle(r);
                dc.SetBrush(wxNullBrush);
            }
            
        } else {
            // state >= currlayer->algo->NumCellStates()
            dc.SetBrush(bgbrush);
            dc.DrawRectangle(r);
            dc.SetBrush(wxNullBrush);
        }
        
        col++;
        if (col < NUMCOLS) {
            r.x += CELLSIZE;
        } else {
            r.x = 0;
            r.y += CELLSIZE;
            col = 0;
        }
    }
    
    dc.SetPen(wxNullPen);
}

// -----------------------------------------------------------------------------

void CellPanel::OnMouseDown(wxMouseEvent& event)
{
    int col = event.GetX() / CELLSIZE;
    int row = event.GetY() / CELLSIZE;
    int state = row * NUMCOLS + col;
    if (state >= 0 && state < currlayer->algo->NumCellStates()) {
        // let user change color of this cell state
        wxColour rgb(currlayer->cellr[state],
                     currlayer->cellg[state],
                     currlayer->cellb[state]);
        wxColourData data;
        data.SetChooseFull(true);    // for Windows
        data.SetColour(rgb);
        
        wxColourDialog dialog(this, &data);
        if ( dialog.ShowModal() == wxID_OK ) {
            wxColourData retData = dialog.GetColourData();
            wxColour c = retData.GetColour();
            if (rgb != c) {
                // change color
                currlayer->cellr[state] = c.Red();
                currlayer->cellg[state] = c.Green();
                currlayer->cellb[state] = c.Blue();
                Refresh(false);
            }
        }
    } 
    event.Skip();
}

// -----------------------------------------------------------------------------

void CellPanel::OnMouseMotion(wxMouseEvent& event)
{
    int col = event.GetX() / CELLSIZE;
    int row = event.GetY() / CELLSIZE;
    int state = row * NUMCOLS + col;
    if (state < 0 || state > 255) {
        statebox->SetLabel(_(" "));
        rgbbox->SetLabel(_(" "));
    } else {
        statebox->SetLabel(wxString::Format(_("%d"),state));
        if (state < currlayer->algo->NumCellStates()) {
            rgbbox->SetLabel(wxString::Format(_("%d,%d,%d"),
                                              currlayer->cellr[state],
                                              currlayer->cellg[state],
                                              currlayer->cellb[state]));
        } else {
            rgbbox->SetLabel(_(" "));
        }
    }
}

// -----------------------------------------------------------------------------

void CellPanel::OnMouseExit(wxMouseEvent& WXUNUSED(event))
{
    statebox->SetLabel(_(" "));
    rgbbox->SetLabel(_(" "));
}

// -----------------------------------------------------------------------------

// define a modal dialog for changing colors

class ColorDialog : public wxDialog
{
public:
    ColorDialog(wxWindow* parent);
    virtual bool TransferDataFromWindow();    // called when user hits OK
    
    enum {
        // control ids
        CELL_PANEL = wxID_HIGHEST + 1,
        ICON_CHECK,
        STATE_BOX,
        RGB_BOX,
        GRADIENT_BUTT,
        FROM_BUTT,
        TO_BUTT,
        DEFAULT_BUTT
    };
    
    void CreateControls();        // initialize all the controls
    
    void AddColorButton(wxWindow* parent, wxBoxSizer* hbox, int id, wxColor* rgb);
    void ChangeButtonColor(int id, wxColor* rgb);
    void UpdateButtonColor(int id, wxColor* rgb);
    
    CellPanel* cellpanel;         // for displaying cell colors/icons
    wxCheckBox* iconcheck;        // show icons?
    
private:
    // event handlers
    void OnCheckBoxClicked(wxCommandEvent& event);
    void OnButton(wxCommandEvent& event);
#if defined(__WXOSX_COCOA__) && wxCHECK_VERSION(3,0,0)
    void OnCharHook(wxKeyEvent& event);
#endif

    DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(ColorDialog, wxDialog)
EVT_CHECKBOX   (wxID_ANY,  ColorDialog::OnCheckBoxClicked)
EVT_BUTTON     (wxID_ANY,  ColorDialog::OnButton)
#if defined(__WXOSX_COCOA__) && wxCHECK_VERSION(3,0,0)
EVT_CHAR_HOOK  (ColorDialog::OnCharHook)
#endif
END_EVENT_TABLE()

// -----------------------------------------------------------------------------

// these consts are used to get nicely spaced controls on each platform:

const int HGAP = 12;    // space left and right of vertically stacked boxes

// following ensures OK/Cancel buttons are better aligned
#ifdef __WXMAC__
    const int STDHGAP = 0;
#elif defined(__WXMSW__)
    const int STDHGAP = 9;
#else
    const int STDHGAP = 10;
#endif

const int BITMAP_WD = 60;     // width of bitmap in color buttons
const int BITMAP_HT = 20;     // height of bitmap in color buttons

// -----------------------------------------------------------------------------

ColorDialog::ColorDialog(wxWindow* parent)
{
    Create(parent, wxID_ANY, _("Set Layer Colors"), wxDefaultPosition, wxDefaultSize);
    CreateControls();
    Centre();
}

// -----------------------------------------------------------------------------

void ColorDialog::CreateControls()
{
    wxString note =
    _("NOTE:  Changes made here are temporary and only affect the current layer and ");
    note += _("its clones.  The colors will be reset to their default values if you open ");
    note += _("a pattern file or create a new pattern, or if you change the current algorithm ");
    note += _("or rule.  If you want to change the default colors, use Preferences > Color.");
    wxStaticText* notebox = new wxStaticText(this, wxID_STATIC, note);
    notebox->Wrap(NUMCOLS * CELLSIZE + 1);
    
    // create bitmap buttons
    wxBoxSizer* frombox = new wxBoxSizer(wxHORIZONTAL);
    wxBoxSizer* tobox = new wxBoxSizer(wxHORIZONTAL);
    AddColorButton(this, frombox, FROM_BUTT, &currlayer->fromrgb);
    AddColorButton(this, tobox, TO_BUTT, &currlayer->torgb);
    
    wxButton* defbutt = new wxButton(this, DEFAULT_BUTT, _("Default Colors"));
    wxButton* gradbutt = new wxButton(this, GRADIENT_BUTT, _("Create Gradient"));
    
    wxBoxSizer* gradbox = new wxBoxSizer(wxHORIZONTAL);
    gradbox->Add(gradbutt, 0, wxALIGN_CENTER_VERTICAL, 0);
    gradbox->Add(new wxStaticText(this, wxID_STATIC, _(" from ")),
                 0, wxALIGN_CENTER_VERTICAL, 0);
    gradbox->Add(frombox, 0, wxALIGN_CENTER_VERTICAL, 0);
    gradbox->Add(new wxStaticText(this, wxID_STATIC, _(" to ")),
                 0, wxALIGN_CENTER_VERTICAL, 0);
    gradbox->Add(tobox, 0, wxALIGN_CENTER_VERTICAL, 0);
    
    // create child window for displaying cell colors/icons
    cellpanel = new CellPanel(this, CELL_PANEL);
    
    iconcheck = new wxCheckBox(this, ICON_CHECK, _("Show icons"));
    iconcheck->SetValue(showicons);
    
    wxStaticText* statebox = new wxStaticText(this, STATE_BOX, _("999"));
    cellpanel->statebox = statebox;
    wxBoxSizer* hbox1 = new wxBoxSizer(wxHORIZONTAL);
    hbox1->Add(statebox, 0, 0, 0);
    hbox1->SetMinSize( hbox1->GetMinSize() );
    
    wxStaticText* rgbbox = new wxStaticText(this, RGB_BOX, _("999,999,999"));
    cellpanel->rgbbox = rgbbox;
    wxBoxSizer* hbox2 = new wxBoxSizer(wxHORIZONTAL);
    hbox2->Add(rgbbox, 0, 0, 0);
    hbox2->SetMinSize( hbox2->GetMinSize() );
    
    statebox->SetLabel(_(" "));
    rgbbox->SetLabel(_(" "));
    
    wxBoxSizer* botbox = new wxBoxSizer(wxHORIZONTAL);
    botbox->Add(new wxStaticText(this, wxID_STATIC, _("State: ")),
                0, wxALIGN_CENTER_VERTICAL, 0);
    botbox->Add(hbox1, 0, wxALIGN_CENTER_VERTICAL, 0);
    botbox->Add(20, 0, 0);
    botbox->Add(new wxStaticText(this, wxID_STATIC, _("RGB: ")),
                0, wxALIGN_CENTER_VERTICAL, 0);
    botbox->Add(hbox2, 0, wxALIGN_CENTER_VERTICAL, 0);
    botbox->AddStretchSpacer();
    botbox->Add(iconcheck, 0, wxALIGN_CENTER_VERTICAL, 0);
    
    wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL);
    vbox->Add(gradbox, 0, wxALIGN_CENTER, 0);
    vbox->AddSpacer(10);
    vbox->Add(cellpanel, 0, wxLEFT | wxRIGHT, 0);
    vbox->AddSpacer(5);
    vbox->Add(botbox, 1, wxGROW | wxLEFT | wxRIGHT, 0);
    
    wxSizer* stdbutts = CreateButtonSizer(wxOK | wxCANCEL);
    wxBoxSizer* stdhbox = new wxBoxSizer( wxHORIZONTAL );
    stdhbox->Add(defbutt, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, HGAP);
    stdhbox->Add(stdbutts, 1, wxALIGN_CENTER_VERTICAL | wxRIGHT, STDHGAP);
    
    wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL);
    topSizer->AddSpacer(10);
    topSizer->Add(notebox, 0, wxLEFT | wxRIGHT, HGAP);
    topSizer->AddSpacer(20);
    topSizer->Add(vbox, 0, wxGROW | wxLEFT | wxRIGHT, HGAP);
    topSizer->AddSpacer(10);
    topSizer->Add(stdhbox, 1, wxGROW | wxTOP | wxBOTTOM, 10);
    SetSizer(topSizer);
    topSizer->SetSizeHints(this);    // calls Fit
}

// -----------------------------------------------------------------------------

void ColorDialog::OnCheckBoxClicked(wxCommandEvent& event)
{
    if ( event.GetId() == ICON_CHECK ) {
        showicons = iconcheck->GetValue() == 1;
        cellpanel->Refresh(false);
    }
}

// -----------------------------------------------------------------------------

void ColorDialog::AddColorButton(wxWindow* parent, wxBoxSizer* hbox, int id, wxColor* rgb)
{
    wxBitmap bitmap(BITMAP_WD, BITMAP_HT);
    wxMemoryDC dc;
    dc.SelectObject(bitmap);
    wxRect rect(0, 0, BITMAP_WD, BITMAP_HT);
    wxBrush brush(*rgb);
    FillRect(dc, rect, brush);
    dc.SelectObject(wxNullBitmap);
    
    wxBitmapButton* bb = new wxBitmapButton(parent, id, bitmap, wxPoint(0,0),
#if defined(__WXOSX_COCOA__)
                                            wxSize(BITMAP_WD + 12, BITMAP_HT + 12));
#else
                                            wxDefaultSize);
#endif
    if (bb) hbox->Add(bb, 0, wxALIGN_CENTER_VERTICAL, 0);
}

// -----------------------------------------------------------------------------

void ColorDialog::UpdateButtonColor(int id, wxColor* rgb)
{
    wxBitmapButton* bb = (wxBitmapButton*) FindWindow(id);
    if (bb) {
        wxBitmap bitmap(BITMAP_WD, BITMAP_HT);
        wxMemoryDC dc;
        dc.SelectObject(bitmap);
        wxRect rect(0, 0, BITMAP_WD, BITMAP_HT);
        wxBrush brush(*rgb);
        FillRect(dc, rect, brush);
        dc.SelectObject(wxNullBitmap);
        bb->SetBitmapLabel(bitmap);
        bb->Refresh();
    }
}

// -----------------------------------------------------------------------------

void ColorDialog::ChangeButtonColor(int id, wxColor* rgb)
{
    wxColourData data;
    data.SetChooseFull(true);    // for Windows
    data.SetColour(*rgb);
    
    wxColourDialog dialog(this, &data);
    if ( dialog.ShowModal() == wxID_OK ) {
        wxColourData retData = dialog.GetColourData();
        wxColour c = retData.GetColour();
        
        if (*rgb != c) {
            // change given color
            rgb->Set(c.Red(), c.Green(), c.Blue());
            
            // also change color of bitmap in corresponding button
            UpdateButtonColor(id, rgb);
            
            cellpanel->Refresh(false);
        }
    }
}

// -----------------------------------------------------------------------------

#if defined(__WXOSX_COCOA__) && wxCHECK_VERSION(3,0,0)

void ColorDialog::OnCharHook(wxKeyEvent& event)
{
    int key = event.GetKeyCode();
    if (key == WXK_RETURN) {
        // fix wxOSX 3.x bug: allow return key to select OK button
        wxCommandEvent okevent(wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK);
        okevent.SetEventObject(this);
        GetEventHandler()->ProcessEvent(okevent);
        return;
    }
    event.Skip();   // process other keys, like escape
}

#endif

// -----------------------------------------------------------------------------

void ColorDialog::OnButton(wxCommandEvent& event)
{
    int id = event.GetId();
    
    if ( id == FROM_BUTT ) {
        ChangeButtonColor(id, &currlayer->fromrgb);
        
    } else if ( id == TO_BUTT ) {
        ChangeButtonColor(id, &currlayer->torgb);
        
    } else if ( id == GRADIENT_BUTT ) {
        // use currlayer->fromrgb and currlayer->torgb
        CreateColorGradient();
        cellpanel->Refresh(false);
        
    } else if ( id == DEFAULT_BUTT ) {
        // restore current layer's default colors, but don't call UpdateLayerColors
        // here because we don't want to change any clone layers at this stage
        // (in case user cancels dialog)
        UpdateCurrentColors();
        UpdateButtonColor(FROM_BUTT, &currlayer->fromrgb);
        UpdateButtonColor(TO_BUTT, &currlayer->torgb);
        cellpanel->Refresh(false);
        
    } else {
        // process other buttons like Cancel and OK
        event.Skip();
    }
}

// -----------------------------------------------------------------------------

bool ColorDialog::TransferDataFromWindow()
{
    // update icon texture data before calling UpdateCloneColors
    UpdateIconColors();
    
    // if current layer has clones then update their colors
    UpdateCloneColors();
    
    return true;
}

// -----------------------------------------------------------------------------

// class for saving and restoring layer colors
class SaveData {
public:
    SaveData() {
        fromrgb = currlayer->fromrgb;
        torgb = currlayer->torgb;
        for (int i = 0; i < currlayer->algo->NumCellStates(); i++) {
            cellr[i] = currlayer->cellr[i];
            cellg[i] = currlayer->cellg[i];
            cellb[i] = currlayer->cellb[i];
        }
        saveshowicons = showicons;
    }
    
    void RestoreData() {
        currlayer->fromrgb = fromrgb;
        currlayer->torgb = torgb;
        for (int i = 0; i < currlayer->algo->NumCellStates(); i++) {
            currlayer->cellr[i] = cellr[i];
            currlayer->cellg[i] = cellg[i];
            currlayer->cellb[i] = cellb[i];
        }
        showicons = saveshowicons;
    }
    
    // this must match color info in Layer class
    wxColor fromrgb;
    wxColor torgb;
    unsigned char cellr[256];
    unsigned char cellg[256];
    unsigned char cellb[256];
    
    // we also save/restore showicons option
    bool saveshowicons;
};

// -----------------------------------------------------------------------------

void SetLayerColors()
{
    if (inscript || viewptr->waitingforclick) return;
    
    if (mainptr->generating) {
        mainptr->command_pending = true;
        mainptr->cmdevent.SetId(ID_SET_COLORS);
        mainptr->Stop();
        return;
    }
    
    bool wastoggled = swapcolors;
    if (swapcolors) viewptr->ToggleCellColors();    // swapcolors is now false
    
    // save current color info so we can restore it if user cancels changes
    SaveData* save_info = new SaveData();
    
    ColorDialog dialog( wxGetApp().GetTopWindow() );
    int button = dialog.ShowModal();
    viewptr->ResetMouseDown();
    if (button != wxID_OK) {
        // user hit Cancel so restore color info saved above
        save_info->RestoreData();
    }
    
    delete save_info;
    
    if (wastoggled) viewptr->ToggleCellColors();    // swapcolors is now true
    
    mainptr->UpdateEverything();
}