notify 9.0.0

Cross-platform filesystem notification library
Documentation
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
//! Watcher implementation for Darwin's FSEvents API
//!
//! The FSEvents API provides a mechanism to notify clients about directories they ought to re-scan
//! in order to keep their internal data structures up-to-date with respect to the true state of
//! the file system. (For example, when files or directories are created, modified, or removed.) It
//! sends these notifications "in bulk", possibly notifying the client of changes to several
//! directories in a single callback.
//!
//! For more information see the [FSEvents API reference][ref].
//!
//! # Event translation
//!
//! A single FSEvents notification can contain several flags and produce multiple [`Event`]s.
//! Creation and removal flags map to [`EventKind::Create`] and [`EventKind::Remove`], using
//! file or directory kinds when FSEvents supplies that information. Content changes map to
//! [`DataChange::Content`]; metadata flags map to [`MetadataKind::Any`],
//! [`MetadataKind::Ownership`], [`MetadataKind::Extended`], or [`MetadataKind::Other`]
//! (Finder information).
//!
//! Renames use [`RenameMode::Any`], since FSEvents does not pair the old and new paths.
//! A root-change notification carries `info = "root changed"` and is translated as a removal
//! when the removal flag is set, or as [`RenameMode::From`] when only the rename flag is set.
//! Without either hint, it is reported as [`RemoveKind::Any`]. Mount and unmount notifications
//! become [`CreateKind::Other`] and [`RemoveKind::Other`], both with `info = "mount"`.
//!
//! `MustScanSubDirs` produces an [`EventKind::Other`] event with [`Flag::Rescan`]. When supplied,
//! the reason is preserved as `info = "rescan: user dropped"` or `"rescan: kernel dropped"`.
//! Historical-completion notifications (`HistoryDone`) are ignored.
//! Clone flags add `info = "is: clone"` unless the event already has an information attribute;
//! events marked as originating in this process carry its process ID.
//!
//! [ref]: https://developer.apple.com/library/mac/documentation/Darwin/Reference/FSEvents_Ref/

#![allow(non_upper_case_globals, dead_code)]

use crate::paths::{absolute_path, reported_path};
use crate::{
    Config, Error, ErrorKind, EventHandler, EventKindMask, RecursiveMode, Result, Sender,
    WatchedPath, Watcher, unbounded,
};
use crate::{PathOp, event::*};
use objc2_core_foundation as cf;
use objc2_core_services as fs;
use std::collections::{BTreeSet, HashMap};
use std::ffi::{CStr, OsStr};
use std::fmt;
use std::ops::Bound;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::ptr::{self, NonNull};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;

bitflags::bitflags! {
    #[repr(C)]
    #[derive(Debug)]
    struct StreamFlags: u32 {
        const NONE = fs::kFSEventStreamEventFlagNone;
        const MUST_SCAN_SUBDIRS = fs::kFSEventStreamEventFlagMustScanSubDirs;
        const USER_DROPPED = fs::kFSEventStreamEventFlagUserDropped;
        const KERNEL_DROPPED = fs::kFSEventStreamEventFlagKernelDropped;
        const IDS_WRAPPED = fs::kFSEventStreamEventFlagEventIdsWrapped;
        const HISTORY_DONE = fs::kFSEventStreamEventFlagHistoryDone;
        const ROOT_CHANGED = fs::kFSEventStreamEventFlagRootChanged;
        const MOUNT = fs::kFSEventStreamEventFlagMount;
        const UNMOUNT = fs::kFSEventStreamEventFlagUnmount;
        const ITEM_CREATED = fs::kFSEventStreamEventFlagItemCreated;
        const ITEM_REMOVED = fs::kFSEventStreamEventFlagItemRemoved;
        const INODE_META_MOD = fs::kFSEventStreamEventFlagItemInodeMetaMod;
        const ITEM_RENAMED = fs::kFSEventStreamEventFlagItemRenamed;
        const ITEM_MODIFIED = fs::kFSEventStreamEventFlagItemModified;
        const FINDER_INFO_MOD = fs::kFSEventStreamEventFlagItemFinderInfoMod;
        const ITEM_CHANGE_OWNER = fs::kFSEventStreamEventFlagItemChangeOwner;
        const ITEM_XATTR_MOD = fs::kFSEventStreamEventFlagItemXattrMod;
        const IS_FILE = fs::kFSEventStreamEventFlagItemIsFile;
        const IS_DIR = fs::kFSEventStreamEventFlagItemIsDir;
        const IS_SYMLINK = fs::kFSEventStreamEventFlagItemIsSymlink;
        const OWN_EVENT = fs::kFSEventStreamEventFlagOwnEvent;
        const IS_HARDLINK = fs::kFSEventStreamEventFlagItemIsHardlink;
        const IS_LAST_HARDLINK = fs::kFSEventStreamEventFlagItemIsLastHardlink;
        const ITEM_CLONED = fs::kFSEventStreamEventFlagItemCloned;
    }
}

const RUNLOOP_STOP_RECHECK_SECONDS: cf::CFTimeInterval = 0.5;

/// FSEvents-based `Watcher` implementation
pub struct FsEventWatcher {
    since_when: Option<fs::FSEventStreamEventId>,
    latency: cf::CFTimeInterval,
    flags: fs::FSEventStreamCreateFlags,
    event_handler: Arc<Mutex<dyn EventHandler>>,
    runloop: Option<RunLoopHandle>,
    watches: HashMap<PathBuf, WatchEntry>,
    // Mirrors `watches` for subtree lookups; paths sort by component.
    watch_paths: BTreeSet<PathBuf>,
    event_kinds: EventKindMask,
    // Kept across stream replacements and dropped after the final stream is released.
    path_reservation: FseventsPathReservation,
}

// `cf_path` is kept out of `WatchInfo` because `WatchInfo` is shared with the stream
// context, which must stay `Send + Sync`.
#[derive(Debug)]
struct WatchEntry {
    info: WatchInfo,
    cf_path: cf::CFRetained<cf::CFString>,
    device: u64,
    inode: u64,
}

#[derive(Clone, Debug)]
struct WatchInfo {
    is_recursive: bool,
    reported_path: PathBuf,
    user_data: Option<u64>,
    // Exclusive lower bound for events at this path and its direct children.
    since: fs::FSEventStreamEventId,
    // Bound for deeper descendants; reset when enabling recursion.
    deep_since: fs::FSEventStreamEventId,
}

// FSEvents applies the path limit across live streams, so all watcher instances
// in this process must share the same count.
static ACTIVE_FSEVENTS_PATHS: AtomicUsize = AtomicUsize::new(0);

/// One watcher's share of the paths counted in [`ACTIVE_FSEVENTS_PATHS`].
#[derive(Debug)]
struct FseventsPathReservation {
    active_paths: &'static AtomicUsize,
    path_count: usize,
}

impl FseventsPathReservation {
    fn new(active_paths: &'static AtomicUsize) -> Self {
        Self {
            active_paths,
            path_count: 0,
        }
    }

    /// Keeps the existing reservation and reserves any additional replacement roots.
    /// Checks the replacement plus other watchers against `budget`; on failure, returns
    /// the current process-wide count without changing the reservation.
    fn reserve(&mut self, path_count: usize, budget: usize) -> std::result::Result<(), usize> {
        let held = self.path_count;
        #[allow(deprecated, reason = "try_update requires Rust 1.95; our MSRV is 1.91")]
        self.active_paths.fetch_update(
            Ordering::Relaxed,
            Ordering::Relaxed,
            |active_path_count| {
                // Counted without the surplus over `path_count`: the budget may have
                // dropped below what is held since that was reserved.
                let combined_path_count = (active_path_count - held).checked_add(path_count)?;
                (combined_path_count <= budget)
                    .then_some(active_path_count.max(combined_path_count))
            },
        )?;
        self.path_count = held.max(path_count);
        Ok(())
    }

    /// Gives back whatever is held beyond `path_count`.
    fn shrink_to(&mut self, path_count: usize) {
        let surplus = self.path_count.saturating_sub(path_count);
        let previous = self.active_paths.fetch_sub(surplus, Ordering::Relaxed);
        debug_assert!(previous >= surplus);
        self.path_count -= surplus;
    }
}

impl Drop for FseventsPathReservation {
    fn drop(&mut self) {
        self.shrink_to(0);
    }
}

#[derive(Debug)]
struct RunLoopHandle {
    runloop: cf::CFRetained<cf::CFRunLoop>,
    stop_flag: Arc<AtomicBool>,
    thread_handle: thread::JoinHandle<fs::FSEventStreamEventId>,
    recursive_info: Arc<Mutex<HashMap<PathBuf, WatchInfo>>>,
}

impl fmt::Debug for FsEventWatcher {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("FsEventWatcher")
            .field("since_when", &self.since_when)
            .field("latency", &self.latency)
            .field("flags", &self.flags)
            .field("event_handler", &Arc::as_ptr(&self.event_handler))
            .field("runloop", &self.runloop)
            .field("watches", &self.watches)
            .finish()
    }
}

// FsEventWatcher is not Send/Sync automatically.
// It's Send because the pointer is not used in other threads.
unsafe impl Send for FsEventWatcher {}

// It's Sync because all methods that change the mutable state use `&mut self`.
unsafe impl Sync for FsEventWatcher {}

fn translate_flags(flags: StreamFlags, precise: bool) -> Vec<Event> {
    let mut evs = Vec::new();
    translate_flags_with(flags, precise, |ev| evs.push(ev));
    evs
}

// Keep this in sync with `translate_flags_with`; the callback uses it to avoid path clones.
fn translated_event_count(flags: &StreamFlags, precise: bool) -> usize {
    if flags.contains(StreamFlags::HISTORY_DONE) {
        return 0;
    }

    let mut count = usize::from(flags.contains(StreamFlags::MUST_SCAN_SUBDIRS));
    if !precise {
        return count + 1;
    }

    let root_changed = flags.contains(StreamFlags::ROOT_CHANGED);
    count += usize::from(root_changed);
    count += usize::from(flags.contains(StreamFlags::MOUNT));
    count += usize::from(flags.contains(StreamFlags::UNMOUNT));
    count += usize::from(flags.contains(StreamFlags::ITEM_CREATED));
    count += usize::from(flags.contains(StreamFlags::ITEM_RENAMED) && !root_changed);
    count += usize::from(flags.contains(StreamFlags::INODE_META_MOD));
    count += usize::from(flags.contains(StreamFlags::FINDER_INFO_MOD));
    count += usize::from(flags.contains(StreamFlags::ITEM_CHANGE_OWNER));
    count += usize::from(flags.contains(StreamFlags::ITEM_XATTR_MOD));
    count += usize::from(flags.contains(StreamFlags::ITEM_MODIFIED));
    count += usize::from(flags.contains(StreamFlags::ITEM_REMOVED) && !root_changed);
    count
}

fn translate_flags_with(flags: StreamFlags, precise: bool, mut emit: impl FnMut(Event)) {
    // HistoryDone marks the end of replay and carries no filesystem change.
    if flags.contains(StreamFlags::HISTORY_DONE) {
        return;
    }

    // `ITEM_CLONED` can be present alongside other flags (including create/modify/remove).
    // Preserve any existing `info` (like "root changed"), but annotate otherwise so downstream
    // can detect and filter clone-related events. See https://github.com/notify-rs/notify/issues/465.
    let clone_related = precise && flags.contains(StreamFlags::ITEM_CLONED);
    let own_process_id = if precise && flags.contains(StreamFlags::OWN_EVENT) {
        Some(std::process::id())
    } else {
        None
    };

    let mut emit_event = |mut ev: Event| {
        if clone_related && ev.info().is_none() {
            ev.attrs.set_info("is: clone");
        }
        if let Some(process_id) = own_process_id {
            ev.attrs.set_process_id(process_id);
        }
        emit(ev);
    };

    // FSEvents provides two possible hints as to why events were dropped,
    // however documentation on what those mean is scant, so we just pass them
    // through in the info attr field. The intent is clear enough, and the
    // additional information is provided if the user wants it.
    if flags.contains(StreamFlags::MUST_SCAN_SUBDIRS) {
        let e = Event::new(EventKind::Other).set_flag(Flag::Rescan);
        emit_event(if flags.contains(StreamFlags::USER_DROPPED) {
            e.set_info("rescan: user dropped")
        } else if flags.contains(StreamFlags::KERNEL_DROPPED) {
            e.set_info("rescan: kernel dropped")
        } else {
            e
        });
    }

    // In imprecise mode, let's not even bother parsing the kind of the event
    // except for the above very special events.
    if !precise {
        emit(Event::new(EventKind::Any));
        return;
    }

    // A watched root changed (renamed or removed). If the flags provide a hint,
    // prefer that over guessing. Otherwise, treat it as a removal to avoid
    // misclassifying a delete as a rename.
    let root_changed = flags.contains(StreamFlags::ROOT_CHANGED);
    if root_changed {
        let kind = if flags.contains(StreamFlags::ITEM_REMOVED) {
            if flags.contains(StreamFlags::IS_DIR) {
                EventKind::Remove(RemoveKind::Folder)
            } else if flags.contains(StreamFlags::IS_FILE) {
                EventKind::Remove(RemoveKind::File)
            } else {
                EventKind::Remove(RemoveKind::Any)
            }
        } else if flags.contains(StreamFlags::ITEM_RENAMED) {
            EventKind::Modify(ModifyKind::Name(RenameMode::From))
        } else {
            EventKind::Remove(RemoveKind::Any)
        };

        emit_event(Event::new(kind).set_info("root changed"));
    }

    // A path was mounted at the event path; we treat that as a create.
    if flags.contains(StreamFlags::MOUNT) {
        emit_event(Event::new(EventKind::Create(CreateKind::Other)).set_info("mount"));
    }

    // A path was unmounted at the event path; we treat that as a remove.
    if flags.contains(StreamFlags::UNMOUNT) {
        emit_event(Event::new(EventKind::Remove(RemoveKind::Other)).set_info("mount"));
    }

    if flags.contains(StreamFlags::ITEM_CREATED) {
        emit_event(if flags.contains(StreamFlags::IS_DIR) {
            Event::new(EventKind::Create(CreateKind::Folder))
        } else if flags.contains(StreamFlags::IS_FILE) {
            Event::new(EventKind::Create(CreateKind::File))
        } else {
            let e = Event::new(EventKind::Create(CreateKind::Other));
            if flags.contains(StreamFlags::IS_SYMLINK) {
                e.set_info("is: symlink")
            } else if flags.contains(StreamFlags::IS_HARDLINK) {
                e.set_info("is: hardlink")
            } else if flags.contains(StreamFlags::ITEM_CLONED) {
                e.set_info("is: clone")
            } else {
                Event::new(EventKind::Create(CreateKind::Any))
            }
        });
    }

    // FSEvents provides no mechanism to associate the old and new sides of a
    // rename event.
    // Avoid emitting duplicate events around a root change by checking `root_changed`.
    if flags.contains(StreamFlags::ITEM_RENAMED) && !root_changed {
        emit_event(Event::new(EventKind::Modify(ModifyKind::Name(
            RenameMode::Any,
        ))));
    }

    // This is only described as "metadata changed", but it may be that it's
    // only emitted for some more precise subset of events... if so, will need
    // amending, but for now we have an Any-shaped bucket to put it in.
    if flags.contains(StreamFlags::INODE_META_MOD) {
        emit_event(Event::new(EventKind::Modify(ModifyKind::Metadata(
            MetadataKind::Any,
        ))));
    }

    if flags.contains(StreamFlags::FINDER_INFO_MOD) {
        emit_event(
            Event::new(EventKind::Modify(ModifyKind::Metadata(MetadataKind::Other)))
                .set_info("meta: finder info"),
        );
    }

    if flags.contains(StreamFlags::ITEM_CHANGE_OWNER) {
        emit_event(Event::new(EventKind::Modify(ModifyKind::Metadata(
            MetadataKind::Ownership,
        ))));
    }

    if flags.contains(StreamFlags::ITEM_XATTR_MOD) {
        emit_event(Event::new(EventKind::Modify(ModifyKind::Metadata(
            MetadataKind::Extended,
        ))));
    }

    // This is specifically described as a data change, which we take to mean
    // is a content change.
    if flags.contains(StreamFlags::ITEM_MODIFIED) {
        emit_event(Event::new(EventKind::Modify(ModifyKind::Data(
            DataChange::Content,
        ))));
    }

    // Avoid emitting duplicate events around a root change by checking `root_changed`.
    if flags.contains(StreamFlags::ITEM_REMOVED) && !root_changed {
        emit_event(if flags.contains(StreamFlags::IS_DIR) {
            Event::new(EventKind::Remove(RemoveKind::Folder))
        } else if flags.contains(StreamFlags::IS_FILE) {
            Event::new(EventKind::Remove(RemoveKind::File))
        } else {
            let e = Event::new(EventKind::Remove(RemoveKind::Other));
            if flags.contains(StreamFlags::IS_SYMLINK) {
                e.set_info("is: symlink")
            } else if flags.contains(StreamFlags::IS_HARDLINK) {
                e.set_info("is: hardlink")
            } else if flags.contains(StreamFlags::ITEM_CLONED) {
                e.set_info("is: clone")
            } else {
                Event::new(EventKind::Remove(RemoveKind::Any))
            }
        });
    }
}

