Welcome to mirror list, hosted at ThFree Co, Russian Federation.

node_edit.cc « space_node « editors « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7982b47f363428a3b0ea5f2f0eec1878d2d863ef (plain)
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
/* SPDX-License-Identifier: GPL-2.0-or-later
 * Copyright 2005 Blender Foundation. All rights reserved. */

/** \file
 * \ingroup spnode
 */

#include <algorithm>

#include "MEM_guardedalloc.h"

#include "DNA_light_types.h"
#include "DNA_material_types.h"
#include "DNA_node_types.h"
#include "DNA_text_types.h"
#include "DNA_world_types.h"

#include "BKE_callbacks.h"
#include "BKE_context.h"
#include "BKE_global.h"
#include "BKE_image.h"
#include "BKE_image_format.h"
#include "BKE_lib_id.h"
#include "BKE_main.h"
#include "BKE_material.h"
#include "BKE_node.h"
#include "BKE_node_tree_update.h"
#include "BKE_report.h"
#include "BKE_scene.h"
#include "BKE_workspace.h"

#include "BLT_translation.h"

#include "DEG_depsgraph.h"
#include "DEG_depsgraph_build.h"
#include "DEG_depsgraph_query.h"

#include "RE_engine.h"
#include "RE_pipeline.h"

#include "ED_image.h"
#include "ED_node.h" /* own include */
#include "ED_render.h"
#include "ED_screen.h"
#include "ED_select_utils.h"
#include "ED_viewer_path.hh"

#include "RNA_access.h"
#include "RNA_define.h"
#include "RNA_enum_types.h"
#include "RNA_prototypes.h"

#include "WM_api.h"
#include "WM_types.h"

#include "UI_view2d.h"

#include "GPU_material.h"

#include "IMB_imbuf_types.h"

#include "NOD_composite.h"
#include "NOD_geometry.h"
#include "NOD_shader.h"
#include "NOD_texture.h"
#include "node_intern.hh" /* own include */

namespace blender::ed::space_node {

#define USE_ESC_COMPO

/* -------------------------------------------------------------------- */
/** \name Composite Job Manager
 * \{ */

enum {
  COM_RECALC_COMPOSITE = 1,
  COM_RECALC_VIEWER = 2,
};

struct CompoJob {
  /* Input parameters. */
  Main *bmain;
  Scene *scene;
  ViewLayer *view_layer;
  bNodeTree *ntree;
  int recalc_flags;
  /* Evaluated state/ */
  Depsgraph *compositor_depsgraph;
  bNodeTree *localtree;
  /* Jon system integration. */
  const bool *stop;
  bool *do_update;
  float *progress;
};

float node_socket_calculate_height(const bNodeSocket &socket)
{
  float sock_height = NODE_SOCKSIZE * NODE_SOCKSIZE_DRAW_MULIPLIER;
  if (socket.flag & SOCK_MULTI_INPUT) {
    sock_height += max_ii(NODE_MULTI_INPUT_LINK_GAP * 0.5f * socket.total_inputs, NODE_SOCKSIZE);
  }
  return sock_height;
}

float2 node_link_calculate_multi_input_position(const float2 &socket_position,
                                                const int index,
                                                const int total_inputs)
{
  const float offset = (total_inputs * NODE_MULTI_INPUT_LINK_GAP - NODE_MULTI_INPUT_LINK_GAP) *
                       0.5f;
  return {socket_position.x, socket_position.y - offset + index * NODE_MULTI_INPUT_LINK_GAP};
}

static void compo_tag_output_nodes(bNodeTree *nodetree, int recalc_flags)
{
  LISTBASE_FOREACH (bNode *, node, &nodetree->nodes) {
    if (node->type == CMP_NODE_COMPOSITE) {
      if (recalc_flags & COM_RECALC_COMPOSITE) {
        node->flag |= NODE_DO_OUTPUT_RECALC;
      }
    }
    else if (ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
      if (recalc_flags & COM_RECALC_VIEWER) {
        node->flag |= NODE_DO_OUTPUT_RECALC;
      }
    }
    else if (node->type == NODE_GROUP) {
      if (node->id) {
        compo_tag_output_nodes((bNodeTree *)node->id, recalc_flags);
      }
    }
  }
}

static int compo_get_recalc_flags(const bContext *C)
{
  wmWindowManager *wm = CTX_wm_manager(C);
  int recalc_flags = 0;

  LISTBASE_FOREACH (wmWindow *, win, &wm->windows) {
    const bScreen *screen = WM_window_get_active_screen(win);

    LISTBASE_FOREACH (ScrArea *, area, &screen->areabase) {
      if (area->spacetype == SPACE_IMAGE) {
        SpaceImage *sima = (SpaceImage *)area->spacedata.first;
        if (sima->image) {
          if (sima->image->type == IMA_TYPE_R_RESULT) {
            recalc_flags |= COM_RECALC_COMPOSITE;
          }
          else if (sima->image->type == IMA_TYPE_COMPOSITE) {
            recalc_flags |= COM_RECALC_VIEWER;
          }
        }
      }
      else if (area->spacetype == SPACE_NODE) {
        SpaceNode *snode = (SpaceNode *)area->spacedata.first;
        if (snode->flag & SNODE_BACKDRAW) {
          recalc_flags |= COM_RECALC_VIEWER;
        }
      }
    }
  }

  return recalc_flags;
}

/* called by compo, only to check job 'stop' value */
static bool compo_breakjob(void *cjv)
{
  CompoJob *cj = (CompoJob *)cjv;

  /* without G.is_break 'ESC' won't quit - which annoys users */
  return (*(cj->stop)
#ifdef USE_ESC_COMPO
          || G.is_break
#endif
  );
}

/* called by compo, wmJob sends notifier */
static void compo_statsdrawjob(void *cjv, const char * /*str*/)
{
  CompoJob *cj = (CompoJob *)cjv;

  *(cj->do_update) = true;
}

/* called by compo, wmJob sends notifier */
static void compo_redrawjob(void *cjv)
{
  CompoJob *cj = (CompoJob *)cjv;

  *(cj->do_update) = true;
}

static void compo_freejob(void *cjv)
{
  CompoJob *cj = (CompoJob *)cjv;

  if (cj->localtree) {
    ntreeLocalMerge(cj->bmain, cj->localtree, cj->ntree);
  }
  if (cj->compositor_depsgraph != nullptr) {
    DEG_graph_free(cj->compositor_depsgraph);
  }
  MEM_freeN(cj);
}

/* only now we copy the nodetree, so adding many jobs while
 * sliding buttons doesn't frustrate */
static void compo_initjob(void *cjv)
{
  CompoJob *cj = (CompoJob *)cjv;
  Main *bmain = cj->bmain;
  Scene *scene = cj->scene;
  ViewLayer *view_layer = cj->view_layer;

  cj->compositor_depsgraph = DEG_graph_new(bmain, scene, view_layer, DAG_EVAL_RENDER);
  DEG_graph_build_for_compositor_preview(cj->compositor_depsgraph, cj->ntree);

  /* NOTE: Don't update animation to preserve unkeyed changes, this means can not use
   * evaluate_on_framechange. */
  DEG_evaluate_on_refresh(cj->compositor_depsgraph);

  bNodeTree *ntree_eval = (bNodeTree *)DEG_get_evaluated_id(cj->compositor_depsgraph,
                                                            &cj->ntree->id);

  cj->localtree = ntreeLocalize(ntree_eval);

  if (cj->recalc_flags) {
    compo_tag_output_nodes(cj->localtree, cj->recalc_flags);
  }
}

/* called before redraw notifiers, it moves finished previews over */
static void compo_updatejob(void * /*cjv*/)
{
  WM_main_add_notifier(NC_SCENE | ND_COMPO_RESULT, nullptr);
}

static void compo_progressjob(void *cjv, float progress)
{
  CompoJob *cj = (CompoJob *)cjv;

  *(cj->progress) = progress;
}

/* only this runs inside thread */
static void compo_startjob(void *cjv,
                           /* Cannot be const, this function implements wm_jobs_start_callback.
                            * NOLINTNEXTLINE: readability-non-const-parameter. */
                           bool *stop,
                           bool *do_update,
                           float *progress)
{
  CompoJob *cj = (CompoJob *)cjv;
  bNodeTree *ntree = cj->localtree;
  Scene *scene = cj->scene;

  if (scene->use_nodes == false) {
    return;
  }

  cj->stop = stop;
  cj->do_update = do_update;
  cj->progress = progress;

  ntree->test_break = compo_breakjob;
  ntree->tbh = cj;
  ntree->stats_draw = compo_statsdrawjob;
  ntree->sdh = cj;
  ntree->progress = compo_progressjob;
  ntree->prh = cj;
  ntree->update_draw = compo_redrawjob;
  ntree->udh = cj;

  // XXX BIF_store_spare();
  /* 1 is do_previews */
  BKE_callback_exec_id(cj->bmain, &scene->id, BKE_CB_EVT_COMPOSITE_PRE);

  if ((cj->scene->r.scemode & R_MULTIVIEW) == 0) {
    ntreeCompositExecTree(cj->scene, ntree, &cj->scene->r, false, true, "");
  }
  else {
    LISTBASE_FOREACH (SceneRenderView *, srv, &scene->r.views) {
      if (BKE_scene_multiview_is_render_view_active(&scene->r, srv) == false) {
        continue;
      }
      ntreeCompositExecTree(cj->scene, ntree, &cj->scene->r, false, true, srv->name);
    }
  }

  ntree->test_break = nullptr;
  ntree->stats_draw = nullptr;
  ntree->progress = nullptr;
}

static void compo_canceljob(void *cjv)
{
  CompoJob *cj = (CompoJob *)cjv;
  Main *bmain = cj->bmain;
  Scene *scene = cj->scene;
  BKE_callback_exec_id(bmain, &scene->id, BKE_CB_EVT_COMPOSITE_CANCEL);
}

static void compo_completejob(void *cjv)
{
  CompoJob *cj = (CompoJob *)cjv;
  Main *bmain = cj->bmain;
  Scene *scene = cj->scene;
  BKE_callback_exec_id(bmain, &scene->id, BKE_CB_EVT_COMPOSITE_POST);
}

/** \} */

}  // namespace blender::ed::space_node

/* -------------------------------------------------------------------- */
/** \name Composite Job C API
 * \{ */

void ED_node_composite_job(const bContext *C, bNodeTree *nodetree, Scene *scene_owner)
{
  using namespace blender::ed::space_node;

  Main *bmain = CTX_data_main(C);
  Scene *scene = CTX_data_scene(C);
  ViewLayer *view_layer = CTX_data_view_layer(C);

  /* to fix bug: T32272. */
  if (G.is_rendering) {
    return;
  }

#ifdef USE_ESC_COMPO
  G.is_break = false;
#endif

  BKE_image_backup_render(
      scene, BKE_image_ensure_viewer(bmain, IMA_TYPE_R_RESULT, "Render Result"), false);

  wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C),
                              CTX_wm_window(C),
                              scene_owner,
                              "Compositing",
                              WM_JOB_EXCL_RENDER | WM_JOB_PROGRESS,
                              WM_JOB_TYPE_COMPOSITE);
  CompoJob *cj = MEM_cnew<CompoJob>("compo job");

  /* customdata for preview thread */
  cj->bmain = bmain;
  cj->scene = scene;
  cj->view_layer = view_layer;
  cj->ntree = nodetree;
  cj->recalc_flags = compo_get_recalc_flags(C);

  /* setup job */
  WM_jobs_customdata_set(wm_job, cj, compo_freejob);
  WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_COMPO_RESULT, NC_SCENE | ND_COMPO_RESULT);
  WM_jobs_callbacks_ex(wm_job,
                       compo_startjob,
                       compo_initjob,
                       compo_updatejob,
                       nullptr,
                       compo_completejob,
                       compo_canceljob);

  WM_jobs_start(CTX_wm_manager(C), wm_job);
}

