1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::mpsc, time::Duration};
use web_time::Instant;
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum Tool {
Pencil,
FloodFill,
LineAlongLane,
/// Editor only — the solver's sidebar never offers it, so its canvas can't end up here.
Lasso,
}
pub enum LibraryStatus {
Loading,
Loaded(Vec<Document>),
Failed(String),
}
#[derive(Clone)]
pub struct StatusMessage {
pub text: String,
pub is_error: bool,
}
impl StatusMessage {
pub fn info(text: impl Into<String>) -> Self {
StatusMessage {
text: text.into(),
is_error: false,
}
}
pub fn error(text: impl Into<String>) -> Self {
StatusMessage {
text: text.into(),
is_error: true,
}
}
}
const STATUS_GRACE_PERIOD: Duration = Duration::from_secs(1);
// Shared between `CanvasGui`s so that the editor and the solver (which have separate
// `CanvasGui`s) can show messages in the same status bar.
pub struct StatusCell {
// The `Instant` is when the message was set: for the first `STATUS_GRACE_PERIOD` after that,
// `maybe_clear_on_dirty` calls are ignored, so a message doesn't disappear before the user
// has had a chance to read it.
inner: RefCell<Option<(StatusMessage, Instant)>>,
}
impl StatusCell {
pub fn new() -> Rc<Self> {
Rc::new(StatusCell {
inner: RefCell::new(None),
})
}
pub fn set(&self, message: StatusMessage) {
*self.inner.borrow_mut() = Some((message, Instant::now()));
}
pub fn get(&self) -> Option<StatusMessage> {
self.inner
.borrow()
.as_ref()
.map(|(message, _)| message.clone())
}
// Called when something dirties the editor (or otherwise makes the current message stale);
// clears the message, unless it was set too recently for the user to have read it yet.
pub fn maybe_clear_on_dirty(&self) {
let mut inner = self.inner.borrow_mut();
if let Some((_, set_at)) = *inner
&& set_at.elapsed() >= STATUS_GRACE_PERIOD
{
*inner = None;
}
}
}
pub type SharedStatus = Rc<StatusCell>;
// Shared the same way as `SharedStatus`, for a progress bar in the status bar. `Some(fraction)`
// (0.0 to 1.0) while a long-running task is in progress, `None` otherwise.
pub type SharedProgress = Rc<RefCell<Option<f32>>>;
use crate::{
export::to_bytes,
grid_solve::{self, DisambigResult, disambig_candidates},
gui_solver::{RenderStyle, SolveGui},
import,
// The abstract-units point, distinct from egui's `Pos2`: everything the lasso does is in
// grid space, and only the painter converts.
layout::Point,
puzzle::{
BACKGROUND, Clue, ClueStyle, Color, ColorInfo, Corner, Document, DynSolution, Palette,
PuzzleDynOps, Solution, UNSOLVED,
},
user_settings::{UserSettings, consts},
};
use egui::{Color32, Pos2, Rect, RichText, Shape, Style, TextStyle, Vec2, Visuals};
/// The editor still only understands rows and columns. Rather than panicking deep inside a
/// drawing routine, every entry point that needs a square picture says so here.
const TRIDDLER_UNSUPPORTED: &str = "the editor can't edit triddlers yet";
use egui_material_icons::icons;
#[cfg(not(target_arch = "wasm32"))]
pub fn edit_image(document: Document) {
use eframe::icon_data::from_png_bytes;
use egui::ViewportBuilder;
let icon_bytes: &'static [u8] = include_bytes!("../icon.png");
let native_options = eframe::NativeOptions {
viewport: ViewportBuilder::default()
.with_inner_size(Vec2::new(800.0, 800.0))
.with_app_id("Number Loom")
.with_icon(from_png_bytes(icon_bytes).unwrap()),
persist_window: true,
..eframe::NativeOptions::default()
};
eframe::run_native(
"Number Loom",
native_options,
Box::new(|cc| {
egui_material_icons::initialize(&cc.egui_ctx);
Ok(Box::new(NonogramGui::new(document)))
}),
)
.unwrap()
}
#[cfg(target_arch = "wasm32")]
pub fn edit_image(document: Document) {
use eframe::wasm_bindgen::JsCast as _;
let web_options = eframe::WebOptions::default();
wasm_bindgen_futures::spawn_local(async {
let sys_doc = web_sys::window()
.expect("No window")
.document()
.expect("No document");
let canvas = sys_doc
.get_element_by_id("the_canvas_id")
.expect("Failed to find the_canvas_id")
.dyn_into::<web_sys::HtmlCanvasElement>()
.expect("the_canvas_id was not a HtmlCanvasElement");
let start_result = eframe::WebRunner::new()
.start(
canvas,
web_options,
Box::new(|cc| {
egui_material_icons::initialize(&cc.egui_ctx);
Ok(Box::new(NonogramGui::new(document)))
}),
)
.await;
// Remove the loading text and spinner:
if let Some(loading_text) = sys_doc.get_element_by_id("loading_text") {
match start_result {
Ok(_) => {
loading_text.remove();
}
Err(e) => {
panic!("Failed to start eframe: {:?}", e);
}
}
}
});
}
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::spawn_local as spawn_async;
#[cfg(not(target_arch = "wasm32"))]
pub fn spawn_async<F>(future: F)
where
F: std::future::Future<Output = ()> + 'static + std::marker::Send,
{
// This sort of weird construct allows us to avoid multithreaded tokio,
// which isn't available on wasm32 (cargo doesn't like having the same crate have different
// features on different platforms, and we might want to use some tokio features on wasm32)
std::thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(future);
});
}
#[cfg(not(target_arch = "wasm32"))]
pub async fn yield_now() {
tokio::task::yield_now().await;
}
#[cfg(target_arch = "wasm32")]
pub async fn yield_now() {
// Taken from https://github.com/rustwasm/wasm-bindgen/issues/3359:
let mut cb = |resolve: js_sys::Function, _reject: js_sys::Function| {
web_sys::window()
.unwrap()
.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, 1)
.expect("Failed to call set_timeout");
};
let p = js_sys::Promise::new(&mut cb);
wasm_bindgen_futures::JsFuture::from(p).await.unwrap();
}
type Version = u32;
pub struct Staleable<T> {
pub val: T,
pub version: Version,
}
impl<T> Staleable<T> {
pub fn update(&mut self, val: T, version: Version) {
self.val = val;
self.version = version;
}
pub fn fresh(&self, version: Version) -> bool {
self.version == version
}
fn get_if_fresh(&self, version: Version) -> Option<&T> {
if self.fresh(version) {
Some(&self.val)
} else {
None
}
}
pub fn get_or_refresh<F>(&mut self, version: Version, refresh: F) -> &mut T
where
F: FnOnce() -> T,
{
if !self.fresh(version) {
self.val = refresh();
self.version = version;
}
&mut self.val
}
}
/// A lasso selection, plus whatever it has been lifted onto a floating layer.
///
/// The mask is stored at an *anchor* position and displaced by `offset`, rather than being
/// rewritten on every drag frame: that keeps a move reversible (drag back off the grid edge and
/// nothing is lost) and makes the whole thing one translation away from where it started.
pub struct Selection {
/// Indexed by dense cell index, like `Solution::cells` — so it is only meaningful for a grid
/// of the same size, which `canvas_with_clues` checks before using it.
mask: Vec<bool>,
/// Lattice steps (see `Geometry::snap_translation`) currently applied to `mask` and
/// `floating`. Zero until the selection is dragged.
offset: (i32, i32),
/// Content lifted off the grid, as `(anchor cell, color)`. `None` until the first move drag.
floating: Option<Vec<(u32, Color)>>,
/// The lasso path in abstract units, while one is being drawn.
drawing: Option<Vec<crate::layout::Point>>,
/// Where the move drag was grabbed, and the offset at that moment.
dragging: Option<(crate::layout::Point, (i32, i32))>,
/// Time origin for the marching ants' dash phase.
since: Instant,
}
impl Selection {
fn new(mask: Vec<bool>) -> Selection {
Selection {
mask,
offset: (0, 0),
floating: None,
drawing: None,
dragging: None,
since: Instant::now(),
}
}
fn anchor_cells(&self) -> impl Iterator<Item = u32> + '_ {
self.mask
.iter()
.enumerate()
.filter(|(_, m)| **m)
.map(|(i, _)| i as u32)
}
/// Where the selected cells sit right now: the anchor mask shifted by `offset`. Cells pushed
/// off the grid simply don't appear — they're still in `mask`, so dragging back restores them.
fn displayed_cells(&self, picture: &crate::puzzle::DynSolution) -> Vec<u32> {
if self.offset == (0, 0) {
return self.anchor_cells().collect();
}
self.anchor_cells()
.filter_map(|cell| picture.translate_cell(cell, self.offset))
.collect()
}
fn is_empty(&self) -> bool {
!self.mask.iter().any(|m| *m)
}
}
/// What the lasso tool needs to know about the pointer in a frame.
#[derive(Clone, Copy, Debug, Default)]
struct LassoPointer {
pressed: bool,
down: bool,
released: bool,
}
impl LassoPointer {
fn from_egui(pointer: &egui::PointerState) -> LassoPointer {
LassoPointer {
pressed: pointer.button_pressed(egui::PointerButton::Primary),
down: pointer.button_down(egui::PointerButton::Primary),
released: pointer.any_released(),
}
}
}
pub struct CanvasGui {
pub document: Document,
pub version: Version,
pub current_color: Color,
pub drag_start_color: Color,
pub undo_stack: Vec<Action>,
pub redo_stack: Vec<Action>,
pub current_tool: Tool,
pub line_tool_state: Option<u32>,
/// The lasso tool's selection, if any. Outlives switching tools only long enough to be
/// flattened; see `flatten_selection`.
pub selection: Option<Selection>,
/// Indexed by dense cell index, like `Solution::cells`.
pub solved_mask: Staleable<(String, Vec<bool>)>,
pub disambiguator: Staleable<Disambiguator>,
pub id: Staleable<String>,
pub status: SharedStatus,
pub progress: SharedProgress,
/// Where the picture itself (not counting any clue gutters) landed on screen, as of the last
/// frame that drew it. `pub` for tests/gui.rs, which needs a point that's reliably on the
/// canvas to aim a click at — a hardcoded one goes stale the moment the layout around it
/// moves.
pub picture_rect: Option<Rect>,
}
pub struct NonogramGui {
// The `pub`s are solely for tests/gui.rs
pub editor_gui: CanvasGui,
scale: f32,
opened_file_receiver: mpsc::Receiver<anyhow::Result<Document>>,
save_result_receiver: mpsc::Receiver<anyhow::Result<()>>,
library_receiver: mpsc::Receiver<anyhow::Result<Vec<Document>>>,
library_dialog: Option<LibraryStatus>,
new_dialog: Option<NewPuzzleDialog>,
auto_solve: bool,
lines_to_affect_string: String,
solve_report: String,
pub solve_mode: bool,
pub solve_gui: Option<SolveGui>,
show_save_share_window: bool,
share_string: String,
pasted_string: String,
quality_warnings: Vec<String>,
}
#[derive(Clone, Debug)]
pub enum Action {
/// Keyed by dense cell index rather than by coordinate: every consumer wants a cell, and
/// indices make undo, the tools, and merging work for any shape with no dispatch at all.
/// Coordinates appear only at the hit-test boundary, as `DynCoord`.
ChangeColor {
changes: HashMap<u32, Color>,
},
ReplaceDocument {
document: Box<Document>,
},
}
#[derive(PartialEq, Eq)]
pub enum ActionMood {
Normal,
Merge,
ReplaceAction,
Undo,
Redo,
}
/// Find a color that's definitely safe, at least.
pub fn default_color(palette: &Palette) -> Color {
if palette.contains_key(&Color(1)) {
Color(1)
} else {
BACKGROUND
}
}
impl CanvasGui {
/// Sync `self.current_color` and `self.drag_start_color` to the document, for safety.
fn clamp_colors_to_palette(&mut self) {
let Some(picture) = self.document.try_solution() else {
return;
};
let palette = picture.palette();
let fallback = default_color(palette);
if !palette.contains_key(&self.current_color) {
self.current_color = fallback;
}
if !palette.contains_key(&self.drag_start_color) {
self.drag_start_color = fallback;
}
}
fn reversed(&self, action: &Action) -> Action {
match action {
Action::ChangeColor { changes } => {
let cells = self.document.try_solution().unwrap().cells();
Action::ChangeColor {
changes: changes
.keys()
.map(|cell| (*cell, cells[*cell as usize]))
.collect(),
}
}
Action::ReplaceDocument { document: _ } => Action::ReplaceDocument {
document: Box::new(self.document.clone()),
},
}
}
pub fn perform(&mut self, action: Action, mood: ActionMood) {
use Action::*;
use ActionMood::*;
let mood = if mood == Merge || mood == ReplaceAction {
match (self.undo_stack.last_mut(), &action) {
// Consecutive `ChangeColor`s can be merged with each other.
(
Some(ChangeColor { changes }),
ChangeColor {
changes: new_changes,
},
) => {
let cells = self.document.solution_mut().cells_mut();
if mood == ReplaceAction {
for cell in new_changes.keys() {
changes.entry(*cell).or_insert(cells[*cell as usize]);
}
changes.retain(|cell, old_col| {
if !new_changes.contains_key(cell) {
cells[*cell as usize] = *old_col;
self.version += 1;
false
} else {
true
}
});
for (cell, col) in new_changes {
if cells[*cell as usize] != *col {
cells[*cell as usize] = *col;
self.version += 1;
}
}
return;
} else {
for (cell, col) in new_changes {
if !changes.contains_key(cell) {
changes.insert(*cell, cells[*cell as usize]);
// Crucially, this only fires on a new cell!
// Otherwise, we'd be flipping cells back and forth as long as we
// were in them!
cells[*cell as usize] = *col;
self.version += 1;
}
}
return;
}
}
_ => Normal, // Unable to merge; add a new undo entry.
}
} else {
mood
};
let reversed_action = self.reversed(&action);
let version_before = self.version;
match action {
Action::ChangeColor { changes } => {
let cells = self.document.solution_mut().cells_mut();
for (cell, new_color) in changes {
if cells[cell as usize] != new_color {
cells[cell as usize] = new_color;
self.version += 1;
}
}
}
Action::ReplaceDocument { document } => {
let mut document = document;
if let Ok(true) = document.has_complete_solution() {
self.document = *document;
self.version += 1;
// A mask means nothing against a picture that was swapped out from under it,
// and a floating layer belongs to the picture it was lifted from.
self.selection = None;
// The new palette may not have the color the old one did.
self.clamp_colors_to_palette();
} else {
self.status
.set(StatusMessage::error("That puzzle has no solution"));
}
}
}
if self.version != version_before {
self.status.maybe_clear_on_dirty();
}
match mood {
Merge | ReplaceAction => {}
Normal => {
self.undo_stack.push(reversed_action);
self.redo_stack.clear();
}
Undo => {
self.redo_stack.push(reversed_action);
}
Redo => {
self.undo_stack.push(reversed_action);
}
}
}
pub fn un_or_re_do(&mut self, un: bool) {
let action = if un {
self.undo_stack.pop()
} else {
self.redo_stack.pop()
};
if let Some(action) = action {
self.perform(
action,
if un {
ActionMood::Undo
} else {
ActionMood::Redo
},
)
}
}
/// `editing` is false in the solver, which shares this sidebar but must not offer the tools
/// that rearrange the picture.
pub fn common_sidebar_items(
&mut self,
ui: &mut egui::Ui,
palette_read_only: bool,
editing: bool,
) {
// A focused `TextEdit` reads its key events without consuming them, so a bare-key
// shortcut still fires while the user is typing into one. Nothing here uses a modifier,
// so every one of them has to be suppressed by hand.
let typing = ui.ctx().wants_keyboard_input();
let (can_undo, can_redo) = (!self.undo_stack.is_empty(), !self.redo_stack.is_empty());
centered_row(ui, "undo_row", |ui| {
ui.label(format!("({})", self.undo_stack.len()));
if ui
.add_enabled(can_undo, egui::Button::new(icons::ICON_UNDO))
.clicked()
|| (can_undo && !typing && ui.input(|i| i.key_pressed(egui::Key::Z)))
{
self.un_or_re_do(true);
}
if ui
.add_enabled(can_redo, egui::Button::new(icons::ICON_REDO))
.clicked()
|| (can_redo && !typing && ui.input(|i| i.key_pressed(egui::Key::Y)))
{
self.un_or_re_do(false);
}
ui.label(format!("({})", self.redo_stack.len()));
});
ui.separator();
self.tool_selector(ui, editing);
ui.separator();
self.palette_editor(ui, palette_read_only);
}
fn tool_selector(&mut self, ui: &mut egui::Ui, editing: bool) {
let was = self.current_tool;
centered_row(ui, "tools", |ui| {
ui.selectable_value(
&mut self.current_tool,
Tool::Pencil,
egui::RichText::new(icons::ICON_BRUSH).size(24.0),
)
.on_hover_text("Pencil");
ui.selectable_value(
&mut self.current_tool,
Tool::LineAlongLane,
egui::RichText::new(icons::ICON_LINE_START).size(24.0),
)
.on_hover_text("Line along a row, column or diagonal");
if editing {
ui.selectable_value(
&mut self.current_tool,
Tool::FloodFill,
egui::RichText::new(icons::ICON_FORMAT_COLOR_FILL).size(24.0),
)
.on_hover_text("Flood Fill");
ui.selectable_value(
&mut self.current_tool,
Tool::Lasso,
egui::RichText::new(icons::ICON_LASSO_SELECT).size(24.0),
)
.on_hover_text("Lasso select: draw a loop, then drag to move what's inside");
}
});
// Leaving the lasso commits whatever it was holding, so no other tool ever has to think
// about a floating layer.
if was == Tool::Lasso && self.current_tool != Tool::Lasso {
self.clear_selection();
}
}
fn flood_fill(&mut self, start: u32) {
let picture = self.document.solution_mut();
let target_color = picture.cells()[start as usize];
if target_color == self.current_color {
return; // Nothing to do
}
let mut changes = HashMap::new();
let mut q = std::collections::VecDeque::new();
let mut visited = std::collections::HashSet::new();
q.push_back(start);
visited.insert(start);
while let Some(cell) = q.pop_front() {
changes.insert(cell, self.current_color);
for neighbor in picture.neighbor_cells(cell) {
if picture.cells()[neighbor as usize] == target_color && visited.insert(neighbor) {
q.push_back(neighbor);
}
}
}
if !changes.is_empty() {
self.perform(Action::ChangeColor { changes }, ActionMood::Normal);
}
}
/// Lift the selection onto a floating layer: remember what was there, then clear it to
/// background. The area moved away from is always background, so this happens the moment a
/// move begins rather than when it ends.
///
/// Re-bases the mask onto wherever the selection is showing right now, so `offset` measures
/// the move from here and the whole thing runs at most once per selection.
fn lift_selection(&mut self) {
let Some(selection) = &mut self.selection else {
return;
};
if selection.floating.is_some() {
return; // Already lifted; a second drag just changes the offset.
}
let picture = self.document.solution_mut();
let displayed = selection.displayed_cells(picture);
let cells = picture.cells();
let mut mask = vec![false; cells.len()];
let mut floating = Vec::with_capacity(displayed.len());
for cell in displayed {
mask[cell as usize] = true;
floating.push((cell, cells[cell as usize]));
}
selection.mask = mask;
selection.offset = (0, 0);
selection.floating = Some(floating);
let changes: HashMap<u32, Color> = selection
.floating
.as_ref()
.unwrap()
.iter()
.map(|(cell, _)| (*cell, BACKGROUND))
.collect();
self.perform(Action::ChangeColor { changes }, ActionMood::Normal);
}
/// Stamp the floating layer back into the picture at wherever it has been dragged to, and
/// re-base the selection there. It remains selected, though.
///
/// Only non-background cells are stamped. Cells dragged off the grid are dropped.
pub fn flatten_selection(&mut self) {
let Some(selection) = &mut self.selection else {
return;
};
let Some(floating) = selection.floating.take() else {
return;
};
let picture = self.document.solution_mut();
let mut mask = vec![false; picture.cells().len()];
let mut changes = HashMap::new();
for (cell, color) in floating {
let Some(dest) = picture.translate_cell(cell, selection.offset) else {
continue;
};
mask[dest as usize] = true;
if color != BACKGROUND {
changes.insert(dest, color);
}
}
selection.mask = mask;
selection.offset = (0, 0);
if !changes.is_empty() {
self.perform(Action::ChangeColor { changes }, ActionMood::Normal);
}
}
/// Flatten whatever is floating and forget the selection entirely.
pub fn clear_selection(&mut self) {
self.flatten_selection();
self.selection = None;
}
/// Fill the selection with background, without moving anything.
fn erase_selection(&mut self) {
let Some(selection) = &self.selection else {
return;
};
let picture = self.document.solution_mut();
let changes: HashMap<u32, Color> = selection
.displayed_cells(picture)
.into_iter()
.map(|cell| (cell, BACKGROUND))
.collect();
if !changes.is_empty() {
self.perform(Action::ChangeColor { changes }, ActionMood::Normal);
}
}
/// Whether the point is inside the selection as it's currently displayed — i.e. whether
/// pressing there starts a move rather than a new lasso.
fn selection_contains(&mut self, p: Point) -> bool {
let picture = self.document.solution_mut();
let Some(cell) = picture.cell_at(p).and_then(|c| picture.cell_of(c)) else {
return false;
};
self.cell_is_selected(cell)
}
/// One frame of lasso pointer input, at `p` in abstract units.
///
/// Takes the three facts it needs rather than egui's `PointerState` so the whole
/// draw-drag-flatten cycle can be driven from a test without a window.
fn lasso_input(&mut self, pointer: LassoPointer, p: Point) {
// Secondary and middle buttons paint in the other tools; here they'd have no meaning, so
// they're simply ignored rather than doing something surprising.
if pointer.pressed {
if self.selection_contains(p) {
self.lift_selection();
let offset = self.selection.as_ref().map_or((0, 0), |s| s.offset);
if let Some(selection) = &mut self.selection {
selection.dragging = Some((p, offset));
}
} else {
self.flatten_selection();
self.selection = None;
let mut selection =
Selection::new(vec![false; self.document.solution_mut().cells().len()]);
selection.drawing = Some(vec![p]);
self.selection = Some(selection);
}
} else if pointer.down {
let snapped =
self.selection
.as_ref()
.and_then(|s| s.dragging)
.map(|(grab, offset_at_grab)| {
let by = crate::layout::Vec2::new(p.x - grab.x, p.y - grab.y);
let (du, dv) = self.document.solution_mut().snap_translation(by);
(offset_at_grab.0 + du, offset_at_grab.1 + dv)
});
if let Some(selection) = &mut self.selection {
if let Some(offset) = snapped {
// The lattice map is linear, so snapping the displacement and adding steps
// gives the same answer as snapping the total.
selection.offset = offset;
} else if let Some(path) = &mut selection.drawing {
// Thin the path as it's drawn: the rasterizer's cost is linear in its length,
// and points a tenth of a cell apart tell us nothing new.
let last = path.last().copied().unwrap_or(p);
if (p.x - last.x).hypot(p.y - last.y) >= 0.1 || path.len() == 1 {
path.push(p);
}
}
}
} else if pointer.released {
let path = self.selection.as_mut().and_then(|selection| {
selection.dragging = None;
selection.drawing.take()
});
if let Some(path) = path {
let mask = cells_in_lasso(self.document.solution_mut(), &path);
if let Some(selection) = &mut self.selection {
selection.mask = mask;
selection.since = Instant::now();
}
if self.selection.as_ref().is_some_and(|s| s.is_empty()) {
self.selection = None; // A stray click shouldn't leave an invisible selection.
}
}
}
}
/// Escape drops the selection; Delete/Backspace clears it to background. Read raw, matching
/// how the undo/redo shortcuts alongside the toolbar already work.
fn lasso_keys(&mut self, ui: &egui::Ui) {
if self.selection.is_none() {
return;
}
let (escape, delete) = ui.input(|i| {
(
i.key_pressed(egui::Key::Escape),
i.key_pressed(egui::Key::Delete) || i.key_pressed(egui::Key::Backspace),
)
});
if escape {
self.clear_selection();
} else if delete {
self.erase_selection();
}
}
/// The traditional four-arrow cursor over the selection says "this can be dragged"; the
/// crosshair elsewhere says "this draws a loop".
fn lasso_cursor(&mut self, ui: &egui::Ui, hovered_cell: Option<u32>) {
// Not over the grid at all — leave the cursor to whatever else is under it.
let Some(cell) = hovered_cell else {
return;
};
let dragging = self
.selection
.as_ref()
.is_some_and(|s| s.dragging.is_some());
let icon = if dragging || self.cell_is_selected(cell) {
egui::CursorIcon::Move
} else {
egui::CursorIcon::Crosshair
};
ui.ctx().set_cursor_icon(icon);
}
/// Whether a cell is part of the selection as displayed. Asks where the cell *came from*
/// rather than materializing the whole displaced set.
fn cell_is_selected(&mut self, cell: u32) -> bool {
let Some(selection) = &self.selection else {
return false;
};
if selection.drawing.is_some() {
return false;
}
let (u, v) = selection.offset;
let anchor = self.document.solution_mut().translate_cell(cell, (-u, -v));
let selection = self.selection.as_ref().unwrap();
anchor.is_some_and(|anchor| selection.mask[anchor as usize])
}
}
/// How finely the lasso path is sampled when marking the cells it passes through, in abstract
/// units. Must be below the smallest cell dimension — a triangle row is only `TRI_ROW_HEIGHT`
/// (0.87) tall and cells are half a base wide — so that no cell the path crosses is stepped over.
const LASSO_STEP: f32 = 0.2;
/// The cells a closed lasso path touches or encloses.
///
/// "Touched" is found by walking the path rather than by remembering which cells the pointer was
/// over: that covers the straight closing segment and fast drags that skip cells between frames,
/// with one rule instead of three. "Enclosed" is an even-odd ray cast against each cell's
/// centroid. Runs once, on release, so `cells × path points` is fine.
pub fn cells_in_lasso(picture: &crate::puzzle::DynSolution, path: &[Point]) -> Vec<bool> {
let mut mask = vec![false; picture.cells().len()];
if path.len() < 2 {
// A click rather than a drag: just the cell under it, if any.
if let Some(cell) = path
.first()
.and_then(|p| picture.cell_at(*p))
.and_then(|c| picture.cell_of(c))
{
mask[cell as usize] = true;
}
return mask;
}
// Touched, including along the closing segment from the last point back to the first.
for (a, b) in path
.iter()
.zip(path.iter().cycle().skip(1))
.take(path.len())
{
let (dx, dy) = (b.x - a.x, b.y - a.y);
let steps = ((dx.hypot(dy) / LASSO_STEP).ceil() as usize).max(1);
for i in 0..=steps {
let t = i as f32 / steps as f32;
let p = Point::new(a.x + dx * t, a.y + dy * t);
if let Some(cell) = picture.cell_at(p).and_then(|c| picture.cell_of(c)) {
mask[cell as usize] = true;
}
}
}
// Enclosed: a horizontal ray from the centroid crosses the closed path an odd number of times.
for cell in 0..mask.len() as u32 {
if mask[cell as usize] {
continue;
}
let c = picture.cell_shape(cell).center(picture.cell_origin(cell));
let mut inside = false;
for (a, b) in path
.iter()
.zip(path.iter().cycle().skip(1))
.take(path.len())
{
if (a.y > c.y) != (b.y > c.y) && c.x < a.x + (c.y - a.y) / (b.y - a.y) * (b.x - a.x) {
inside = !inside;
}
}
mask[cell as usize] = inside;
}
mask
}
/// The contiguous block of one color under the pointer, as the clue gutters need it: which lane
/// it runs along in each clue family, and how long it is there. The same figure the sidebar
/// rosette adds up — its two arms, plus the hovered cell itself.
#[derive(Clone, PartialEq, Debug)]
pub struct HoverBlocks {
/// `(lane, length)` per clue family, as `DynSolution::blocks_at_cell` reports it.
pub by_family: Vec<(usize, usize)>,
/// The hovered cell's color: what the numbers are drawn in.
pub rgb: (u8, u8, u8),
}
impl HoverBlocks {
/// How long the hovered block is along `lane`, if it runs along that lane at all.
pub fn on_lane(&self, lane: usize) -> Option<usize> {
self.by_family
.iter()
.find(|(l, _)| *l == lane)
.map(|(_, len)| *len)
}
}
/// What a canvas needs in order to draw clue gutters around the picture. Only the solve view
/// supplies this; the editor draws the picture alone.
pub struct ClueOverlay<'a> {
pub puzzle: &'a crate::puzzle::DynPuzzle,
/// One `Vec<LineStatus>` per clue family, in family order.
pub analysis: Option<&'a Vec<Vec<crate::grid_solve::LineStatus>>>,
pub is_stale: bool,
/// The hovered cell's block lengths, shown in place of the analysis marks on its own lanes.
pub hover: Option<HoverBlocks>,
}
impl CanvasGui {
/// How far each lane's clues reach out from the grid, in abstract units.
fn clue_run_length(puzzle: &crate::puzzle::DynPuzzle, lane: usize) -> f32 {
let parts = crate::with_puzzle!(puzzle, |p| {
p.lines[lane]
.iter()
.map(|c| c.express(&p.palette).len())
.sum::<usize>()
});
crate::layout::GutterLane::clue_run_length(parts)
}
/// Draw the picture and handle pointer input. Returns the hovered cell, if any.
///
/// Shape-specific work happens in exactly two places: the hit test, and the render loop.
/// Everything else — the tools, undo, the overlays — works in dense cell indices and is the
/// same for every shape.
pub fn canvas(
&mut self,
ui: &mut egui::Ui,
scale: f32,
render_style: RenderStyle,
) -> Option<u32> {
self.canvas_with_clues(ui, scale, render_style, None)
}
/// As `canvas`, but reserving room around the picture for clue gutters and drawing them.
///
/// Clues share the picture's painter and coordinate system rather than living in their own
/// widgets, because a hexagon's three clue blocks are not axis-aligned rectangles and can't be
/// laid out by a grid of separate panels.
pub fn canvas_with_clues(
&mut self,
ui: &mut egui::Ui,
scale: f32,
render_style: RenderStyle,
clues: Option<ClueOverlay<'_>>,
) -> Option<u32> {
let extent = self.document.solution_mut().extent();
// Grow the drawing area to cover wherever the clues reach.
let (mut lo, mut hi) = (
crate::layout::Point::new(0.0, 0.0),
crate::layout::Point::new(extent.x, extent.y),
);
if let Some(overlay) = &clues {
for (_, gutter) in self.document.solution_mut().gutters() {
for g in gutter {
let len = Self::clue_run_length(overlay.puzzle, g.lane);
let tip = crate::layout::Point::new(
g.anchor.x + g.outward.x * len,
g.anchor.y + g.outward.y * len,
);
let half = crate::layout::CLUE_BOX;
lo.x = lo.x.min(tip.x - half);
lo.y = lo.y.min(tip.y - half);
hi.x = hi.x.max(tip.x + half);
hi.y = hi.y.max(tip.y + half);
}
}
}
let full = Vec2::new(hi.x - lo.x, hi.y - lo.y);
let (mut response, painter) = ui.allocate_painter(
Vec2::new(scale * full.x, scale * full.y) + Vec2::new(2.0, 2.0), // for the border
egui::Sense::click_and_drag(),
);
let canvas_without_border = response.rect.shrink(1.0);
// One abstract unit is one cell edge, so this is a plain uniform scale. `lo` is where the
// outermost clue sits, so the picture itself is offset by `-lo`.
let to_screen = egui::emath::RectTransform::from_to(
Rect::from_min_size(Pos2::new(lo.x, lo.y), full),
canvas_without_border,
);
let from_screen = to_screen.inverse();
// The picture's own area, with any clue gutters excluded: this is somewhere a click
// reliably lands on a cell.
self.picture_rect = Some(to_screen.transform_rect(Rect::from_min_size(
Pos2::ZERO,
Vec2::new(extent.x, extent.y),
)));
let cell_under = |picture: &crate::puzzle::DynSolution, pos: Pos2| -> Option<u32> {
let p = from_screen * pos;
picture
.cell_at(crate::layout::Point::new(p.x, p.y))
.and_then(|coord| picture.cell_of(coord))
};
let hovered_cell = response
.hover_pos()
.and_then(|pos| cell_under(self.document.solution_mut(), pos));
// A mask is a dense-cell-index array, so it means nothing once the grid is a different
// size. Checking here rather than at every resize/load site means there's no call site
// to forget.
if let Some(selection) = &self.selection
&& selection.mask.len() != self.document.solution_mut().cells().len()
{
self.selection = None;
}
if self.current_tool == Tool::Lasso {
// The lasso is the one tool that must keep tracking the pointer once it leaves the
// grid — a loop drawn around the outside of a shape is perfectly ordinary — so it
// works from the abstract-unit position directly, not from a cell.
if let Some(pointer_pos) = response.interact_pointer_pos() {
let p = from_screen * pointer_pos;
let pointer = LassoPointer::from_egui(&ui.input(|i| i.pointer.clone()));
self.lasso_input(pointer, Point::new(p.x, p.y));
}
self.lasso_keys(ui);
self.lasso_cursor(ui, hovered_cell);
} else if hovered_cell.is_some() {
// There's no brush or paint-bucket in the standard cursor set, so the best these can
// do is say how precise the tool is: the two that paint a cell the pointer is exactly
// on get a crosshair, and flood fill — which acts on a whole region — gets the
// blockier `Cell` instead, just so it doesn't look identical to them.
ui.ctx().set_cursor_icon(match self.current_tool {
Tool::Pencil | Tool::LineAlongLane => egui::CursorIcon::Crosshair,
Tool::FloodFill => egui::CursorIcon::Cell,
Tool::Lasso => unreachable!("handled above"),
});
}
if let Some(pointer_pos) = response.interact_pointer_pos() {
let picture = self.document.solution_mut();
if let Some(cell) = cell_under(picture, pointer_pos).filter(|_| {
// Handled above, without needing a cell.
self.current_tool != Tool::Lasso
}) {
let pointer = &ui.input(|i| i.pointer.clone());
let paint_color = if pointer.middle_down() {
if picture.palette().contains_key(&UNSOLVED) {
UNSOLVED
} else {
BACKGROUND
}
} else if pointer.secondary_down() {
BACKGROUND
} else if picture.cells()[cell as usize] != self.current_color {
self.current_color
} else {
BACKGROUND
};
// Paranoia, since it would cause a crash.
debug_assert!(
picture.palette().contains_key(&paint_color),
"painting with {paint_color:?}, which is not in the palette"
);
let paint_color = if picture.palette().contains_key(&paint_color) {
paint_color
} else {
BACKGROUND
};
match self.current_tool {
Tool::Pencil => {
let mood = if pointer.any_pressed() {
self.drag_start_color = paint_color;
ActionMood::Normal
} else {
ActionMood::Merge
};
self.perform(
Action::ChangeColor {
changes: [(cell, self.drag_start_color)].into(),
},
mood,
);
}
Tool::FloodFill => {
if pointer.any_click() {
let original_color = self.current_color;
self.current_color = paint_color;
self.flood_fill(cell);
self.current_color = original_color;
}
}
Tool::LineAlongLane => {
if pointer.any_pressed() {
self.drag_start_color = paint_color;
self.line_tool_state = Some(cell);
self.perform(
Action::ChangeColor {
changes: [(cell, self.drag_start_color)].into(),
},
ActionMood::Normal,
);
} else if pointer.any_down() {
if let Some(start) = self.line_tool_state {
let changes = self.line_between(start, cell);
self.perform(
Action::ChangeColor { changes },
ActionMood::ReplaceAction,
);
}
} else if pointer.any_released() {
self.line_tool_state = None;
}
}
// Handled above, where the pointer is still allowed to be off the grid.
Tool::Lasso => {}
}
}
}
let mut shapes = vec![];
let disambiguator = self.disambiguator.get_if_fresh(self.version);
let disambig_report = disambiguator.as_ref().and_then(|d| d.report.as_ref());
let solved_mask = self.solved_mask.get_if_fresh(self.version);
let overlays_suppress_unsolved = disambig_report.is_some()
|| disambiguator.is_some_and(|d| d.progress > 0.0 && d.progress < 1.0);
let picture = self.document.try_solution().unwrap();
let palette = picture.palette();
// The one place the shape matters when drawing. After this match the loop is fully
// monomorphized: the inner iterator just walks a slice and advances an `f32`.
crate::with_solution!(picture, |sol| {
for row in sol.geometry.rows() {
for drawn in row.cells() {
let index = drawn.cell as usize;
let color_info = &palette[&sol.cells[index]];
let solved =
solved_mask.is_none_or(|sm| sm.1[index]) || overlays_suppress_unsolved;
let mut dr = (&palette[&BACKGROUND], 1.0);
if let Some(report) = disambig_report.as_ref() {
let (c, score) = report[index];
dr = (&palette[&c], score);
}
shapes.extend(cell_shape(
color_info,
solved,
dr,
drawn.shape,
drawn.origin,
&to_screen,
render_style,
));
}
}
});
// The floating layer, drawn on top of the picture at wherever it's been dragged to. The
// cells it was lifted from already read as background, so this is the only thing standing
// between the two positions.
if let Some(selection) = &self.selection
&& let Some(floating) = &selection.floating
{
for (cell, color) in floating {
// Background cells don't move.
if *color == BACKGROUND {
continue;
}
let Some(dest) = picture.translate_cell(*cell, selection.offset) else {
continue; // Dragged off the grid; still in the layer, just not visible.
};
shapes.extend(cell_shape(
&palette[color],
true,
(&palette[&BACKGROUND], 1.0),
picture.cell_shape(dest),
picture.cell_origin(dest),
&to_screen,
render_style,
));
}
}
// Clue gutters, in the same coordinate system as the picture.
if let Some(overlay) = &clues {
let lane_families: Vec<usize> = picture
.lane_map()
.lanes()
.iter()
.map(|l| l.family)
.collect();
let family_starts: Vec<usize> = (0..picture.lane_map().family_count())
.map(|f| picture.lane_map().family(f).start)
.collect();
for (_, gutter) in picture.gutters() {
for g in gutter {
let expressed = crate::with_puzzle!(overlay.puzzle, |p| {
let mut v: Vec<(ColorInfo, Option<u16>)> = p.lines[g.lane]
.iter()
.flat_map(|c| {
c.express(&p.palette)
.into_iter()
.map(|(ci, n)| (ci.clone(), n))
})
.collect();
// Clues run in the lane's own direction, so the box nearest the grid is
// the last one; `reversed` covers the families whose clues are labelled
// at the far end from where the lane is stored.
if !g.reversed {
v.reverse();
}
v
});
let family = lane_families[g.lane];
for (i, (color_info, count)) in expressed.iter().enumerate() {
let c = g.clue_box_center(i);
let points = crate::layout::tri_clue_rhombus(
c,
family,
g.edge_dir,
crate::layout::CLUE_BOX,
crate::layout::CLUE_BOX_SHORT,
)
.map(|p| to_screen * Pos2::new(p.x, p.y));
let text = match count {
Some(n) => n.to_string(),
None => color_info.ch.to_string(),
};
crate::gui_solver::draw_string_in_rhombus(
ui,
&painter,
&points,
&text,
scale,
color_info.rgb,
);
}
// The indicator strip between the clues and the grid: the hovered block's
// length on the three lanes it runs along, and the analysis mark (which the
// number deliberately covers up) everywhere else.
let at = to_screen
* Pos2::new(
g.anchor.x + g.outward.x * (crate::layout::CLUE_PAD / 2.0),
g.anchor.y + g.outward.y * (crate::layout::CLUE_PAD / 2.0),
);
let hovered = overlay
.hover
.as_ref()
.and_then(|h| Some((h.on_lane(g.lane)?, h.rgb)));
match hovered {
Some((len, rgb)) => crate::gui_solver::draw_bare_number(
ui,
&painter,
at,
&len.to_string(),
scale,
rgb,
),
None => {
if let Some(analysis) = overlay.analysis {
let family = lane_families[g.lane];
let index = g.lane - family_starts[family];
if let Some(status) =
analysis.get(family).and_then(|f| f.get(index))
{
crate::gui_solver::draw_analysis_mark(
&painter,
at,
scale,
status,
overlay.is_stale,
);
}
}
}
}
}
}
}
// Grid lines, precomputed by the geometry: one boundary per lane, with every fifth one
// heavier — which for a triddler means every fifth lane *within a family*.
for guide in picture.guides() {
let points = [
to_screen * Pos2::new(guide.from.x, guide.from.y),
to_screen * Pos2::new(guide.to.x, guide.to.y),
];
let stroke = egui::Stroke::new(
1.0,
egui::Color32::from_black_alpha(if guide.emphasis { 64 } else { 16 }),
);
shapes.push(egui::Shape::line_segment(points, stroke));
}
if let Some(selection) = &self.selection {
if let Some(path) = &selection.drawing {
// The loop as it's being drawn (open)
let points: Vec<Pos2> = path
.iter()
.map(|p| to_screen * Pos2::new(p.x, p.y))
.collect();
shapes.push(egui::Shape::line(
points,
egui::Stroke::new(1.0, Color32::from_black_alpha(160)),
));
} else {
shapes.extend(marching_ants(
&selection_outline(picture, &selection.displayed_cells(picture)),
&to_screen,
selection.since.elapsed().as_secs_f32(),
));
}
// Only while a selection exists, so the idle app stays idle.
ui.ctx().request_repaint_after(Duration::from_millis(50));
}
painter.extend(shapes);
response.mark_changed();
hovered_cell
}
/// The cells between two points along whichever lane best matches the drag.
///
/// A square grid offers two directions through a cell; a triddler offers three. Picking the
/// family whose lane actually contains both endpoints generalizes the old "is this drag more
/// horizontal than vertical?" test.
fn line_between(&mut self, start: u32, end: u32) -> HashMap<u32, Color> {
let picture = self.document.solution_mut();
let lanes = picture.lane_map();
let mut changes = HashMap::new();
if start == end {
changes.insert(end, self.drag_start_color);
return changes;
}
// Cell *centres*, not raw origins: a triangle's centroid sits off-corner and at a
// different offset for ▲ than ▼, so mixing origins would misjudge lane direction
// whenever a lane's cells alternate orientation.
let center = |cell: u32| picture.cell_shape(cell).center(picture.cell_origin(cell));
let start_center = center(start);
let end_center = center(end);
let drag =
crate::layout::Vec2::new(end_center.x - start_center.x, end_center.y - start_center.y);
let drag_len = (drag.x * drag.x + drag.y * drag.y).sqrt();
// A lane's cells zigzag between ▲ and ▼ centroids on a triangular grid, so the step to
// an immediate neighbor is not representative of the lane's direction — e.g. from a ▲,
// the very next step is purely vertical even on a "/" lane. Use the span from the lane's
// first cell to its last instead, which averages the zigzag out into the lane's true
// on-screen direction, and gives a stable average per-cell spacing along it.
let mut best: Option<(usize, f32)> = None; // (lane, |cos angle| to drag)
for membership in lanes.memberships(start) {
let lane = lanes.lane(membership.lane as usize);
if lane.cells.len() < 2 {
continue; // No direction to compare against.
}
let first = center(lane.cells[0]);
let last = center(*lane.cells.last().unwrap());
let span = crate::layout::Vec2::new(last.x - first.x, last.y - first.y);
let span_len = (span.x * span.x + span.y * span.y).sqrt();
// Angle between the lane's direction and the drag, ignoring which way along the
// lane it points, so dragging toward either end still snaps to that lane.
let cos_angle = ((span.x * drag.x + span.y * drag.y) / (span_len * drag_len)).abs();
if best.is_none_or(|(_, best_cos)| cos_angle > best_cos) {
best = Some((membership.lane as usize, cos_angle));
}
}
match best {
Some((lane_idx, _)) => {
let lane = lanes.lane(lane_idx);
let from_pos = lanes
.memberships(start)
.iter()
.find(|m| m.lane as usize == lane_idx)
.unwrap()
.position as usize;
let first = center(lane.cells[0]);
let last = center(*lane.cells.last().unwrap());
let span = crate::layout::Vec2::new(last.x - first.x, last.y - first.y);
let span_len = (span.x * span.x + span.y * span.y).sqrt();
let avg_spacing = span_len / (lane.cells.len() - 1) as f32;
// Distance travelled along the lane, in cell steps, found by projecting the
// drag onto the lane's own (first-to-last) direction.
let signed_distance = (drag.x * span.x + drag.y * span.y) / span_len;
let delta = (signed_distance / avg_spacing).round() as isize;
let to_pos =
(from_pos as isize + delta).clamp(0, lane.cells.len() as isize - 1) as usize;
let (from, to) = (from_pos.min(to_pos), from_pos.max(to_pos));
for cell in &lane.cells[from..=to] {
changes.insert(*cell, self.drag_start_color);
}
}
// `start` sits in no lane with a usable direction; just paint the endpoint.
None => {
changes.insert(end, self.drag_start_color);
}
}
changes
}
fn palette_editor(&mut self, ui: &mut egui::Ui, read_only: bool) {
let mut picked_color = self.current_color;
let mut removed_color = None;
let mut add_color = false;
use itertools::Itertools;
for (color, color_info) in self
.document
.solution_mut()
.palette_mut()
.iter_mut()
.sorted_by_key(|(color, _)| *color)
{
// TODO: actually paint a palette entry for unsolved,
// in case the user doesn't have a middle button.
if *color == UNSOLVED && read_only {
continue;
}
let (r, g, b) = color_info.rgb;
let button_text = if color_info.corner.is_some() {
color_info.ch.to_string()
} else {
"■".to_string()
};
ui.horizontal(|ui| {
ui.label(RichText::new(icons::ICON_CHEVRON_FORWARD).size(24.0).color(
Color32::from_black_alpha(if *color == picked_color { 255 } else { 0 }),
));
let color_text = RichText::new(button_text)
.monospace()
.size(24.0)
.color(egui::Color32::from_rgb(r, g, b));
if ui.add(egui::Button::new(color_text)).clicked() {
picked_color = *color;
};
if !read_only {
let mut edited_color = [r as f32 / 256.0, g as f32 / 256.0, b as f32 / 256.0];
let edit = ui.color_edit_button_rgb(&mut edited_color);
// `egui` only allows rectangular-swatch-of-current-color as the palette marker,
// which doesn't look good in this case. (In fact, the color is also somewhat wrong)
// HACK: draw a pencil icon over it.
let visuals = *ui.style().interact(&edit);
let painter = ui.painter();
painter.rect(
edit.rect,
visuals.corner_radius,
visuals.bg_fill,
visuals.bg_stroke,
egui::StrokeKind::Inside,
);
painter.text(
edit.rect.center(),
egui::Align2::CENTER_CENTER,
icons::ICON_EDIT,
egui::FontId::proportional(edit.rect.height() * 0.7),
visuals.fg_stroke.color,
);
if edit.on_hover_text("Edit this color").changed() {
// TODO: this should probably also be undoable
picked_color = *color;
color_info.rgb = (
(edited_color[0] * 256.0) as u8,
(edited_color[1] * 256.0) as u8,
(edited_color[2] * 256.0) as u8,
);
}
if *color != BACKGROUND && ui.button(icons::ICON_DELETE).clicked() {
removed_color = Some(*color);
}
}
});
}
if !read_only && ui.button("New color").clicked() {
add_color = true;
}
self.current_color = picked_color;
if Some(self.current_color) == removed_color {
self.current_color = BACKGROUND;
}
if let Some(removed_color) = removed_color {
let mut new_document = self.document.clone();
let new_picture = new_document.solution_mut();
for cell in new_picture.cells_mut().iter_mut() {
if *cell == removed_color {
*cell = self.current_color;
}
}
new_picture.palette_mut().remove(&removed_color);
self.perform(
Action::ReplaceDocument {
document: Box::new(new_document),
},
ActionMood::Normal,
);
}
if add_color {
let mut new_document = self.document.clone();
let new_picture = new_document.solution_mut();
let next_color = Color(new_picture.palette().keys().map(|k| k.0).max().unwrap() + 1);
new_picture.palette_mut().insert(
next_color,
ColorInfo {
ch: (next_color.0 + 65) as char, // TODO: will break chargrid export
name: "New color".to_string(),
rgb: (128, 128, 128),
color: next_color,
corner: None,
},
);
self.perform(
Action::ReplaceDocument {
document: Box::new(new_document),
},
ActionMood::Normal,
);
}
}
}
pub fn triangle_shape(corner: Corner, color: egui::Color32, scale: Vec2) -> egui::Shape {
let Corner { left, upper } = corner;
let mut points = vec![];
// The `+`ed offsets are empirircally-set to make things fit better.
if left || upper {
points.push((Vec2::new(0.0, 0.0) * scale + Vec2::new(0.25, -0.5)).to_pos2());
}
if !left || upper {
points.push((Vec2::new(1.0, 0.0) * scale + Vec2::new(0.25, -0.5)).to_pos2());
}
if !left || !upper {
points.push((Vec2::new(1.0, 1.0) * scale + Vec2::new(0.25, 0.5)).to_pos2());
}
if left || !upper {
points.push((Vec2::new(0.0, 1.0) * scale + Vec2::new(0.25, 0.5)).to_pos2());
}
Shape::convex_polygon(points, color, (0.0, color))
}
/// The outline of a set of cells, as a list of abstract-unit segments.
///
/// Found by cancellation: push every selected cell's edges into a table, and an edge shared by
/// two selected cells lands there twice. What's left having landed once is exactly the boundary.
/// Works for squares and triangles.
fn selection_outline(picture: &DynSolution, cells: &[u32]) -> Vec<(Point, Point)> {
/// A cell corner quantized onto a fixed sub-cell grid. Corners land on exact lattice values,
/// so this is stable, and two cells' shared edge always produces the identical key.
type Vertex = (i32, i32);
/// An edge, as its two vertices in a canonical order.
type EdgeKey = (Vertex, Vertex);
let key =
|p: Point| -> Vertex { ((p.x * 4096.0).round() as i32, (p.y * 4096.0).round() as i32) };
let mut edges: HashMap<EdgeKey, ((Point, Point), u32)> = HashMap::new();
for cell in cells {
let shape = picture.cell_shape(*cell);
let (points, n) = shape.vertices(picture.cell_origin(*cell));
for i in 0..n {
let (a, b) = (points[i], points[(i + 1) % n]);
let (ka, kb) = (key(a), key(b));
let k = if ka <= kb { (ka, kb) } else { (kb, ka) };
edges.entry(k).or_insert(((a, b), 0)).1 += 1;
}
}
edges
.into_values()
.filter(|(_, count)| *count == 1)
.map(|(edge, _)| edge)
.collect()
}
/// Stitch a boundary's unordered edges into closed loops, each a list of points ending back where
/// it started. A cell's edges are wound consistently, and that winding survives cancellation, so
/// each vertex is the tail of exactly one surviving edge: following tail-to-head therefore always
/// closes a loop.
///
/// Loops matter (rather than the raw edge list) so the marching ants can be drawn as one dashed
/// path per loop: dashing a whole path keeps the dash phase continuous across corners, where
/// dashing each edge in isolation would restart the pattern at every corner.
fn outline_loops(outline: &[(Point, Point)]) -> Vec<Vec<Point>> {
type Vertex = (i32, i32);
let key =
|p: Point| -> Vertex { ((p.x * 4096.0).round() as i32, (p.y * 4096.0).round() as i32) };
let mut next: HashMap<Vertex, (Point, Point)> = HashMap::new();
for &(a, b) in outline {
next.insert(key(a), (a, b));
}
let mut loops = Vec::new();
let mut visited: std::collections::HashSet<Vertex> = std::collections::HashSet::new();
for &(start, _) in outline {
let start_key = key(start);
if !visited.insert(start_key) {
continue;
}
let mut loop_points = vec![start];
let mut cur = start_key;
while let Some(&(_, b)) = next.get(&cur) {
loop_points.push(b);
cur = key(b);
if cur == start_key || !visited.insert(cur) {
break;
}
}
loops.push(loop_points);
}
loops
}
/// Dash length and gap for the marching ants, in points, and how fast the dashes crawl.
const ANT_DASH: f32 = 4.0;
const ANT_SPEED: f32 = 12.0;
/// Draw a selection outline as marching ants: dark dashes crawling over a light line, so the
/// outline reads against both a filled cell and an empty one.
fn marching_ants(
outline: &[(Point, Point)],
to_screen: &egui::emath::RectTransform,
elapsed: f32,
) -> Vec<Shape> {
let loops = outline_loops(outline);
let mut shapes = Vec::with_capacity(loops.len() * 2);
// `dashed_line_with_offset` walks the offset forward from each path's start and assumes it's
// non-negative; a negative one makes it extrapolate the first dash backward past the start
// point, flashing a stray segment there. `%` alone can return negative, so use `rem_euclid`.
let offset = (-(elapsed * ANT_SPEED)).rem_euclid(ANT_DASH * 2.0);
for loop_points in loops {
let points: Vec<Pos2> = loop_points
.iter()
.map(|p| to_screen * Pos2::new(p.x, p.y))
.collect();
shapes.push(Shape::line(
points.clone(),
egui::Stroke::new(1.5, Color32::from_white_alpha(220)),
));
shapes.extend(Shape::dashed_line_with_offset(
&points,
egui::Stroke::new(1.5, Color32::from_black_alpha(220)),
&[ANT_DASH],
&[ANT_DASH],
offset,
));
}
shapes
}
/// Build the shapes for one cell. `shape` and `origin` come from the geometry, so a triangle is
/// drawn as a triangle and every overlay lands on the real centroid rather than the middle of a
/// bounding box.
fn cell_shape(
ci: &ColorInfo,
solved: bool,
disambig: (&ColorInfo, f32),
shape: crate::layout::CellShape,
origin: crate::layout::Point,
to_screen: &egui::emath::RectTransform,
render_style: RenderStyle,
) -> Vec<egui::Shape> {
let (r, g, b) = ci.rgb;
let color = if ci.color == UNSOLVED {
if render_style == RenderStyle::Experimental {
egui::Color32::from_rgb(160, 160, 160)
} else {
egui::Color32::WHITE
}
} else {
egui::Color32::from_rgb(r, g, b)
};
let screen = |p: crate::layout::Point| to_screen * Pos2::new(p.x, p.y);
let polygon = |(points, n): ([crate::layout::Point; 4], usize), fill| {
egui::Shape::convex_polygon(
points[..n].iter().map(|p| screen(*p)).collect(),
fill,
egui::Stroke::default(),
)
};
// A `Corner` color is a half-square used by trianogram clues, and appears only on a square grid. It's a different thing
// from a triangular *cell*.
let mut res = vec![match ci.corner {
None => polygon(shape.vertices(origin), color),
Some(corner) => {
let mut half = triangle_shape(corner, color, to_screen.scale());
half.translate(screen(origin).to_vec2());
half
}
}];
let center = screen(shape.center(origin));
let unit = to_screen.scale().x;
if ci.color == BACKGROUND {
match render_style {
RenderStyle::TraditionalDots => {
res.push(egui::Shape::circle_filled(
center,
unit * 0.1,
egui::Color32::from_rgb(190, 190, 190),
));
}
RenderStyle::TraditionalXes => {
let stroke = egui::Stroke::new(2.0, Color32::from_rgb(190, 190, 190));
let radius = unit * 0.2;
res.push(egui::Shape::line_segment(
[
center + Vec2::new(-radius, -radius),
center + Vec2::new(radius, radius),
],
stroke,
));
res.push(egui::Shape::line_segment(
[
center + Vec2::new(radius, -radius),
center + Vec2::new(-radius, radius),
],
stroke,
));
}
RenderStyle::Experimental => {}
}
}
if ci.color == UNSOLVED && render_style == RenderStyle::Experimental {
res.push(polygon(
shape.shrunk(origin, 0.6),
egui::Color32::from_rgb(230, 230, 230),
));
}
if !solved {
res.push(egui::Shape::circle_filled(
center,
unit * 0.3,
egui::Color32::from_rgb(190, 190, 190),
))
}
if disambig.1 < 1.0 {
let (r, g, b) = disambig.0.rgb;
res.push(polygon(
shape.shrunk(origin, 0.5),
Color32::from_rgba_unmultiplied(r, g, b, ((1.0 - disambig.1) * 255.0) as u8),
));
}
res
}
impl NonogramGui {
pub fn new(mut document: Document) -> Self {
// (Public for testing)
//
// A document loaded from a clue-only format (olsak, webpbn) has no picture yet, so solve
// for one. A self-contradictory puzzle can't produce one at all; rather than panicking,
// fall back to a blank canvas and say so once the status cell exists.
let mut load_error = None;
if let Err(e) = document.solution() {
load_error = Some(format!("could not solve this puzzle: {e}"));
document = Document::from_solution(
DynSolution::Square(Solution::blank_bw(20, 20)),
document.file.clone(),
);
}
let picture = document.try_solution().expect("just ensured there is one");
let solved_mask = vec![true; picture.cells().len()];
let current_color = default_color(picture.palette());
if document.author.is_empty()
&& let Some(author) = UserSettings::get(consts::EDITOR_AUTHOR_NAME)
{
document.author = author;
}
NonogramGui {
editor_gui: CanvasGui {
document,
version: 0,
current_color,
drag_start_color: current_color,
undo_stack: vec![],
redo_stack: vec![],
current_tool: Tool::Pencil,
line_tool_state: None,
selection: None,
picture_rect: None,
solved_mask: Staleable {
val: ("".to_string(), solved_mask),
version: 0,
},
disambiguator: Staleable {
val: Disambiguator::new(),
version: 0,
},
id: Staleable {
val: "".to_string(),
version: 0,
},
status: {
let status = StatusCell::new();
if let Some(message) = load_error {
status.set(StatusMessage::error(message));
}
status
},
progress: Rc::new(RefCell::new(None)),
},
scale: 16.0,
opened_file_receiver: mpsc::channel().1,
save_result_receiver: mpsc::channel().1,
library_receiver: mpsc::channel().1,
new_dialog: None,
library_dialog: None,
auto_solve: UserSettings::get_bool(consts::EDITOR_AUTO_SOLVE),
lines_to_affect_string: "5".to_string(),
solve_report: "".to_string(),
solve_mode: false,
solve_gui: None,
show_save_share_window: false,
share_string: "".to_string(),
pasted_string: "".to_string(),
quality_warnings: vec![],
}
}
/// Parses `lines_to_affect_string` (the resizer's "how many lines" box). On a bad value,
/// marks the field visibly wrong (appends "??") rather than showing a separate error — the
/// existing convention both resizers use.
fn resize_lines(&mut self) -> Option<usize> {
match self.lines_to_affect_string.parse::<usize>() {
Ok(lines) => Some(lines),
Err(_) => {
self.lines_to_affect_string += "??";
None
}
}
}
fn resize(&mut self, top: Option<bool>, left: Option<bool>, add: bool) {
// This resizer is inherently square: it adds and removes whole rows and columns.
// Triangular puzzles resize by nudging one of six bounds instead — see `tri_resize`.
let Some(picture) = self.editor_gui.document.square_solution_mut() else {
self.editor_gui
.status
.set(StatusMessage::error(TRIDDLER_UNSUPPORTED));
return;
};
let mut g = picture.to_columns();
let Some(lines) = self.resize_lines() else {
return;
};
if let Some(left) = left {
if add {
g.resize(g.len() + lines, vec![BACKGROUND; g.first().unwrap().len()]);
if left {
g.rotate_right(lines);
}
} else {
if left {
g.rotate_left(lines);
}
g.truncate(g.len() - lines);
}
} else if let Some(top) = top {
if add {
for row in g.iter_mut() {
row.resize(row.len() + lines, BACKGROUND);
if top {
row.rotate_right(lines);
}
}
} else {
for row in g.iter_mut() {
if top {
row.rotate_left(lines);
}
row.truncate(row.len() - lines);
}
}
}
let mut new_doc = Box::new(self.editor_gui.document.clone());
{
let solution = new_doc.solution_mut();
*solution = DynSolution::Square(Solution::from_columns(
solution.clue_style(),
solution.palette().clone(),
g,
));
}
self.editor_gui.perform(
Action::ReplaceDocument { document: new_doc },
ActionMood::Normal,
);
}
/// Triangular counterpart to `resize`: grows or shrinks one of the outline's six bounds
/// (see `Solution::resized`/`geometry::Side`) instead of adding/removing rows or columns.
fn tri_resize(&mut self, side: crate::geometry::Side, add: bool) {
let Some(lines) = self.resize_lines() else {
return;
};
let Some(tri) = self
.editor_gui
.document
.try_solution()
.and_then(|s| s.as_tri())
else {
self.editor_gui
.status
.set(StatusMessage::error(TRIDDLER_UNSUPPORTED));
return;
};
let delta = if add { lines as i32 } else { -(lines as i32) };
let Some(resized) = tri.resized(side, delta) else {
let message = if add {
"can't grow any further"
} else {
"can't shrink any further"
};
self.editor_gui.status.set(StatusMessage::error(message));
return;
};
let mut new_doc = Box::new(self.editor_gui.document.clone());
*new_doc.solution_mut() = DynSolution::Tri(resized);
self.editor_gui.perform(
Action::ReplaceDocument { document: new_doc },
ActionMood::Normal,
);
}
fn resizer(&mut self, ui: &mut egui::Ui) {
ui.vertical_centered(|ui| {
ui.label(format!(
"Canvas size: {}",
self.editor_gui.document.dims_label()
));
});
centered_row(ui, "resizer_row", |ui| {
egui::Grid::new("resizer").show(ui, |ui| {
ui.label("");
ui.horizontal(|ui| {
if ui.button(icons::ICON_ADD).clicked() {
self.resize(Some(true), None, true);
}
if ui.button(icons::ICON_REMOVE).clicked() {
self.resize(Some(true), None, false);
}
});
ui.label("");
ui.end_row();
ui.vertical(|ui| {
if ui.button(icons::ICON_ADD).clicked() {
self.resize(None, Some(true), true);
}
if ui.button(icons::ICON_REMOVE).clicked() {
self.resize(None, Some(true), false);
}
});
ui.text_edit_singleline(&mut self.lines_to_affect_string);
ui.vertical(|ui| {
if ui.button(icons::ICON_ADD).clicked() {
self.resize(None, Some(false), true);
}
if ui.button(icons::ICON_REMOVE).clicked() {
self.resize(None, Some(false), false);
}
});
ui.end_row();
ui.label("");
ui.horizontal(|ui| {
if ui.button(icons::ICON_ADD).clicked() {
self.resize(Some(false), None, true);
}
if ui.button(icons::ICON_REMOVE).clicked() {
self.resize(Some(false), None, false);
}
});
ui.label("");
});
});
}
/// Triangular counterpart to `resizer`: a hexagon holding the same "how many lines" box,
/// with a +/- pair on each of its six sides — one per `geometry::Side` — grown/shrunk via
/// `tri_resize`. Each pair sits flush against, and rotated parallel to, its own hexagon edge.
fn tri_resizer(&mut self, ui: &mut egui::Ui) {
ui.vertical_centered(|ui| {
ui.label(format!(
"Outline size: {}",
self.editor_gui.document.dims_label()
));
});
// Used to grey out a "+" that would have no effect at all (see `Outline::can_grow`) —
// not to decide what clicking it does, `tri_resize` re-checks that against a fresh
// `Solution` on its own.
let outline = self
.editor_gui
.document
.try_solution()
.and_then(|s| s.as_tri())
.map(|t| *t.geometry.dims());
// Layout constants, all in screen pixels.
const APOTHEM: f32 = 22.0; // centre-to-edge distance of the hexagon.
const CIRCUMRADIUS: f32 = APOTHEM / 0.866_025_4; // centre-to-vertex distance.
const EDIT_SIZE: Vec2 = Vec2::new(30.0, 18.0);
const BUTTON_ALONG: f32 = 12.0; // button extent parallel to its edge.
const BUTTON_ACROSS: f32 = 12.0; // button extent along the outward normal.
const BUTTON_GAP: f32 = 3.0; // gap between the +/- pair, along the edge.
const BUTTON_DISTANCE: f32 = APOTHEM + BUTTON_ACROSS / 2.0 + 3.0;
const MARK_RADIUS: f32 = 3.0; // half-length of the hand-drawn +/- strokes.
const PAD: f32 = 4.0; // headroom for stroke width / hover expansion at the edges.
let to_vec2 = |v: crate::layout::Vec2| Vec2::new(v.x, v.y);
let sides = crate::geometry::Side::all();
let outward_dirs: Vec<Vec2> = sides
.iter()
.map(|s| to_vec2(s.outward_and_edge_dir().0))
.collect();
// All the widget's geometry, as a pure function of where its centre ends up. Called
// once below against a placeholder centre just to measure how much room the widget
// actually needs, then again against the real centre once that's known — rather than
// guessing a fixed canvas size up front and hoping the content fits inside it (which
// previously left it either clipped or sitting in an oversized, wastefully padded box).
let layout = |center: Pos2| {
// Hexagon vertices: `Side::all()` is in cyclic (adjacent-sharing-a-vertex) order,
// and adjacent outward normals are exactly 60° apart, so their sum bisects the angle
// between them — the direction of the vertex they share. No trig needed.
let hex_points: Vec<Pos2> = (0..6)
.map(|i| {
let a = outward_dirs[i];
let b = outward_dirs[(i + 1) % 6];
center + (a + b).normalized() * CIRCUMRADIUS
})
.collect();
let mut buttons = Vec::with_capacity(12);
for side in sides {
let (outward, edge_dir) = side.outward_and_edge_dir();
let (outward, edge_dir) = (to_vec2(outward), to_vec2(edge_dir));
let base = center + outward * BUTTON_DISTANCE;
for add in [true, false] {
let sign = if add { 1.0 } else { -1.0 };
let button_center =
base + edge_dir * (sign * BUTTON_GAP / 2.0 + sign * BUTTON_ALONG / 2.0);
// A small rectangle with one axis along the edge and the other along the
// outward normal — the same "centre ± dir*half ± perp*half" construction
// `layout::tri_clue_rhombus` uses for the (differently-shaped) clue boxes.
let along = edge_dir * (BUTTON_ALONG / 2.0);
let across = outward * (BUTTON_ACROSS / 2.0);
let corners = [
button_center + along + across,
button_center - along + across,
button_center - along - across,
button_center + along - across,
];
buttons.push((side, add, button_center, outward, edge_dir, corners));
}
}
(hex_points, buttons)
};
let (probe_hex, probe_buttons) = layout(Pos2::ZERO);
let mut bounds = Rect::from_center_size(Pos2::ZERO, EDIT_SIZE);
for p in probe_hex
.iter()
.chain(probe_buttons.iter().flat_map(|b| b.5.iter()))
{
bounds.extend_with(*p);
}
let canvas = bounds.size() + Vec2::splat(2.0 * PAD);
// Take the full width, so the hexagon ends up centred in the sidebar the way the square
// resizer's cross does — everything below is placed relative to `response.rect`'s centre,
// so widening the reservation is all it takes.
let strip = Vec2::new(ui.available_width().max(canvas.x), canvas.y);
let (response, painter) = ui.allocate_painter(strip, egui::Sense::hover());
// Place the bounding box computed above flush inside the reserved rect (plus `PAD`), so
// there's no dead space on any side and nothing is clipped.
let center = response.rect.center() - bounds.center().to_vec2();
let (hex_points, buttons) = layout(center);
painter.add(egui::Shape::convex_polygon(
hex_points,
ui.visuals().extreme_bg_color,
ui.visuals().window_stroke(),
));
ui.put(
Rect::from_center_size(center, EDIT_SIZE),
egui::TextEdit::singleline(&mut self.lines_to_affect_string),
);
let mut clicked: Option<(crate::geometry::Side, bool)> = None;
for (side, add, button_center, outward, edge_dir, corners) in buttons {
// Only "+" can ever be pointless enough to grey out — see `Outline::can_grow`. If
// "+5" would be capped to "+1" it's still worth doing, so this only fires when *no*
// growth at all is possible, not when the requested amount would be capped.
let enabled = !add || outline.is_none_or(|o| o.can_grow(side));
let id = ui.id().with((side as u8, add));
let button_rect = Rect::from_points(&corners);
let button_response = ui.interact(button_rect, id, egui::Sense::click());
let visuals = if enabled {
if button_response.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
*ui.style().interact(&button_response)
} else {
// Grey out exactly the way `Ui::disable` does (`Visuals::gray_out`), and — to
// match plain `egui::Button`, whose outline only appears on hover — force no
// border at all rather than reusing `noninteractive`'s (which is meant for
// window/separator outlines and is always visible).
let base = ui.visuals().widgets.inactive;
egui::style::WidgetVisuals {
bg_fill: ui.visuals().gray_out(base.bg_fill),
weak_bg_fill: ui.visuals().gray_out(base.weak_bg_fill),
bg_stroke: egui::Stroke::NONE,
fg_stroke: egui::Stroke::new(
base.fg_stroke.width,
ui.visuals().gray_out(base.fg_stroke.color),
),
corner_radius: base.corner_radius,
expansion: base.expansion,
}
};
painter.add(egui::Shape::convex_polygon(
corners.to_vec(),
visuals.bg_fill,
// `bg_stroke`, not `fg_stroke`: egui only draws a button's outline when it's
// hovered or active (`inactive.bg_stroke` is `Stroke::NONE`), so using it here
// gets that same "no outline at rest" look for free.
visuals.bg_stroke,
));
// Hand-drawn +/- (a rotated cross/dash), rather than rotated text: simpler and more
// robust than centring a rotated glyph, and matches how `draw_analysis_mark` in
// gui_solver.rs already draws a rotated mark with plain line segments.
let stroke = egui::Stroke::new(1.5, visuals.fg_stroke.color);
painter.line_segment(
[
button_center - edge_dir * MARK_RADIUS,
button_center + edge_dir * MARK_RADIUS,
],
stroke,
);
if add {
painter.line_segment(
[
button_center - outward * MARK_RADIUS,
button_center + outward * MARK_RADIUS,
],
stroke,
);
}
if enabled && button_response.clicked() {
clicked = Some((side, add));
}
}
if let Some((side, add)) = clicked {
self.tri_resize(side, add);
}
// Hack: we need more space to not overlap the next section:
ui.add_space(28.0);
}
fn edit_sidebar(&mut self, ui: &mut egui::Ui) {
ui.vertical(|ui| {
// The id tracks the title, and `Save/share` needs it whether or not the "Metadata"
// section happens to be expanded — so this can't live inside that section's body,
// which egui skips entirely while it's collapsed.
let backup_title = self.editor_gui.document.get_or_make_up_title().unwrap();
let id = self
.editor_gui
.id
.get_or_refresh(self.editor_gui.version, || backup_title.clone());
if self.editor_gui.document.id != *id {
self.editor_gui.document.id = id.clone();
}
self.metadata_editor(ui);
ui.separator();
self.editor_gui.common_sidebar_items(ui, false, true);
ui.separator();
match self.editor_gui.document.try_solution().map(|s| s.shape()) {
Some(crate::geometry::Shape::Triangular(_)) => self.tri_resizer(ui),
_ => self.resizer(ui),
}
ui.separator();
if ui.checkbox(&mut self.auto_solve, "auto-solve").changed() {
let _ = UserSettings::set(consts::EDITOR_AUTO_SOLVE, &self.auto_solve.to_string());
if !self.auto_solve {
// The shading clears itself (it's only drawn while fresh), but the report is
// plain text that would otherwise linger after the aid is switched off.
self.solve_report.clear();
}
}
if ui.button("Solve").clicked() || self.auto_solve {
let puzzle = self.editor_gui.document.try_solution().unwrap().to_puzzle();
let (report, _solved_mask) =
self.editor_gui
.solved_mask
.get_or_refresh(self.editor_gui.version, || match puzzle.plain_solve() {
Ok(grid_solve::Report {
solve_counts,
cells_left,
solution: _solution,
solved_mask,
}) => (
// Unsolved cells first: that's the number that says whether the
// puzzle works. The skim/scrub counts are solver diagnostics.
format!("unsolved cells: {cells_left}\n{solve_counts}"),
solved_mask,
),
Err(e) => (format!("Error: {:?}", e), vec![]),
});
self.solve_report = report.clone();
}
ui.colored_label(
if self.editor_gui.solved_mask.fresh(self.editor_gui.version) {
Color32::BLACK
} else {
Color32::GRAY
},
&self.solve_report,
);
ui.separator();
let picture = self.editor_gui.document.try_solution().unwrap().clone();
self.editor_gui
.disambiguator
.get_or_refresh(self.editor_gui.version, Disambiguator::new)
.disambig_widget(
&picture,
&self.editor_gui.status,
&self.editor_gui.progress,
ui,
);
});
}
/// Title, author, description and license; in a collapsable section.
fn metadata_editor(&mut self, ui: &mut egui::Ui) {
egui::CollapsingHeader::new("Metadata").show(ui, |ui| {
ui.add(
egui::TextEdit::singleline(&mut self.editor_gui.document.title).hint_text("Title"),
);
ui.horizontal(|ui| {
ui.label("by ");
if ui
.add(
egui::TextEdit::singleline(&mut self.editor_gui.document.author)
.hint_text("Author"),
)
.changed()
{
let _ = UserSettings::set(
consts::EDITOR_AUTHOR_NAME,
&self.editor_gui.document.author,
);
}
});
ui.label("Description:");
ui.text_edit_multiline(&mut self.editor_gui.document.description);
let cc_by_license_str = "CC BY 4.0";
let mut is_cc_by = self.editor_gui.document.license == cc_by_license_str;
ui.label("License:");
ui.horizontal(|ui| {
if ui.radio_value(&mut is_cc_by, true, "").changed() {
self.editor_gui.document.license = cc_by_license_str.to_string();
};
ui.add(
egui::Hyperlink::from_label_and_url(
cc_by_license_str,
"https://creativecommons.org/licenses/by/4.0/",
)
.open_in_new_tab(true),
);
});
ui.horizontal(|ui| {
if ui.radio_value(&mut is_cc_by, false, "").changed() {
self.editor_gui.document.license.clear();
};
ui.add_enabled(
!is_cc_by,
egui::TextEdit::singleline(&mut self.editor_gui.document.license),
);
});
});
}
fn loader(&mut self, ui: &mut egui::Ui) {
if ui.button("Open").clicked() {
let (sender, receiver) = mpsc::channel();
self.opened_file_receiver = receiver;
spawn_async(async move {
let handle = rfd::AsyncFileDialog::new()
.add_filter(
"all recognized formats",
&["png", "gif", "bmp", "xml", "pbn", "txt", "g"],
)
.add_filter("image", &["png", "gif", "bmp"])
.add_filter("PBN", &["xml", "pbn"])
.add_filter("chargrid", &["txt"])
.add_filter("Olsak", &["g"])
.add_filter("woven", &["woven"])
.pick_file()
.await;
if let Some(handle) = handle {
let document =
crate::import::load(&handle.file_name(), handle.read().await, None);
sender.send(document).unwrap();
}
});
}
if let Ok(result) = self.opened_file_receiver.try_recv() {
match result {
Ok(document) => {
let document = Box::new(document);
self.editor_gui
.perform(Action::ReplaceDocument { document }, ActionMood::Normal);
}
Err(e) => {
self.editor_gui
.status
.set(StatusMessage::error(format!("Error loading file: {:?}", e)));
}
}
}
}
fn enter_solve_mode(&mut self) {
self.solve_mode = true;
self.solve_gui = Some(crate::gui_solver::SolveGui::new(
self.editor_gui.document.clone(),
Rc::clone(&self.editor_gui.status),
Rc::clone(&self.editor_gui.progress),
));
}
/// The document-wide controls across the top: zoom, the New/Library/Open/Save dialogs, and
/// the Edit/Puzzle mode toggle. Runs before the sidebar and canvas each frame, so a mode
/// switched here takes effect on the same frame.
fn toolbar(&mut self, ctx: &egui::Context, ui: &mut egui::Ui) {
// See the matching note in `common_sidebar_items`: bare-key shortcuts have to opt out of
// firing while a text field has the focus.
let typing = ctx.wants_keyboard_input();
ui.horizontal(|ui| {
if ui.button(icons::ICON_ZOOM_IN).clicked()
|| (!typing && ui.input(|i| i.key_pressed(egui::Key::Equals)))
{
self.scale = (self.scale + 2.0).min(50.0);
}
if ui.button(icons::ICON_ZOOM_OUT).clicked()
|| (!typing && ui.input(|i| i.key_pressed(egui::Key::Minus)))
{
self.scale = (self.scale - 2.0).max(1.0);
}
if ui.button("New").clicked() {
let clue_style = self.editor_gui.document.solution_mut().clue_style();
// Only a square puzzle has a width/height to seed the dialog's (square-shaped)
// defaults from; a triddler's own dimensions don't map onto this at all.
let (x_size, y_size) = self
.editor_gui
.document
.try_solution()
.and_then(|s| s.as_square())
.map(|sq| (sq.x_size(), sq.y_size()))
.unwrap_or((10, 10));
self.new_dialog = Some(NewPuzzleDialog {
shape: NewPuzzleShape::Square,
clue_style,
x_size,
y_size,
tri_side: 3,
});
}
let mut new_document = None;
if let Some(dialog) = self.new_dialog.as_mut() {
egui::Window::new("New puzzle").show(ctx, |ui| {
ui.horizontal(|ui| {
ui.radio_value(&mut dialog.shape, NewPuzzleShape::Square, "Square");
ui.radio_value(&mut dialog.shape, NewPuzzleShape::Triangular, "Triddler");
});
match dialog.shape {
NewPuzzleShape::Square => {
ui.add(
egui::Slider::new(&mut dialog.x_size, 5..=100)
.step_by(5.0)
.text("x size"),
);
ui.add(
egui::Slider::new(&mut dialog.y_size, 5..=100)
.step_by(5.0)
.text("y size"),
);
ui.radio_value(
&mut dialog.clue_style,
crate::puzzle::ClueStyle::Nono,
"Nonogram",
);
ui.radio_value(
&mut dialog.clue_style,
crate::puzzle::ClueStyle::Triano,
"Trianogram",
);
}
NewPuzzleShape::Triangular => {
// Trianogram clues on a triddler are rejected at construction, so
// there's nothing to choose here — a triddler is always a nonogram.
ui.add(
egui::Slider::new(&mut dialog.tri_side, 1..=10)
.text("hexagon side"),
);
}
}
if ui.button("Ok").clicked() {
let new_solution = match dialog.shape {
NewPuzzleShape::Square => DynSolution::Square(Solution::new(
dialog.clue_style,
match dialog.clue_style {
ClueStyle::Nono => import::bw_palette(),
ClueStyle::Triano => import::triano_palette(),
},
crate::geometry::Geometry::new(crate::geometry::Rect {
width: dialog.x_size,
height: dialog.y_size,
}),
vec![BACKGROUND; dialog.x_size * dialog.y_size],
)),
NewPuzzleShape::Triangular => {
let geometry = crate::geometry::Geometry::new(
crate::geometry::Outline::hexagon(dialog.tri_side),
);
let cells = vec![BACKGROUND; geometry.cell_count()];
DynSolution::Tri(Solution::new(
ClueStyle::Nono,
import::bw_palette(),
geometry,
cells,
))
}
};
new_document = Some(Document::from_solution(
new_solution,
"blank.xml".to_owned(),
));
self.solve_mode = false;
}
});
}
if ui.button("Library").clicked() {
let (sender, receiver) = mpsc::channel();
self.library_receiver = receiver;
self.library_dialog = Some(LibraryStatus::Loading);
spawn_async(async move {
let result = crate::import::puzzles_from_github().await;
let _ = sender.send(result);
});
}
if let Ok(result) = self.library_receiver.try_recv() {
match result {
Ok(library) => self.library_dialog = Some(LibraryStatus::Loaded(library)),
Err(e) => self.library_dialog = Some(LibraryStatus::Failed(e.to_string())),
}
}
let mut next_enter_solve_mode = false;
let mut close_library = false;
if let Some(status) = &self.library_dialog {
egui::Window::new("Puzzle Library")
.max_size(ctx.screen_rect().size() * 0.9)
.show(ctx, |ui| {
match status {
LibraryStatus::Loading => {
ui.vertical_centered(|ui| {
ui.add(egui::Spinner::new());
ui.label("Loading library...");
});
}
LibraryStatus::Loaded(docs) => {
egui::ScrollArea::vertical().show(ui, |ui| {
egui::Grid::new("library_grid").show(ui, |ui| {
for (i, doc) in docs.iter().enumerate() {
if crate::gui_gallery::gallery_puzzle_preview(ui, doc)
.clicked()
{
new_document = Some(doc.clone());
next_enter_solve_mode = true;
close_library = true;
}
if i % 2 == 1 {
ui.end_row();
}
}
});
});
}
LibraryStatus::Failed(e) => {
ui.vertical_centered(|ui| {
ui.label(
RichText::new(format!("Failed to load library: {}", e))
.color(Color32::RED),
);
});
}
}
ui.separator();
if ui.button("Cancel").clicked() {
close_library = true;
}
});
}
if close_library {
self.library_dialog = None;
}
self.loader(ui);
if ui.button("Save/share").clicked() {
self.share_string =
crate::formats::woven::to_woven(&mut self.editor_gui.document).unwrap();
self.quality_warnings = self.editor_gui.document.quality_check();
self.show_save_share_window = true;
}
if self.show_save_share_window {
egui::Window::new("Save/share")
.open(&mut self.show_save_share_window)
.default_width(780.0)
.show(ctx, |ui| {
if !self.quality_warnings.is_empty() {
if self.quality_warnings.len() == 1 {
ui.label("Warning:");
} else {
ui.label("Warnings:");
}
for warning in &self.quality_warnings {
ui.label(warning);
}
ui.separator();
}
ui.label("Share String:");
ui.add(
egui::TextEdit::multiline(&mut self.share_string.clone())
.font(TextStyle::Monospace)
.desired_width(730.0),
);
if ui.button("Copy to clipboard").clicked() {
ctx.copy_text(self.share_string.clone());
}
if self.editor_gui.document.license == "CC BY 4.0" {
if self.editor_gui.document.author.trim().is_empty() {
ui.label(
"(The author field in your puzzle is empty; please use \
'anonymous' if that's what you want.)",
);
}
ui.add(
egui::Hyperlink::from_label_and_url(
"Contribute this puzzle to Number Loom",
"https://forms.gle/WXxWVsEMqy3NHXmK9",
)
.open_in_new_tab(true),
);
} else {
ui.label(
"If you'd like to contribute your puzzle to Number Loom's \
library, please set the license to 'CC BY 4.0'",
);
}
ui.separator();
ui.label("Paste a 'WOVEN' string to load:");
ui.add(
egui::TextEdit::multiline(&mut self.pasted_string)
.font(TextStyle::Monospace)
.desired_width(730.0),
);
if ui.button("Load").clicked() {
match crate::formats::woven::from_woven(
&self.pasted_string,
"unknown.woven".to_string(),
) {
Ok(doc) => {
new_document = Some(doc);
next_enter_solve_mode = true;
}
Err(e) => {
self.editor_gui.status.set(StatusMessage::error(format!(
"Error loading WOVEN puzzle: {:?}",
e
)));
}
}
}
ui.separator();
ui.label("Supported file types:");
ui.label(" .png (or other image formats): solution image");
ui.label(" .xml/.pbn: the format used by the \"pbnsolve\" solver");
ui.label(" .txt: grid of characters");
ui.label(" .g: the format used by the Olšák solver");
ui.label(" .woven: Number Loom's custom format");
ui.label(" .html: printable puzzle");
ui.horizontal(|ui| {
ui.label("Filename:");
ui.add(
egui::TextEdit::singleline(&mut self.editor_gui.document.file)
.desired_width(450.0),
);
});
if ui.button("Save").clicked() {
let mut document_copy = self.editor_gui.document.clone();
let (sender, receiver) = mpsc::channel();
self.save_result_receiver = receiver;
spawn_async(async move {
let handle = rfd::AsyncFileDialog::new()
.add_filter(
"all recognized formats",
&["png", "gif", "bmp", "xml", "pbn", "txt", "g", "html"],
)
.add_filter("image", &["png", "gif", "bmp"])
.add_filter("PBN", &["xml", "pbn"])
.add_filter("chargrid", &["txt"])
.add_filter("Olšák", &["g"])
.add_filter("woven", &["woven"])
.add_filter("HTML (for printing)", &["html"])
.set_file_name(document_copy.file.clone())
.save_file()
.await;
if let Some(handle) = handle {
let result = async {
let bytes = to_bytes(
&mut document_copy,
Some(handle.file_name()),
None,
)?;
handle.write(&bytes).await?;
Ok(())
}
.await;
sender.send(result).unwrap();
}
});
}
if let Ok(Err(e)) = self.save_result_receiver.try_recv() {
self.editor_gui
.status
.set(StatusMessage::error(format!("Error saving file: {:?}", e)));
}
});
}
if let Some(new_document) = new_document {
let document = Box::new(new_document);
self.editor_gui
.perform(Action::ReplaceDocument { document }, ActionMood::Normal);
self.new_dialog = None;
self.library_dialog = None;
self.show_save_share_window = false;
}
ui.separator();
if ui
.selectable_value(&mut self.solve_mode, false, "Edit")
.clicked()
{
self.solve_gui = None;
}
if ui
.selectable_value(&mut self.solve_mode, true, "Puzzle")
.clicked()
|| next_enter_solve_mode
{
self.enter_solve_mode();
}
});
}
}
/// Starting width of the tool sidebar; the user may adjust it.
const SIDEBAR_WIDTH: f32 = 150.0;
/// Lay out a row of widgets centred within the available width.
///
/// egui won't do this on its own. `Layout::left_to_right` places items from the left edge
/// whatever its `main_align` says — `horizontal_placement` hardcodes `Align::LEFT` — and
/// `vertical_centered` only centres a child whose size it knows *before* laying it out, which a
/// `ui.horizontal` row is not. The obvious fix, a sizing pass followed by a real one, would mean
/// running `add_contents` twice per frame; these rows are made of buttons, so the measuring pass
/// would act on every click a second time.
///
/// So: pad by however wide the row turned out last frame, and record this frame's width for the
/// next one. Only the very first frame a row is shown is off-centre.
fn centered_row<R>(
ui: &mut egui::Ui,
id_salt: &str,
add_contents: impl FnOnce(&mut egui::Ui) -> R,
) -> R {
let id = ui.id().with(id_salt);
let previous: Option<f32> = ui.data(|d| d.get_temp(id));
let pad = previous.map_or(0.0, |w| ((ui.available_width() - w) / 2.0).max(0.0));
let row = ui.horizontal(|ui| {
ui.add_space(pad);
add_contents(ui)
});
ui.data_mut(|d| d.insert_temp(id, row.response.rect.width() - pad));
row.inner
}
/// Which edge of a `TopBottomPanel` faces the rest of the window, and so carries its separator.
enum Edge {
Top,
Bottom,
}
/// The frame for the toolbar and the status bar.
///
/// `TopBottomPanel` paints its separator line *inside* its own rect, overlapping the frame's
/// margin on whichever edge faces the window. With egui's symmetric default margin that leaves
/// only one pixel of clear space between the line and the buttons on that side, against two on
/// the other — which reads as the bar being a pixel or two too short for its contents. Widening
/// that one margin by the line's own width restores the balance.
fn bar_frame(ctx: &egui::Context, separator_on: Edge) -> egui::Frame {
let style = ctx.style();
let base = egui::Frame::side_top_panel(&style);
let line = style
.visuals
.widgets
.noninteractive
.bg_stroke
.width
.ceil()
.max(0.0) as i8;
let mut margin = base.inner_margin;
match separator_on {
Edge::Top => margin.top += line,
Edge::Bottom => margin.bottom += line,
}
base.inner_margin(margin)
}
/// Breathing room between the canvas and the panels around it.
const CANVAS_MARGIN: i8 = 16;
#[derive(PartialEq, Eq)]
enum NewPuzzleShape {
Square,
Triangular,
}
struct NewPuzzleDialog {
shape: NewPuzzleShape,
clue_style: crate::puzzle::ClueStyle,
x_size: usize,
y_size: usize,
/// Hexagon side length, used only when `shape` is `Triangular`. Doesn't cover every possible
/// triddler outline (see `Outline`) — just a reasonable default shape to start editing from.
tri_side: i32,
}
impl eframe::App for NonogramGui {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.main_ui(ctx);
}
}
impl NonogramGui {
/// The whole window, panel by panel. Separate from `eframe::App::update` for testing.
pub fn main_ui(&mut self, ctx: &egui::Context) {
// Styling. Has to be here instead of `edit_image` to take effect on the Web.
let spacing = egui::Spacing {
interact_size: Vec2::new(20.0, 20.0), // Used by the color-picker buttons
..egui::Spacing::default()
};
let style = Style {
visuals: Visuals::light(),
spacing,
..Style::default()
};
ctx.set_style(style);
// Panel order matters: egui hands each panel the space its predecessors didn't claim, so
// the top and bottom bars span the full width, and the sidebar then splits what's left
// with the canvas.
egui::TopBottomPanel::top("toolbar")
.frame(bar_frame(ctx, Edge::Bottom))
.show(ctx, |ui| {
self.toolbar(ctx, ui);
});
egui::TopBottomPanel::bottom("status_bar")
.frame(bar_frame(ctx, Edge::Top))
.show(ctx, |ui| {
// `editor_gui.status`/`editor_gui.progress` are shared (via `Rc<RefCell<_>>`) with
// `solve_gui.canvas`, so this shows the latest message/progress regardless of which
// mode is active.
ui.horizontal(|ui| {
// Reserves a consistent height for the bar even when there's nothing to show,
// so the rest of the UI doesn't jump around as messages come and go.
ui.label("");
if let Some(progress) = *self.editor_gui.progress.borrow() {
// ~50% wider than the sidebar (150.0) is by default.
ui.add(
egui::ProgressBar::new(progress)
.animate(true)
.desired_width(225.0),
);
}
if let Some(status) = self.editor_gui.status.get() {
let color = if status.is_error {
Color32::DARK_RED
} else {
ui.visuals().text_color()
};
ui.colored_label(color, &status.text);
}
});
});
egui::SidePanel::left("sidebar")
.resizable(true)
.default_width(SIDEBAR_WIDTH)
.width_range(SIDEBAR_WIDTH..=400.0)
.show(ctx, |ui| {
// Both sidebars can outgrow a short window — the editor's once "Metadata" is
// expanded, the solver's once a puzzle has a long palette.
egui::ScrollArea::vertical().show(ui, |ui| {
if let Some(solve_gui) = &mut self.solve_gui {
solve_gui.sidebar(ui);
} else {
self.edit_sidebar(ui);
}
});
});
egui::CentralPanel::default()
.frame(egui::Frame::central_panel(&ctx.style()).inner_margin(CANVAS_MARGIN))
.show(ctx, |ui| {
// egui routes ctrl-scroll (and trackpad pinch) into `zoom_delta` rather than into
// the scroll offset, so the scroll area below pans on a plain wheel and leaves
// this alone. Only zoom when the pointer is actually over the canvas, so the
// gesture doesn't fire while the user is over the sidebar.
let zoom_here = ui.rect_contains_pointer(ui.max_rect());
// A zoomed-in puzzle is routinely bigger than the window in both directions.
egui::ScrollArea::both().show(ui, |ui| {
if let Some(solve_gui) = &mut self.solve_gui {
solve_gui.body(ui, self.scale);
} else {
self.editor_gui
.canvas(ui, self.scale, RenderStyle::Experimental);
}
});
if zoom_here {
let zoom = ui.input(|i| i.zoom_delta());
if zoom != 1.0 {
self.scale = (self.scale * zoom).clamp(1.0, 50.0);
}
}
});
}
}
pub struct Disambiguator {
/// Indexed by dense cell index, like `Solution::cells`.
report: Option<Vec<(Color, f32)>>,
pub terminate_s: mpsc::Sender<()>,
progress_r: mpsc::Receiver<f32>,
progress: f32,
report_r: mpsc::Receiver<DisambigResult>,
}
impl Default for Disambiguator {
fn default() -> Self {
Self::new()
}
}
impl Disambiguator {
pub fn new() -> Self {
Disambiguator {
report: None,
progress: 0.0,
terminate_s: mpsc::channel().0,
progress_r: mpsc::channel().1,
report_r: mpsc::channel().1,
}
}
// Must do this any time the resolution changes!
// (Currently that only happens through `ReplacePicture`)
pub fn reset(&mut self) {
self.report = None;
self.progress = 0.0;
}
pub fn disambig_widget(
&mut self,
picture: &DynSolution,
status: &SharedStatus,
progress: &SharedProgress,
ui: &mut egui::Ui,
) {
while let Ok(p) = self.progress_r.try_recv() {
self.progress = p;
}
let report_running = self.progress > 0.0 && self.progress < 1.0;
// Taking the report before drawing means "Clear" becomes available on the same frame the
// report lands, rather than the one after.
if let Ok(result) = self.report_r.try_recv() {
// Clear any stale message (e.g. a load error from before) now that disambiguation
// has something new to say (or, for `Report`, nothing to say).
status.maybe_clear_on_dirty();
match result {
DisambigResult::Unnecessary => {
status.set(StatusMessage::info("Disambiguation is unnecessary"));
}
DisambigResult::Report(report) => {
self.report = Some(report);
}
}
}
// Both buttons share a row: "Clear" discards what the button beside it produced. They
// only record what was clicked, since acting on it needs `self` mutably.
let (mut start, mut stop, mut clear) = (false, false, false);
ui.horizontal(|ui| {
if !report_running {
start = ui.button("Disambiguate!").clicked();
} else {
stop = ui.button("Stop").clicked();
}
clear = ui
.add_enabled(self.report.is_some(), egui::Button::new("Clear"))
.clicked();
});
if start {
let (p_s, p_r) = mpsc::channel();
let (r_s, r_r) = mpsc::channel();
let (t_s, t_r) = mpsc::channel();
self.progress_r = p_r;
self.terminate_s = t_s;
self.report_r = r_r;
let solution = picture.clone();
spawn_async(async move {
let result = disambig_candidates(&solution, p_s, t_r).await;
r_s.send(result).unwrap();
});
}
if stop {
let _ = self.terminate_s.send(()); // Don't panic if it's already gone!
self.progress = 0.0;
}
*progress.borrow_mut() = if self.progress > 0.0 && self.progress < 1.0 {
Some(self.progress)
} else {
None
};
if clear {
self.report = None;
}
}
}
#[cfg(test)]
mod lasso_tests {
use super::*;
use crate::geometry::{Geometry, Outline, Tri};
use crate::puzzle::{ClueStyle, Solution};
fn square(w: usize, h: usize) -> DynSolution {
DynSolution::Square(Solution::blank_bw(w, h))
}
fn selected(mask: &[bool]) -> Vec<u32> {
mask.iter()
.enumerate()
.filter(|(_, m)| **m)
.map(|(i, _)| i as u32)
.collect()
}
/// A loop traced around the middle 3×3 of a 5×5 grid selects exactly those nine cells: the
/// eight the path runs through, plus the one in the centre that it only encloses.
#[test]
fn a_loop_selects_what_it_traces_and_what_it_encloses() {
let picture = square(5, 5);
// Through the centres of the ring cells, so "touched" is unambiguous.
let path = vec![
Point::new(1.5, 1.5),
Point::new(3.5, 1.5),
Point::new(3.5, 3.5),
Point::new(1.5, 3.5),
];
let mask = cells_in_lasso(&picture, &path);
let want: Vec<u32> = (1..=3)
.flat_map(|y| (1..=3).map(move |x| y * 5 + x))
.collect();
assert_eq!(selected(&mask), want);
}
/// The ends are joined by a straight line, so a path that stops short still closes — the
/// player never has to land exactly back where they started.
#[test]
fn an_open_path_is_closed_across_the_gap() {
let picture = square(5, 5);
// Three sides of the same box: the fourth is supplied by the closing segment.
let open = vec![
Point::new(1.5, 1.5),
Point::new(3.5, 1.5),
Point::new(3.5, 3.5),
Point::new(1.5, 3.5),
Point::new(1.5, 2.5),
];
let closed = vec![
Point::new(1.5, 1.5),
Point::new(3.5, 1.5),
Point::new(3.5, 3.5),
Point::new(1.5, 3.5),
];
assert_eq!(
selected(&cells_in_lasso(&picture, &open)),
selected(&cells_in_lasso(&picture, &closed))
);
}
/// A fast drag reports few points, but the path between them still counts as touched —
/// otherwise a quick diagonal flick would select a dotted line of cells.
#[test]
fn a_sparse_path_still_touches_every_cell_it_crosses() {
let picture = square(5, 1);
let path = vec![Point::new(0.5, 0.5), Point::new(4.5, 0.5)];
assert_eq!(
selected(&cells_in_lasso(&picture, &path)),
vec![0, 1, 2, 3, 4]
);
}
/// The outline is the boundary and nothing else: a single square cell contributes its four
/// edges, and two side-by-side cells contribute six, not eight — the shared edge cancels.
#[test]
fn the_outline_drops_shared_edges() {
let picture = square(3, 3);
assert_eq!(selection_outline(&picture, &[0]).len(), 4);
assert_eq!(selection_outline(&picture, &[0, 1]).len(), 6);
// A 2×2 block: eight boundary edges, with the four interior ones cancelled.
assert_eq!(selection_outline(&picture, &[0, 1, 3, 4]).len(), 8);
}
/// The dense cell index of `(x, y)` in the 6×6 grid the move tests use.
fn at(x: usize, y: usize) -> usize {
y * 6 + x
}
/// A canvas over a blank 6×6 with a 2×2 block of `Color(1)` at (1,1).
fn canvas_with_a_block() -> CanvasGui {
let mut sol = Solution::blank_bw(6, 6);
for (x, y) in [(1, 1), (2, 1), (1, 2), (2, 2)] {
sol.cells[at(x, y)] = Color(1);
}
let mut gui = NonogramGui::new(Document::from_solution(
DynSolution::Square(sol),
"test".to_string(),
))
.editor_gui;
gui.current_tool = Tool::Lasso;
gui
}
fn press(gui: &mut CanvasGui, p: Point) {
gui.lasso_input(
LassoPointer {
pressed: true,
down: true,
..Default::default()
},
p,
);
}
fn drag(gui: &mut CanvasGui, p: Point) {
gui.lasso_input(
LassoPointer {
down: true,
..Default::default()
},
p,
);
}
fn release(gui: &mut CanvasGui, p: Point) {
gui.lasso_input(
LassoPointer {
released: true,
..Default::default()
},
p,
);
}
/// Lasso the block, drag it two cells right and one down, then switch tools. The block should
/// be at its new home, and every cell it came from should be background.
#[test]
fn a_dragged_selection_moves_and_leaves_background_behind() {
let mut gui = canvas_with_a_block();
press(&mut gui, Point::new(0.5, 0.5));
for p in [
Point::new(3.5, 0.5),
Point::new(3.5, 3.5),
Point::new(0.5, 3.5),
] {
drag(&mut gui, p);
}
release(&mut gui, Point::new(0.5, 3.5));
// Grab inside the selection and drag it.
press(&mut gui, Point::new(1.5, 1.5));
drag(&mut gui, Point::new(3.5, 2.5));
release(&mut gui, Point::new(3.5, 2.5));
// Still floating: the source is already background, the destination not yet stamped.
let cells = gui.document.try_solution().unwrap().cells();
assert!(cells.iter().all(|c| *c == BACKGROUND), "source not cleared");
gui.clear_selection();
let cells = gui.document.try_solution().unwrap().cells();
let lit: Vec<usize> = cells
.iter()
.enumerate()
.filter(|(_, c)| **c == Color(1))
.map(|(i, _)| i)
.collect();
// The block moved by (+2, +1): (1,1)..(2,2) became (3,2)..(4,3).
let want: Vec<usize> = [(3, 2), (4, 2), (3, 3), (4, 3)]
.iter()
.map(|(x, y)| at(*x, *y))
.collect();
assert_eq!(lit, want);
}
/// Only non-background cells are stamped.
#[test]
fn a_move_does_not_erase_at_the_destination() {
let mut gui = canvas_with_a_block();
// A lone cell at (4,1), in the path of the incoming selection's background corner.
let target = at(4, 1);
gui.document.solution_mut().cells_mut()[target] = Color(1);
// Lasso a 3×3 region covering the block plus background at its right edge.
press(&mut gui, Point::new(0.5, 0.5));
for p in [
Point::new(3.5, 0.5),
Point::new(3.5, 3.5),
Point::new(0.5, 3.5),
] {
drag(&mut gui, p);
}
release(&mut gui, Point::new(0.5, 3.5));
// Shift right by two: the selection's background cells now overlap (4,1).
press(&mut gui, Point::new(1.5, 1.5));
drag(&mut gui, Point::new(3.5, 1.5));
release(&mut gui, Point::new(3.5, 1.5));
gui.clear_selection();
let cells = gui.document.try_solution().unwrap().cells();
assert_eq!(cells[target], Color(1), "a background cell overwrote art");
}
/// Flattening is one undoable step on top of the lift, so two undos put everything back.
#[test]
fn a_move_can_be_undone() {
let mut gui = canvas_with_a_block();
let original = gui.document.try_solution().unwrap().cells().to_vec();
press(&mut gui, Point::new(0.5, 0.5));
for p in [
Point::new(3.5, 0.5),
Point::new(3.5, 3.5),
Point::new(0.5, 3.5),
] {
drag(&mut gui, p);
}
release(&mut gui, Point::new(0.5, 3.5));
press(&mut gui, Point::new(1.5, 1.5));
drag(&mut gui, Point::new(3.5, 2.5));
release(&mut gui, Point::new(3.5, 2.5));
gui.clear_selection();
gui.un_or_re_do(true); // The flatten.
gui.un_or_re_do(true); // The lift.
assert_eq!(gui.document.try_solution().unwrap().cells(), original);
}
/// Dragging off the edge and back loses nothing: the mask keeps the whole selection, and only
/// flattening makes the clipping permanent.
#[test]
fn dragging_past_the_edge_and_back_restores_everything() {
let mut gui = canvas_with_a_block();
let original = gui.document.try_solution().unwrap().cells().to_vec();
press(&mut gui, Point::new(0.5, 0.5));
for p in [
Point::new(3.5, 0.5),
Point::new(3.5, 3.5),
Point::new(0.5, 3.5),
] {
drag(&mut gui, p);
}
release(&mut gui, Point::new(0.5, 3.5));
press(&mut gui, Point::new(1.5, 1.5));
drag(&mut gui, Point::new(-8.5, 1.5)); // Well off the left edge.
drag(&mut gui, Point::new(1.5, 1.5)); // ...and back to where it started.
release(&mut gui, Point::new(1.5, 1.5));
gui.clear_selection();
assert_eq!(gui.document.try_solution().unwrap().cells(), original);
}
/// Triangles too: a ▲ and the ▼ beside it share an edge, so their outline is a rhombus with
/// four sides rather than two separate triangles with six.
#[test]
fn the_outline_works_for_triangles() {
let sol: Solution<Tri> = Solution::new(
ClueStyle::Nono,
HashMap::from([(BACKGROUND, ColorInfo::default_bg())]),
Geometry::new(Outline::hexagon(2)),
vec![BACKGROUND; Geometry::<Tri>::new(Outline::hexagon(2)).cell_count()],
);
let picture = DynSolution::Tri(sol);
assert_eq!(selection_outline(&picture, &[0]).len(), 3);
// Cells 0 and 1 are adjacent within the top row of the hexagon.
assert_eq!(selection_outline(&picture, &[0, 1]).len(), 4);
}
}
#[cfg(test)]
mod line_tool_tests {
use super::*;
use crate::puzzle::Solution;
fn at(x: usize, y: usize) -> u32 {
(y * 6 + x) as u32
}
fn canvas() -> CanvasGui {
let sol = Solution::blank_bw(6, 6);
let mut gui = NonogramGui::new(Document::from_solution(
DynSolution::Square(sol),
"test".to_string(),
))
.editor_gui;
gui.current_tool = Tool::LineAlongLane;
gui.drag_start_color = Color(1);
gui
}
/// Dragging mostly-horizontally, but not to a cell that shares the start's row, still snaps
/// to the row: the nearest lane by angle, not an exact row/column match.
#[test]
fn a_near_horizontal_drag_snaps_to_the_row() {
let mut gui = canvas();
// From (1,1), drag toward (4,2): mostly rightward with a little drop, so the row
// (angle 0) is closer than the column (angle 90) to the drag direction.
let changes = gui.line_between(at(1, 1), at(4, 2));
let mut got: Vec<u32> = changes.keys().copied().collect();
got.sort();
assert_eq!(got, vec![at(1, 1), at(2, 1), at(3, 1), at(4, 1)]);
assert!(changes.values().all(|c| *c == Color(1)));
}
/// Symmetric case: a near-vertical drag snaps to the column instead.
#[test]
fn a_near_vertical_drag_snaps_to_the_column() {
let mut gui = canvas();
// From (1,1), drag toward (2,4): mostly downward with a little sideways drift.
let changes = gui.line_between(at(1, 1), at(2, 4));
let mut got: Vec<u32> = changes.keys().copied().collect();
got.sort();
assert_eq!(got, vec![at(1, 1), at(1, 2), at(1, 3), at(1, 4)]);
}
/// A drag that goes backward along the lane (toward its start) still snaps and paints the
/// span behind the origin, not just the endpoint.
#[test]
fn dragging_backward_along_a_lane_still_draws_the_span() {
let mut gui = canvas();
let changes = gui.line_between(at(4, 2), at(1, 3));
let mut got: Vec<u32> = changes.keys().copied().collect();
got.sort();
assert_eq!(got, vec![at(1, 2), at(2, 2), at(3, 2), at(4, 2)]);
}
/// A triangular grid's `/` and `\` lanes zigzag between ▲ and ▼ cell centroids, so a lane's
/// direction can't be judged from a single neighboring cell: from a ▲, the very next cell
/// along a "/" lane sits directly *below* it (a purely vertical step), which used to fool the
/// snapping into thinking that lane wasn't diagonal at all. Regardless of which orientation
/// a lane starts (or ends) on, dragging along its full length should paint the whole thing.
#[test]
fn diagonal_lanes_are_reachable_from_either_triangle_orientation() {
use crate::geometry::{Geometry, Outline, Tri};
use crate::puzzle::ClueStyle;
let geometry = Geometry::<Tri>::new(Outline::hexagon(2));
let sol: Solution<Tri> = Solution::new(
ClueStyle::Nono,
HashMap::from([(BACKGROUND, ColorInfo::default_bg())]),
geometry,
vec![BACKGROUND; Geometry::<Tri>::new(Outline::hexagon(2)).cell_count()],
);
let lane_map = sol.geometry.lane_map().clone();
let mut gui = NonogramGui::new(Document::from_solution(
DynSolution::Tri(sol),
"test".to_string(),
))
.editor_gui;
gui.current_tool = Tool::LineAlongLane;
gui.drag_start_color = Color(1);
// Every "/" and "\" lane (families 1 and 2) with more than one cell: dragging end to end
// should paint every cell in it, no matter which orientation each end happens to be.
for family in [1usize, 2usize] {
for lane_idx in lane_map.family(family) {
let lane = lane_map.lane(lane_idx);
if lane.cells.len() < 2 {
continue;
}
let first = lane.cells[0];
let last = *lane.cells.last().unwrap();
let mut got: Vec<u32> = gui.line_between(first, last).keys().copied().collect();
got.sort();
let mut want = lane.cells.clone();
want.sort();
assert_eq!(
got,
want,
"family {family} lane {lane_idx} (len {}) didn't paint end to end",
lane.cells.len()
);
}
}
}
}
#[cfg(test)]
mod palette_tests {
use super::*;
use crate::puzzle::Solution;
fn doc(sol: Solution<crate::geometry::Square>) -> Document {
Document::from_solution(DynSolution::Square(sol), "test".to_string())
}
#[test]
fn swapping_the_document_cant_leave_the_color_dangling() {
let mut fancy = Solution::blank_bw(3, 3);
fancy
.palette
.insert(Color(3), ColorInfo::default_fg(Color(3)));
let mut gui = NonogramGui::new(doc(fancy)).editor_gui;
gui.current_color = Color(3);
gui.drag_start_color = Color(3);
// The black-and-white palette has no `Color(3)`.
gui.perform(
Action::ReplaceDocument {
document: Box::new(doc(Solution::blank_bw(3, 3))),
},
ActionMood::Normal,
);
let palette = gui.document.try_solution().unwrap().palette();
assert!(palette.contains_key(&gui.current_color));
assert!(palette.contains_key(&gui.drag_start_color));
}
#[test]
fn a_color_the_new_palette_still_has_is_left_alone() {
let mut gui = NonogramGui::new(doc(Solution::blank_bw(3, 3))).editor_gui;
gui.current_color = BACKGROUND;
gui.drag_start_color = BACKGROUND;
gui.perform(
Action::ReplaceDocument {
document: Box::new(doc(Solution::blank_bw(4, 4))),
},
ActionMood::Normal,
);
assert_eq!(gui.current_color, BACKGROUND);
assert_eq!(gui.drag_start_color, BACKGROUND);
}
}