struct StreamContextInfo {
    event_handler: Arc<Mutex<dyn EventHandler>>,
    recursive_info: Arc<Mutex<HashMap<PathBuf, WatchInfo>>>,
    event_kinds: EventKindMask,
}

// Free the context when the stream created by `FSEventStreamCreate` is released.
unsafe extern "C-unwind" fn release_context(info: *const libc::c_void) {
    // Safety:
    // - The [documentation] for `FSEventStreamContext` states that `release` is only
    //   called when the stream is deallocated, so it is safe to convert `info` back into a
    //   box and drop it.
    //
    // [docs]: https://developer.apple.com/documentation/coreservices/fseventstreamcontext?language=objc
    unsafe {
        drop(Box::from_raw(
            info as *const StreamContextInfo as *mut StreamContextInfo,
        ));
    }
}

impl FsEventWatcher {
    fn from_event_handler(
        event_handler: Arc<Mutex<dyn EventHandler>>,
        event_kinds: EventKindMask,
        latency: cf::CFTimeInterval,
    ) -> Result<Self> {
        Ok(FsEventWatcher {
            since_when: None,
            latency,
            flags: fs::kFSEventStreamCreateFlagFileEvents
                | fs::kFSEventStreamCreateFlagNoDefer
                | fs::kFSEventStreamCreateFlagWatchRoot,
            event_handler,
            runloop: None,
            watches: HashMap::new(),
            watch_paths: BTreeSet::new(),
            event_kinds,
            path_reservation: FseventsPathReservation::new(&ACTIVE_FSEVENTS_PATHS),
        })
    }

    fn watch_inner(&mut self, path: &Path, config: crate::WatchPathConfig) -> Result<()> {
        let (canonical_path, previous) = self.append_path(path, config)?;
        let entry = &self.watches[&canonical_path];
        let unchanged = previous.as_ref().is_some_and(|previous| {
            previous.device == entry.device
                && previous.inode == entry.inode
                && previous.info.is_recursive == entry.info.is_recursive
        });
        if (unchanged || self.is_covered(&canonical_path, entry.device))
            && let Some(runloop) = &self.runloop
        {
            // The stream already delivers these events. Update the callback's path
            // representation and recursive mode without rebuilding the stream.
            runloop
                .recursive_info
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .insert(canonical_path, entry.info.clone());
            return Ok(());
        }

        if let Err(err) = self.reserve_roots(self.stream_roots().count()) {
            self.set_watch(canonical_path, previous);
            return Err(err.add_path(path.into()));
        }
        self.restart()
    }

    fn unwatch_inner(&mut self, path: &Path) -> Result<()> {
        let (canonical_path, entry) = self.remove_path(path)?;
        if self.is_covered(&canonical_path, entry.device)
            && let Some(runloop) = &self.runloop
        {
            runloop
                .recursive_info
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .remove(&canonical_path);
            return Ok(());
        }

        // Without a recursive watch, the watches it covered become stream roots.
        if let Err(err) = self.reserve_roots(self.stream_roots().count()) {
            self.set_watch(canonical_path, Some(entry));
            return Err(err.add_path(path.into()));
        }
        self.restart()
    }

    #[expect(
        clippy::result_large_err,
        reason = "Match Watcher::update_paths without boxing its public batch error"
    )]
    fn update_paths_inner(
        &mut self,
        ops: Vec<crate::PathOp>,
    ) -> crate::StdResult<(), crate::UpdatePathsError> {
        if ops.is_empty() {
            return Ok(());
        }
        let previous_roots: HashMap<_, _> = self
            .stream_roots()
            .map(|(path, entry)| (path.clone(), (entry.device, entry.inode)))
            .collect();
        let mut roots = previous_roots.len();

        let result = crate::update_paths(ops, |op| {
            let change = match &op {
                PathOp::Watch(path, config) => self
                    .watch_entry(path, config.clone())
                    .map(|(canonical_path, entry)| (canonical_path, Some(entry))),
                PathOp::Unwatch(path) => self
                    .watched_path(path)
                    .map(|canonical_path| (canonical_path, None)),
            };
            let (canonical_path, entry) = match change {
                Ok(change) => change,
                Err(err) => return Err((op, err)),
            };

            // Only this path's subtree can gain or lose roots. Include descendants
            // when its recursive coverage changes.
            let covers = |entry: Option<&WatchEntry>| {
                entry
                    .filter(|entry| {
                        entry.info.is_recursive && !self.is_covered(&canonical_path, entry.device)
                    })
                    .map(|entry| entry.device)
            };
            let nested = covers(self.watches.get(&canonical_path)) != covers(entry.as_ref());
            let before = self.roots_at(&canonical_path, nested);
            let previous = self.set_watch(canonical_path.clone(), entry);
            let after = self.roots_at(&canonical_path, nested);
            if let Err(err) = self.reserve_roots(roots + after - before) {
                self.set_watch(canonical_path, previous);
                let err = err.add_path(op.as_path().into());
                return Err((op, err));
            }
            roots = roots + after - before;
            Ok(())
        });

        let root_count = self.stream_roots().count();
        debug_assert_eq!(roots, root_count);
        let roots_unchanged = root_count == previous_roots.len()
            && self.stream_roots().all(|(path, entry)| {
                previous_roots.get(path) == Some(&(entry.device, entry.inode))
            });
        if roots_unchanged && let Some(runloop) = &self.runloop {
            *runloop
                .recursive_info
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner()) = self
                .watches
                .iter()
                .map(|(path, entry)| (path.clone(), entry.info.clone()))
                .collect();
            // Operations that cancelled out may have reserved more than the stream uses.
            self.path_reservation.shrink_to(previous_roots.len());
            return result;
        }

        match self.restart() {
            Err(run_error) => match result {
                Ok(()) => Err(crate::UpdatePathsError {
                    source: run_error,
                    origin: None,
                    remaining: Default::default(),
                }),
                Err(path_op_error) => {
                    log::error!(
                        "Unable to run fsevents watcher after updating paths error: {run_error:?}"
                    );
                    Err(path_op_error)
                }
            },
            Ok(()) => result,
        }
    }

    /// Reserves replacement roots while retaining the running stream's reservation.
    fn reserve_roots(&mut self, roots: usize) -> Result<()> {
        // Over roughly RLIMIT_NOFILE/10 paths across all live streams, FSEvents
        // closes fd 0, which this process owns. The corruption then surfaces as
        // EBADF on unrelated files.
        let budget = fsevents_path_budget().unwrap_or(usize::MAX);
        self.path_reservation
            .reserve(roots, budget)
            .map_err(|active_path_count| {
                log::error!(
                    "refusing to watch {roots} FSEvents paths: {active_path_count} are active in \
                     this process and the safe limit is {budget}. Raise RLIMIT_NOFILE, watch \
                     fewer paths, or use macos_kqueue."
                );
                Error::new(ErrorKind::MaxFilesWatch)
            })
    }

    /// Replaces the stream after the caller has reserved its new roots.
    fn restart(&mut self) -> Result<()> {
        self.stop();
        let result = self.run();
        // The old stream is released: give back what the new one does not use.
        let roots = if self.is_running() {
            self.stream_roots().count()
        } else {
            0
        };
        self.path_reservation.shrink_to(roots);
        result
    }

    #[inline]
    fn is_running(&self) -> bool {
        self.runloop.is_some()
    }

    fn stop(&mut self) {
        if !self.is_running() {
            return;
        }

        if let Some(RunLoopHandle {
            runloop,
            stop_flag,
            thread_handle,
            ..
        }) = self.runloop.take()
        {
            // Don't wait for the runloop to become "waiting" before stopping; if the
            // stream is under heavy load that can delay shutdown indefinitely.
            stop_flag.store(true, Ordering::Release);
            runloop.stop();
            runloop.wake_up();
            // Wait for the thread to shut down.
            self.since_when = Some(thread_handle.join().expect("thread to shut down"));
        }
    }

    fn remove_path(&mut self, path: &Path) -> Result<(PathBuf, WatchEntry)> {
        let path = self.watched_path(path)?;
        let entry = self.set_watch(path.clone(), None);
        entry
            .map(|entry| (path, entry))
            .ok_or_else(Error::watch_not_found)
    }

    /// The path that the watch on `path` is registered under.
    fn watched_path(&self, path: &Path) -> Result<PathBuf> {
        let p = path
            .canonicalize()
            .ok()
            .or_else(|| {
                self.watches
                    .iter()
                    .find(|(_, entry)| entry.info.reported_path == path)
                    .map(|(path, _)| path.clone())
            })
            .or_else(|| absolute_path(path).ok())
            .unwrap_or_else(|| path.to_owned());

        if self.watches.contains_key(&p) {
            Ok(p)
        } else {
            Err(Error::watch_not_found())
        }
    }

    fn append_path(
        &mut self,
        path: &Path,
        config: crate::WatchPathConfig,
    ) -> Result<(PathBuf, Option<WatchEntry>)> {
        let (canonical_path, entry) = self.watch_entry(path, config)?;
        let previous = self.set_watch(canonical_path.clone(), Some(entry));
        Ok((canonical_path, previous))
    }

    /// Prepares a watch entry without changing registrations.
    // https://github.com/thibaudgg/rb-fsevent/blob/master/ext/fsevent_watch/main.c
    fn watch_entry(
        &self,
        path: &Path,
        config: crate::WatchPathConfig,
    ) -> Result<(PathBuf, WatchEntry)> {
        if !path.exists() {
            return Err(Error::path_not_found().add_path(path.into()));
        }
        let canonical_path = path.to_path_buf().canonicalize()?;
        let Some(cf_path) = path_to_cfstring_ref(&canonical_path) else {
            // Most likely the directory was deleted, or permissions changed,
            // while the above code was running.
            return Err(Error::path_not_found().add_path(path.into()));
        };

        let metadata = std::fs::metadata(&canonical_path)?;
        let (device, inode) = (metadata.dev(), metadata.ino());

        // Keep queued events when rewatching the same target; only newly added
        // recursive coverage starts at the current ID.
        let is_recursive = config.recursive_mode().is_recursive();
        let now = || unsafe { fs::FSEventsGetCurrentEventId() };
        let previous = self
            .watches
            .get(&canonical_path)
            .filter(|previous| previous.device == device && previous.inode == inode)
            .map(|previous| &previous.info);
        let (since, deep_since) = match previous {
            Some(previous) if previous.is_recursive || !is_recursive => {
                (previous.since, previous.deep_since)
            }
            Some(previous) => (previous.since, now()),
            None => {
                let now = now();
                (now, now)
            }
        };

        let entry = WatchEntry {
            info: WatchInfo {
                is_recursive,
                reported_path: path.to_path_buf(),
                user_data: config.user_data(),
                since,
                deep_since,
            },
            cf_path,
            device,
            inode,
        };
        Ok((canonical_path, entry))
    }

    /// Updates the watch map and path index, returning the previous entry.
    fn set_watch(&mut self, path: PathBuf, entry: Option<WatchEntry>) -> Option<WatchEntry> {
        match entry {
            Some(entry) => {
                self.watch_paths.insert(path.clone());
                self.watches.insert(path, entry)
            }
            None => {
                self.watch_paths.remove(&path);
                self.watches.remove(&path)
            }
        }
    }

    /// Counts roots at `path`, including descendants only when `nested` is set.
    fn roots_at(&self, path: &Path, nested: bool) -> usize {
        self.watch_paths
            .range::<Path, _>((Bound::Included(path), Bound::Unbounded))
            .take_while(|watched| {
                if nested {
                    watched.starts_with(path)
                } else {
                    watched.as_path() == path
                }
            })
            .filter(|watched| !self.is_covered(watched, self.watches[*watched].device))
            .count()
    }

    // A recursive watch covers nested watches on the same volume. Non-recursive
    // ancestors may filter out deeper events, and FSEvents may not cross mounts.
    fn is_covered(&self, path: &Path, device: u64) -> bool {
        path.ancestors().skip(1).any(|ancestor| {
            self.watches
                .get(ancestor)
                .is_some_and(|covering| covering.info.is_recursive && covering.device == device)
        })
    }

    fn stream_roots(&self) -> impl Iterator<Item = (&PathBuf, &WatchEntry)> {
        self.watches
            .iter()
            .filter(|(path, entry)| !self.is_covered(path, entry.device))
    }

    fn stream_paths(&self) -> cf::CFRetained<cf::CFMutableArray<cf::CFString>> {
        let paths: cf::CFRetained<cf::CFMutableArray<cf::CFString>> = cf::CFMutableArray::empty();
        for (_, entry) in self.stream_roots() {
            paths.append(&entry.cf_path);
        }
        paths
    }

    fn run(&mut self) -> Result<()> {
        let stream_paths = self.stream_paths();
        if stream_paths.is_empty() {
            self.since_when = None;
            return Ok(());
        }

        // Already held unless an earlier stream failed to start and gave it back.
        self.reserve_roots(stream_paths.iter().count())?;

        // The stream owns the callback context. Creation and spawn failures clean it up;
        // panics before cleanup can still leak it.
        let recursive_info = Arc::new(Mutex::new(
            self.watches
                .iter()
                .map(|(path, entry)| (path.clone(), entry.info.clone()))
                .collect(),
        ));
        let context = Box::into_raw(Box::new(StreamContextInfo {
            event_handler: self.event_handler.clone(),
            recursive_info: recursive_info.clone(),
            event_kinds: self.event_kinds,
        }));

        let stream_context = fs::FSEventStreamContext {
            version: 0,
            info: context as *mut libc::c_void,
            retain: None,
            release: Some(release_context),
            copyDescription: None,
        };

        // A concrete initial ID preserves pending events across restarts before the first callback.
        // All roots resume from the same ID; watch_for filters events predating each watch.
        let since_when = self
            .since_when
            .unwrap_or_else(|| unsafe { fs::FSEventsGetCurrentEventId() });
        let stream = unsafe {
            fs::FSEventStreamCreate(
                cf::kCFAllocatorDefault,
                Some(callback),
                &stream_context as *const _ as *mut _,
                stream_paths.as_opaque(),
                since_when,
                self.latency,
                self.flags,
            )
        };
        if stream.is_null() {
            // SAFETY: Apple documents `release` as called only when the stream is
            // deallocated. No stream was created, so we still own the context.
            unsafe {
                release_context(context.cast());
            }
            log::error!("FSEventStreamCreate returned NULL");
            return Err(Error::new(ErrorKind::WatchStartFailed));
        }

        // Wrapper to help send CFRunLoop types across threads.
        struct CFRunLoopSendWrapper(cf::CFRetained<cf::CFRunLoop>);

        // Safety:
        // - According to the Apple documentation, it's safe to move `CFRunLoop`s across threads.
        //   https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html
        unsafe impl Send for CFRunLoopSendWrapper {}

        // Wrapper to help send FSEventStreamRef types across threads.
        struct FSEventStreamSendWrapper(fs::FSEventStreamRef);

        // SAFETY: The stream is moved before it is scheduled or started. If spawning succeeds,
        // only the receiving thread accesses it: it schedules, starts, stops, invalidates and
        // releases the stream on its own runloop. The stream owns its boxed StreamContextInfo until
        // release_context runs; shared handler and watch data are protected by Arc<Mutex<_>>.
        // See Apple's create-then-schedule lifecycle:
        // https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/FSEvents_ProgGuide/UsingtheFSEventsFramework/UsingtheFSEventsFramework.html
        unsafe impl Send for FSEventStreamSendWrapper {}

        // move into thread
        let stream_to_send = FSEventStreamSendWrapper(stream);

        // channel to pass runloop around
        let (rl_tx, rl_rx) = unbounded();

        // Used to stop the runloop thread without relying on privileged APIs or
        // on `CFRunLoopIsWaiting()` becoming true under heavy event load.
        let stop_flag = Arc::new(AtomicBool::new(false));
        let stop_flag_thread = Arc::clone(&stop_flag);

        let thread_handle = thread::Builder::new()
            .name("notify-rs fsevents loop".to_string())
            .spawn(move || {
                let _ = &stream_to_send;
                let stream = stream_to_send.0;

                unsafe {
                    // Safety:
                    // This may panic if OOM occurs.
                    // Related: https://github.com/madsmtm/objc2/issues/797
                    let cur_runloop =
                        cf::CFRunLoop::current().expect("Failed to get current runloop");

                    #[allow(deprecated)]
                    fs::FSEventStreamScheduleWithRunLoop(
                        stream,
                        &cur_runloop,
                        cf::kCFRunLoopDefaultMode.expect("Failed to get default runloop mode"),
                    );
                    if !fs::FSEventStreamStart(stream) {
                        fs::FSEventStreamInvalidate(stream);
                        fs::FSEventStreamRelease(stream);
                        log::error!("FSEventStreamStart returned false");
                        rl_tx
                            .send(Err(Error::new(ErrorKind::WatchStartFailed)))
                            .expect("Unable to send error for FSEventStreamStart");
                        return since_when;
                    }

                    // `stop()` will call `CFRunLoopStop` + `CFRunLoopWakeUp` and then join this
                    // thread.
                    rl_tx
                        .send(Ok(CFRunLoopSendWrapper(cur_runloop)))
                        .expect("Unable to send runloop to watcher");

                    // `CFRunLoopStop` is discarded if `stop()` calls it before this thread
                    // enters the runloop, so re-check the stop flag after each bounded run.
                    while !stop_flag_thread.load(Ordering::Acquire) {
                        let result = cf::CFRunLoop::run_in_mode(
                            cf::kCFRunLoopDefaultMode,
                            RUNLOOP_STOP_RECHECK_SECONDS,
                            false,
                        );
                        if result == cf::CFRunLoopRunResult::Finished {
                            break;
                        }
                    }
                    fs::FSEventStreamStop(stream);
                    // The runloop has finished all callbacks. Preserve the last
                    // delivered ID before releasing the stream so its replacement
                    // also receives events queued before or during the restart.
                    // RootChanged events have ID zero; never rewind past the
                    // point where this stream started.
                    let since_when = fs::FSEventStreamGetLatestEventId(stream).max(since_when);
                    fs::FSEventStreamInvalidate(stream);
                    fs::FSEventStreamRelease(stream);
                    since_when
                }
            })
            .inspect_err(|_| {
                // SAFETY: Spawning failed, so no thread has used the stream. Releasing it
                // also frees its context. It was never scheduled, so do not invalidate it.
                unsafe { fs::FSEventStreamRelease(stream) };
            })?;
        // block until runloop has been sent
        let runloop_wrapper = match rl_rx.recv() {
            Ok(Ok(runloop_wrapper)) => runloop_wrapper,
            Ok(Err(err)) => {
                thread_handle
                    .join()
                    .expect("thread to shut down after FSEvent stream startup failure");
                return Err(err);
            }
            Err(_) => {
                thread_handle
                    .join()
                    .expect("thread to shut down after FSEvent stream startup channel close");
                return Err(Error::generic(
                    "unable to receive FSEvent stream startup result",
                ));
            }
        };
        self.runloop = Some(RunLoopHandle {
            runloop: runloop_wrapper.0,
            stop_flag,
            thread_handle,
            recursive_info,
        });

        Ok(())
    }

    fn configure_raw_mode(&mut self, _config: Config, tx: Sender<Result<bool>>) {
        tx.send(Ok(false))
            .expect("configuration channel disconnect");
    }
}