/** \} */

namespace blender::ed::space_node {

/* -------------------------------------------------------------------- */
/** \name Composite Poll & Utility Functions
 * \{ */

bool composite_node_active(bContext *C)
{
  if (ED_operator_node_active(C)) {
    SpaceNode *snode = CTX_wm_space_node(C);
    if (ED_node_is_compositor(snode)) {
      return true;
    }
  }
  return false;
}

bool composite_node_editable(bContext *C)
{
  if (ED_operator_node_editable(C)) {
    SpaceNode *snode = CTX_wm_space_node(C);
    if (ED_node_is_compositor(snode)) {
      return true;
    }
  }
  return false;
}

static void send_notifiers_after_tree_change(ID *id, bNodeTree *ntree)
{
  WM_main_add_notifier(NC_NODE | NA_EDITED, nullptr);

  if (ntree->type == NTREE_SHADER && id != nullptr) {
    if (GS(id->name) == ID_MA) {
      WM_main_add_notifier(NC_MATERIAL | ND_SHADING, id);
    }
    else if (GS(id->name) == ID_LA) {
      WM_main_add_notifier(NC_LAMP | ND_LIGHTING, id);
    }
    else if (GS(id->name) == ID_WO) {
      WM_main_add_notifier(NC_WORLD | ND_WORLD, id);
    }
  }
  else if (ntree->type == NTREE_COMPOSIT) {
    WM_main_add_notifier(NC_SCENE | ND_NODES, id);
  }
  else if (ntree->type == NTREE_TEXTURE) {
    WM_main_add_notifier(NC_TEXTURE | ND_NODES, id);
  }
  else if (ntree->type == NTREE_GEOMETRY) {
    WM_main_add_notifier(NC_OBJECT | ND_MODIFIER, id);
  }
}

/** \} */

}  // namespace blender::ed::space_node

/* -------------------------------------------------------------------- */
/** \name Node Editor Public API Functions
 * \{ */

void ED_node_tree_propagate_change(const bContext *C, Main *bmain, bNodeTree *root_ntree)
{
  if (C != nullptr) {
    SpaceNode *snode = CTX_wm_space_node(C);
    if (snode != nullptr && root_ntree != nullptr) {
      blender::ed::space_node::send_notifiers_after_tree_change(snode->id, root_ntree);
    }
  }

  NodeTreeUpdateExtraParams params = {nullptr};
  params.tree_changed_fn = [](ID *id, bNodeTree *ntree, void * /*user_data*/) {
    blender::ed::space_node::send_notifiers_after_tree_change(id, ntree);
    DEG_id_tag_update(&ntree->id, ID_RECALC_COPY_ON_WRITE);
  };
  params.tree_output_changed_fn = [](ID * /*id*/, bNodeTree *ntree, void * /*user_data*/) {
    DEG_id_tag_update(&ntree->id, ID_RECALC_NTREE_OUTPUT);
  };

  BKE_ntree_update_main_tree(bmain, root_ntree, &params);
}

void ED_node_set_tree_type(SpaceNode *snode, bNodeTreeType *typeinfo)
{
  if (typeinfo) {
    BLI_strncpy(snode->tree_idname, typeinfo->idname, sizeof(snode->tree_idname));
  }
  else {
    snode->tree_idname[0] = '\0';
  }
}

bool ED_node_is_compositor(SpaceNode *snode)
{
  return STREQ(snode->tree_idname, ntreeType_Composite->idname);
}

bool ED_node_is_shader(SpaceNode *snode)
{
  return STREQ(snode->tree_idname, ntreeType_Shader->idname);
}

bool ED_node_is_texture(SpaceNode *snode)
{
  return STREQ(snode->tree_idname, ntreeType_Texture->idname);
}

bool ED_node_is_geometry(SpaceNode *snode)
{
  return STREQ(snode->tree_idname, ntreeType_Geometry->idname);
}

void ED_node_shader_default(const bContext *C, ID *id)
{
  Main *bmain = CTX_data_main(C);

  if (GS(id->name) == ID_MA) {
    /* Materials */
    Object *ob = CTX_data_active_object(C);
    Material *ma = (Material *)id;
    Material *ma_default;

    if (ob && ob->type == OB_VOLUME) {
      ma_default = BKE_material_default_volume();
    }
    else {
      ma_default = BKE_material_default_surface();
    }

    ma->nodetree = ntreeCopyTree(bmain, ma_default->nodetree);
    ma->nodetree->owner_id = &ma->id;
    BKE_ntree_update_main_tree(bmain, ma->nodetree, nullptr);
  }
  else if (ELEM(GS(id->name), ID_WO, ID_LA)) {
    /* Emission */
    bNodeTree *ntree = ntreeAddTreeEmbedded(
        nullptr, id, "Shader Nodetree", ntreeType_Shader->idname);
    bNode *shader, *output;

    if (GS(id->name) == ID_WO) {
      World *world = (World *)id;

      shader = nodeAddStaticNode(nullptr, ntree, SH_NODE_BACKGROUND);
      output = nodeAddStaticNode(nullptr, ntree, SH_NODE_OUTPUT_WORLD);
      nodeAddLink(ntree,
                  shader,
                  nodeFindSocket(shader, SOCK_OUT, "Background"),
                  output,
                  nodeFindSocket(output, SOCK_IN, "Surface"));

      bNodeSocket *color_sock = nodeFindSocket(shader, SOCK_IN, "Color");
      copy_v3_v3(((bNodeSocketValueRGBA *)color_sock->default_value)->value, &world->horr);
    }
    else {
      shader = nodeAddStaticNode(nullptr, ntree, SH_NODE_EMISSION);
      output = nodeAddStaticNode(nullptr, ntree, SH_NODE_OUTPUT_LIGHT);
      nodeAddLink(ntree,
                  shader,
                  nodeFindSocket(shader, SOCK_OUT, "Emission"),
                  output,
                  nodeFindSocket(output, SOCK_IN, "Surface"));
    }

    shader->locx = 10.0f;
    shader->locy = 300.0f;
    output->locx = 300.0f;
    output->locy = 300.0f;
    nodeSetActive(ntree, output);
    BKE_ntree_update_main_tree(bmain, ntree, nullptr);
  }
  else {
    printf("ED_node_shader_default called on wrong ID type.\n");
    return;
  }
}

void ED_node_composit_default(const bContext *C, Scene *sce)
{
  /* but lets check it anyway */
  if (sce->nodetree) {
    if (G.debug & G_DEBUG) {
      printf("error in composite initialize\n");
    }
    return;
  }

  sce->nodetree = ntreeAddTreeEmbedded(
      nullptr, &sce->id, "Compositing Nodetree", ntreeType_Composite->idname);

  sce->nodetree->chunksize = 256;
  sce->nodetree->edit_quality = NTREE_QUALITY_HIGH;
  sce->nodetree->render_quality = NTREE_QUALITY_HIGH;

  bNode *out = nodeAddStaticNode(C, sce->nodetree, CMP_NODE_COMPOSITE);
  out->locx = 300.0f;
  out->locy = 400.0f;

  bNode *in = nodeAddStaticNode(C, sce->nodetree, CMP_NODE_R_LAYERS);
  in->locx = 10.0f;
  in->locy = 400.0f;
  nodeSetActive(sce->nodetree, in);

  /* links from color to color */
  bNodeSocket *fromsock = (bNodeSocket *)in->outputs.first;
  bNodeSocket *tosock = (bNodeSocket *)out->inputs.first;
  nodeAddLink(sce->nodetree, in, fromsock, out, tosock);

  BKE_ntree_update_main_tree(CTX_data_main(C), sce->nodetree, nullptr);
}

void ED_node_texture_default(const bContext *C, Tex *tex)
{
  /* but lets check it anyway */
  if (tex->nodetree) {
    if (G.debug & G_DEBUG) {
      printf("error in texture initialize\n");
    }
    return;
  }

  tex->nodetree = ntreeAddTreeEmbedded(
      nullptr, &tex->id, "Texture Nodetree", ntreeType_Texture->idname);

  bNode *out = nodeAddStaticNode(C, tex->nodetree, TEX_NODE_OUTPUT);
  out->locx = 300.0f;
  out->locy = 300.0f;

  bNode *in = nodeAddStaticNode(C, tex->nodetree, TEX_NODE_CHECKER);
  in->locx = 10.0f;
  in->locy = 300.0f;
  nodeSetActive(tex->nodetree, in);

  bNodeSocket *fromsock = (bNodeSocket *)in->outputs.first;
  bNodeSocket *tosock = (bNodeSocket *)out->inputs.first;
  nodeAddLink(tex->nodetree, in, fromsock, out, tosock);

  BKE_ntree_update_main_tree(CTX_data_main(C), tex->nodetree, nullptr);
}

namespace blender::ed::space_node {

/**
 * Here we set the active tree(s), even called for each redraw now, so keep it fast :)
 */
void snode_set_context(const bContext &C)
{
  SpaceNode *snode = CTX_wm_space_node(&C);
  bNodeTreeType *treetype = ntreeTypeFind(snode->tree_idname);
  bNodeTree *ntree = snode->nodetree;
  ID *id = snode->id, *from = snode->from;

  /* check the tree type */
  if (!treetype || (treetype->poll && !treetype->poll(&C, treetype))) {
    /* invalid tree type, skip
     * NOTE: not resetting the node path here, invalid #bNodeTreeType
     * may still be registered at a later point. */
    return;
  }

  if (snode->nodetree && !STREQ(snode->nodetree->idname, snode->tree_idname)) {
    /* current tree does not match selected type, clear tree path */
    ntree = nullptr;
    id = nullptr;
    from = nullptr;
  }

  if (!(snode->flag & SNODE_PIN) || ntree == nullptr) {
    if (treetype->get_from_context) {
      /* reset and update from context */
      ntree = nullptr;
      id = nullptr;
      from = nullptr;

      treetype->get_from_context(&C, treetype, &ntree, &id, &from);
    }
  }

  if (snode->nodetree != ntree || snode->id != id || snode->from != from ||
      (snode->treepath.last == nullptr && ntree)) {
    ED_node_tree_start(snode, ntree, id, from);
  }
}

}  // namespace blender::ed::space_node