// A twelfth rather than a tenth: the edge also shifts with how many descriptors
// the process already holds.
fn fsevents_path_budget() -> Option<usize> {
    let mut limit = unsafe { std::mem::zeroed::<libc::rlimit>() };
    if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 {
        return None;
    }
    let soft = usize::try_from(limit.rlim_cur).ok()?;
    Some(soft / 12)
}

unsafe extern "C-unwind" fn callback(
    stream_ref: fs::ConstFSEventStreamRef,
    info: *mut libc::c_void,
    num_events: libc::size_t,                          // size_t numEvents
    event_paths: NonNull<libc::c_void>,                // void *eventPaths
    event_flags: NonNull<fs::FSEventStreamEventFlags>, // const FSEventStreamEventFlags eventFlags[]
    event_ids: NonNull<fs::FSEventStreamEventId>,      // const FSEventStreamEventId eventIds[]
) {
    // Never unwind into CoreServices; if something goes wrong, drop the events and log.
    // This also protects against panics from user-provided `EventHandler` implementations.
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe {
        callback_impl(
            stream_ref,
            info,
            num_events,
            event_paths,
            event_flags,
            event_ids,
        )
    }))
    .map_err(|_| {
        log::error!("panic in FSEvents callback; dropping pending events");
    });
}

/// Finds the most specific watch whose coverage of `path` began before `event_id`.
/// Newer watches are skipped so queued events can reach a recursive ancestor.
/// `None` skips the ID check.
///
/// Looks up the path and its ancestors by hash, without scanning all watches.
fn watch_for<'a>(
    recursive_info: &'a HashMap<PathBuf, WatchInfo>,
    path: &Path,
    event_id: Option<fs::FSEventStreamEventId>,
) -> Option<(&'a PathBuf, &'a WatchInfo)> {
    let is_after = |since| event_id.is_none_or(|event_id| event_id > since);
    if let Some(watch) = recursive_info
        .get_key_value(path)
        .filter(|(_, watch_info)| is_after(watch_info.since))
    {
        return Some(watch);
    }
    path.ancestors()
        .skip(1)
        .enumerate()
        .find_map(|(depth, ancestor)| {
            let (watch_path, watch_info) = recursive_info.get_key_value(ancestor)?;
            // Any watch matches its direct children.
            let since = if depth == 0 {
                watch_info.since
            } else if watch_info.is_recursive {
                watch_info.deep_since
            } else {
                return None;
            };
            is_after(since).then_some((watch_path, watch_info))
        })
}

unsafe fn callback_impl(
    _stream_ref: fs::ConstFSEventStreamRef,
    info: *mut libc::c_void,
    num_events: libc::size_t,                          // size_t numEvents
    event_paths: NonNull<libc::c_void>,                // void *eventPaths
    event_flags: NonNull<fs::FSEventStreamEventFlags>, // const FSEventStreamEventFlags eventFlags[]
    event_ids: NonNull<fs::FSEventStreamEventId>,      // const FSEventStreamEventId eventIds[]
) {
    let event_paths = event_paths.as_ptr() as *const *const libc::c_char;
    // SAFETY: The stream owns this boxed context and releases it only after callbacks finish.
    let info = unsafe { &*(info as *const StreamContextInfo) };
    let event_handler_mutex = &info.event_handler;
    let event_kinds = info.event_kinds;
    let mut event_handler_guard = None;

    for p in 0..num_events {
        // Paths are not guaranteed to be valid UTF-8 (e.g. NFS); keep them as raw bytes.
        // SAFETY: FSEvents provides `num_events` valid, NUL-terminated paths for this callback.
        let path = unsafe { CStr::from_ptr(*event_paths.add(p)) };
        let path = Path::new(OsStr::from_bytes(path.to_bytes()));

        // SAFETY: FSEvents provides `num_events` flags, and `p` is within that range.
        let raw_flag = unsafe { *event_flags.as_ptr().add(p) };
        let flag = StreamFlags::from_bits_truncate(raw_flag);
        let unknown_bits = raw_flag & !StreamFlags::all().bits();
        if unknown_bits != 0 {
            // `FSEventStreamEventFlags` is an extensible bitfield; tolerate future flags.
            log::trace!("unknown FSEventStreamEventFlags bits: 0x{unknown_bits:08x}");
        }

        // SAFETY: FSEvents provides `num_events` IDs, and `p` is within that range.
        let event_id = unsafe { *event_ids.as_ptr().add(p) };
        // Keep ID-zero events (such as RootChanged) and rescan notices regardless of watch age.
        let event_id =
            Some(event_id).filter(|&id| id != 0 && !flag.contains(StreamFlags::MUST_SCAN_SUBDIRS));

        let recursive_info = info
            .recursive_info
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let Some((watch_path, watch_info)) = watch_for(&recursive_info, path, event_id) else {
            // FSEvents reports MustScanSubDirs at an ancestor of the
            // registered watches (often `/` or the common parent). Those
            // paths fail membership, but the recovery notice must still
            // reach the handler.
            if flag.contains(StreamFlags::MUST_SCAN_SUBDIRS) {
                drop(recursive_info);
                let mut ev = Event::new(EventKind::Other).set_flag(Flag::Rescan);
                ev = if flag.contains(StreamFlags::USER_DROPPED) {
                    ev.set_info("rescan: user dropped")
                } else if flag.contains(StreamFlags::KERNEL_DROPPED) {
                    ev.set_info("rescan: kernel dropped")
                } else {
                    ev
                };
                ev.paths.push(path.to_path_buf());
                if event_kinds.matches(&ev.kind) {
                    let event_handler = event_handler_guard.get_or_insert_with(|| {
                        match event_handler_mutex.lock() {
                            Ok(guard) => guard,
                            Err(poisoned) => poisoned.into_inner(),
                        }
                    });
                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        event_handler.handle_event(Ok(ev));
                    }))
                    .map_err(|_| {
                        log::error!("panic in FSEvents event handler; dropping event");
                    });
                }
            }
            continue;
        };
        let translated_count = translated_event_count(&flag, true);
        if translated_count == 0 {
            continue;
        }
        // Most FSEvents flags produce one Event; move the reported path in that case.
        let mut event_path = Some(reported_path(watch_path, &watch_info.reported_path, path));
        let user_data = watch_info.user_data;
        // Do not hold the watch information lock while invoking user code.
        drop(recursive_info);
        let single_translated_event = translated_count == 1;

        log::trace!("FSEvent: path = `{}`, flag = {:?}", path.display(), flag);

        translate_flags_with(flag, true, |mut ev| {
            // Filter events based on EventKindMask before adding the path.
            if !event_kinds.matches(&ev.kind) {
                return;
            }
            if let Some(user_data) = user_data {
                ev = ev.set_user_data(user_data);
            }
            if single_translated_event {
                ev.paths
                    .push(event_path.take().expect("single translated event path"));
            } else {
                ev.paths
                    .push(event_path.as_ref().expect("translated event path").clone());
            }

            let event_handler =
                event_handler_guard.get_or_insert_with(|| match event_handler_mutex.lock() {
                    Ok(guard) => guard,
                    Err(poisoned) => poisoned.into_inner(),
                });
            // Protect against panicking event handlers, which would otherwise unwind into
            // the CoreServices callback.
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                event_handler.handle_event(Ok(ev));
            }))
            .map_err(|_| {
                log::error!("panic in FSEvents event handler; dropping event");
            });
        });
    }
}

impl Watcher for FsEventWatcher {
    /// Create a new watcher.
    fn new<F: EventHandler>(event_handler: F, config: Config) -> Result<Self> {
        Self::from_event_handler(
            Arc::new(Mutex::new(event_handler)),
            config.event_kinds(),
            config.fsevent_latency().as_secs_f64(),
        )
    }

    fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
        self.watch_with(path, crate::WatchPathConfig::new(recursive_mode))
    }

    fn watch_with(&mut self, path: &Path, config: crate::WatchPathConfig) -> Result<()> {
        let user_data = config.user_data();
        self.watch_inner(path, config)
            .map_err(|err| err.set_user_data_opt(user_data))
    }

    fn unwatch(&mut self, path: &Path) -> Result<()> {
        self.unwatch_inner(path)
    }

    fn update_paths(&mut self, ops: Vec<PathOp>) -> crate::StdResult<(), crate::UpdatePathsError> {
        self.update_paths_inner(ops)
    }

    fn configure(&mut self, config: Config) -> Result<bool> {
        let (tx, rx) = unbounded();
        self.configure_raw_mode(config, tx);
        rx.recv()?
    }

    fn watched_paths(&self) -> Result<Vec<WatchedPath>> {
        // Unlike the channel-based backends, FSEvents keeps watch state on the watcher itself.
        // The runloop callback reads a separate map of watch information, so it does not
        // mutate or read this map concurrently.
        Ok(self
            .watches
            .iter()
            .map(|(_path, WatchEntry { info, .. })| {
                WatchedPath::new(
                    info.reported_path.clone(),
                    if info.is_recursive {
                        RecursiveMode::Recursive
                    } else {
                        RecursiveMode::NonRecursive
                    },
                )
            })
            .collect())
    }

    fn kind() -> crate::WatcherKind {
        crate::WatcherKind::Fsevent
    }
}

impl Drop for FsEventWatcher {
    fn drop(&mut self) {
        self.stop();
    }
}

/// Resolve the nearest reachable ancestor through a Core Foundation file reference,
/// then append any missing path components.
///
/// Adapted from <https://docs.rs/fsevent-sys/4.1.0/src/fsevent_sys/core_foundation.rs.html#149-230>.
fn path_to_cfstring_ref(source: &Path) -> Option<cf::CFRetained<cf::CFString>> {
    let url = cf::CFURL::from_file_path(source)?;

    let mut placeholder = url.absolute_url()?;

    let imaginary = cf::CFMutableArray::empty();

    // These CFURL APIs accept null error outputs. We only need success/failure,
    // so avoid taking ownership of CFErrors during retries or URL conversion.
    while !unsafe { placeholder.resource_is_reachable(ptr::null_mut()) } {
        if let Some(child) = placeholder.last_path_component() {
            imaginary.insert(0, &*child);
        }

        placeholder = cf::CFURL::new_copy_deleting_last_path_component(None, Some(&placeholder))?;
    }

    let url =
        unsafe { cf::CFURL::new_file_reference_url(None, Some(&placeholder), ptr::null_mut()) }?;

    let mut placeholder =
        unsafe { cf::CFURL::new_file_path_url(None, Some(&url), ptr::null_mut()) }?;

    for component in imaginary {
        placeholder = cf::CFURL::new_copy_appending_path_component(
            None,
            Some(&placeholder),
            Some(&component),
            false,
        )?;
    }

    placeholder.file_system_path(cf::CFURLPathStyle::CFURLPOSIXPathStyle)
}

#[cfg(test)]
mod tests {
    use std::sync::mpsc;
    use std::time::{Duration, Instant};

    use crate::{ErrorKind, WatchPathConfig};

    use super::*;
    use crate::test::*;

    fn watcher() -> (TestWatcher<FsEventWatcher>, Receiver) {
        channel()
    }

    fn watch_info(is_recursive: bool) -> WatchInfo {
        WatchInfo {
            is_recursive,
            reported_path: PathBuf::from("/reported"),
            user_data: None,
            since: 0,
            deep_since: 0,
        }
    }

    #[test]
    fn watch_for_matches_each_kind_of_watch() {
        let mut recursive_info = HashMap::new();
        recursive_info.insert(PathBuf::from("/repo"), watch_info(false));
        recursive_info.insert(PathBuf::from("/repo/src"), watch_info(false));
        recursive_info.insert(PathBuf::from("/deep"), watch_info(true));
        recursive_info.insert(PathBuf::from("/deep/inner"), watch_info(false));
        recursive_info.insert(PathBuf::from("/single/file.txt"), watch_info(false));

        let cases = [
            // A watched path itself, recursive or not.
            ("/repo", Some("/repo")),
            ("/deep", Some("/deep")),
            ("/single/file.txt", Some("/single/file.txt")),
            // A direct child of a non-recursive watch.
            ("/repo/readme.md", Some("/repo")),
            ("/repo/src/main.rs", Some("/repo/src")),
            // A grandchild of a non-recursive watch whose own parent is unwatched.
            ("/repo/target/debug", None),
            // Any descendant of a recursive watch.
            ("/deep/a", Some("/deep")),
            ("/deep/a/b/c", Some("/deep")),
            // The more specific of a recursive watch and a nested watch.
            ("/deep/inner/x", Some("/deep/inner")),
            ("/deep/inner/x/y", Some("/deep")),
            // A sibling sharing a prefix of characters, not of components.
            ("/repository/readme.md", None),
            ("/deeper/a", None),
            // The parent of a watched file, and its other children.
            ("/single", None),
            ("/single/other.txt", None),
            // Nothing watched above it at all.
            ("/elsewhere/x", None),
            ("/", None),
        ];
        for (path, expected) in cases {
            let matched = watch_for(&recursive_info, Path::new(path), None)
                .map(|(watch_path, _)| watch_path.as_path());
            assert_eq!(matched, expected.map(Path::new), "{path}");
        }
    }