void ED_node_set_active(
    Main *bmain, SpaceNode *snode, bNodeTree *ntree, bNode *node, bool *r_active_texture_changed)
{
  const bool was_active_texture = (node->flag & NODE_ACTIVE_TEXTURE) != 0;
  if (r_active_texture_changed) {
    *r_active_texture_changed = false;
  }

  nodeSetActive(ntree, node);

  if (node->type != NODE_GROUP) {
    const bool was_output = (node->flag & NODE_DO_OUTPUT) != 0;
    bool do_update = false;

    /* generic node group output: set node as active output */
    if (node->type == NODE_GROUP_OUTPUT) {
      LISTBASE_FOREACH (bNode *, node_iter, &ntree->nodes) {
        if (node_iter->type == NODE_GROUP_OUTPUT) {
          node_iter->flag &= ~NODE_DO_OUTPUT;
        }
      }

      node->flag |= NODE_DO_OUTPUT;
      if (!was_output) {
        do_update = true;
        BKE_ntree_update_tag_active_output_changed(ntree);
      }
    }

    /* tree specific activate calls */
    if (ntree->type == NTREE_SHADER) {
      if (ELEM(node->type,
               SH_NODE_OUTPUT_MATERIAL,
               SH_NODE_OUTPUT_WORLD,
               SH_NODE_OUTPUT_LIGHT,
               SH_NODE_OUTPUT_LINESTYLE)) {
        LISTBASE_FOREACH (bNode *, node_iter, &ntree->nodes) {
          if (node_iter->type == node->type) {
            node_iter->flag &= ~NODE_DO_OUTPUT;
          }
        }

        node->flag |= NODE_DO_OUTPUT;
        BKE_ntree_update_tag_active_output_changed(ntree);
      }

      ED_node_tree_propagate_change(nullptr, bmain, ntree);

      if ((node->flag & NODE_ACTIVE_TEXTURE) && !was_active_texture) {
        /* If active texture changed, free glsl materials. */
        LISTBASE_FOREACH (Material *, ma, &bmain->materials) {
          if (ma->nodetree && ma->use_nodes && ntreeHasTree(ma->nodetree, ntree)) {
            GPU_material_free(&ma->gpumaterial);

            /* Sync to active texpaint slot, otherwise we can end up painting on a different slot
             * than we are looking at. */
            if (ma->texpaintslot) {
              if (node->id != nullptr && GS(node->id->name) == ID_IM) {
                Image *image = (Image *)node->id;
                for (int i = 0; i < ma->tot_slots; i++) {
                  if (ma->texpaintslot[i].ima == image) {
                    ma->paint_active_slot = i;
                  }
                }
              }
            }
          }
        }

        LISTBASE_FOREACH (World *, wo, &bmain->worlds) {
          if (wo->nodetree && wo->use_nodes && ntreeHasTree(wo->nodetree, ntree)) {
            GPU_material_free(&wo->gpumaterial);
          }
        }

        /* Sync to Image Editor under the following conditions:
         * - current image is not pinned
         * - current image is not a Render Result or ViewerNode (want to keep looking at these) */
        if (node->id != nullptr && GS(node->id->name) == ID_IM) {
          Image *image = (Image *)node->id;
          ED_space_image_sync(bmain, image, true);
        }

        if (r_active_texture_changed) {
          *r_active_texture_changed = true;
        }
        ED_node_tree_propagate_change(nullptr, bmain, ntree);
        WM_main_add_notifier(NC_IMAGE, nullptr);
      }

      WM_main_add_notifier(NC_MATERIAL | ND_NODES, node->id);
    }
    else if (ntree->type == NTREE_COMPOSIT) {
      /* make active viewer, currently only 1 supported... */
      if (ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
        LISTBASE_FOREACH (bNode *, node_iter, &ntree->nodes) {
          if (ELEM(node_iter->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
            node_iter->flag &= ~NODE_DO_OUTPUT;
          }
        }

        node->flag |= NODE_DO_OUTPUT;
        if (was_output == 0) {
          BKE_ntree_update_tag_active_output_changed(ntree);
          ED_node_tree_propagate_change(nullptr, bmain, ntree);
        }

        /* Adding a node doesn't link this yet. */
        node->id = (ID *)BKE_image_ensure_viewer(bmain, IMA_TYPE_COMPOSITE, "Viewer Node");
      }
      else if (node->type == CMP_NODE_COMPOSITE) {
        if (was_output == 0) {
          LISTBASE_FOREACH (bNode *, node_iter, &ntree->nodes) {
            if (node_iter->type == CMP_NODE_COMPOSITE) {
              node_iter->flag &= ~NODE_DO_OUTPUT;
            }
          }

          node->flag |= NODE_DO_OUTPUT;
          BKE_ntree_update_tag_active_output_changed(ntree);
          ED_node_tree_propagate_change(nullptr, bmain, ntree);
        }
      }
      else if (do_update) {
        ED_node_tree_propagate_change(nullptr, bmain, ntree);
      }
    }
    else if (ntree->type == NTREE_TEXTURE) {
      /* XXX */
#if 0
      if (node->id) {
        BIF_preview_changed(-1);
        allqueue(REDRAWBUTSSHADING, 1);
        allqueue(REDRAWIPO, 0);
      }
#endif
    }
    else if (ntree->type == NTREE_GEOMETRY) {
      if (node->type == GEO_NODE_VIEWER) {
        if ((node->flag & NODE_DO_OUTPUT) == 0) {
          LISTBASE_FOREACH (bNode *, node_iter, &ntree->nodes) {
            if (node_iter->type == GEO_NODE_VIEWER) {
              node_iter->flag &= ~NODE_DO_OUTPUT;
            }
          }
          node->flag |= NODE_DO_OUTPUT;
        }
        blender::ed::viewer_path::activate_geometry_node(*bmain, *snode, *node);
      }
    }
  }
}

void ED_node_post_apply_transform(bContext * /*C*/, bNodeTree * /*ntree*/)
{
  /* XXX This does not work due to layout functions relying on node->block,
   * which only exists during actual drawing. Can we rely on valid totr rects?
   */
  /* make sure nodes have correct bounding boxes after transform */
  // node_update_nodetree(C, ntree, 0.0f, 0.0f);
}

/** \} */

namespace blender::ed::space_node {

/* -------------------------------------------------------------------- */
/** \name Generic Operator Functions for Nodes
 * \{ */

#if 0 /* UNUSED */

static bool edit_node_poll(bContext *C)
{
  return ED_operator_node_active(C);
}

static void edit_node_properties(wmOperatorType *ot)
{
  /* XXX could node be a context pointer? */
  RNA_def_string(ot->srna, "node", nullptr, MAX_NAME, "Node", "");
  RNA_def_int(ot->srna, "socket", 0, 0, MAX_SOCKET, "Socket", "", 0, MAX_SOCKET);
  RNA_def_enum(ot->srna, "in_out", rna_enum_node_socket_in_out_items, SOCK_IN, "Socket Side", "");
}

static int edit_node_invoke_properties(bContext *C, wmOperator *op)
{
  if (!RNA_struct_property_is_set(op->ptr, "node")) {
    bNode *node = CTX_data_pointer_get_type(C, "node", &RNA_Node).data;
    if (!node) {
      return 0;
    }
    else {
      RNA_string_set(op->ptr, "node", node->name);
    }
  }

  if (!RNA_struct_property_is_set(op->ptr, "in_out")) {
    RNA_enum_set(op->ptr, "in_out", SOCK_IN);
  }

  if (!RNA_struct_property_is_set(op->ptr, "socket")) {
    RNA_int_set(op->ptr, "socket", 0);
  }

  return 1;
}

static void edit_node_properties_get(
    wmOperator *op, bNodeTree *ntree, bNode **r_node, bNodeSocket **r_sock, int *r_in_out)
{
  bNode *node;
  bNodeSocket *sock = nullptr;
  char nodename[MAX_NAME];
  int sockindex;
  int in_out;

  RNA_string_get(op->ptr, "node", nodename);
  node = nodeFindNodebyName(ntree, nodename);

  in_out = RNA_enum_get(op->ptr, "in_out");

  sockindex = RNA_int_get(op->ptr, "socket");
  switch (in_out) {
    case SOCK_IN:
      sock = BLI_findlink(&node->inputs, sockindex);
      break;
    case SOCK_OUT:
      sock = BLI_findlink(&node->outputs, sockindex);
      break;
  }

  if (r_node) {
    *r_node = node;
  }
  if (r_sock) {
    *r_sock = sock;
  }
  if (r_in_out) {
    *r_in_out = in_out;
  }
}
#endif

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Generic
 * \{ */

static bool socket_is_occluded(const float2 &location,
                               const bNode &node_the_socket_belongs_to,
                               const SpaceNode &snode)
{
  LISTBASE_FOREACH_BACKWARD (bNode *, node, &snode.edittree->nodes) {
    if (node == &node_the_socket_belongs_to) {
      /* Nodes after this one are underneath and can't occlude the socket. */
      return false;
    }

    rctf socket_hitbox;
    const float socket_hitbox_radius = NODE_SOCKSIZE - 0.1f * U.widget_unit;
    BLI_rctf_init_pt_radius(&socket_hitbox, location, socket_hitbox_radius);
    if (BLI_rctf_inside_rctf(&node->totr, &socket_hitbox)) {
      return true;
    }
  }
  return false;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Size Widget Operator
 * \{ */

struct NodeSizeWidget {
  float mxstart, mystart;
  float oldlocx, oldlocy;
  float oldoffsetx, oldoffsety;
  float oldwidth, oldheight;
  int directions;
};

static void node_resize_init(
    bContext *C, wmOperator *op, const float2 &cursor, const bNode *node, NodeResizeDirection dir)
{
  NodeSizeWidget *nsw = MEM_cnew<NodeSizeWidget>(__func__);

  op->customdata = nsw;

  nsw->mxstart = cursor.x;
  nsw->mystart = cursor.y;

  /* store old */
  nsw->oldlocx = node->locx;
  nsw->oldlocy = node->locy;
  nsw->oldoffsetx = node->offsetx;
  nsw->oldoffsety = node->offsety;
  nsw->oldwidth = node->width;
  nsw->oldheight = node->height;
  nsw->directions = dir;

  WM_cursor_modal_set(CTX_wm_window(C), node_get_resize_cursor(dir));
  /* add modal handler */
  WM_event_add_modal_handler(C, op);
}

static void node_resize_exit(bContext *C, wmOperator *op, bool cancel)
{
  WM_cursor_modal_restore(CTX_wm_window(C));

  /* Restore old data on cancel. */
  if (cancel) {
    SpaceNode *snode = CTX_wm_space_node(C);
    bNode *node = nodeGetActive(snode->edittree);
    NodeSizeWidget *nsw = (NodeSizeWidget *)op->customdata;

    node->locx = nsw->oldlocx;
    node->locy = nsw->oldlocy;
    node->offsetx = nsw->oldoffsetx;
    node->offsety = nsw->oldoffsety;
    node->width = nsw->oldwidth;
    node->height = nsw->oldheight;
  }

  MEM_freeN(op->customdata);
  op->customdata = nullptr;
}

static int node_resize_modal(bContext *C, wmOperator *op, const wmEvent *event)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  ARegion *region = CTX_wm_region(C);
  bNode *node = nodeGetActive(snode->edittree);
  NodeSizeWidget *nsw = (NodeSizeWidget *)op->customdata;

  switch (event->type) {
    case MOUSEMOVE: {
      int2 mval;
      WM_event_drag_start_mval(event, region, mval);
      float mx, my;
      UI_view2d_region_to_view(&region->v2d, mval.x, mval.y, &mx, &my);
      const float dx = (mx - nsw->mxstart) / UI_DPI_FAC;
      const float dy = (my - nsw->mystart) / UI_DPI_FAC;

      if (node) {
        float *pwidth = &node->width;
        float oldwidth = nsw->oldwidth;
        float widthmin = node->typeinfo->minwidth;
        float widthmax = node->typeinfo->maxwidth;

        {
          if (nsw->directions & NODE_RESIZE_RIGHT) {
            *pwidth = oldwidth + dx;
            CLAMP(*pwidth, widthmin, widthmax);
          }
          if (nsw->directions & NODE_RESIZE_LEFT) {
            float locmax = nsw->oldlocx + oldwidth;

            node->locx = nsw->oldlocx + dx;
            CLAMP(node->locx, locmax - widthmax, locmax - widthmin);
            *pwidth = locmax - node->locx;
          }
        }

        /* height works the other way round ... */
        {
          float heightmin = UI_DPI_FAC * node->typeinfo->minheight;
          float heightmax = UI_DPI_FAC * node->typeinfo->maxheight;
          if (nsw->directions & NODE_RESIZE_TOP) {
            float locmin = nsw->oldlocy - nsw->oldheight;

            node->locy = nsw->oldlocy + dy;
            CLAMP(node->locy, locmin + heightmin, locmin + heightmax);
            node->height = node->locy - locmin;
          }
          if (nsw->directions & NODE_RESIZE_BOTTOM) {
            node->height = nsw->oldheight - dy;
            CLAMP(node->height, heightmin, heightmax);
          }
        }

        /* XXX make callback? */
        if (node->type == NODE_FRAME) {
          /* keep the offset symmetric around center point */
          if (nsw->directions & NODE_RESIZE_LEFT) {
            node->locx = nsw->oldlocx + 0.5f * dx;
            node->offsetx = nsw->oldoffsetx + 0.5f * dx;
          }
          if (nsw->directions & NODE_RESIZE_RIGHT) {
            node->locx = nsw->oldlocx + 0.5f * dx;
            node->offsetx = nsw->oldoffsetx - 0.5f * dx;
          }
          if (nsw->directions & NODE_RESIZE_TOP) {
            node->locy = nsw->oldlocy + 0.5f * dy;
            node->offsety = nsw->oldoffsety + 0.5f * dy;
          }
          if (nsw->directions & NODE_RESIZE_BOTTOM) {
            node->locy = nsw->oldlocy + 0.5f * dy;
            node->offsety = nsw->oldoffsety - 0.5f * dy;
          }
        }
      }

      ED_region_tag_redraw(region);

      break;
    }
    case LEFTMOUSE:
    case MIDDLEMOUSE:
    case RIGHTMOUSE: {
      if (event->val == KM_RELEASE) {
        node_resize_exit(C, op, false);
        ED_node_post_apply_transform(C, snode->edittree);

        return OPERATOR_FINISHED;
      }
      if (event->val == KM_PRESS) {
        node_resize_exit(C, op, true);
        ED_region_tag_redraw(region);

        return OPERATOR_CANCELLED;
      }
      break;
    }
    case EVT_ESCKEY:
      node_resize_exit(C, op, true);
      ED_region_tag_redraw(region);
      return OPERATOR_CANCELLED;
  }

  return OPERATOR_RUNNING_MODAL;
}

static int node_resize_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  ARegion *region = CTX_wm_region(C);
  const bNode *node = nodeGetActive(snode->edittree);

  if (node == nullptr) {
    return OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH;
  }

  /* convert mouse coordinates to v2d space */
  float2 cursor;
  int2 mval;
  WM_event_drag_start_mval(event, region, mval);
  UI_view2d_region_to_view(&region->v2d, mval.x, mval.y, &cursor.x, &cursor.y);
  const NodeResizeDirection dir = node_get_resize_direction(node, cursor.x, cursor.y);
  if (dir == NODE_RESIZE_NONE) {
    return OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH;
  }

  node_resize_init(C, op, cursor, node, dir);
  return OPERATOR_RUNNING_MODAL;
}

static void node_resize_cancel(bContext *C, wmOperator *op)
{
  node_resize_exit(C, op, true);
}

void NODE_OT_resize(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Resize Node";
  ot->idname = "NODE_OT_resize";
  ot->description = "Resize a node";

  /* api callbacks */
  ot->invoke = node_resize_invoke;
  ot->modal = node_resize_modal;
  ot->poll = ED_operator_node_active;
  ot->cancel = node_resize_cancel;

  /* flags */
  ot->flag = OPTYPE_BLOCKING;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Hidden Sockets
 * \{ */

bool node_has_hidden_sockets(bNode *node)
{
  LISTBASE_FOREACH (bNodeSocket *, sock, &node->inputs) {
    if (sock->flag & SOCK_HIDDEN) {
      return true;
    }
  }
  LISTBASE_FOREACH (bNodeSocket *, sock, &node->outputs) {
    if (sock->flag & SOCK_HIDDEN) {
      return true;
    }
  }
  return false;
}

void node_set_hidden_sockets(SpaceNode *snode, bNode *node, int set)
{
  if (set == 0) {
    LISTBASE_FOREACH (bNodeSocket *, sock, &node->inputs) {
      sock->flag &= ~SOCK_HIDDEN;
    }
    LISTBASE_FOREACH (bNodeSocket *, sock, &node->outputs) {
      sock->flag &= ~SOCK_HIDDEN;
    }
  }
  else {
    /* hide unused sockets */
    LISTBASE_FOREACH (bNodeSocket *, sock, &node->inputs) {
      if (sock->link == nullptr) {
        sock->flag |= SOCK_HIDDEN;
      }
    }
    LISTBASE_FOREACH (bNodeSocket *, sock, &node->outputs) {
      if (nodeCountSocketLinks(snode->edittree, sock) == 0) {
        sock->flag |= SOCK_HIDDEN;
      }
    }
  }
}

/* checks snode->mouse position, and returns found node/socket */
static bool cursor_isect_multi_input_socket(const float2 &cursor, const bNodeSocket &socket)
{
  const float node_socket_height = node_socket_calculate_height(socket);
  const float2 location(socket.locx, socket.locy);
  /* `.xmax = socket->locx + NODE_SOCKSIZE * 5.5f`
   * would be the same behavior as for regular sockets.
   * But keep it smaller because for multi-input socket you
   * sometimes want to drag the link to the other side, if you may
   * accidentally pick the wrong link otherwise. */
  rctf multi_socket_rect;
  BLI_rctf_init(&multi_socket_rect,
                location.x - NODE_SOCKSIZE * 4.0f,
                location.x + NODE_SOCKSIZE * 2.0f,
                location.y - node_socket_height,
                location.y + node_socket_height);
  if (BLI_rctf_isect_pt(&multi_socket_rect, cursor.x, cursor.y)) {
    return true;
  }
  return false;
}

bool node_find_indicated_socket(SpaceNode &snode,
                                bNode **nodep,
                                bNodeSocket **sockp,
                                const float2 &cursor,
                                const eNodeSocketInOut in_out)
{
  rctf rect;

  const float size_sock_padded = NODE_SOCKSIZE + 4;

  *nodep = nullptr;
  *sockp = nullptr;

  /* check if we click in a socket */
  LISTBASE_FOREACH_BACKWARD (bNode *, node, &snode.edittree->nodes) {
    BLI_rctf_init_pt_radius(&rect, cursor, size_sock_padded);

    if (!(node->flag & NODE_HIDDEN)) {
      /* extra padding inside and out - allow dragging on the text areas too */
      if (in_out == SOCK_IN) {
        rect.xmax += NODE_SOCKSIZE;
        rect.xmin -= NODE_SOCKSIZE * 4;
      }
      else if (in_out == SOCK_OUT) {
        rect.xmax += NODE_SOCKSIZE * 4;
        rect.xmin -= NODE_SOCKSIZE;
      }
    }

    if (in_out & SOCK_IN) {
      LISTBASE_FOREACH (bNodeSocket *, sock, &node->inputs) {
        if (!nodeSocketIsHidden(sock)) {
          const float2 location(sock->locx, sock->locy);
          if (sock->flag & SOCK_MULTI_INPUT && !(node->flag & NODE_HIDDEN)) {
            if (cursor_isect_multi_input_socket(cursor, *sock)) {
              if (!socket_is_occluded(location, *node, snode)) {
                *nodep = node;
                *sockp = sock;
                return true;
              }
            }
          }
          else if (BLI_rctf_isect_pt(&rect, location.x, location.y)) {
            if (!socket_is_occluded(location, *node, snode)) {
              *nodep = node;
              *sockp = sock;
              return true;
            }
          }
        }
      }
    }
    if (in_out & SOCK_OUT) {
      LISTBASE_FOREACH (bNodeSocket *, sock, &node->outputs) {
        if (!nodeSocketIsHidden(sock)) {
          const float2 location(sock->locx, sock->locy);
          if (BLI_rctf_isect_pt(&rect, location.x, location.y)) {
            if (!socket_is_occluded(location, *node, snode)) {
              *nodep = node;
              *sockp = sock;
              return true;
            }
          }
        }
      }
    }
  }

  return false;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Link Dimming
 * \{ */

float node_link_dim_factor(const View2D &v2d, const bNodeLink &link)
{
  if (link.fromsock == nullptr || link.tosock == nullptr) {
    return 1.0f;
  }

  const float2 from(link.fromsock->locx, link.fromsock->locy);
  const float2 to(link.tosock->locx, link.tosock->locy);

  const float min_endpoint_distance = std::min(
      std::max(BLI_rctf_length_x(&v2d.cur, from.x), BLI_rctf_length_y(&v2d.cur, from.y)),
      std::max(BLI_rctf_length_x(&v2d.cur, to.x), BLI_rctf_length_y(&v2d.cur, to.y)));

  if (min_endpoint_distance == 0.0f) {
    return 1.0f;
  }
  const float viewport_width = BLI_rctf_size_x(&v2d.cur);
  return std::clamp(1.0f - min_endpoint_distance / viewport_width * 10.0f, 0.05f, 1.0f);
}

bool node_link_is_hidden_or_dimmed(const View2D &v2d, const bNodeLink &link)
{
  return nodeLinkIsHidden(&link) || node_link_dim_factor(v2d, link) < 0.5f;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Duplicate Operator
 * \{ */

static void node_duplicate_reparent_recursive(const Map<const bNode *, bNode *> &node_map,
                                              bNode *node)
{
  bNode *parent;

  node->flag |= NODE_TEST;

  /* find first selected parent */
  for (parent = node->parent; parent; parent = parent->parent) {
    if (parent->flag & SELECT) {
      if (!(parent->flag & NODE_TEST)) {
        node_duplicate_reparent_recursive(node_map, parent);
      }
      break;
    }
  }
  /* reparent node copy to parent copy */
  if (parent) {
    nodeDetachNode(node_map.lookup(node));
    nodeAttachNode(node_map.lookup(node), node_map.lookup(parent));
  }
}

static int node_duplicate_exec(bContext *C, wmOperator *op)
{
  Main *bmain = CTX_data_main(C);
  SpaceNode *snode = CTX_wm_space_node(C);
  bNodeTree *ntree = snode->edittree;
  const bool keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
  bool linked = RNA_boolean_get(op->ptr, "linked") || ((U.dupflag & USER_DUP_NTREE) == 0);
  const bool dupli_node_tree = !linked;
  bool changed = false;

  ED_preview_kill_jobs(CTX_wm_manager(C), bmain);

  Map<const bNode *, bNode *> node_map;
  Map<const bNodeSocket *, bNodeSocket *> socket_map;
  Map<const ID *, ID *> duplicated_node_groups;

  bNode *lastnode = (bNode *)ntree->nodes.last;
  LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
    if (node->flag & SELECT) {
      bNode *new_node = bke::node_copy_with_mapping(
          ntree, *node, LIB_ID_COPY_DEFAULT, true, socket_map);
      node_map.add_new(node, new_node);

      if (node->id && dupli_node_tree) {
        ID *new_group = duplicated_node_groups.lookup_or_add_cb(node->id, [&]() {
          ID *new_group = BKE_id_copy(bmain, node->id);
          /* Remove user added by copying. */
          id_us_min(new_group);
          return new_group;
        });
        id_us_plus(new_group);
        id_us_min(new_node->id);
        new_node->id = new_group;
      }
      changed = true;
    }

    /* make sure we don't copy new nodes again! */
    if (node == lastnode) {
      break;
    }
  }

  if (!changed) {
    return OPERATOR_CANCELLED;
  }

  /* Copy links between selected nodes. */
  bNodeLink *lastlink = (bNodeLink *)ntree->links.last;
  LISTBASE_FOREACH (bNodeLink *, link, &ntree->links) {
    /* This creates new links between copied nodes.
     * If keep_inputs is set, also copies input links from unselected (when fromnode==nullptr)!
     */
    if (link->tonode && (link->tonode->flag & NODE_SELECT) &&
        (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT)))) {
      bNodeLink *newlink = MEM_cnew<bNodeLink>("bNodeLink");
      newlink->flag = link->flag;
      newlink->tonode = node_map.lookup(link->tonode);
      newlink->tosock = socket_map.lookup(link->tosock);

      if (link->tosock->flag & SOCK_MULTI_INPUT) {
        newlink->multi_input_socket_index = link->multi_input_socket_index;
      }

      if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
        newlink->fromnode = node_map.lookup(link->fromnode);
        newlink->fromsock = socket_map.lookup(link->fromsock);
      }
      else {
        /* input node not copied, this keeps the original input linked */
        newlink->fromnode = link->fromnode;
        newlink->fromsock = link->fromsock;
      }

      BLI_addtail(&ntree->links, newlink);
    }

    /* make sure we don't copy new links again! */
    if (link == lastlink) {
      break;
    }
  }

  /* clear flags for recursive depth-first iteration */
  LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
    node->flag &= ~NODE_TEST;
  }
  /* reparent copied nodes */
  LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
    if ((node->flag & SELECT) && !(node->flag & NODE_TEST)) {
      node_duplicate_reparent_recursive(node_map, node);
    }

    /* only has to check old nodes */
    if (node == lastnode) {
      break;
    }
  }

  /* deselect old nodes, select the copies instead */
  LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
    if (node->flag & SELECT) {
      /* has been set during copy above */
      bNode *newnode = node_map.lookup(node);

      nodeSetSelected(node, false);
      node->flag &= ~(NODE_ACTIVE | NODE_ACTIVE_TEXTURE);
      nodeSetSelected(newnode, true);
    }

    /* make sure we don't copy new nodes again! */
    if (node == lastnode) {
      break;
    }
  }

  ED_node_tree_propagate_change(C, bmain, snode->edittree);
  return OPERATOR_FINISHED;
}

void NODE_OT_duplicate(wmOperatorType *ot)
{
  PropertyRNA *prop;

  /* identifiers */
  ot->name = "Duplicate Nodes";
  ot->description = "Duplicate selected nodes";
  ot->idname = "NODE_OT_duplicate";

  /* api callbacks */
  ot->exec = node_duplicate_exec;
  ot->poll = ED_operator_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_boolean(
      ot->srna, "keep_inputs", false, "Keep Inputs", "Keep the input links to duplicated nodes");

  prop = RNA_def_boolean(ot->srna,
                         "linked",
                         true,
                         "Linked",
                         "Duplicate node but not node trees, linking to the original data");
  RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}

/* XXX: some code needing updating to operators. */

/* goes over all scenes, reads render layers */
static int node_read_viewlayers_exec(bContext *C, wmOperator * /*op*/)
{
  Main *bmain = CTX_data_main(C);
  SpaceNode *snode = CTX_wm_space_node(C);
  Scene *curscene = CTX_data_scene(C);

  ED_preview_kill_jobs(CTX_wm_manager(C), bmain);

  /* first tag scenes unread */
  LISTBASE_FOREACH (Scene *, scene, &bmain->scenes) {
    scene->id.tag |= LIB_TAG_DOIT;
  }

  LISTBASE_FOREACH (bNode *, node, &snode->edittree->nodes) {
    if ((node->type == CMP_NODE_R_LAYERS) ||
        (node->type == CMP_NODE_CRYPTOMATTE && node->custom1 == CMP_CRYPTOMATTE_SRC_RENDER)) {
      ID *id = node->id;
      if (id == nullptr) {
        continue;
      }
      if (id->tag & LIB_TAG_DOIT) {
        RE_ReadRenderResult(curscene, (Scene *)id);
        ntreeCompositTagRender((Scene *)id);
        id->tag &= ~LIB_TAG_DOIT;
      }
    }
  }

  ED_node_tree_propagate_change(C, bmain, snode->edittree);

  return OPERATOR_FINISHED;
}

void NODE_OT_read_viewlayers(wmOperatorType *ot)
{

  ot->name = "Read View Layers";
  ot->idname = "NODE_OT_read_viewlayers";
  ot->description = "Read all render layers of all used scenes";

  ot->exec = node_read_viewlayers_exec;

  ot->poll = composite_node_active;

  /* flags */
  ot->flag = 0;
}

int node_render_changed_exec(bContext *C, wmOperator * /*op*/)
{
  Scene *sce = CTX_data_scene(C);

  /* This is actually a test whether scene is used by the compositor or not.
   * All the nodes are using same render result, so there is no need to do
   * anything smart about check how exactly scene is used. */
  bNode *node = nullptr;
  LISTBASE_FOREACH (bNode *, node_iter, &sce->nodetree->nodes) {
    if (node_iter->id == (ID *)sce) {
      node = node_iter;
      break;
    }
  }

  if (node) {
    ViewLayer *view_layer = (ViewLayer *)BLI_findlink(&sce->view_layers, node->custom1);

    if (view_layer) {
      PointerRNA op_ptr;

      WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
      RNA_string_set(&op_ptr, "layer", view_layer->name);
      RNA_string_set(&op_ptr, "scene", sce->id.name + 2);

      /* To keep keyframe positions. */
      sce->r.scemode |= R_NO_FRAME_UPDATE;

      WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr, nullptr);

      WM_operator_properties_free(&op_ptr);

      return OPERATOR_FINISHED;
    }
  }
  return OPERATOR_CANCELLED;
}

void NODE_OT_render_changed(wmOperatorType *ot)
{
  ot->name = "Render Changed Layer";
  ot->idname = "NODE_OT_render_changed";
  ot->description = "Render current scene, when input node's layer has been changed";

  ot->exec = node_render_changed_exec;

  ot->poll = composite_node_active;

  /* flags */
  ot->flag = 0;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Hide Operator
 * \{ */

static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
{
  int tot_eq = 0, tot_neq = 0;

  /* Toggles the flag on all selected nodes.
   * If the flag is set on all nodes it is unset.
   * If the flag is not set on all nodes, it is set.
   */

  LISTBASE_FOREACH (bNode *, node, &snode->edittree->nodes) {
    if (node->flag & SELECT) {

      if (toggle_flag == NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW) == 0) {
        continue;
      }
      if (toggle_flag == NODE_OPTIONS &&
          !(node->typeinfo->draw_buttons || node->typeinfo->draw_buttons_ex)) {
        continue;
      }

      if (node->flag & toggle_flag) {
        tot_eq++;
      }
      else {
        tot_neq++;
      }
    }
  }
  LISTBASE_FOREACH (bNode *, node, &snode->edittree->nodes) {
    if (node->flag & SELECT) {

      if (toggle_flag == NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW) == 0) {
        continue;
      }
      if (toggle_flag == NODE_OPTIONS &&
          !(node->typeinfo->draw_buttons || node->typeinfo->draw_buttons_ex)) {
        continue;
      }

      if ((tot_eq && tot_neq) || tot_eq == 0) {
        node->flag |= toggle_flag;
      }
      else {
        node->flag &= ~toggle_flag;
      }
    }
  }
}

static int node_hide_toggle_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode *snode = CTX_wm_space_node(C);

  /* sanity checking (poll callback checks this already) */
  if ((snode == nullptr) || (snode->edittree == nullptr)) {
    return OPERATOR_CANCELLED;
  }

  node_flag_toggle_exec(snode, NODE_HIDDEN);

  WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, nullptr);

  return OPERATOR_FINISHED;
}

void NODE_OT_hide_toggle(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Hide";
  ot->description = "Toggle hiding of selected nodes";
  ot->idname = "NODE_OT_hide_toggle";

  /* callbacks */
  ot->exec = node_hide_toggle_exec;
  ot->poll = ED_operator_node_active;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

static int node_preview_toggle_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode *snode = CTX_wm_space_node(C);

  /* sanity checking (poll callback checks this already) */
  if ((snode == nullptr) || (snode->edittree == nullptr)) {
    return OPERATOR_CANCELLED;
  }

  ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));

  node_flag_toggle_exec(snode, NODE_PREVIEW);

  ED_node_tree_propagate_change(C, CTX_data_main(C), snode->edittree);

  return OPERATOR_FINISHED;
}

void NODE_OT_preview_toggle(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Toggle Node Preview";
  ot->description = "Toggle preview display for selected nodes";
  ot->idname = "NODE_OT_preview_toggle";

  /* callbacks */
  ot->exec = node_preview_toggle_exec;
  ot->poll = ED_operator_node_active;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

static int node_deactivate_viewer_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode &snode = *CTX_wm_space_node(C);
  WorkSpace &workspace = *CTX_wm_workspace(C);

  bNode *active_viewer = viewer_path::find_geometry_nodes_viewer(workspace.viewer_path, snode);

  LISTBASE_FOREACH (bNode *, node, &snode.edittree->nodes) {
    if (node->type != GEO_NODE_VIEWER) {
      continue;
    }
    if (!(node->flag & SELECT)) {
      continue;
    }
    if (node == active_viewer) {
      node->flag &= ~NODE_DO_OUTPUT;
      BKE_ntree_update_tag_node_property(snode.edittree, node);
    }
  }

  ED_node_tree_propagate_change(C, CTX_data_main(C), snode.edittree);

  return OPERATOR_FINISHED;
}