    #[test]
    fn watch_for_agrees_with_a_scan_of_every_watch() {
        // The decision a scan of every watched path makes, keeping the
        // longest match, which `watch_for` replaces: kept here as the
        // reference it must agree with.
        fn scan<'a>(
            recursive_info: &'a HashMap<PathBuf, WatchInfo>,
            path: &Path,
        ) -> Option<&'a PathBuf> {
            recursive_info
                .iter()
                .filter(|(watch_path, watch_info)| {
                    path.starts_with(watch_path)
                        && (watch_info.is_recursive
                            || path == watch_path.as_path()
                            || path.parent() == Some(watch_path.as_path()))
                })
                .map(|(watch_path, _)| watch_path)
                .max_by_key(|watch_path| watch_path.as_os_str().as_bytes().len())
        }

        let watches: [(&str, bool); 7] = [
            ("/a", false),
            ("/a/b", true),
            ("/a/b/c", false),
            ("/a/b/c/d", true),
            ("/x/y", false),
            ("/x/y/z.txt", false),
            ("/r", true),
        ];
        let paths = [
            "/",
            "/a",
            "/a/b",
            "/a/b/c",
            "/a/b/c/d",
            "/a/b/c/d/e",
            "/a/b/c/d/e/f",
            "/a/b/q/r",
            "/a/z",
            "/a/z/q",
            "/ab",
            "/x",
            "/x/y",
            "/x/y/z.txt",
            "/x/y/w",
            "/x/y/w/v",
            "/r",
            "/r/s/t",
            "/rs",
        ];
        // Every subset of the watches, so each path is judged against watches
        // that are recursive, non-recursive, nested in each other and absent.
        for mask in 0u32..(1 << watches.len()) {
            let recursive_info: HashMap<PathBuf, WatchInfo> = watches
                .iter()
                .enumerate()
                .filter(|(index, _)| mask & (1 << index) != 0)
                .map(|(_, &(watch_path, is_recursive))| {
                    (PathBuf::from(watch_path), watch_info(is_recursive))
                })
                .collect();
            for path in paths {
                assert_eq!(
                    watch_for(&recursive_info, Path::new(path), None)
                        .map(|(watch_path, _)| watch_path),
                    scan(&recursive_info, Path::new(path)),
                    "{path} against {recursive_info:?}"
                );
            }
        }
    }

    fn runloop_thread_id(watcher: &FsEventWatcher) -> thread::ThreadId {
        watcher
            .runloop
            .as_ref()
            .expect("watcher to be running")
            .thread_handle
            .thread()
            .id()
    }

    fn wait_for_path(rx: &mpsc::Receiver<Result<Event>>, path: &Path) -> Event {
        let deadline = Instant::now() + Duration::from_secs(10);
        loop {
            let event = rx
                .recv_timeout(deadline.saturating_duration_since(Instant::now()))
                .unwrap_or_else(|err| panic!("missing event for {}: {err}", path.display()))
                .expect("watcher event");
            if event.paths.iter().any(|event_path| event_path == path) {
                return event;
            }
        }
    }

    // Block the native runloop, rather than racing a sleep against event delivery.
    // The source owns its context and is released along with the runloop.
    fn pause_runloop(watcher: &FsEventWatcher) -> mpsc::Sender<()> {
        type Pause = (mpsc::Sender<()>, mpsc::Receiver<()>);

        unsafe extern "C-unwind" fn perform(info: *mut libc::c_void) {
            let (entered, resume) = unsafe { &*info.cast::<Pause>() };
            let _ = entered.send(());
            let _ = resume.recv_timeout(Duration::from_secs(20));
        }

        unsafe extern "C-unwind" fn release(info: *const libc::c_void) {
            drop(unsafe { Box::from_raw(info.cast_mut().cast::<Pause>()) });
        }

        let (entered_tx, entered_rx) = mpsc::channel::<()>();
        let (resume_tx, resume_rx) = mpsc::channel();
        let mut context = cf::CFRunLoopSourceContext {
            version: 0,
            info: Box::into_raw(Box::new((entered_tx, resume_rx))).cast(),
            retain: None,
            release: Some(release),
            copyDescription: None,
            equal: None,
            hash: None,
            schedule: None,
            cancel: None,
            perform: Some(perform),
        };
        let runloop = &watcher.runloop.as_ref().expect("running watcher").runloop;
        let source = unsafe {
            cf::CFRunLoopSource::new(cf::kCFAllocatorDefault, isize::MIN, &mut context)
                .expect("pause source")
        };
        runloop.add_source(Some(&source), unsafe { cf::kCFRunLoopDefaultMode });
        source.signal();
        runloop.wake_up();
        entered_rx
            .recv_timeout(Duration::from_secs(10))
            .expect("runloop paused");
        resume_tx
    }

    // Resume only after the old stream is stopping, leaving queued events for its replacement.
    fn restart_while_paused(
        watcher: &mut FsEventWatcher,
        resume: mpsc::Sender<()>,
        change: &str,
        apply: impl FnOnce(&mut FsEventWatcher),
    ) {
        let stop_flag = watcher.runloop.as_ref().unwrap().stop_flag.clone();
        thread::scope(|scope| {
            scope.spawn(move || {
                let deadline = Instant::now() + Duration::from_secs(10);
                while !stop_flag.load(Ordering::Acquire) && Instant::now() < deadline {
                    thread::sleep(Duration::from_millis(1));
                }
                let stopped = stop_flag.load(Ordering::Acquire);
                resume.send(()).expect("resume runloop");
                assert!(stopped, "{change} did not stop the old stream");
            });
            apply(watcher);
        });
    }

    #[test]
    fn queued_events_survive_watch_changes() {
        for change in [
            "watch",
            "rewatch",
            "unwatch",
            "update_paths",
            "failed_update_paths",
        ] {
            let dir = tempfile::tempdir().unwrap();
            let root = dir.path().canonicalize().unwrap();
            let a = root.join("a");
            let b = root.join("b");
            let c = root.join("c");
            for path in [&a, &b, &c] {
                std::fs::create_dir(path).unwrap();
            }

            let (tx, rx) = mpsc::channel();
            let mut watcher = FsEventWatcher::new(tx, Config::default()).unwrap();
            watcher
                .update_paths(vec![
                    PathOp::watch_recursive(a.clone()),
                    PathOp::watch_recursive(b.clone()),
                ])
                .unwrap();

            // A separate stream confirms that FSEvents has produced the pending
            // event while the stream under test cannot invoke its callback.
            let (observer_tx, observer_rx) = mpsc::channel();
            let mut observer = FsEventWatcher::new(observer_tx, Config::default()).unwrap();
            observer.watch(&a, RecursiveMode::Recursive).unwrap();
            let resume = pause_runloop(&watcher);
            let path = a.join("pending");
            std::fs::write(&path, "pending event").unwrap();
            wait_for_path(&observer_rx, &path);
            assert!(
                rx.try_iter()
                    .all(|event| !event.unwrap().paths.contains(&path))
            );

            restart_while_paused(&mut watcher, resume, change, |watcher| match change {
                "watch" => watcher.watch(&c, RecursiveMode::Recursive).unwrap(),
                "rewatch" => watcher.watch(&a, RecursiveMode::NonRecursive).unwrap(),
                "unwatch" => watcher.unwatch(&b).unwrap(),
                "update_paths" => watcher
                    .update_paths(vec![
                        PathOp::unwatch(b.clone()),
                        PathOp::watch_recursive(c.clone()),
                    ])
                    .unwrap(),
                "failed_update_paths" => {
                    let err = watcher
                        .update_paths(vec![
                            PathOp::unwatch(b.clone()),
                            PathOp::unwatch(root.join("missing")),
                            PathOp::watch_recursive(c.clone()),
                        ])
                        .unwrap_err();
                    assert!(matches!(err.source.kind, ErrorKind::WatchNotFound));
                    assert_eq!(err.remaining.len(), 1);
                }
                _ => unreachable!(),
            });
            wait_for_path(&rx, &path);
        }
    }

    #[test]
    fn events_before_a_watch_are_not_delivered() {
        for change in ["watch", "update_paths"] {
            let dir = tempfile::tempdir().unwrap();
            let root = dir.path().canonicalize().unwrap();
            let a = root.join("a");
            let b = root.join("b");
            for path in [&a, &b] {
                std::fs::create_dir(path).unwrap();
            }

            let (tx, rx) = mpsc::channel();
            let mut watcher = FsEventWatcher::new(tx, Config::default()).unwrap();
            watcher.watch(&a, RecursiveMode::Recursive).unwrap();
            // Establish the old stream's resume ID.
            let first = a.join("first");
            std::fs::create_dir(&first).unwrap();
            wait_for_path(&rx, &first);

            // Confirm each change with an observer before adding the watch.
            // Directory creation avoids the separate create/write events of file writes.
            let (observer_tx, observer_rx) = mpsc::channel();
            let mut observer = FsEventWatcher::new(observer_tx, Config::default()).unwrap();
            observer.watch(&root, RecursiveMode::Recursive).unwrap();
            let resume = pause_runloop(&watcher);
            let before = b.join("before");
            let pending = a.join("pending");
            for path in [&before, &pending] {
                std::fs::create_dir(path).unwrap();
                wait_for_path(&observer_rx, path);
            }

            restart_while_paused(&mut watcher, resume, change, |watcher| match change {
                "watch" => watcher.watch(&b, RecursiveMode::Recursive).unwrap(),
                "update_paths" => watcher
                    .update_paths(vec![PathOp::watch_recursive(b.clone())])
                    .unwrap(),
                _ => unreachable!(),
            });

            let after = b.join("after");
            std::fs::create_dir(&after).unwrap();
            // Drain through a post-registration event to include the earlier IDs.
            let mut delivered = Vec::new();
            while !delivered.contains(&after) {
                let event = rx
                    .recv_timeout(Duration::from_secs(10))
                    .unwrap_or_else(|err| panic!("{change}: missing event after the watch: {err}"))
                    .expect("watcher event");
                delivered.extend(event.paths);
            }
            assert!(delivered.contains(&pending), "{change}: {delivered:?}");
            assert!(!delivered.contains(&before), "{change}: {delivered:?}");
        }
    }

    #[test]
    fn rewatching_keeps_the_starting_event_of_an_unchanged_target() {
        fn advance_event_id(dir: &Path) {
            let id = unsafe { fs::FSEventsGetCurrentEventId() };
            std::fs::create_dir(dir.join(id.to_string())).unwrap();
            let deadline = Instant::now() + Duration::from_secs(10);
            while unsafe { fs::FSEventsGetCurrentEventId() } == id {
                assert!(Instant::now() < deadline, "FSEvents recorded no change");
                thread::sleep(Duration::from_millis(1));
            }
        }

        let dir = tempfile::tempdir().unwrap();
        let parent = dir.path().canonicalize().unwrap();
        let root = parent.join("root");
        std::fs::create_dir(&root).unwrap();
        let mut watcher = FsEventWatcher::new(|_| {}, Config::default()).unwrap();
        let watch = |watcher: &mut FsEventWatcher, mode| {
            advance_event_id(&parent);
            watcher
                .append_path(&root, WatchPathConfig::new(mode))
                .unwrap();
            let info = &watcher.watches[&root].info;
            (info.since, info.deep_since)
        };

        let (since, _) = watch(&mut watcher, RecursiveMode::NonRecursive);
        // Enabling recursion preserves the direct-child boundary.
        let (widened_since, deep_since) = watch(&mut watcher, RecursiveMode::Recursive);
        assert_eq!(widened_since, since);
        assert!(deep_since > since);
        assert_eq!(
            watch(&mut watcher, RecursiveMode::Recursive),
            (since, deep_since)
        );

        // Replacing the target resets both boundaries.
        std::fs::rename(&root, parent.join("old")).unwrap();
        std::fs::create_dir(&root).unwrap();
        let (replaced_since, replaced_deep_since) = watch(&mut watcher, RecursiveMode::Recursive);
        assert!(replaced_since > deep_since);
        assert_eq!(replaced_deep_since, replaced_since);

        // Removing and re-adding the watch resets both boundaries.
        watcher.remove_path(&root).unwrap();
        let (rewatched_since, rewatched_deep_since) = watch(&mut watcher, RecursiveMode::Recursive);
        assert!(rewatched_since > replaced_since);
        assert_eq!(rewatched_deep_since, rewatched_since);
    }

    #[test]
    fn events_during_stream_restart_are_replayed() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let (tx, rx) = mpsc::channel();
        let mut watcher = FsEventWatcher::new(tx, Config::default()).unwrap();
        watcher.watch(&root, RecursiveMode::Recursive).unwrap();

        let before = root.join("before");
        std::fs::write(&before, "before restart").unwrap();
        wait_for_path(&rx, &before);
        watcher.stop();
        assert!(watcher.since_when.is_some());

        let (observer_tx, observer_rx) = mpsc::channel();
        let mut observer = FsEventWatcher::new(observer_tx, Config::default()).unwrap();
        observer.watch(&root, RecursiveMode::Recursive).unwrap();
        let during = root.join("during");
        std::fs::write(&during, "during restart").unwrap();
        wait_for_path(&observer_rx, &during);

        watcher.run().unwrap();
        wait_for_path(&rx, &during);

        watcher.unwatch(&root).unwrap();
        assert_eq!(watcher.since_when, None);
    }

    #[test]
    fn unchanged_stream_roots_keep_pending_events() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let child = root.join("child");
        let nested = child.join("nested");
        let missing = root.join("missing");
        std::fs::create_dir_all(&nested).unwrap();

        let (tx, rx) = mpsc::channel();
        let mut watcher = FsEventWatcher::new(tx, Config::default()).unwrap();
        watcher.watch(&root, RecursiveMode::Recursive).unwrap();
        watcher.watch(&child, RecursiveMode::Recursive).unwrap();
        let thread_id = runloop_thread_id(&watcher);
        let resume = pause_runloop(&watcher);
        let pending = root.join("pending");
        std::fs::write(&pending, "pending event").unwrap();

        watcher.watch(&root, RecursiveMode::Recursive).unwrap();
        assert_eq!(runloop_thread_id(&watcher), thread_id);
        watcher.unwatch(&child).unwrap();
        assert_eq!(runloop_thread_id(&watcher), thread_id);
        assert!(matches!(
            watcher.unwatch(&missing).unwrap_err().kind,
            ErrorKind::WatchNotFound
        ));
        assert_eq!(runloop_thread_id(&watcher), thread_id);

        watcher.update_paths(vec![]).unwrap();
        assert_eq!(runloop_thread_id(&watcher), thread_id);
        watcher
            .update_paths(vec![PathOp::watch_recursive(child.clone())])
            .unwrap();
        assert_eq!(runloop_thread_id(&watcher), thread_id);
        watcher
            .update_paths(vec![PathOp::unwatch(child.clone())])
            .unwrap();
        assert_eq!(runloop_thread_id(&watcher), thread_id);

        let err = watcher
            .update_paths(vec![PathOp::watch_recursive(missing.clone())])
            .unwrap_err();
        assert!(matches!(err.source.kind, ErrorKind::PathNotFound));
        assert_eq!(runloop_thread_id(&watcher), thread_id);

        // Successful operations before an error must still update the callback,
        // even when the native stream's roots have not changed.
        let err = watcher
            .update_paths(vec![
                PathOp::Watch(
                    root.clone(),
                    WatchPathConfig::new(RecursiveMode::NonRecursive),
                ),
                PathOp::unwatch(missing),
                PathOp::watch_recursive(child),
            ])
            .unwrap_err();
        assert!(matches!(err.source.kind, ErrorKind::WatchNotFound));
        assert_eq!(err.remaining.len(), 1);
        assert_eq!(runloop_thread_id(&watcher), thread_id);
        let recursive_info = watcher
            .runloop
            .as_ref()
            .unwrap()
            .recursive_info
            .lock()
            .unwrap();
        assert!(!recursive_info[&root].is_recursive);
        assert!(watch_for(&recursive_info, &nested.join("entry"), None).is_none());
        drop(recursive_info);
        resume.send(()).expect("resume runloop");
        wait_for_path(&rx, &pending);

        let path = root.join("entry");
        std::fs::write(&path, "still watched").unwrap();
        wait_for_path(&rx, &path);
    }

    #[test]
    fn rewatching_a_replaced_root_restarts_the_stream() {
        for batch in [false, true] {
            let dir = tempfile::tempdir().unwrap();
            let parent = dir.path().canonicalize().unwrap();
            let root = parent.join("root");
            std::fs::create_dir(&root).unwrap();

            let (tx, rx) = mpsc::channel();
            let mut watcher = FsEventWatcher::new(tx, Config::default()).unwrap();
            watcher.watch(&root, RecursiveMode::Recursive).unwrap();
            let thread_id = runloop_thread_id(&watcher);

            std::fs::rename(&root, parent.join("old")).unwrap();
            std::fs::create_dir(&root).unwrap();
            if batch {
                watcher
                    .update_paths(vec![PathOp::watch_recursive(root.clone())])
                    .unwrap();
            } else {
                watcher.watch(&root, RecursiveMode::Recursive).unwrap();
            }
            assert_ne!(runloop_thread_id(&watcher), thread_id);

            let path = root.join("entry");
            std::fs::write(&path, "replacement root").unwrap();
            wait_for_path(&rx, &path);
        }
    }

    #[test]
    fn rewatching_same_path_replaces_recursive_info() {
        let dir = tempfile::tempdir().unwrap();
        let mut watcher = FsEventWatcher::new(|_| {}, Config::default()).unwrap();

        watcher
            .append_path(dir.path(), WatchPathConfig::new(RecursiveMode::Recursive))
            .expect("watch recursively");
        watcher
            .append_path(
                dir.path(),
                WatchPathConfig::new(RecursiveMode::NonRecursive),
            )
            .expect("rewatch non-recursively");

        let watched = watcher.watched_paths().expect("watched paths");
        assert_eq!(
            watched,
            vec![WatchedPath::new(
                dir.path().to_path_buf(),
                RecursiveMode::NonRecursive
            )]
        );
        assert_eq!(watcher.stream_paths().iter().count(), 1);
    }

    #[test]
    fn user_data_changes_update_callback_without_restarting_stream() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let mut watcher = FsEventWatcher::new(|_| {}, Config::default()).unwrap();
        watcher.watch(&root, RecursiveMode::Recursive).unwrap();
        let thread = runloop_thread_id(&watcher);
        let config = WatchPathConfig::new(RecursiveMode::Recursive).with_user_data(42);
        watcher.watch_with(&root, config).unwrap();
        assert_eq!(runloop_thread_id(&watcher), thread);
        assert_eq!(
            watcher
                .runloop
                .as_ref()
                .unwrap()
                .recursive_info
                .lock()
                .unwrap()[&root]
                .user_data,
            Some(42)
        );
        watcher
            .update_paths(vec![PathOp::watch_recursive(root.clone())])
            .unwrap();
        assert_eq!(runloop_thread_id(&watcher), thread);
        assert_eq!(
            watcher
                .runloop
                .as_ref()
                .unwrap()
                .recursive_info
                .lock()
                .unwrap()[&root]
                .user_data,
            None
        );
    }

    #[test]
    fn only_recursive_ancestors_cover_nested_watches() {
        let dir = tempfile::tempdir().unwrap();
        let child = dir.path().join("child");
        let grandchild = child.join("first").join("second").join("grandchild");
        std::fs::create_dir_all(&grandchild).unwrap();

        let mut watcher = FsEventWatcher::new(|_| {}, Config::default()).unwrap();
        for (path, mode) in [
            (dir.path(), RecursiveMode::Recursive),
            (child.as_path(), RecursiveMode::NonRecursive),
            (grandchild.as_path(), RecursiveMode::Recursive),
        ] {
            watcher
                .append_path(path, WatchPathConfig::new(mode))
                .expect("watch");
        }

        assert_eq!(watcher.stream_paths().iter().count(), 1);
        assert_eq!(watcher.watched_paths().expect("watched paths").len(), 3);

        watcher.remove_path(dir.path()).expect("unwatch parent");
        // The remaining non-recursive child would discard changes to the deeper
        // watch's intermediate ancestors, so both watches need stream roots.
        assert_eq!(watcher.stream_paths().iter().count(), 2);

        watcher.remove_path(&child).expect("unwatch child");
        assert_eq!(watcher.stream_paths().iter().count(), 1);
    }

    #[test]
    fn sibling_watches_each_get_a_stream_root() {
        let dir = tempfile::tempdir().unwrap();
        let first = dir.path().join("first");
        let second = dir.path().join("second");
        std::fs::create_dir(&first).unwrap();
        std::fs::create_dir(&second).unwrap();

        let mut watcher = FsEventWatcher::new(|_| {}, Config::default()).unwrap();
        watcher
            .append_path(&first, WatchPathConfig::new(RecursiveMode::Recursive))
            .expect("watch first");
        watcher
            .append_path(&second, WatchPathConfig::new(RecursiveMode::Recursive))
            .expect("watch second");

        assert_eq!(watcher.stream_paths().iter().count(), 2);
    }

    #[test]
    fn roots_at_counts_a_path_and_the_watches_nested_in_it() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let parent = root.join("parent");
        // Byte order would sort these siblings between `parent` and its subtree.
        let siblings = [root.join("parent-other"), root.join("parent.d")];
        let nested = [parent.join("first"), parent.join("second/deep")];
        for path in siblings.iter().chain(&nested) {
            std::fs::create_dir_all(path).unwrap();
        }

        let mut watcher = FsEventWatcher::new(|_| {}, Config::default()).unwrap();
        for path in siblings.iter().chain(&nested) {
            watcher
                .append_path(path, WatchPathConfig::new(RecursiveMode::NonRecursive))
                .unwrap();
        }
        assert_eq!(watcher.roots_at(&parent, true), 2);
        assert_eq!(watcher.roots_at(&parent, false), 0);
        assert_eq!(watcher.roots_at(&root, true), 4);

        watcher
            .append_path(&parent, WatchPathConfig::new(RecursiveMode::Recursive))
            .unwrap();
        assert_eq!(watcher.roots_at(&parent, true), 1);
        assert_eq!(watcher.roots_at(&parent, false), 1);
        assert_eq!(watcher.roots_at(&root, true), 3);
        assert_eq!(watcher.stream_paths().iter().count(), 3);

        watcher.remove_path(&parent).unwrap();
        assert_eq!(watcher.roots_at(&parent, true), 2);
    }

    #[test]
    fn covering_watch_keeps_receiving_outside_the_nested_watch() {
        let tmpdir = testdir();
        let child = tmpdir.path().join("child");
        let sibling = tmpdir.path().join("sibling");
        std::fs::create_dir(&child).expect("create child");
        std::fs::create_dir(&sibling).expect("create sibling");

        let (mut watcher, mut rx) = watcher();
        watcher.watch_recursively(&tmpdir);
        let thread_id = runloop_thread_id(&watcher.watcher);
        watcher.watch_recursively(&child);
        assert_eq!(runloop_thread_id(&watcher.watcher), thread_id);

        let path = sibling.join("entry");
        std::fs::File::create_new(&path).expect("create");

        rx.wait_unordered([expected(path).create_file()]);
    }

    #[test]
    fn covered_watch_updates_callback_without_restarting_stream() {
        let tmpdir = testdir();
        let root = tmpdir.path().join("root");
        let child = root.join("child");
        let nested = child.join("nested");
        let alias = tmpdir.path().join("alias");
        std::fs::create_dir_all(&nested).expect("create dirs");
        std::os::unix::fs::symlink(&child, &alias).expect("symlink");

        let (mut watcher, mut rx) = watcher();
        watcher.watch_recursively(&root);
        let thread_id = runloop_thread_id(&watcher.watcher);
        watcher.watch_recursively(&alias);
        assert_eq!(runloop_thread_id(&watcher.watcher), thread_id);

        std::fs::File::create_new(nested.join("first")).expect("create");
        rx.wait_unordered([expected(alias.join("nested/first")).create_file()]);

        watcher.watch_nonrecursively(&alias);
        assert_eq!(runloop_thread_id(&watcher.watcher), thread_id);
        assert!(
            watcher
                .watcher
                .watched_paths()
                .expect("watched paths")
                .contains(&WatchedPath::new(
                    alias.clone(),
                    RecursiveMode::NonRecursive
                ))
        );

        std::fs::File::create_new(child.join("immediate")).expect("create");
        std::fs::File::create_new(nested.join("second")).expect("create");
        rx.wait_unordered([
            expected(alias.join("immediate")).create_file(),
            // The non-recursive alias no longer matches deeper events, but the
            // original recursive root still covers them.
            expected(nested.join("second")).create_file(),
        ]);
    }

    #[test]
    fn non_recursive_parent_does_not_skip_stream_restart() {
        let tmpdir = testdir();
        let child = tmpdir.path().join("child");
        let nested = child.join("nested");
        std::fs::create_dir_all(&nested).expect("create dirs");

        let (mut watcher, mut rx) = watcher();
        watcher.watch_nonrecursively(&tmpdir);
        let thread_id = runloop_thread_id(&watcher.watcher);
        watcher.watch_recursively(&child);
        assert_ne!(runloop_thread_id(&watcher.watcher), thread_id);

        let path = nested.join("entry");
        std::fs::File::create_new(&path).expect("create");
        rx.wait_unordered([expected(path).create_file()]);
    }

    #[test]
    fn failed_watch_keeps_stream_running() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();
        watcher.watch_recursively(&tmpdir);
        let thread_id = runloop_thread_id(&watcher.watcher);

        let err = watcher
            .watcher
            .watch(&tmpdir.path().join("missing"), RecursiveMode::Recursive)
            .expect_err("watch missing path");
        assert!(matches!(err.kind, ErrorKind::PathNotFound));
        assert_eq!(runloop_thread_id(&watcher.watcher), thread_id);

        let path = tmpdir.path().join("entry");
        std::fs::File::create_new(&path).expect("create");
        rx.wait_unordered([expected(path).create_file()]);
    }

    #[test]
    fn nested_watch_keeps_receiving_after_unwatching_its_parent() {
        let tmpdir = testdir();
        let child = tmpdir.path().join("child");
        std::fs::create_dir(&child).expect("create dir");

        let (mut watcher, mut rx) = watcher();
        watcher.watch_recursively(&tmpdir);
        watcher.watch_recursively(&child);
        watcher
            .watcher
            .unwatch(tmpdir.path())
            .expect("unwatch parent");

        let path = child.join("entry");
        std::fs::File::create_new(&path).expect("create");

        rx.wait_unordered([expected(path).create_file()]);
    }

    #[test]
    fn stop_does_not_wait_for_runloop_to_be_waiting() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::mpsc;
        use std::time::Instant;

        // Regression test for a shutdown hang where `stop()` waited for
        // `CFRunLoopIsWaiting()` to become true. If the runloop is busy (e.g. under
        // heavy event load), it may never enter a waiting state.

        let dir = tempfile::tempdir().unwrap();

        let (tx, _rx) = mpsc::channel::<crate::Result<Event>>();
        let mut watcher = FsEventWatcher::new(tx, Default::default()).unwrap();
        watcher.watch(dir.path(), RecursiveMode::Recursive).unwrap();

        let runloop = watcher
            .runloop
            .as_ref()
            .expect("watcher to be running")
            .runloop
            .clone();
        let mode = unsafe { cf::kCFRunLoopDefaultMode.expect("default runloop mode") };

        // Keep the runloop continuously "busy" by creating a source that signals itself in its
        // perform callback.
        struct SourceHammer {
            source: *const cf::CFRunLoopSource,
            fires: AtomicUsize,
        }

        unsafe extern "C-unwind" fn hammer_source(info: *mut std::ffi::c_void) {
            // SAFETY: The boxed SourceHammer stays alive until the runloop has stopped.
            let Some(hammer) = (unsafe { (info as *const SourceHammer).as_ref() }) else {
                return;
            };
            hammer.fires.fetch_add(1, Ordering::Relaxed);

            // Signal the source again so the runloop has more work to do.
            // SAFETY: The source is retained for the entire time the runloop can call us.
            let Some(source) = (unsafe { hammer.source.as_ref() }) else {
                return;
            };
            source.signal();
        }

        let mut hammer = Box::new(SourceHammer {
            source: std::ptr::null(),
            fires: AtomicUsize::new(0),
        });

        let mut ctx = cf::CFRunLoopSourceContext {
            version: 0,
            info: (&mut *hammer as *mut SourceHammer).cast(),
            retain: None,
            release: None,
            copyDescription: None,
            equal: None,
            hash: None,
            schedule: None,
            cancel: None,
            perform: Some(hammer_source),
        };

        let source = unsafe {
            cf::CFRunLoopSource::new(cf::kCFAllocatorDefault, 0, &mut ctx)
                .expect("source to be created")
        };
        hammer.source = cf::CFRetained::as_ptr(&source).as_ptr();

        runloop.add_source(Some(&source), Some(mode));
        source.signal();
        runloop.wake_up();

        // Ensure our setup actually made the runloop busy.
        let setup_start = Instant::now();
        while hammer.fires.load(Ordering::Relaxed) == 0
            && setup_start.elapsed() < Duration::from_secs(1)
        {
            std::thread::yield_now();
        }
        assert!(
            hammer.fires.load(Ordering::Relaxed) > 0,
            "runloop source never fired; test setup failed"
        );

        let (done_tx, done_rx) = mpsc::channel::<()>();
        std::thread::spawn(move || {
            drop(watcher);
            let _ = done_tx.send(());
        });

        // If shutdown regresses, this would hang indefinitely; keep the test bounded.
        done_rx
            .recv_timeout(Duration::from_secs(5))
            .expect("dropping FsEventWatcher timed out (possible shutdown hang)");

        // No cleanup: The source is owned by the runloop; removing sources cross-thread can be
        // sensitive on some systems. Dropping the last reference to the runloop will release it.
    }

    #[test]
    fn test_fsevent_watcher_drop() {
        use super::*;
        use std::time::Duration;

        let dir = tempfile::tempdir().unwrap();

        let (tx, rx) = std::sync::mpsc::channel();

        {
            let mut watcher = FsEventWatcher::new(tx, Default::default()).unwrap();
            watcher.watch(dir.path(), RecursiveMode::Recursive).unwrap();
            thread::sleep(Duration::from_millis(2000));
            println!("is running -> {}", watcher.is_running());

            thread::sleep(Duration::from_millis(1000));
            watcher.unwatch(dir.path()).unwrap();
            println!("is running -> {}", watcher.is_running());
        }

        thread::sleep(Duration::from_millis(1000));

        for res in rx {
            let e = res.unwrap();
            println!("debug => {:?} {:?}", e.kind, e.paths);
        }

        println!("in test: {} works", file!());
    }

    #[test]
    fn test_steam_context_info_send_and_sync() {
        fn check_send<T: Send + Sync>() {}
        check_send::<StreamContextInfo>();
    }

    /// Invokes `callback_impl` with IDs newer than the watches built by [`watch_info`].
    /// Paths are bytes to support non-UTF-8 names.
    fn run_callback(
        recursive_info: HashMap<PathBuf, WatchInfo>,
        events: &[(&[u8], u32)],
    ) -> Vec<crate::Result<Event>> {
        let events: Vec<_> = events
            .iter()
            .zip(1..)
            .map(|(&(path, flags), id)| (path, flags, id))
            .collect();
        run_callback_with_ids(recursive_info, &events)
    }

    /// [`run_callback`] for raw `(path, flags, id)` events.
    fn run_callback_with_ids(
        recursive_info: HashMap<PathBuf, WatchInfo>,
        events: &[(&[u8], u32, fs::FSEventStreamEventId)],
    ) -> Vec<crate::Result<Event>> {
        use std::ffi::CString;
        use std::ptr;

        let (tx, rx) = std::sync::mpsc::channel::<crate::Result<Event>>();
        let event_handler: Arc<Mutex<dyn EventHandler>> = Arc::new(Mutex::new(tx));

        let context = Box::new(StreamContextInfo {
            event_handler,
            recursive_info: Arc::new(Mutex::new(recursive_info)),
            event_kinds: EventKindMask::ALL,
        });
        let context_ptr = Box::into_raw(context) as *mut libc::c_void;

        let c_paths: Vec<CString> = events
            .iter()
            .map(|(path, ..)| CString::new(*path).expect("cstring"))
            .collect();
        let path_ptrs: Vec<_> = c_paths.iter().map(|p| p.as_ptr()).collect();
        let event_paths = NonNull::new(path_ptrs.as_ptr() as *mut libc::c_void).unwrap();

        let flags_arr: Vec<fs::FSEventStreamEventFlags> = events
            .iter()
            .map(|(_, flags, _)| *flags as fs::FSEventStreamEventFlags)
            .collect();
        let event_flags =
            NonNull::new(flags_arr.as_ptr() as *mut fs::FSEventStreamEventFlags).unwrap();

        let ids_arr: Vec<fs::FSEventStreamEventId> = events.iter().map(|(.., id)| *id).collect();
        let event_ids = NonNull::new(ids_arr.as_ptr() as *mut fs::FSEventStreamEventId).unwrap();

        let res = std::panic::catch_unwind(|| unsafe {
            callback_impl(
                ptr::null(),
                context_ptr,
                events.len(),
                event_paths,
                event_flags,
                event_ids,
            );
        });
        unsafe {
            drop(Box::from_raw(context_ptr as *mut StreamContextInfo));
        }
        assert!(res.is_ok(), "callback_impl should not panic");

        rx.try_iter().collect()
    }

    #[test]
    fn callback_impl_delivers_rescan_for_ancestor_recovery_paths() {
        let mut recursive_info = HashMap::new();
        recursive_info.insert(
            PathBuf::from("/watched/a"),
            WatchInfo {
                reported_path: PathBuf::from("/watched/a"),
                ..watch_info(true)
            },
        );
        recursive_info.insert(
            PathBuf::from("/watched/b"),
            WatchInfo {
                reported_path: PathBuf::from("/watched/b"),
                ..watch_info(false)
            },
        );

        let recovery_flags = [
            StreamFlags::MUST_SCAN_SUBDIRS.bits(),
            (StreamFlags::MUST_SCAN_SUBDIRS | StreamFlags::USER_DROPPED).bits(),
            (StreamFlags::MUST_SCAN_SUBDIRS | StreamFlags::KERNEL_DROPPED).bits(),
        ];
        for flags in recovery_flags {
            for path in [
                b"/watched/a".as_slice(),
                b"/watched".as_slice(),
                b"/".as_slice(),
            ] {
                let events = run_callback(recursive_info.clone(), &[(path, flags)]);
                let path_buf = PathBuf::from(std::str::from_utf8(path).unwrap());
                assert!(
                    events.iter().any(|event| {
                        let event = event.as_ref().expect("callback event");
                        event.need_rescan() && event.paths == [path_buf.clone()]
                    }),
                    "missing rescan for {} flags {flags:#x}: {events:?}",
                    String::from_utf8_lossy(path)
                );
            }
        }

        let ordinary = (StreamFlags::ITEM_MODIFIED | StreamFlags::IS_FILE).bits();
        for (path, expected) in [
            (b"/watched".as_slice(), false),
            (b"/".as_slice(), false),
            (b"/watched/a/deep/file".as_slice(), true),
            (b"/watched/b/file".as_slice(), true),
            (b"/watched/b/deep/file".as_slice(), false),
        ] {
            let events = run_callback(recursive_info.clone(), &[(path, ordinary)]);
            assert_eq!(
                !events.is_empty(),
                expected,
                "ordinary path {}",
                String::from_utf8_lossy(path)
            );
            assert!(
                events
                    .iter()
                    .all(|event| !event.as_ref().expect("callback event").need_rescan())
            );
        }
    }

    #[test]
    fn callback_drops_events_from_before_the_watch() {
        let watch = |user_data, since, deep_since| WatchInfo {
            user_data: Some(user_data),
            since,
            deep_since,
            ..watch_info(true)
        };
        let recursive_info = HashMap::from([
            // Watched non-recursively at 10 and made recursive at 20.
            (PathBuf::from("/watched"), watch(1, 10, 20)),
            (PathBuf::from("/watched/nested"), watch(2, 30, 30)),
        ]);
        let created = (StreamFlags::ITEM_CREATED | StreamFlags::IS_FILE).bits();
        // None means the event is dropped; Some identifies the receiving watch.
        let cases: [(&[u8], u32, fs::FSEventStreamEventId, Option<u64>); 13] = [
            // Events must be strictly newer than the watch.
            (b"/watched/file", created, 9, None),
            (b"/watched/file", created, 10, None),
            (b"/watched/file", created, 11, Some(1)),
            // Newly added recursive coverage has its own boundary.
            (b"/watched/deep/file", created, 20, None),
            (b"/watched/deep/file", created, 21, Some(1)),
            // Older events still reach the recursive ancestor.
            (b"/watched/nested", created, 30, Some(1)),
            (b"/watched/nested", created, 31, Some(2)),
            (b"/watched/nested/file", created, 20, None),
            (b"/watched/nested/file", created, 30, Some(1)),
            (b"/watched/nested/file", created, 31, Some(2)),
            // Root changes and rescan notices bypass the ID check.
            (
                b"/watched/nested",
                StreamFlags::ROOT_CHANGED.bits(),
                0,
                Some(2),
            ),
            (
                b"/watched/nested",
                StreamFlags::MUST_SCAN_SUBDIRS.bits(),
                1,
                Some(2),
            ),
            (b"/watched", StreamFlags::HISTORY_DONE.bits(), 0, None),
        ];
        for (path, flags, id, expected) in cases {
            let delivered: Vec<_> =
                run_callback_with_ids(recursive_info.clone(), &[(path, flags, id)])
                    .into_iter()
                    .map(|event| event.unwrap().user_data())
                    .collect();
            assert_eq!(
                delivered,
                Vec::from_iter(expected.map(Some)),
                "{} at {id}",
                String::from_utf8_lossy(path)
            );
        }
    }

    #[test]
    fn callback_user_data_identifies_events_and_watch_specific_rescans() {
        let mut info = watch_info(true);
        info.user_data = Some(42);
        let recursive_info = HashMap::from([
            (PathBuf::from("/watched"), info),
            (PathBuf::from("/watched/nested"), watch_info(true)),
        ]);
        let events: Vec<_> = run_callback(
            recursive_info,
            &[
                (
                    b"/watched/file",
                    (StreamFlags::ITEM_CREATED | StreamFlags::IS_FILE).bits(),
                ),
                (b"/watched", StreamFlags::MUST_SCAN_SUBDIRS.bits()),
                (b"/", StreamFlags::MUST_SCAN_SUBDIRS.bits()),
                (
                    b"/watched/nested/file",
                    (StreamFlags::ITEM_CREATED | StreamFlags::IS_FILE).bits(),
                ),
            ],
        )
        .into_iter()
        .map(Result::unwrap)
        .collect();
        assert_eq!(
            events.iter().map(Event::user_data).collect::<Vec<_>>(),
            [Some(42), Some(42), None, None]
        );
        assert!(events[1].need_rescan());
        assert!(events[2].need_rescan());
    }

    #[test]
    fn callback_impl_handles_non_utf8_paths_without_panicking() {
        use std::os::unix::ffi::OsStrExt;

        let mut recursive_info = HashMap::new();
        recursive_info.insert(
            PathBuf::from("/tmp"),
            WatchInfo {
                reported_path: PathBuf::from("/tmp"),
                ..watch_info(true)
            },
        );

        let bytes = b"/tmp/\xff";
        let events = run_callback(
            recursive_info,
            &[(bytes.as_slice(), StreamFlags::ITEM_CREATED.bits())],
        );

        let event = events
            .first()
            .expect("expected event")
            .as_ref()
            .expect("expected Ok(Event)");
        assert!(
            event.kind.is_create(),
            "expected create event, got {event:?}"
        );
        assert_eq!(event.paths.len(), 1);
        assert_eq!(event.paths[0].as_os_str().as_bytes(), bytes);
    }

    #[test]
    fn callback_impl_ignores_unknown_flag_bits_without_panicking() {
        // Include an unknown bit so the old `from_bits(...).unwrap_or_else(panic!)` behavior
        // would have panicked. New behavior should tolerate it.
        let unknown_mask = !StreamFlags::all().bits();
        let unknown_bit = unknown_mask & unknown_mask.wrapping_neg();
        assert_ne!(unknown_bit, 0, "StreamFlags unexpectedly uses all bits");
        let raw_flag = StreamFlags::ITEM_CREATED.bits() | unknown_bit;
        assert!(
            StreamFlags::from_bits(raw_flag).is_none(),
            "raw_flag must include an unknown bit for this test to be meaningful"
        );

        let mut recursive_info = HashMap::new();
        recursive_info.insert(
            PathBuf::from("/tmp"),
            WatchInfo {
                reported_path: PathBuf::from("/tmp"),
                ..watch_info(true)
            },
        );

        let events = run_callback(recursive_info, &[(b"/tmp/file".as_slice(), raw_flag)]);

        let event = events
            .first()
            .expect("expected event")
            .as_ref()
            .expect("expected Ok(Event)");
        assert!(
            event.kind.is_create(),
            "expected create event, got {event:?}"
        );
    }

    #[test]
    fn translate_flags_ignores_is_file_only_events() {
        assert!(translate_flags(StreamFlags::IS_FILE, true).is_empty());
        assert!(
            translate_flags(StreamFlags::IS_FILE | StreamFlags::ITEM_CLONED, true).is_empty(),
            "type-only clone flags should not produce events"
        );
    }

    #[test]
    fn translate_flags_sets_clone_info_for_file_events() {
        let create = translate_flags(
            StreamFlags::ITEM_CREATED | StreamFlags::IS_FILE | StreamFlags::ITEM_CLONED,
            true,
        );
        assert_eq!(create.len(), 1);
        assert_eq!(create[0].kind, EventKind::Create(CreateKind::File));
        assert_eq!(create[0].info(), Some("is: clone"));

        let modify = translate_flags(
            StreamFlags::INODE_META_MOD
                | StreamFlags::ITEM_MODIFIED
                | StreamFlags::IS_FILE
                | StreamFlags::ITEM_CLONED,
            true,
        );
        assert_eq!(modify.len(), 2);
        assert!(
            modify
                .iter()
                .any(|e| matches!(e.kind, EventKind::Modify(ModifyKind::Metadata(_))))
        );
        assert!(
            modify
                .iter()
                .any(|e| matches!(e.kind, EventKind::Modify(ModifyKind::Data(_))))
        );
        assert!(
            modify.iter().all(|e| e.info() == Some("is: clone")),
            "all events should be annotated as clone-related: {modify:?}"
        );
    }

    #[test]
    fn translate_flags_does_not_override_existing_info() {
        let evs = translate_flags(
            StreamFlags::ROOT_CHANGED
                | StreamFlags::ITEM_REMOVED
                | StreamFlags::IS_FILE
                | StreamFlags::ITEM_CLONED,
            true,
        );
        assert_eq!(evs.len(), 1);
        assert_eq!(evs[0].info(), Some("root changed"));
    }

    #[test]
    fn does_not_crash_with_empty_path() {
        let mut watcher = FsEventWatcher::new(|_| {}, Default::default()).unwrap();

        let watch_result = watcher.watch(Path::new(""), RecursiveMode::Recursive);
        assert!(
            matches!(
                watch_result,
                Err(Error {
                    kind: ErrorKind::PathNotFound,
                    ..
                })
            ),
            "actual: {watch_result:#?}"
        );

        let unwatch_result = watcher.unwatch(Path::new(""));
        assert!(
            matches!(
                unwatch_result,
                Err(Error {
                    kind: ErrorKind::WatchNotFound,
                    ..
                })
            ),
            "actual: {unwatch_result:#?}"
        );
    }

    #[test]
    fn create_file() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();
        watcher.watch_recursively(&tmpdir);

        let path = tmpdir.path().join("entry");
        std::fs::File::create_new(&path).expect("create");

        rx.wait_unordered([expected(path).create_file()]);
    }

    #[test]
    fn write_file() {
        let tmpdir = testdir();

        let path = tmpdir.path().join("entry");
        std::fs::File::create_new(&path).expect("create");

        let (mut watcher, mut rx) = watcher();

        watcher.watch_recursively(&tmpdir);

        std::fs::write(&path, b"123").expect("write");

        rx.wait_unordered([expected(&path).modify_data_content()]);
    }

    #[test]
    fn chmod_file() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let path = tmpdir.path().join("entry");
        let file = std::fs::File::create_new(&path).expect("create");
        let mut permissions = file.metadata().expect("metadata").permissions();
        permissions.set_readonly(true);

        watcher.watch_recursively(&tmpdir);
        file.set_permissions(permissions).expect("set_permissions");

        rx.wait_unordered([expected(&path).modify_meta_owner()]);
    }

    #[test]
    fn rename_file() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let path = tmpdir.path().join("entry");
        std::fs::File::create_new(&path).expect("create");

        watcher.watch_recursively(&tmpdir);
        let new_path = tmpdir.path().join("renamed");

        std::fs::rename(&path, &new_path).expect("rename");

        rx.wait_unordered([expected(path).rename_any(), expected(new_path).rename_any()]);
    }

    #[test]
    fn delete_file() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();
        let file = tmpdir.path().join("file");
        std::fs::write(&file, "").expect("write");

        watcher.watch_nonrecursively(&tmpdir);

        std::fs::remove_file(&file).expect("remove");

        rx.wait_unordered([expected(&file).remove_file()]);
    }

    #[test]
    fn delete_self_file() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();
        let file = tmpdir.path().join("file");
        std::fs::write(&file, "").expect("write");

        watcher.watch_nonrecursively(&file);

        std::fs::remove_file(&file).expect("remove");

        rx.wait_unordered([expected(file).remove_file()]);
    }

    #[test]
    fn delete_self_dir() {
        let tmpdir = testdir();
        let dir = tmpdir.path().join("dir");
        std::fs::create_dir(&dir).expect("create");

        let (mut watcher, mut rx) = watcher();
        watcher.watch_nonrecursively(&dir);

        std::fs::remove_dir(&dir).expect("remove");

        rx.wait_unordered([expected(&dir).remove_folder()]);
    }

    #[test]
    fn create_write_overwrite() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();
        let overwritten_file = tmpdir.path().join("overwritten_file");
        let overwriting_file = tmpdir.path().join("overwriting_file");
        std::fs::write(&overwritten_file, "123").expect("write1");

        watcher.watch_nonrecursively(&tmpdir);

        std::fs::File::create(&overwriting_file).expect("create");
        std::fs::write(&overwriting_file, "321").expect("write2");
        std::fs::rename(&overwriting_file, &overwritten_file).expect("rename");

        rx.wait_unordered([
            expected(&overwriting_file).create(),
            expected(&overwriting_file).modify_data_content().multiple(),
            expected(&overwriting_file).rename_any(),
            expected(&overwritten_file).rename_any(),
        ]);
    }

    #[test]
    fn create_dir() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();
        watcher.watch_recursively(&tmpdir);

        let path = tmpdir.path().join("entry");
        std::fs::create_dir(&path).expect("create");

        rx.wait_unordered([expected(&path).create_folder()]);
    }

    #[test]
    fn chmod_dir() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let path = tmpdir.path().join("entry");
        std::fs::create_dir(&path).expect("create_dir");
        let mut permissions = std::fs::metadata(&path).expect("metadata").permissions();
        permissions.set_readonly(true);

        watcher.watch_recursively(&tmpdir);
        std::fs::set_permissions(&path, permissions).expect("set_permissions");

        rx.wait_unordered([expected(&path).modify_meta_owner()]);
    }

    #[test]
    fn rename_dir() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let path = tmpdir.path().join("entry");
        let new_path = tmpdir.path().join("new_path");
        std::fs::create_dir(&path).expect("create_dir");

        watcher.watch_recursively(&tmpdir);
        std::fs::rename(&path, &new_path).expect("rename");

        rx.wait_ordered([
            expected(&path).rename_any(),
            expected(&new_path).rename_any(),
        ]);
    }

    #[test]
    fn delete_dir() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let path = tmpdir.path().join("entry");
        std::fs::create_dir(&path).expect("create_dir");

        watcher.watch_recursively(&tmpdir);
        std::fs::remove_dir(&path).expect("remove");

        rx.wait_unordered([expected(path).remove_folder()]);
    }

    #[test]
    fn rename_dir_twice() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let path = tmpdir.path().join("entry");
        let new_path = tmpdir.path().join("new_path");
        let new_path2 = tmpdir.path().join("new_path2");
        std::fs::create_dir(&path).expect("create_dir");

        watcher.watch_recursively(&tmpdir);
        std::fs::rename(&path, &new_path).expect("rename");
        std::fs::rename(&new_path, &new_path2).expect("rename2");

        rx.wait_unordered([
            expected(&path).rename_any(),
            expected(&new_path).rename_any(),
            expected(&new_path2).rename_any(),
        ]);
    }

    #[test]
    fn move_out_of_watched_dir() {
        let tmpdir = testdir();
        let subdir = tmpdir.path().join("subdir");
        let (mut watcher, mut rx) = watcher();

        let path = subdir.join("entry");
        std::fs::create_dir_all(&subdir).expect("create_dir_all");
        std::fs::File::create_new(&path).expect("create");

        watcher.watch_recursively(&subdir);
        let new_path = tmpdir.path().join("entry");

        std::fs::rename(&path, &new_path).expect("rename");

        rx.wait_unordered([expected(path).rename_any()]);
    }

    #[test]
    #[ignore = "https://github.com/notify-rs/notify/issues/729"]
    fn create_write_write_rename_write_remove() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let file1 = tmpdir.path().join("entry");
        let file2 = tmpdir.path().join("entry2");
        std::fs::File::create_new(&file2).expect("create file2");
        let new_path = tmpdir.path().join("renamed");

        watcher.watch_recursively(&tmpdir);
        std::fs::write(&file1, "123").expect("write 1");
        std::fs::write(&file2, "321").expect("write 2");
        std::fs::rename(&file1, &new_path).expect("rename");
        std::fs::write(&new_path, b"1").expect("write 3");
        std::fs::remove_file(&new_path).expect("remove");

        rx.wait_ordered([
            expected(&file1).create_file(),
            expected(&file1).modify_data_content(),
            expected(&file2).modify_data_content(),
            expected(&file1).rename_any(),
            expected(&new_path).rename_any(),
            expected(&new_path).modify_data_content(),
            expected(&new_path).remove_file(),
        ]);
    }

    #[test]
    fn rename_twice() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let path = tmpdir.path().join("entry");
        std::fs::File::create_new(&path).expect("create");

        watcher.watch_recursively(&tmpdir);
        let new_path1 = tmpdir.path().join("renamed1");
        let new_path2 = tmpdir.path().join("renamed2");

        std::fs::rename(&path, &new_path1).expect("rename1");
        std::fs::rename(&new_path1, &new_path2).expect("rename2");

        rx.wait_unordered([
            expected(&path).rename_any(),
            expected(&new_path1).rename_any(),
            expected(&new_path2).rename_any(),
        ]);
    }

    #[test]
    fn set_file_mtime() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let path = tmpdir.path().join("entry");
        let file = std::fs::File::create_new(&path).expect("create");

        watcher.watch_recursively(&tmpdir);

        file.set_modified(
            std::time::SystemTime::now()
                .checked_sub(Duration::from_secs(60 * 60))
                .expect("time"),
        )
        .expect("set_time");

        rx.wait_unordered([expected(&path).modify_meta_any()]);
    }

    #[test]
    fn write_file_non_recursive_watch() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let path = tmpdir.path().join("entry");
        std::fs::File::create_new(&path).expect("create");

        watcher.watch_nonrecursively(&path);

        std::fs::write(&path, b"123").expect("write");

        rx.wait_unordered([expected(path).modify_data_content()]);
    }

    #[test]
    fn write_to_a_hardlink_pointed_to_the_watched_file_triggers_an_event() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let subdir = tmpdir.path().join("subdir");
        let file = subdir.join("file");
        let hardlink = tmpdir.path().join("hardlink");

        std::fs::create_dir(&subdir).expect("create");
        std::fs::write(&file, "").expect("file");
        std::fs::hard_link(&file, &hardlink).expect("hardlink");

        watcher.watch_nonrecursively(&file);

        std::fs::write(&hardlink, "123123").expect("write to the hard link");

        rx.wait_unordered([expected(file).modify_data_content()]);
    }

    #[test]
    fn recursive_creation() {
        let tmpdir = testdir();
        let nested1 = tmpdir.path().join("1");
        let nested2 = tmpdir.path().join("1/2");
        let nested3 = tmpdir.path().join("1/2/3");
        let nested4 = tmpdir.path().join("1/2/3/4");
        let nested5 = tmpdir.path().join("1/2/3/4/5");
        let nested6 = tmpdir.path().join("1/2/3/4/5/6");
        let nested7 = tmpdir.path().join("1/2/3/4/5/6/7");
        let nested8 = tmpdir.path().join("1/2/3/4/5/6/7/8");
        let nested9 = tmpdir.path().join("1/2/3/4/5/6/7/8/9");

        let (mut watcher, mut rx) = watcher();

        watcher.watch_recursively(&tmpdir);

        std::fs::create_dir_all(&nested9).expect("create_dir_all");

        rx.wait_ordered([
            expected(&nested1).create_folder(),
            expected(&nested2).create_folder(),
            expected(&nested3).create_folder(),
            expected(&nested4).create_folder(),
            expected(&nested5).create_folder(),
            expected(&nested6).create_folder(),
            expected(&nested7).create_folder(),
            expected(&nested8).create_folder(),
            expected(&nested9).create_folder(),
        ]);
    }

    #[test]
    fn fsevent_watcher_respects_event_kind_mask() {
        use crate::Watcher;
        use notify_types::event::EventKindMask;

        let tmpdir = testdir();
        let (tx, rx) = std::sync::mpsc::channel();

        // Create watcher with CREATE-only mask (no MODIFY events)
        let config = Config::default().with_event_kinds(EventKindMask::CREATE);

        let mut watcher = FsEventWatcher::new(tx, config).expect("create watcher");
        watcher
            .watch(tmpdir.path(), crate::RecursiveMode::Recursive)
            .expect("watch");

        let path = tmpdir.path().join("test_file");

        // Create a file - should generate CREATE event
        std::fs::File::create_new(&path).expect("create");

        // Small delay to let events propagate
        std::thread::sleep(Duration::from_millis(100));

        // Modify the file - should NOT generate event (filtered by mask)
        std::fs::write(&path, "modified content").expect("write modified");

        std::thread::sleep(Duration::from_millis(100));

        // Collect all events
        let events: Vec<_> = rx.try_iter().filter_map(|r| r.ok()).collect();

        // Should have CREATE event
        assert!(
            events.iter().any(|e| e.kind.is_create()),
            "Expected CREATE event, got: {:?}",
            events
        );

        // Should NOT have MODIFY event (filtered out)
        assert!(
            !events.iter().any(|e| e.kind.is_modify()),
            "Should not receive MODIFY events with CREATE-only mask, got: {:?}",
            events
        );
    }

    #[test]
    fn path_budget_is_shared_across_live_streams() {
        static ACTIVE_PATHS: AtomicUsize = AtomicUsize::new(0);
        let mut first = FseventsPathReservation::new(&ACTIVE_PATHS);
        let mut second = FseventsPathReservation::new(&ACTIVE_PATHS);

        first
            .reserve(15, 21)
            .expect("first stream must fit within the budget");
        assert_eq!(second.reserve(15, 21), Err(15));

        // Replacing a stream takes only the increase, and keeps the rest meanwhile.
        first.reserve(18, 21).expect("three more paths must fit");
        assert_eq!(second.reserve(4, 21), Err(18));
        assert_eq!(first.reserve(22, 21), Err(18));
        assert_eq!(first.path_count, 18);

        first.shrink_to(10);
        second
            .reserve(11, 21)
            .expect("released paths must be available");
        assert_eq!(ACTIVE_PATHS.load(Ordering::Relaxed), 21);

        // A lower budget refuses the paths of a replacement stream even when
        // no more of them have to be reserved.
        assert_eq!(first.reserve(10, 20), Err(21));
        assert_eq!(first.reserve(9, 19), Err(21));
        first.reserve(9, 20).expect("one path fewer must fit");
        assert_eq!(first.path_count, 10);

        drop(first);
        drop(second);
        assert_eq!(ACTIVE_PATHS.load(Ordering::Relaxed), 0);
    }

    // The `root_limit` tests fill the path budget, which every watcher in the
    // process shares, and pin it to that of macOS's default descriptor limit.
    // They have to run without the other tests:
    // `fsevent::tests::root_limit -- --ignored --test-threads=1`.
    struct RootLimit {
        budget: usize,
        root: PathBuf,
        _dir: tempfile::TempDir,
        _limit: RestoreLimit,
    }

    impl RootLimit {
        fn new() -> Self {
            let dir = tempfile::tempdir().unwrap();
            let root = dir.path().canonicalize().unwrap();

            // The first stream of a process raises the soft descriptor limit, once. That
            // is most likely CoreFoundation registering `CFSocket`, which adds 2304 to
            // it. Run a stream through an event before pinning the limit, so that it
            // stays pinned.
            let (tx, rx) = mpsc::channel();
            let mut watcher = FsEventWatcher::new(tx, Config::default()).unwrap();
            watcher.watch(&root, RecursiveMode::NonRecursive).unwrap();
            let path = root.join("first_stream");
            std::fs::write(&path, "").unwrap();
            wait_for_path(&rx, &path);
            drop(watcher);

            let limit = RestoreLimit::lower(256);
            Self {
                budget: fsevents_path_budget().expect("path budget"),
                root,
                _dir: dir,
                _limit: limit,
            }
        }

        fn dirs(&self, count: usize) -> Vec<PathBuf> {
            (0..count)
                .map(|i| {
                    let path = self.root.join(format!("dir_{i}"));
                    std::fs::create_dir(&path).unwrap();
                    path
                })
                .collect()
        }
    }

    fn watched(watcher: &FsEventWatcher) -> Vec<WatchedPath> {
        let mut watched = watcher.watched_paths().unwrap();
        watched.sort_by(|a, b| a.path.cmp(&b.path));
        watched
    }

    fn active_paths() -> usize {
        ACTIVE_FSEVENTS_PATHS.load(Ordering::Relaxed)
    }

    #[test]
    #[ignore = "fills the process-wide path budget; run alone with --ignored --test-threads=1"]
    fn root_limit_refused_watch_keeps_the_stream_running() {
        let limit = RootLimit::new();
        let dirs = limit.dirs(limit.budget + 1);
        let (last, spare) = (&dirs[limit.budget - 1], &dirs[limit.budget]);
        let (tx, rx) = mpsc::channel();
        let mut watcher = FsEventWatcher::new(tx, Config::default()).unwrap();
        watcher
            .update_paths(
                dirs[..limit.budget - 1]
                    .iter()
                    .map(PathOp::watch_non_recursive)
                    .collect(),
            )
            .unwrap();
        watcher.watch(last, RecursiveMode::NonRecursive).unwrap();
        let thread_id = runloop_thread_id(&watcher);
        let before = watched(&watcher);

        let config = WatchPathConfig::new(RecursiveMode::Recursive).with_user_data(7);
        let err = watcher.watch_with(spare, config).unwrap_err();
        assert!(matches!(err.kind, ErrorKind::MaxFilesWatch), "{err:?}");
        assert_eq!(err.paths, [spare.as_path()]);
        assert_eq!(err.user_data(), Some(7));
        assert_eq!(runloop_thread_id(&watcher), thread_id);
        assert_eq!(watched(&watcher), before);
        assert_eq!(active_paths(), limit.budget);

        for dir in [&dirs[0], last] {
            let path = dir.join("entry");
            std::fs::write(&path, "still watched").unwrap();
            wait_for_path(&rx, &path);
        }
    }

    #[test]
    #[ignore = "fills the process-wide path budget; run alone with --ignored --test-threads=1"]
    fn root_limit_lowered_below_the_stream_refuses_to_replace_it() {
        let limit = RootLimit::new();
        let dirs = limit.dirs(limit.budget);
        let (tx, rx) = mpsc::channel();
        let mut watcher = FsEventWatcher::new(tx, Config::default()).unwrap();
        watcher
            .update_paths(dirs.iter().map(PathOp::watch_non_recursive).collect())
            .unwrap();
        let thread_id = runloop_thread_id(&watcher);
        let before = watched(&watcher);

        // One path short of the stream that an unwatch would leave.
        let lowered = RestoreLimit::lower((12 * (limit.budget - 1) - 1) as libc::rlim_t);
        let single = watcher.unwatch(&dirs[0]);
        let batch = watcher.update_paths(vec![PathOp::unwatch(&dirs[0])]);
        drop(lowered);
        let err = single.unwrap_err();
        assert!(matches!(err.kind, ErrorKind::MaxFilesWatch), "{err:?}");
        let err = batch.unwrap_err();
        assert!(
            matches!(err.source.kind, ErrorKind::MaxFilesWatch),
            "{err:?}"
        );
        assert_eq!(runloop_thread_id(&watcher), thread_id);
        assert_eq!(watched(&watcher), before);
        assert_eq!(active_paths(), limit.budget);

        let path = dirs[0].join("entry");
        std::fs::write(&path, "still watched").unwrap();
        wait_for_path(&rx, &path);

        watcher.unwatch(&dirs[0]).unwrap();
        assert_eq!(active_paths(), limit.budget - 1);
    }

    #[test]
    #[ignore = "fills the process-wide path budget; run alone with --ignored --test-threads=1"]
    fn root_limit_refuses_to_uncover_nested_watches() {
        let limit = RootLimit::new();
        let children = limit.dirs(limit.budget + 1);
        let nested = children[0].join("nested");
        std::fs::create_dir(&nested).unwrap();
        let (tx, rx) = mpsc::channel();
        let mut watcher = FsEventWatcher::new(tx, Config::default()).unwrap();
        let mut ops = vec![PathOp::Watch(
            limit.root.clone(),
            WatchPathConfig::new(RecursiveMode::Recursive).with_user_data(1),
        )];
        ops.extend(children.iter().map(PathOp::watch_non_recursive));
        watcher.update_paths(ops).unwrap();
        assert_eq!(active_paths(), 1);
        let thread_id = runloop_thread_id(&watcher);
        let before = watched(&watcher);

        // Each of these would make a stream root of every child.
        let err = watcher
            .watch(&limit.root, RecursiveMode::NonRecursive)
            .unwrap_err();
        assert!(matches!(err.kind, ErrorKind::MaxFilesWatch), "{err:?}");
        let err = watcher.unwatch(&limit.root).unwrap_err();
        assert!(matches!(err.kind, ErrorKind::MaxFilesWatch), "{err:?}");
        assert_eq!(err.paths, [limit.root.as_path()]);
        let err = watcher
            .update_paths(vec![
                PathOp::unwatch(&limit.root),
                PathOp::unwatch(&children[0]),
            ])
            .unwrap_err();
        assert!(
            matches!(err.source.kind, ErrorKind::MaxFilesWatch),
            "{err:?}"
        );
        assert!(matches!(&err.origin, Some(PathOp::Unwatch(path)) if *path == limit.root));
        assert_eq!(err.remaining.len(), 1);
        assert_eq!(runloop_thread_id(&watcher), thread_id);
        assert_eq!(watched(&watcher), before);
        assert_eq!(active_paths(), 1);

        // Only the root reports this path, and only while it is still recursive.
        let path = nested.join("entry");
        std::fs::write(&path, "still recursive").unwrap();
        assert_eq!(wait_for_path(&rx, &path).user_data(), Some(1));

        // With one child fewer, the rest fit exactly.
        watcher
            .update_paths(vec![
                PathOp::unwatch(&children[0]),
                PathOp::unwatch(&limit.root),
            ])
            .unwrap();
        assert_eq!(active_paths(), limit.budget);
        let path = children[1].join("entry");
        std::fs::write(&path, "now a stream root").unwrap();
        wait_for_path(&rx, &path);
    }

    #[test]
    #[ignore = "fills the process-wide path budget; run alone with --ignored --test-threads=1"]
    fn root_limit_batch_keeps_the_operations_before_the_refused_one() {
        let limit = RootLimit::new();
        let dirs = limit.dirs(limit.budget + 2);
        let refused = &dirs[limit.budget];
        let (tx, rx) = mpsc::channel();
        let mut watcher = FsEventWatcher::new(tx, Config::default()).unwrap();
        watcher
            .watch(&dirs[0], RecursiveMode::NonRecursive)
            .unwrap();

        let ops = dirs[1..]
            .iter()
            .zip(1..)
            .map(|(dir, id)| {
                let config = WatchPathConfig::new(RecursiveMode::NonRecursive).with_user_data(id);
                PathOp::Watch(dir.clone(), config)
            })
            .collect();
        let err = watcher.update_paths(ops).unwrap_err();
        assert!(
            matches!(err.source.kind, ErrorKind::MaxFilesWatch),
            "{err:?}"
        );
        assert_eq!(err.source.paths, [refused.as_path()]);
        assert_eq!(err.source.user_data(), Some(limit.budget as u64));
        assert_eq!(
            err.origin.as_ref().map(PathOp::as_path),
            Some(refused.as_path())
        );
        assert_eq!(
            err.remaining
                .iter()
                .map(PathOp::as_path)
                .collect::<Vec<_>>(),
            [dirs[limit.budget + 1].as_path()]
        );
        let mut applied = dirs[..limit.budget].to_vec();
        applied.sort();
        assert_eq!(
            watched(&watcher)
                .into_iter()
                .map(|watched| watched.path)
                .collect::<Vec<_>>(),
            applied
        );
        assert_eq!(active_paths(), limit.budget);
        for dir in [&dirs[0], &dirs[limit.budget - 1]] {
            let path = dir.join("entry");
            std::fs::write(&path, "watched").unwrap();
            wait_for_path(&rx, &path);
        }

        // The limit applies after each operation, in order.
        let err = watcher
            .update_paths(vec![
                PathOp::watch_non_recursive(refused),
                PathOp::unwatch(&dirs[0]),
            ])
            .unwrap_err();
        assert!(
            matches!(err.source.kind, ErrorKind::MaxFilesWatch),
            "{err:?}"
        );
        assert_eq!(err.remaining.len(), 1);
        watcher
            .update_paths(vec![
                PathOp::unwatch(&dirs[0]),
                PathOp::watch_non_recursive(refused),
            ])
            .unwrap();
        assert_eq!(active_paths(), limit.budget);
        let path = refused.join("entry");
        std::fs::write(&path, "watched").unwrap();
        wait_for_path(&rx, &path);
    }

    #[test]
    #[ignore = "fills the process-wide path budget; run alone with --ignored --test-threads=1"]
    fn root_limit_is_shared_and_held_while_a_stream_is_replaced() {
        let limit = RootLimit::new();
        let dirs = limit.dirs(limit.budget + 1);
        let (last, spare) = (&dirs[limit.budget - 1], &dirs[limit.budget]);
        let (tx, rx) = mpsc::channel();
        let mut first = FsEventWatcher::new(tx, Config::default()).unwrap();
        first
            .update_paths(
                dirs[..limit.budget - 1]
                    .iter()
                    .map(PathOp::watch_non_recursive)
                    .collect(),
            )
            .unwrap();
        let mut second = FsEventWatcher::new(|_| {}, Config::default()).unwrap();

        // `first` reserves the path it adds before it stops its stream, so `second`
        // cannot take it while that stream is being replaced.
        let resume = pause_runloop(&first);
        let stop_flag = first.runloop.as_ref().unwrap().stop_flag.clone();
        thread::scope(|scope| {
            scope.spawn(|| first.watch(last, RecursiveMode::NonRecursive).unwrap());
            let deadline = Instant::now() + Duration::from_secs(10);
            while !stop_flag.load(Ordering::Acquire) && Instant::now() < deadline {
                thread::sleep(Duration::from_millis(1));
            }
            let result = second.watch(spare, RecursiveMode::NonRecursive);
            resume.send(()).expect("resume runloop");
            assert!(matches!(result.unwrap_err().kind, ErrorKind::MaxFilesWatch));
        });
        assert_eq!(active_paths(), limit.budget);

        // Paths that one watcher gives back are available to the other.
        first.unwatch(&dirs[0]).unwrap();
        second.watch(spare, RecursiveMode::NonRecursive).unwrap();
        assert_eq!(active_paths(), limit.budget);
        let path = last.join("entry");
        std::fs::write(&path, "watched").unwrap();
        wait_for_path(&rx, &path);

        drop(first);
        assert_eq!(active_paths(), 1);
        drop(second);
        assert_eq!(active_paths(), 0);
    }

    #[test]
    fn rename_then_remove_remove_event_must_be_the_last_one() {
        let tmpdir = testdir();
        let (mut watcher, mut rx) = watcher();

        let path = tmpdir.path().join("entry");
        std::fs::File::create_new(&path).expect("create");

        watcher.watch_recursively(&tmpdir);
        let new_path1 = tmpdir.path().join("renamed1");
        let new_path2 = tmpdir.path().join("renamed2");

        std::fs::rename(&path, &new_path1).expect("rename1");
        std::fs::rename(&new_path1, &new_path2).expect("rename2");

        std::fs::remove_file(&new_path2).expect("remove_file");

        loop {
            let ev = rx.recv();
            if matches!(ev.kind, EventKind::Remove(RemoveKind::File)) {
                assert_eq!(&ev.paths, &[new_path2]);
                break;
            }
        }

        rx.ensure_empty();
    }
}