void NODE_OT_deactivate_viewer(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Deactivate Viewer Node";
  ot->description = "Deactivate selected viewer node in geometry nodes";
  ot->idname = __func__;

  /* callbacks */
  ot->exec = node_deactivate_viewer_exec;
  ot->poll = ED_operator_node_active;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

static int node_options_toggle_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode *snode = CTX_wm_space_node(C);

  /* sanity checking (poll callback checks this already) */
  if ((snode == nullptr) || (snode->edittree == nullptr)) {
    return OPERATOR_CANCELLED;
  }

  node_flag_toggle_exec(snode, NODE_OPTIONS);

  WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, nullptr);

  return OPERATOR_FINISHED;
}

void NODE_OT_options_toggle(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Toggle Node Options";
  ot->description = "Toggle option buttons display for selected nodes";
  ot->idname = "NODE_OT_options_toggle";

  /* callbacks */
  ot->exec = node_options_toggle_exec;
  ot->poll = ED_operator_node_active;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

static int node_socket_toggle_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode *snode = CTX_wm_space_node(C);

  /* sanity checking (poll callback checks this already) */
  if ((snode == nullptr) || (snode->edittree == nullptr)) {
    return OPERATOR_CANCELLED;
  }

  ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));

  /* Toggle for all selected nodes */
  bool hidden = false;
  LISTBASE_FOREACH (bNode *, node, &snode->edittree->nodes) {
    if (node->flag & SELECT) {
      if (node_has_hidden_sockets(node)) {
        hidden = true;
        break;
      }
    }
  }

  LISTBASE_FOREACH (bNode *, node, &snode->edittree->nodes) {
    if (node->flag & SELECT) {
      node_set_hidden_sockets(snode, node, !hidden);
    }
  }

  ED_node_tree_propagate_change(C, CTX_data_main(C), snode->edittree);

  WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, nullptr);

  return OPERATOR_FINISHED;
}

void NODE_OT_hide_socket_toggle(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Toggle Hidden Node Sockets";
  ot->description = "Toggle unused node socket display";
  ot->idname = "NODE_OT_hide_socket_toggle";

  /* callbacks */
  ot->exec = node_socket_toggle_exec;
  ot->poll = ED_operator_node_active;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Mute Operator
 * \{ */

static int node_mute_exec(bContext *C, wmOperator * /*op*/)
{
  Main *bmain = CTX_data_main(C);
  SpaceNode *snode = CTX_wm_space_node(C);

  ED_preview_kill_jobs(CTX_wm_manager(C), bmain);

  LISTBASE_FOREACH (bNode *, node, &snode->edittree->nodes) {
    if ((node->flag & SELECT) && !node->typeinfo->no_muting) {
      node->flag ^= NODE_MUTED;
      BKE_ntree_update_tag_node_mute(snode->edittree, node);
    }
  }

  ED_node_tree_propagate_change(C, bmain, snode->edittree);

  return OPERATOR_FINISHED;
}

void NODE_OT_mute_toggle(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Toggle Node Mute";
  ot->description = "Toggle muting of the nodes";
  ot->idname = "NODE_OT_mute_toggle";

  /* callbacks */
  ot->exec = node_mute_exec;
  ot->poll = ED_operator_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Delete Operator
 * \{ */

static int node_delete_exec(bContext *C, wmOperator * /*op*/)
{
  Main *bmain = CTX_data_main(C);
  SpaceNode *snode = CTX_wm_space_node(C);

  ED_preview_kill_jobs(CTX_wm_manager(C), bmain);

  LISTBASE_FOREACH_MUTABLE (bNode *, node, &snode->edittree->nodes) {
    if (node->flag & SELECT) {
      nodeRemoveNode(bmain, snode->edittree, node, true);
    }
  }

  ED_node_tree_propagate_change(C, bmain, snode->edittree);

  return OPERATOR_FINISHED;
}

void NODE_OT_delete(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Delete";
  ot->description = "Delete selected nodes";
  ot->idname = "NODE_OT_delete";

  /* api callbacks */
  ot->exec = node_delete_exec;
  ot->poll = ED_operator_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Switch View
 * \{ */

static bool node_switch_view_poll(bContext *C)
{
  SpaceNode *snode = CTX_wm_space_node(C);

  if (snode && snode->edittree) {
    return true;
  }

  return false;
}

static int node_switch_view_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode *snode = CTX_wm_space_node(C);

  LISTBASE_FOREACH_MUTABLE (bNode *, node, &snode->edittree->nodes) {
    if (node->flag & SELECT) {
      /* call the update function from the Switch View node */
      node->update = NODE_UPDATE_OPERATOR;
    }
  }

  ED_node_tree_propagate_change(C, CTX_data_main(C), snode->edittree);

  return OPERATOR_FINISHED;
}

void NODE_OT_switch_view_update(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Update Views";
  ot->description = "Update views of selected node";
  ot->idname = "NODE_OT_switch_view_update";

  /* api callbacks */
  ot->exec = node_switch_view_exec;
  ot->poll = node_switch_view_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Delete with Reconnect Operator
 * \{ */

static int node_delete_reconnect_exec(bContext *C, wmOperator * /*op*/)
{
  Main *bmain = CTX_data_main(C);
  SpaceNode *snode = CTX_wm_space_node(C);

  ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));

  LISTBASE_FOREACH_MUTABLE (bNode *, node, &snode->edittree->nodes) {
    if (node->flag & SELECT) {
      nodeInternalRelink(snode->edittree, node);
      nodeRemoveNode(bmain, snode->edittree, node, true);
    }
  }

  ED_node_tree_propagate_change(C, bmain, snode->edittree);

  return OPERATOR_FINISHED;
}

void NODE_OT_delete_reconnect(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Delete with Reconnect";
  ot->description = "Delete nodes; will reconnect nodes as if deletion was muted";
  ot->idname = "NODE_OT_delete_reconnect";

  /* api callbacks */
  ot->exec = node_delete_reconnect_exec;
  ot->poll = ED_operator_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node File Output Add Socket Operator
 * \{ */

static int node_output_file_add_socket_exec(bContext *C, wmOperator *op)
{
  Scene *scene = CTX_data_scene(C);
  SpaceNode *snode = CTX_wm_space_node(C);
  PointerRNA ptr = CTX_data_pointer_get(C, "node");
  bNodeTree *ntree = nullptr;
  bNode *node = nullptr;
  char file_path[MAX_NAME];

  if (ptr.data) {
    node = (bNode *)ptr.data;
    ntree = (bNodeTree *)ptr.owner_id;
  }
  else if (snode && snode->edittree) {
    ntree = snode->edittree;
    node = nodeGetActive(snode->edittree);
  }

  if (!node || node->type != CMP_NODE_OUTPUT_FILE) {
    return OPERATOR_CANCELLED;
  }

  RNA_string_get(op->ptr, "file_path", file_path);
  ntreeCompositOutputFileAddSocket(ntree, node, file_path, &scene->r.im_format);

  ED_node_tree_propagate_change(C, CTX_data_main(C), snode->edittree);

  return OPERATOR_FINISHED;
}

void NODE_OT_output_file_add_socket(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Add File Node Socket";
  ot->description = "Add a new input to a file output node";
  ot->idname = "NODE_OT_output_file_add_socket";

  /* callbacks */
  ot->exec = node_output_file_add_socket_exec;
  ot->poll = composite_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_string(
      ot->srna, "file_path", "Image", MAX_NAME, "File Path", "Subpath of the output file");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Multi File Output Remove Socket Operator
 * \{ */

static int node_output_file_remove_active_socket_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  PointerRNA ptr = CTX_data_pointer_get(C, "node");
  bNodeTree *ntree = nullptr;
  bNode *node = nullptr;

  if (ptr.data) {
    node = (bNode *)ptr.data;
    ntree = (bNodeTree *)ptr.owner_id;
  }
  else if (snode && snode->edittree) {
    ntree = snode->edittree;
    node = nodeGetActive(snode->edittree);
  }

  if (!node || node->type != CMP_NODE_OUTPUT_FILE) {
    return OPERATOR_CANCELLED;
  }

  if (!ntreeCompositOutputFileRemoveActiveSocket(ntree, node)) {
    return OPERATOR_CANCELLED;
  }

  ED_node_tree_propagate_change(C, CTX_data_main(C), ntree);

  return OPERATOR_FINISHED;
}

void NODE_OT_output_file_remove_active_socket(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Remove File Node Socket";
  ot->description = "Remove active input from a file output node";
  ot->idname = "NODE_OT_output_file_remove_active_socket";

  /* callbacks */
  ot->exec = node_output_file_remove_active_socket_exec;
  ot->poll = composite_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Multi File Output Move Socket Node
 * \{ */

static int node_output_file_move_active_socket_exec(bContext *C, wmOperator *op)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  PointerRNA ptr = CTX_data_pointer_get(C, "node");
  bNode *node = nullptr;

  if (ptr.data) {
    node = (bNode *)ptr.data;
  }
  else if (snode && snode->edittree) {
    node = nodeGetActive(snode->edittree);
  }

  if (!node || node->type != CMP_NODE_OUTPUT_FILE) {
    return OPERATOR_CANCELLED;
  }

  NodeImageMultiFile *nimf = (NodeImageMultiFile *)node->storage;

  bNodeSocket *sock = (bNodeSocket *)BLI_findlink(&node->inputs, nimf->active_input);
  if (!sock) {
    return OPERATOR_CANCELLED;
  }

  int direction = RNA_enum_get(op->ptr, "direction");

  if (direction == 1) {
    bNodeSocket *before = sock->prev;
    if (!before) {
      return OPERATOR_CANCELLED;
    }
    BLI_remlink(&node->inputs, sock);
    BLI_insertlinkbefore(&node->inputs, before, sock);
    nimf->active_input--;
  }
  else {
    bNodeSocket *after = sock->next;
    if (!after) {
      return OPERATOR_CANCELLED;
    }
    BLI_remlink(&node->inputs, sock);
    BLI_insertlinkafter(&node->inputs, after, sock);
    nimf->active_input++;
  }

  ED_node_tree_propagate_change(C, CTX_data_main(C), snode->edittree);

  return OPERATOR_FINISHED;
}

void NODE_OT_output_file_move_active_socket(wmOperatorType *ot)
{
  static const EnumPropertyItem direction_items[] = {
      {1, "UP", 0, "Up", ""}, {2, "DOWN", 0, "Down", ""}, {0, nullptr, 0, nullptr, nullptr}};

  /* identifiers */
  ot->name = "Move File Node Socket";
  ot->description = "Move the active input of a file output node up or down the list";
  ot->idname = "NODE_OT_output_file_move_active_socket";

  /* callbacks */
  ot->exec = node_output_file_move_active_socket_exec;
  ot->poll = composite_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_enum(ot->srna, "direction", direction_items, 2, "Direction", "");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Copy Node Color Operator
 * \{ */

static int node_copy_color_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode &snode = *CTX_wm_space_node(C);
  bNodeTree &ntree = *snode.edittree;

  bNode *active_node = nodeGetActive(&ntree);
  if (!active_node) {
    return OPERATOR_CANCELLED;
  }

  LISTBASE_FOREACH (bNode *, node, &ntree.nodes) {
    if (node->flag & NODE_SELECT && node != active_node) {
      if (active_node->flag & NODE_CUSTOM_COLOR) {
        node->flag |= NODE_CUSTOM_COLOR;
        copy_v3_v3(node->color, active_node->color);
      }
      else {
        node->flag &= ~NODE_CUSTOM_COLOR;
      }
    }
  }

  WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, nullptr);

  return OPERATOR_FINISHED;
}

void NODE_OT_node_copy_color(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Copy Color";
  ot->description = "Copy color to all selected nodes";
  ot->idname = "NODE_OT_node_copy_color";

  /* api callbacks */
  ot->exec = node_copy_color_exec;
  ot->poll = ED_operator_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Copy to Clipboard Operator
 * \{ */

static int node_clipboard_copy_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  bNodeTree *ntree = snode->edittree;

  ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));

  /* clear current clipboard */
  BKE_node_clipboard_clear();
  BKE_node_clipboard_init(ntree);

  Map<const bNode *, bNode *> node_map;
  Map<const bNodeSocket *, bNodeSocket *> socket_map;

  LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
    if (node->flag & SELECT) {
      /* No ID refcounting, this node is virtual,
       * detached from any actual Blender data currently. */
      bNode *new_node = bke::node_copy_with_mapping(nullptr,
                                                    *node,
                                                    LIB_ID_CREATE_NO_USER_REFCOUNT |
                                                        LIB_ID_CREATE_NO_MAIN,
                                                    false,
                                                    socket_map);
      node_map.add_new(node, new_node);
    }
  }

  for (bNode *new_node : node_map.values()) {
    BKE_node_clipboard_add_node(new_node);

    /* Parent pointer must be redirected to new node or detached if parent is not copied. */
    if (new_node->parent) {
      if (node_map.contains(new_node->parent)) {
        new_node->parent = node_map.lookup(new_node->parent);
      }
      else {
        nodeDetachNode(new_node);
      }
    }
  }

  /* Copy links between selected nodes. */
  LISTBASE_FOREACH (bNodeLink *, link, &ntree->links) {
    BLI_assert(link->tonode);
    BLI_assert(link->fromnode);
    if (link->tonode->flag & NODE_SELECT && link->fromnode->flag & NODE_SELECT) {
      bNodeLink *newlink = MEM_cnew<bNodeLink>(__func__);
      newlink->flag = link->flag;
      newlink->tonode = node_map.lookup(link->tonode);
      newlink->tosock = socket_map.lookup(link->tosock);
      newlink->fromnode = node_map.lookup(link->fromnode);
      newlink->fromsock = socket_map.lookup(link->fromsock);
      newlink->multi_input_socket_index = link->multi_input_socket_index;

      BKE_node_clipboard_add_link(newlink);
    }
  }

  return OPERATOR_FINISHED;
}

void NODE_OT_clipboard_copy(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Copy to Clipboard";
  ot->description = "Copies selected nodes to the clipboard";
  ot->idname = "NODE_OT_clipboard_copy";

  /* api callbacks */
  ot->exec = node_clipboard_copy_exec;
  ot->poll = ED_operator_node_active;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Paste from Clipboard
 * \{ */

static int node_clipboard_paste_exec(bContext *C, wmOperator *op)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  bNodeTree *ntree = snode->edittree;

  /* validate pointers in the clipboard */
  bool is_clipboard_valid = BKE_node_clipboard_validate();
  const ListBase *clipboard_nodes_lb = BKE_node_clipboard_get_nodes();
  const ListBase *clipboard_links_lb = BKE_node_clipboard_get_links();

  if (BLI_listbase_is_empty(clipboard_nodes_lb)) {
    BKE_report(op->reports, RPT_ERROR, "Clipboard is empty");
    return OPERATOR_CANCELLED;
  }

  if (BKE_node_clipboard_get_type() != ntree->type) {
    BKE_report(op->reports, RPT_ERROR, "Clipboard nodes are an incompatible type");
    return OPERATOR_CANCELLED;
  }

  /* only warn */
  if (is_clipboard_valid == false) {
    BKE_report(op->reports,
               RPT_WARNING,
               "Some nodes references could not be restored, will be left empty");
  }

  /* make sure all clipboard nodes would be valid in the target tree */
  bool all_nodes_valid = true;
  LISTBASE_FOREACH (bNode *, node, clipboard_nodes_lb) {
    const char *disabled_hint = nullptr;
    if (!node->typeinfo->poll_instance ||
        !node->typeinfo->poll_instance(node, ntree, &disabled_hint)) {
      all_nodes_valid = false;
      if (disabled_hint) {
        BKE_reportf(op->reports,
                    RPT_ERROR,
                    "Cannot add node %s into node tree %s:\n  %s",
                    node->name,
                    ntree->id.name + 2,
                    disabled_hint);
      }
      else {
        BKE_reportf(op->reports,
                    RPT_ERROR,
                    "Cannot add node %s into node tree %s",
                    node->name,
                    ntree->id.name + 2);
      }
    }
  }
  if (!all_nodes_valid) {
    return OPERATOR_CANCELLED;
  }

  ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));

  /* deselect old nodes */
  node_deselect_all(*snode);

  /* calculate "barycenter" for placing on mouse cursor */
  float2 center = {0.0f, 0.0f};
  int num_nodes = 0;
  LISTBASE_FOREACH_INDEX (bNode *, node, clipboard_nodes_lb, num_nodes) {
    center.x += BLI_rctf_cent_x(&node->totr);
    center.y += BLI_rctf_cent_y(&node->totr);
  }
  mul_v2_fl(center, 1.0 / num_nodes);

  Map<const bNode *, bNode *> node_map;
  Map<const bNodeSocket *, bNodeSocket *> socket_map;

  /* copy nodes from clipboard */
  LISTBASE_FOREACH (bNode *, node, clipboard_nodes_lb) {
    bNode *new_node = bke::node_copy_with_mapping(
        ntree, *node, LIB_ID_COPY_DEFAULT, true, socket_map);
    node_map.add_new(node, new_node);
  }

  for (bNode *new_node : node_map.values()) {
    /* pasted nodes are selected */
    nodeSetSelected(new_node, true);

    /* The parent pointer must be redirected to new node. */
    if (new_node->parent) {
      if (node_map.contains(new_node->parent)) {
        new_node->parent = node_map.lookup(new_node->parent);
      }
    }
  }

  LISTBASE_FOREACH (bNodeLink *, link, clipboard_links_lb) {
    bNodeLink *new_link = nodeAddLink(ntree,
                                      node_map.lookup(link->fromnode),
                                      socket_map.lookup(link->fromsock),
                                      node_map.lookup(link->tonode),
                                      socket_map.lookup(link->tosock));
    new_link->multi_input_socket_index = link->multi_input_socket_index;
  }

  ntree->ensure_topology_cache();

  for (bNode *new_node : node_map.values()) {
    /* Update multi input socket indices in case all connected nodes weren't copied. */
    update_multi_input_indices_for_removed_links(*new_node);
  }

  Main *bmain = CTX_data_main(C);
  ED_node_tree_propagate_change(C, bmain, snode->edittree);
  /* Pasting nodes can create arbitrary new relations, because nodes can reference IDs. */
  DEG_relations_tag_update(bmain);

  return OPERATOR_FINISHED;
}

void NODE_OT_clipboard_paste(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Paste from Clipboard";
  ot->description = "Pastes nodes from the clipboard to the active node tree";
  ot->idname = "NODE_OT_clipboard_paste";

  /* api callbacks */
  ot->exec = node_clipboard_paste_exec;
  ot->poll = ED_operator_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node-Tree Add Interface Socket Operator
 * \{ */

static bNodeSocket *ntree_get_active_interface_socket(ListBase *lb)
{
  LISTBASE_FOREACH (bNodeSocket *, socket, lb) {
    if (socket->flag & SELECT) {
      return socket;
    }
  }
  return nullptr;
}

static int ntree_socket_add_exec(bContext *C, wmOperator *op)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  bNodeTree *ntree = snode->edittree;

  PointerRNA ntree_ptr;
  RNA_id_pointer_create((ID *)ntree, &ntree_ptr);

  const eNodeSocketInOut in_out = (eNodeSocketInOut)RNA_enum_get(op->ptr, "in_out");
  ListBase *sockets = (in_out == SOCK_IN) ? &ntree->inputs : &ntree->outputs;

  const char *default_name = (in_out == SOCK_IN) ? DATA_("Input") : DATA_("Output");
  bNodeSocket *active_sock = ntree_get_active_interface_socket(sockets);

  bNodeSocket *sock;
  if (active_sock) {
    /* insert a copy of the active socket right after it */
    sock = ntreeInsertSocketInterface(
        ntree, in_out, active_sock->idname, active_sock->next, active_sock->name);
    /* XXX this only works for actual sockets, not interface templates! */
    // nodeSocketCopyValue(sock, &ntree_ptr, active_sock, &ntree_ptr);
  }
  else {
    /* XXX TODO: define default socket type for a tree! */
    sock = ntreeAddSocketInterface(ntree, in_out, "NodeSocketFloat", default_name);
  }

  /* Deactivate sockets. */
  LISTBASE_FOREACH (bNodeSocket *, socket_iter, sockets) {
    socket_iter->flag &= ~SELECT;
  }
  /* make the new socket active */
  sock->flag |= SELECT;

  ED_node_tree_propagate_change(C, CTX_data_main(C), snode->edittree);

  WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, nullptr);

  return OPERATOR_FINISHED;
}

void NODE_OT_tree_socket_add(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Add Node Tree Interface Socket";
  ot->description = "Add an input or output socket to the current node tree";
  ot->idname = "NODE_OT_tree_socket_add";

  /* api callbacks */
  ot->exec = ntree_socket_add_exec;
  ot->poll = ED_operator_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_enum(ot->srna, "in_out", rna_enum_node_socket_in_out_items, SOCK_IN, "Socket Type", "");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node-Tree Remove Interface Socket Operator
 * \{ */

static int ntree_socket_remove_exec(bContext *C, wmOperator *op)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  bNodeTree *ntree = snode->edittree;
  const eNodeSocketInOut in_out = (eNodeSocketInOut)RNA_enum_get(op->ptr, "in_out");

  bNodeSocket *iosock = ntree_get_active_interface_socket(in_out == SOCK_IN ? &ntree->inputs :
                                                                              &ntree->outputs);
  if (iosock == nullptr) {
    return OPERATOR_CANCELLED;
  }

  /* preferably next socket becomes active, otherwise try previous socket */
  bNodeSocket *active_sock = (iosock->next ? iosock->next : iosock->prev);
  ntreeRemoveSocketInterface(ntree, iosock);

  /* set active socket */
  if (active_sock) {
    active_sock->flag |= SELECT;
  }

  ED_node_tree_propagate_change(C, CTX_data_main(C), ntree);

  WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, nullptr);

  return OPERATOR_FINISHED;
}

void NODE_OT_tree_socket_remove(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Remove Node Tree Interface Socket";
  ot->description = "Remove an input or output socket to the current node tree";
  ot->idname = "NODE_OT_tree_socket_remove";

  /* api callbacks */
  ot->exec = ntree_socket_remove_exec;
  ot->poll = ED_operator_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
  RNA_def_enum(ot->srna, "in_out", rna_enum_node_socket_in_out_items, SOCK_IN, "Socket Type", "");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node-Tree Change Interface Socket Type Operator
 * \{ */

static int ntree_socket_change_type_exec(bContext *C, wmOperator *op)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  bNodeTree *ntree = snode->edittree;
  const eNodeSocketInOut in_out = (eNodeSocketInOut)RNA_enum_get(op->ptr, "in_out");
  const bNodeSocketType *socket_type = rna_node_socket_type_from_enum(
      RNA_enum_get(op->ptr, "socket_type"));
  ListBase *sockets = (in_out == SOCK_IN) ? &ntree->inputs : &ntree->outputs;

  Main *main = CTX_data_main(C);

  bNodeSocket *iosock = ntree_get_active_interface_socket(sockets);
  if (iosock == nullptr) {
    return OPERATOR_CANCELLED;
  }

  /* The type remains the same, so we don't need to change anything. */
  if (iosock->typeinfo == socket_type) {
    return OPERATOR_FINISHED;
  }

  /* Don't handle sub-types for now. */
  nodeModifySocketType(ntree, nullptr, iosock, socket_type->idname);

  /* Need the extra update here because the loop above does not check for valid links in the node
   * group we're currently editing. */
  BKE_ntree_update_tag_interface(ntree);

  /* Deactivate sockets. */
  LISTBASE_FOREACH (bNodeSocket *, socket_iter, sockets) {
    socket_iter->flag &= ~SELECT;
  }
  /* Make the new socket active. */
  iosock->flag |= SELECT;

  ED_node_tree_propagate_change(C, main, ntree);

  WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, nullptr);

  return OPERATOR_FINISHED;
}

static bool socket_change_poll_type(void *userdata, bNodeSocketType *socket_type)
{
  /* Check if the node tree supports the socket type. */
  bNodeTreeType *ntreetype = (bNodeTreeType *)userdata;
  if (ntreetype->valid_socket_type && !ntreetype->valid_socket_type(ntreetype, socket_type)) {
    return false;
  }

  /* Only use basic socket types for this enum. */
  if (socket_type->subtype != PROP_NONE) {
    return false;
  }

  return true;
}

static const EnumPropertyItem *socket_change_type_itemf(bContext *C,
                                                        PointerRNA * /*ptr*/,
                                                        PropertyRNA * /*prop*/,
                                                        bool *r_free)
{
  if (!C) {
    return DummyRNA_NULL_items;
  }

  SpaceNode *snode = CTX_wm_space_node(C);
  if (!snode || !snode->edittree) {
    return DummyRNA_NULL_items;
  }

  return rna_node_socket_type_itemf(snode->edittree->typeinfo, socket_change_poll_type, r_free);
}

void NODE_OT_tree_socket_change_type(wmOperatorType *ot)
{
  PropertyRNA *prop;

  /* identifiers */
  ot->name = "Change Node Tree Interface Socket Type";
  ot->description = "Change the type of a socket of the current node tree";
  ot->idname = "NODE_OT_tree_socket_change_type";

  /* api callbacks */
  ot->invoke = WM_menu_invoke;
  ot->exec = ntree_socket_change_type_exec;
  ot->poll = ED_operator_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_enum(ot->srna, "in_out", rna_enum_node_socket_in_out_items, SOCK_IN, "Socket Type", "");
  prop = RNA_def_enum(ot->srna, "socket_type", DummyRNA_DEFAULT_items, 0, "Socket Type", "");
  RNA_def_enum_funcs(prop, socket_change_type_itemf);
  ot->prop = prop;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node-Tree Move Interface Socket Operator
 * \{ */

static const EnumPropertyItem move_direction_items[] = {
    {1, "UP", 0, "Up", ""},
    {2, "DOWN", 0, "Down", ""},
    {0, nullptr, 0, nullptr, nullptr},
};

static int ntree_socket_move_exec(bContext *C, wmOperator *op)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  bNodeTree *ntree = snode->edittree;
  int direction = RNA_enum_get(op->ptr, "direction");

  const eNodeSocketInOut in_out = (eNodeSocketInOut)RNA_enum_get(op->ptr, "in_out");
  ListBase *sockets = in_out == SOCK_IN ? &ntree->inputs : &ntree->outputs;

  bNodeSocket *iosock = ntree_get_active_interface_socket(sockets);

  if (iosock == nullptr) {
    return OPERATOR_CANCELLED;
  }

  switch (direction) {
    case 1: { /* up */
      bNodeSocket *before = iosock->prev;
      BLI_remlink(sockets, iosock);
      if (before) {
        BLI_insertlinkbefore(sockets, before, iosock);
      }
      else {
        BLI_addhead(sockets, iosock);
      }
      break;
    }
    case 2: { /* down */
      bNodeSocket *after = iosock->next;
      BLI_remlink(sockets, iosock);
      if (after) {
        BLI_insertlinkafter(sockets, after, iosock);
      }
      else {
        BLI_addtail(sockets, iosock);
      }
      break;
    }
  }

  BKE_ntree_update_tag_interface(ntree);
  ED_node_tree_propagate_change(C, CTX_data_main(C), ntree);

  WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, nullptr);

  return OPERATOR_FINISHED;
}

void NODE_OT_tree_socket_move(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Move Node Tree Socket";
  ot->description = "Move a socket up or down in the current node tree's sockets stack";
  ot->idname = "NODE_OT_tree_socket_move";

  /* api callbacks */
  ot->exec = ntree_socket_move_exec;
  ot->poll = ED_operator_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  RNA_def_enum(ot->srna, "direction", move_direction_items, 1, "Direction", "");
  RNA_def_enum(ot->srna, "in_out", rna_enum_node_socket_in_out_items, SOCK_IN, "Socket Type", "");
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Shader Script Update
 * \{ */

static bool node_shader_script_update_poll(bContext *C)
{
  Scene *scene = CTX_data_scene(C);
  const RenderEngineType *type = RE_engines_find(scene->r.engine);
  SpaceNode *snode = CTX_wm_space_node(C);

  /* test if we have a render engine that supports shaders scripts */
  if (!(type && type->update_script_node)) {
    return false;
  }

  /* see if we have a shader script node in context */
  bNode *node = (bNode *)CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript).data;

  if (!node && snode && snode->edittree) {
    node = nodeGetActive(snode->edittree);
  }

  if (node && node->type == SH_NODE_SCRIPT) {
    NodeShaderScript *nss = (NodeShaderScript *)node->storage;

    if (node->id || nss->filepath[0]) {
      return ED_operator_node_editable(C);
    }
  }

  /* see if we have a text datablock in context */
  Text *text = (Text *)CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
  if (text) {
    return true;
  }

  /* we don't check if text datablock is actually in use, too slow for poll */

  return false;
}

/* recursively check for script nodes in groups using this text and update */
static bool node_shader_script_update_text_recursive(RenderEngine *engine,
                                                     RenderEngineType *type,
                                                     bNodeTree *ntree,
                                                     Text *text)
{
  bool found = false;

  ntree->done = true;

  /* update each script that is using this text datablock */
  LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
    if (node->type == NODE_GROUP) {
      bNodeTree *ngroup = (bNodeTree *)node->id;
      if (ngroup && !ngroup->done) {
        found |= node_shader_script_update_text_recursive(engine, type, ngroup, text);
      }
    }
    else if (node->type == SH_NODE_SCRIPT && node->id == &text->id) {
      type->update_script_node(engine, ntree, node);
      found = true;
    }
  }

  return found;
}

static int node_shader_script_update_exec(bContext *C, wmOperator *op)
{
  Main *bmain = CTX_data_main(C);
  Scene *scene = CTX_data_scene(C);
  SpaceNode *snode = CTX_wm_space_node(C);
  PointerRNA nodeptr = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript);
  bool found = false;

  /* setup render engine */
  RenderEngineType *type = RE_engines_find(scene->r.engine);
  RenderEngine *engine = RE_engine_create(type);
  engine->reports = op->reports;

  /* get node */
  bNodeTree *ntree_base = nullptr;
  bNode *node = nullptr;
  if (nodeptr.data) {
    ntree_base = (bNodeTree *)nodeptr.owner_id;
    node = (bNode *)nodeptr.data;
  }
  else if (snode && snode->edittree) {
    ntree_base = snode->edittree;
    node = nodeGetActive(snode->edittree);
  }

  if (node) {
    /* update single node */
    type->update_script_node(engine, ntree_base, node);

    found = true;
  }
  else {
    /* update all nodes using text datablock */
    Text *text = (Text *)CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;

    if (text) {
      /* clear flags for recursion check */
      FOREACH_NODETREE_BEGIN (bmain, ntree, id) {
        if (ntree->type == NTREE_SHADER) {
          ntree->done = false;
        }
      }
      FOREACH_NODETREE_END;

      FOREACH_NODETREE_BEGIN (bmain, ntree, id) {
        if (ntree->type == NTREE_SHADER) {
          if (!ntree->done) {
            found |= node_shader_script_update_text_recursive(engine, type, ntree, text);
          }
        }
      }
      FOREACH_NODETREE_END;

      if (!found) {
        BKE_report(op->reports, RPT_INFO, "Text not used by any node, no update done");
      }
    }
  }

  RE_engine_free(engine);

  return (found) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
}

void NODE_OT_shader_script_update(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Script Node Update";
  ot->description = "Update shader script node with new sockets and options from the script";
  ot->idname = "NODE_OT_shader_script_update";

  /* api callbacks */
  ot->exec = node_shader_script_update_exec;
  ot->poll = node_shader_script_update_poll;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Node Viewer Border
 * \{ */

static void viewer_border_corner_to_backdrop(SpaceNode *snode,
                                             ARegion *region,
                                             int x,
                                             int y,
                                             int backdrop_width,
                                             int backdrop_height,
                                             float *fx,
                                             float *fy)
{
  float bufx = backdrop_width * snode->zoom;
  float bufy = backdrop_height * snode->zoom;

  *fx = (bufx > 0.0f ? (float(x) - 0.5f * region->winx - snode->xof) / bufx + 0.5f : 0.0f);
  *fy = (bufy > 0.0f ? (float(y) - 0.5f * region->winy - snode->yof) / bufy + 0.5f : 0.0f);
}

static int viewer_border_exec(bContext *C, wmOperator *op)
{
  Main *bmain = CTX_data_main(C);
  void *lock;

  ED_preview_kill_jobs(CTX_wm_manager(C), bmain);

  Image *ima = BKE_image_ensure_viewer(bmain, IMA_TYPE_COMPOSITE, "Viewer Node");
  ImBuf *ibuf = BKE_image_acquire_ibuf(ima, nullptr, &lock);

  if (ibuf) {
    ARegion *region = CTX_wm_region(C);
    SpaceNode *snode = CTX_wm_space_node(C);
    bNodeTree *btree = snode->nodetree;
    rcti rect;
    rctf rectf;

    /* get border from operator */
    WM_operator_properties_border_to_rcti(op, &rect);

    /* convert border to unified space within backdrop image */
    viewer_border_corner_to_backdrop(
        snode, region, rect.xmin, rect.ymin, ibuf->x, ibuf->y, &rectf.xmin, &rectf.ymin);

    viewer_border_corner_to_backdrop(
        snode, region, rect.xmax, rect.ymax, ibuf->x, ibuf->y, &rectf.xmax, &rectf.ymax);

    /* clamp coordinates */
    rectf.xmin = max_ff(rectf.xmin, 0.0f);
    rectf.ymin = max_ff(rectf.ymin, 0.0f);
    rectf.xmax = min_ff(rectf.xmax, 1.0f);
    rectf.ymax = min_ff(rectf.ymax, 1.0f);

    if (rectf.xmin < rectf.xmax && rectf.ymin < rectf.ymax) {
      btree->viewer_border = rectf;

      if (rectf.xmin == 0.0f && rectf.ymin == 0.0f && rectf.xmax == 1.0f && rectf.ymax == 1.0f) {
        btree->flag &= ~NTREE_VIEWER_BORDER;
      }
      else {
        btree->flag |= NTREE_VIEWER_BORDER;
      }

      ED_node_tree_propagate_change(C, bmain, btree);
      WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, nullptr);
    }
    else {
      btree->flag &= ~NTREE_VIEWER_BORDER;
    }
  }

  BKE_image_release_ibuf(ima, ibuf, lock);

  return OPERATOR_FINISHED;
}

void NODE_OT_viewer_border(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Viewer Region";
  ot->description = "Set the boundaries for viewer operations";
  ot->idname = "NODE_OT_viewer_border";

  /* api callbacks */
  ot->invoke = WM_gesture_box_invoke;
  ot->exec = viewer_border_exec;
  ot->modal = WM_gesture_box_modal;
  ot->cancel = WM_gesture_box_cancel;
  ot->poll = composite_node_active;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

  /* properties */
  WM_operator_properties_gesture_box(ot);
}

static int clear_viewer_border_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  bNodeTree *btree = snode->nodetree;

  btree->flag &= ~NTREE_VIEWER_BORDER;
  ED_node_tree_propagate_change(C, CTX_data_main(C), btree);
  WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, nullptr);

  return OPERATOR_FINISHED;
}

void NODE_OT_clear_viewer_border(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Clear Viewer Region";
  ot->description = "Clear the boundaries for viewer operations";
  ot->idname = "NODE_OT_clear_viewer_border";

  /* api callbacks */
  ot->exec = clear_viewer_border_exec;
  ot->poll = composite_node_active;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Cryptomatte Add Socket
 * \{ */

static int node_cryptomatte_add_socket_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  PointerRNA ptr = CTX_data_pointer_get(C, "node");
  bNodeTree *ntree = nullptr;
  bNode *node = nullptr;

  if (ptr.data) {
    node = (bNode *)ptr.data;
    ntree = (bNodeTree *)ptr.owner_id;
  }
  else if (snode && snode->edittree) {
    ntree = snode->edittree;
    node = nodeGetActive(snode->edittree);
  }

  if (!node || node->type != CMP_NODE_CRYPTOMATTE_LEGACY) {
    return OPERATOR_CANCELLED;
  }

  ntreeCompositCryptomatteAddSocket(ntree, node);

  ED_node_tree_propagate_change(C, CTX_data_main(C), ntree);

  return OPERATOR_FINISHED;
}

void NODE_OT_cryptomatte_layer_add(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Add Cryptomatte Socket";
  ot->description = "Add a new input layer to a Cryptomatte node";
  ot->idname = "NODE_OT_cryptomatte_layer_add";

  /* callbacks */
  ot->exec = node_cryptomatte_add_socket_exec;
  ot->poll = composite_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Cryptomatte Remove Socket
 * \{ */

static int node_cryptomatte_remove_socket_exec(bContext *C, wmOperator * /*op*/)
{
  SpaceNode *snode = CTX_wm_space_node(C);
  PointerRNA ptr = CTX_data_pointer_get(C, "node");
  bNodeTree *ntree = nullptr;
  bNode *node = nullptr;

  if (ptr.data) {
    node = (bNode *)ptr.data;
    ntree = (bNodeTree *)ptr.owner_id;
  }
  else if (snode && snode->edittree) {
    ntree = snode->edittree;
    node = nodeGetActive(snode->edittree);
  }

  if (!node || node->type != CMP_NODE_CRYPTOMATTE_LEGACY) {
    return OPERATOR_CANCELLED;
  }

  if (!ntreeCompositCryptomatteRemoveSocket(ntree, node)) {
    return OPERATOR_CANCELLED;
  }

  ED_node_tree_propagate_change(C, CTX_data_main(C), ntree);

  return OPERATOR_FINISHED;
}

void NODE_OT_cryptomatte_layer_remove(wmOperatorType *ot)
{
  /* identifiers */
  ot->name = "Remove Cryptomatte Socket";
  ot->description = "Remove layer from a Cryptomatte node";
  ot->idname = "NODE_OT_cryptomatte_layer_remove";

  /* callbacks */
  ot->exec = node_cryptomatte_remove_socket_exec;
  ot->poll = composite_node_editable;

  /* flags */
  ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}

/** \} */

}  // namespace blender::ed::space_node