window_w32.cpp 90.7 KB
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
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"

#ifdef HAVE_WIN32UI

#include <opencv2/core/utils/logger.hpp>
#include <opencv2/core/utils/trace.hpp>

#include "backend.hpp"

using namespace cv;

#include <windowsx.h> // required for GET_X_LPARAM() and GET_Y_LPARAM() macros

#ifdef __GNUC__
#  pragma GCC diagnostic ignored "-Wmissing-declarations"
#endif

#if (_WIN32_IE < 0x0500)
#pragma message("WARNING: Win32 UI needs to be compiled with _WIN32_IE >= 0x0500 (_WIN32_IE_IE50)")
#define _WIN32_IE 0x0500
#endif

#include <commctrl.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#ifdef HAVE_OPENGL
#include <memory>
#include <algorithm>
#include <vector>
#include <functional>
#include <GL/gl.h>
#include "opencv2/core/opengl.hpp"
#endif

static const char* trackbar_text =
"                                                                                             ";

#if defined _M_X64 || defined __x86_64 || defined _M_ARM64

#define icvGetWindowLongPtr GetWindowLongPtr
#define icvSetWindowLongPtr(hwnd, id, ptr) SetWindowLongPtr(hwnd, id, (LONG_PTR)(ptr))
#define icvGetClassLongPtr  GetClassLongPtr

#define CV_USERDATA GWLP_USERDATA
#define CV_WNDPROC GWLP_WNDPROC
#define CV_HCURSOR GCLP_HCURSOR
#define CV_HBRBACKGROUND GCLP_HBRBACKGROUND

#else

#define icvGetWindowLongPtr GetWindowLong
#define icvSetWindowLongPtr(hwnd, id, ptr) SetWindowLong(hwnd, id, (size_t)ptr)
#define icvGetClassLongPtr GetClassLong

#define CV_USERDATA GWL_USERDATA
#define CV_WNDPROC GWL_WNDPROC
#define CV_HCURSOR GCL_HCURSOR
#define CV_HBRBACKGROUND GCL_HBRBACKGROUND

#endif

#ifndef WM_MOUSEHWHEEL
    #define WM_MOUSEHWHEEL 0x020E
#endif

#if defined(__MINGW32__) || defined(__MINGW64__)
static inline void mingw_strcpy_s(char *dest, size_t destsz, const char *src){
    strcpy(dest, src);
}

static inline void mingw_strcat_s(char *dest, size_t destsz, const char *src){
    strcat(dest, src);
}

#define strcpy_s mingw_strcpy_s
#define strcat_s mingw_strcat_s
#endif

static void FillBitmapInfo(BITMAPINFO* bmi, int width, int height, int bpp, int origin)
{
    CV_Assert(bmi && width >= 0 && height >= 0 && (bpp == 8 || bpp == 24 || bpp == 32));

    BITMAPINFOHEADER* bmih = &(bmi->bmiHeader);

    memset(bmih, 0, sizeof(*bmih));
    bmih->biSize = sizeof(BITMAPINFOHEADER);
    bmih->biWidth = width;
    bmih->biHeight = origin ? abs(height) : -abs(height);
    bmih->biPlanes = 1;
    bmih->biBitCount = (unsigned short)bpp;
    bmih->biCompression = BI_RGB;

    if (bpp == 8)
    {
        RGBQUAD* palette = bmi->bmiColors;
        int i;
        for (i = 0; i < 256; i++)
        {
            palette[i].rgbBlue = palette[i].rgbGreen = palette[i].rgbRed = (BYTE)i;
            palette[i].rgbReserved = 0;
        }
    }
}

struct CvWindow;

struct CvTrackbar : public std::enable_shared_from_this<CvTrackbar>
{
    CvTrackbar(CvWindow& window, const std::string& name_)
        : signature(CV_TRACKBAR_MAGIC_VAL)
        , name(name_)
        , parent(&window)
    {
        // nothing
    }
    ~CvTrackbar()
    {
        signature = -1;
    }

    int signature;
    HWND hwnd = 0;
    std::string name;
    CvWindow* parent;  // TODO weak_ptr
    HWND buddy = 0;
    int* data = nullptr;
    int pos = 0;
    int maxval = 0;
    int minval = 0;
    void (*notify)(int) = nullptr;  // deprecated
    void (*notify2)(int, void*) = nullptr;  // deprecated
    TrackbarCallback onChangeCallback = nullptr;
    void* userdata = nullptr;
    int id = -1;
};


struct CvWindow : public std::enable_shared_from_this<CvWindow>
{
    CvWindow(const std::string& name_)
        : signature(CV_WINDOW_MAGIC_VAL)
        , name(name_)
    {
        // nothing
    }

    ~CvWindow()
    {
        signature = -1;
    }

    void destroy();

    int signature;
    cv::Mutex mutex;
    HWND hwnd = 0;
    std::string name;
    HWND frame = 0;

    HDC dc = 0;
    HGDIOBJ image = 0;
    int last_key = 0;
    int flags = 0;
    int status = 0;//0 normal, 1 fullscreen (YV)

    CvMouseCallback on_mouse = nullptr;
    void* on_mouse_param = nullptr;

    struct
    {
        HWND toolbar = 0;
        int pos = 0;
        int rows = 0;
        WNDPROC toolBarProc = nullptr;
        std::vector< std::shared_ptr<CvTrackbar> > trackbars;
    }
    toolbar;

    int width = -1;
    int height = -1;

    // OpenGL support

#ifdef HAVE_OPENGL
    bool useGl = false;
    HGLRC hGLRC = 0;

    CvOpenGlDrawCallback glDrawCallback = nullptr;
    void* glDrawData = nullptr;
#endif
};

#define HG_BUDDY_WIDTH  130

#ifndef TBIF_SIZE
    #define TBIF_SIZE  0x40
#endif

#ifndef TB_SETBUTTONINFO
    #define TB_SETBUTTONINFO (WM_USER + 66)
#endif

#ifndef TBM_GETTOOLTIPS
    #define TBM_GETTOOLTIPS  (WM_USER + 30)
#endif

static
std::vector< std::shared_ptr<CvWindow> >& getWindowsList()
{
    static std::vector< std::shared_ptr<CvWindow> > g_windows;
    return g_windows;
}


// Mutex must be locked
static
std::shared_ptr<CvWindow> icvFindWindowByName(const std::string& name)
{
    auto& g_windows = getWindowsList();
    for (auto it = g_windows.begin(); it != g_windows.end(); ++it)
    {
        auto window = *it;
        if (!window)
            continue;
        if (window->name == name)
            return window;
    }
    return std::shared_ptr<CvWindow>();
}

static inline
std::shared_ptr<CvWindow> icvFindWindowByName(const char* name)
{
    CV_Assert(name);
    return icvFindWindowByName(std::string(name));
}

// Mutex must be locked
static
std::shared_ptr<CvWindow> icvFindWindowByHandle(HWND hwnd)
{
    auto& g_windows = getWindowsList();
    for (auto it = g_windows.begin(); it != g_windows.end(); ++it)
    {
        auto window = *it;
        if (!window)
            continue;
        if (window->hwnd == hwnd || window->frame == hwnd)
            return window;
    }
    return std::shared_ptr<CvWindow>();
}


static LRESULT CALLBACK HighGUIProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK MainWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static void icvUpdateWindowPos(CvWindow& window);

typedef int (CV_CDECL * CvWin32WindowCallback)(HWND, UINT, WPARAM, LPARAM, int*);
static CvWin32WindowCallback hg_on_preprocess = 0, hg_on_postprocess = 0;
static HINSTANCE hg_hinstance = 0;

static const char* const highGUIclassName = "HighGUI class";
static const char* const mainHighGUIclassName = "Main HighGUI class";

static void icvCleanupHighgui()
{
    cvDestroyAllWindows();
    UnregisterClass(highGUIclassName, hg_hinstance);
    UnregisterClass(mainHighGUIclassName, hg_hinstance);
}

CV_IMPL int cvInitSystem(int, char**)
{
    static int wasInitialized = 0;

    // check initialization status
    if (!wasInitialized)
    {
        (void)getWindowMutex();  // force mutex initialization
        (void)getWindowsList();  // Initialize the storage

        // Register the class
        WNDCLASS wndc;
        wndc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
        wndc.lpfnWndProc = WindowProc;
        wndc.cbClsExtra = 0;
        wndc.cbWndExtra = 0;
        wndc.hInstance = hg_hinstance;
        wndc.lpszClassName = highGUIclassName;
        wndc.lpszMenuName = highGUIclassName;
        wndc.hIcon = LoadIcon(0, IDI_APPLICATION);
        wndc.hCursor = (HCURSOR)LoadCursor(0, (LPSTR)(size_t)IDC_CROSS);
        wndc.hbrBackground = (HBRUSH)GetStockObject(DKGRAY_BRUSH);

        RegisterClass(&wndc);

        wndc.lpszClassName = mainHighGUIclassName;
        wndc.lpszMenuName = mainHighGUIclassName;
        wndc.hbrBackground = (HBRUSH)GetStockObject(DKGRAY_BRUSH);
        wndc.lpfnWndProc = MainWindowProc;

        RegisterClass(&wndc);
        atexit(icvCleanupHighgui);

        wasInitialized = 1;
    }

    setlocale(LC_NUMERIC,"C");  // FIXIT must be removed

    return 0;
}

CV_IMPL int cvStartWindowThread(){
    return 0;
}


static std::shared_ptr<CvWindow> icvWindowByHWND(HWND hwnd)
{
    AutoLock lock(getWindowMutex());
    CvWindow* window = (CvWindow*)icvGetWindowLongPtr(hwnd, CV_USERDATA);
    window = window != 0 &&
           window->signature == CV_WINDOW_MAGIC_VAL ? window : 0;
    if (window)
    {
        return window->shared_from_this();
    }
    else
    {
        return std::shared_ptr<CvWindow>();
    }
}


static std::shared_ptr<CvTrackbar> icvTrackbarByHWND(HWND hwnd)
{
    AutoLock lock(getWindowMutex());
    CvTrackbar* trackbar = (CvTrackbar*)icvGetWindowLongPtr(hwnd, CV_USERDATA);
    trackbar = trackbar != 0 && trackbar->signature == CV_TRACKBAR_MAGIC_VAL &&
           trackbar->hwnd == hwnd ? trackbar : 0;
    if (trackbar)
    {
        return trackbar->shared_from_this();
    }
    else
    {
        return std::shared_ptr<CvTrackbar>();
    }
}


static const char* const icvWindowPosRootKey = "Software\\OpenCV\\HighGUI\\Windows\\";

// Window positions saving/loading added by Philip Gruebele.
//<a href="mailto:pgruebele@cox.net">pgruebele@cox.net</a>
// Restores the window position from the registry saved position.
static void
icvLoadWindowPos(const char* name, CvRect& rect)
{
    HKEY hkey;
    char szKey[1024];
    strcpy_s(szKey, 1024, icvWindowPosRootKey);
    strcat_s(szKey, 1024, name);

    rect.x = rect.y = CW_USEDEFAULT;
    rect.width = rect.height = 320;

    if (RegOpenKeyEx(HKEY_CURRENT_USER,szKey,0,KEY_QUERY_VALUE,&hkey) == ERROR_SUCCESS)
    {
        // Yes we are installed.
        DWORD dwType = 0;
        DWORD dwSize = sizeof(int);

        RegQueryValueEx(hkey, "Left", NULL, &dwType, (BYTE*)&rect.x, &dwSize);
        RegQueryValueEx(hkey, "Top", NULL, &dwType, (BYTE*)&rect.y, &dwSize);
        RegQueryValueEx(hkey, "Width", NULL, &dwType, (BYTE*)&rect.width, &dwSize);
        RegQueryValueEx(hkey, "Height", NULL, &dwType, (BYTE*)&rect.height, &dwSize);

        // Snap rect into closest monitor in case it falls outside it. // Adi Shavit
        // set WIN32 RECT to be the loaded size
        POINT tl_w32 = { rect.x, rect.y };
        POINT tr_w32 = { rect.x + rect.width, rect.y };

        // find monitor containing top-left and top-right corners, or NULL
        HMONITOR hMonitor_l = MonitorFromPoint(tl_w32, MONITOR_DEFAULTTONULL);
        HMONITOR hMonitor_r = MonitorFromPoint(tr_w32, MONITOR_DEFAULTTONULL);

        // if neither are contained - the move window to origin of closest.
        if (NULL == hMonitor_l && NULL == hMonitor_r)
        {
           // find monitor nearest to top-left corner
           HMONITOR hMonitor_closest = MonitorFromPoint(tl_w32, MONITOR_DEFAULTTONEAREST);

           // get coordinates of nearest monitor
           MONITORINFO mi;
           mi.cbSize = sizeof(mi);
           GetMonitorInfo(hMonitor_closest, &mi);

           rect.x = mi.rcWork.left;
           rect.y = mi.rcWork.top;
        }

        if (rect.width != (int)CW_USEDEFAULT && (rect.width < 0 || rect.width > 3000))
           rect.width = 100;
        if (rect.height != (int)CW_USEDEFAULT && (rect.height < 0 || rect.height > 3000))
           rect.height = 100;

        RegCloseKey(hkey);
    }
}


// Window positions saving/loading added by Philip Gruebele.
//<a href="mailto:pgruebele@cox.net">pgruebele@cox.net</a>
// philipg.  Saves the window position in the registry
static void
icvSaveWindowPos(const char* name, CvRect rect)
{
    static const DWORD MAX_RECORD_COUNT = 100;
    HKEY hkey;
    char szKey[1024];
    char rootKey[1024];
    strcpy_s(szKey, 1024, icvWindowPosRootKey);
    strcat_s(szKey, 1024, name);

    if (RegOpenKeyEx(HKEY_CURRENT_USER,szKey,0,KEY_READ,&hkey) != ERROR_SUCCESS)
    {
        HKEY hroot;
        DWORD count = 0;
        FILETIME oldestTime = { UINT_MAX, UINT_MAX };
        char oldestKey[1024];
        char currentKey[1024];

        strcpy_s(rootKey, 1024, icvWindowPosRootKey);
        rootKey[strlen(rootKey)-1] = '\0';
        if (RegCreateKeyEx(HKEY_CURRENT_USER, rootKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ+KEY_WRITE, 0, &hroot, NULL) != ERROR_SUCCESS)
            //RegOpenKeyEx(HKEY_CURRENT_USER,rootKey,0,KEY_READ,&hroot) != ERROR_SUCCESS)
            return;

        for(;;)
        {
            DWORD csize = sizeof(currentKey);
            FILETIME accesstime = { 0, 0 };
            LONG code = RegEnumKeyEx(hroot, count, currentKey, &csize, NULL, NULL, NULL, &accesstime);
            if (code != ERROR_SUCCESS && code != ERROR_MORE_DATA)
                break;
            count++;
            if (oldestTime.dwHighDateTime > accesstime.dwHighDateTime ||
                (oldestTime.dwHighDateTime == accesstime.dwHighDateTime &&
                oldestTime.dwLowDateTime > accesstime.dwLowDateTime))
            {
                oldestTime = accesstime;
                strcpy_s(oldestKey, 1024, currentKey);
            }
        }

        if (count >= MAX_RECORD_COUNT)
            RegDeleteKey(hroot, oldestKey);
        RegCloseKey(hroot);

        if (RegCreateKeyEx(HKEY_CURRENT_USER,szKey,0,NULL,REG_OPTION_NON_VOLATILE, KEY_WRITE, 0, &hkey, NULL) != ERROR_SUCCESS)
            return;
    }
    else
    {
        RegCloseKey(hkey);
        if (RegOpenKeyEx(HKEY_CURRENT_USER,szKey,0,KEY_WRITE,&hkey) != ERROR_SUCCESS)
            return;
    }

    RegSetValueEx(hkey, "Left", 0, REG_DWORD, (BYTE*)&rect.x, sizeof(rect.x));
    RegSetValueEx(hkey, "Top", 0, REG_DWORD, (BYTE*)&rect.y, sizeof(rect.y));
    RegSetValueEx(hkey, "Width", 0, REG_DWORD, (BYTE*)&rect.width, sizeof(rect.width));
    RegSetValueEx(hkey, "Height", 0, REG_DWORD, (BYTE*)&rect.height, sizeof(rect.height));
    RegCloseKey(hkey);
}

static Rect getImageRect_(CvWindow& window);

CvRect cvGetWindowRect_W32(const char* name)
{
    CV_FUNCNAME("cvGetWindowRect_W32");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    Rect r = getImageRect_(*window);

    CvRect result = cvRect(r.x, r.y, r.width, r.height);
    return result;
}

static Rect getImageRect_(CvWindow& window)
{
    RECT rect = { 0 };
    GetClientRect(window.hwnd, &rect);
    POINT pt = {rect.left, rect.top};
    ClientToScreen(window.hwnd, &pt);
    Rect result(pt.x, pt.y, rect.right - rect.left, rect.bottom - rect.top);
    return result;
}

double cvGetModeWindow_W32(const char* name)//YV
{
    CV_FUNCNAME("cvGetModeWindow_W32");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    return window->status;
}

static bool setModeWindow_(CvWindow& window, int mode);

void cvSetModeWindow_W32(const char* name, double prop_value)//Yannick Verdie
{
    CV_FUNCNAME("cvSetModeWindow_W32");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    if (!window)
         CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    (void)setModeWindow_(*window, (int)prop_value);
}

static bool setModeWindow_(CvWindow& window, int mode)
{
    if (window.flags & CV_WINDOW_AUTOSIZE)//if the flag CV_WINDOW_AUTOSIZE is set
        return false;

    if (window.status == mode)
        return true;

    {
        DWORD dwStyle = (DWORD)GetWindowLongPtr(window.frame, GWL_STYLE);
        CvRect position;

        if (window.status == CV_WINDOW_FULLSCREEN && mode == CV_WINDOW_NORMAL)
        {
            icvLoadWindowPos(window.name.c_str(), position);
            SetWindowLongPtr(window.frame, GWL_STYLE, dwStyle | WS_CAPTION | WS_THICKFRAME);

            SetWindowPos(window.frame, HWND_TOP, position.x, position.y , position.width,position.height, SWP_NOZORDER | SWP_FRAMECHANGED);
            window.status=CV_WINDOW_NORMAL;

            return true;
        }

        if (window.status == CV_WINDOW_NORMAL && mode == CV_WINDOW_FULLSCREEN)
        {
            //save dimension
            RECT rect = { 0 };
            GetWindowRect(window.frame, &rect);
            CvRect rectCV = cvRect(rect.left, rect.top,rect.right - rect.left, rect.bottom - rect.top);
            icvSaveWindowPos(window.name.c_str(), rectCV);

            //Look at coordinate for fullscreen
            HMONITOR hMonitor;
            MONITORINFO mi;
            hMonitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST);

            mi.cbSize = sizeof(mi);
            GetMonitorInfo(hMonitor, &mi);

            //fullscreen
            position.x=mi.rcMonitor.left;position.y=mi.rcMonitor.top;
            position.width=mi.rcMonitor.right - mi.rcMonitor.left;position.height=mi.rcMonitor.bottom - mi.rcMonitor.top;
            SetWindowLongPtr(window.frame, GWL_STYLE, dwStyle & ~WS_CAPTION & ~WS_THICKFRAME);

            SetWindowPos(window.frame, HWND_TOP, position.x, position.y , position.width,position.height, SWP_NOZORDER | SWP_FRAMECHANGED);
            window.status=CV_WINDOW_FULLSCREEN;

            return true;
        }
    }

    return false;
}

static double getPropTopmost_(CvWindow& window);

double cvGetPropTopmost_W32(const char* name)
{
    CV_Assert(name);

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error(Error::StsNullPtr, "NULL window");

    return getPropTopmost_(*window);
}

static double getPropTopmost_(CvWindow& window)
{
    LONG style = GetWindowLongA(window.frame, GWL_EXSTYLE); // -20
    if (!style)
    {
        std::ostringstream errorMsg;
        errorMsg << "window(" << window.name << "): failed to retrieve extended window style using GetWindowLongA(); error code: " << GetLastError();
        CV_Error(Error::StsError, errorMsg.str());
    }

    bool result = (style & WS_EX_TOPMOST) == WS_EX_TOPMOST;
    return result ? 1.0 : 0.0;
}

static bool setPropTopmost_(CvWindow& window, bool topmost);

void cvSetPropTopmost_W32(const char* name, const bool topmost)
{
    CV_Assert(name);

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error(Error::StsNullPtr, "NULL window");

    (void)setPropTopmost_(*window, topmost);
}

static bool setPropTopmost_(CvWindow& window, bool topmost)
{
    HWND flag    = topmost ? HWND_TOPMOST : HWND_TOP;
    BOOL success = SetWindowPos(window.frame, flag, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

    if (!success)
    {
        std::ostringstream errorMsg;
        errorMsg << "window(" << window.name << "): error reported by SetWindowPos(" << (topmost ? "HWND_TOPMOST" : "HWND_TOP") << "), error code:  " << GetLastError();
        CV_Error(Error::StsError, errorMsg.str());
        return false;
    }
    return true;
}

static double getPropVsync_(CvWindow& window);

double cvGetPropVsync_W32(const char* name)
{
#ifndef HAVE_OPENGL
    CV_UNUSED(name);
    CV_Error(Error::OpenGlNotSupported, "Library was built without OpenGL support");
#else
    if (!name)
        CV_Error(Error::StsNullPtr, "'name' argument must not be NULL");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsBadArg, ("there is no window named '%s'", name));

    double result = getPropVsync_(*window);
    return cvIsNaN(result) ? -1.0 : result;
#endif
}

static double getPropVsync_(CvWindow& window)
{
#ifndef HAVE_OPENGL
    CV_UNUSED(window);
    CV_Error(Error::OpenGlNotSupported, "Library was built without OpenGL support");
#else
    // https://www.khronos.org/opengl/wiki/Swap_Interval
    // https://www.khronos.org/registry/OpenGL/extensions/EXT/WGL_EXT_extensions_string.txt
    // https://www.khronos.org/registry/OpenGL/extensions/EXT/WGL_EXT_swap_control.txt

    if (!wglMakeCurrent(window.dc, window.hGLRC))
        CV_Error(Error::OpenGlApiCallError, "Can't Activate The GL Rendering Context");

    typedef const char* (APIENTRY* PFNWGLGETEXTENSIONSSTRINGEXTPROC)(void);
    PFNWGLGETEXTENSIONSSTRINGEXTPROC wglGetExtensionsString = NULL;
    wglGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wglGetProcAddress("wglGetExtensionsStringEXT");
    if (wglGetExtensionsString == NULL)
        return std::numeric_limits<double>::quiet_NaN(); // wglGetProcAddress failed to get wglGetExtensionsStringEXT

    const char* wgl_extensions = wglGetExtensionsString();
    if (wgl_extensions == NULL)
        return std::numeric_limits<double>::quiet_NaN(); // Can't get WGL extensions string

    if (strstr(wgl_extensions, "WGL_EXT_swap_control") == NULL)
        return std::numeric_limits<double>::quiet_NaN(); // WGL extensions don't contain WGL_EXT_swap_control

    typedef int (APIENTRY* PFNWGLGETSWAPINTERVALPROC)(void);
    PFNWGLGETSWAPINTERVALPROC wglGetSwapInterval = 0;
    wglGetSwapInterval = (PFNWGLGETSWAPINTERVALPROC)wglGetProcAddress("wglGetSwapIntervalEXT");
    if (wglGetSwapInterval == NULL)
        return std::numeric_limits<double>::quiet_NaN(); // wglGetProcAddress failed to get wglGetSwapIntervalEXT

    return wglGetSwapInterval();
#endif
}

static bool setPropVsync_(CvWindow& window, bool enable_vsync);

void cvSetPropVsync_W32(const char* name, const bool enable_vsync)
{
#ifndef HAVE_OPENGL
    CV_UNUSED(name);
    CV_UNUSED(enable_vsync);
    CV_Error(Error::OpenGlNotSupported, "Library was built without OpenGL support");
#else
    if (!name)
        CV_Error(Error::StsNullPtr, "'name' argument must not be NULL");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsBadArg, ("there is no window named '%s'", name));

    (void)setPropVsync_(*window, enable_vsync);
#endif
}

static bool setPropVsync_(CvWindow& window, bool enable_vsync)
{
#ifndef HAVE_OPENGL
    CV_UNUSED(window);
    CV_UNUSED(enable_vsync);
    CV_Error(Error::OpenGlNotSupported, "Library was built without OpenGL support");
#else
    if (!wglMakeCurrent(window.dc, window.hGLRC))
        CV_Error(Error::OpenGlApiCallError, "Can't Activate The GL Rendering Context");

    typedef const char* (APIENTRY* PFNWGLGETEXTENSIONSSTRINGEXTPROC)(void);
    PFNWGLGETEXTENSIONSSTRINGEXTPROC wglGetExtensionsString = NULL;
    wglGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wglGetProcAddress("wglGetExtensionsStringEXT");
    if (wglGetExtensionsString == NULL)
        CV_Error(Error::OpenGlApiCallError, "wglGetProcAddress failed to get wglGetExtensionsStringEXT");

    const char* wgl_extensions = wglGetExtensionsString();
    if (wgl_extensions == NULL)
        CV_Error(Error::OpenGlApiCallError, "Can't get WGL extensions string");

    if (strstr(wgl_extensions, "WGL_EXT_swap_control") == NULL)
        CV_Error(Error::OpenGlApiCallError, "WGL extensions don't contain WGL_EXT_swap_control");

    typedef BOOL(APIENTRY* PFNWGLSWAPINTERVALPROC)(int);
    PFNWGLSWAPINTERVALPROC wglSwapInterval = 0;
    wglSwapInterval = (PFNWGLSWAPINTERVALPROC)wglGetProcAddress("wglSwapIntervalEXT");
    if (wglSwapInterval == NULL)
        CV_Error(Error::OpenGlApiCallError, "wglGetProcAddress failed to get wglSwapIntervalEXT");

    wglSwapInterval(enable_vsync);
    return true;
#endif
}

void setWindowTitle_W32(const std::string& name, const std::string& title)
{
    auto window = icvFindWindowByName(name);

    if (!window)
    {
        namedWindow(name);
        window = icvFindWindowByName(name);
    }

    if (!window)
        CV_Error(Error::StsNullPtr, "NULL window");

    if (!SetWindowText(window->frame, title.c_str()))
        CV_Error_(Error::StsError, ("Failed to set \"%s\" window title to \"%s\"", name.c_str(), title.c_str()));
}

double cvGetPropWindowAutoSize_W32(const char* name)
{
    double result = -1;

    CV_FUNCNAME("cvSetCloseCallback");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    result = window->flags & CV_WINDOW_AUTOSIZE;

    return result;
}

double cvGetRatioWindow_W32(const char* name)
{
    double result = -1;

    CV_FUNCNAME("cvGetRatioWindow_W32");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    result = static_cast<double>(window->width) / window->height;

    return result;
}

double cvGetOpenGlProp_W32(const char* name)
{
    double result = -1;

#ifdef HAVE_OPENGL
    CV_FUNCNAME("cvGetOpenGlProp_W32");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    if (!window)
        return -1;

    result = window->useGl;
#endif

    CV_UNUSED(name);

    return result;
}

double cvGetPropVisible_W32(const char* name)
{
    double result = -1;

    CV_FUNCNAME("cvGetPropVisible_W32");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    result = (bool)window ? 1.0 : 0.0;

    return result;
}


// OpenGL support

#ifdef HAVE_OPENGL

namespace
{
    void createGlContext(HWND hWnd, HDC& hGLDC, HGLRC& hGLRC, bool& useGl)
    {
        CV_FUNCNAME("createGlContext");

        AutoLock lock(getWindowMutex());

        useGl = false;

        int PixelFormat;

        static PIXELFORMATDESCRIPTOR pfd =
        {
            sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
            1,                             // Version Number
            PFD_DRAW_TO_WINDOW |           // Format Must Support Window
            PFD_SUPPORT_OPENGL |           // Format Must Support OpenGL
            PFD_DOUBLEBUFFER,              // Must Support Double Buffering
            PFD_TYPE_RGBA,                 // Request An RGBA Format
            32,                            // Select Our Color Depth
            0, 0, 0, 0, 0, 0,              // Color Bits Ignored
            0,                             // No Alpha Buffer
            0,                             // Shift Bit Ignored
            0,                             // No Accumulation Buffer
            0, 0, 0, 0,                    // Accumulation Bits Ignored
            32,                            // 32 Bit Z-Buffer (Depth Buffer)
            0,                             // No Stencil Buffer
            0,                             // No Auxiliary Buffer
            PFD_MAIN_PLANE,                // Main Drawing Layer
            0,                             // Reserved
            0, 0, 0                        // Layer Masks Ignored
        };

        hGLDC = GetDC(hWnd);
        if (!hGLDC)
            CV_Error(Error::OpenGlApiCallError, "Can't Create A GL Device Context");

        PixelFormat = ChoosePixelFormat(hGLDC, &pfd);
        if (!PixelFormat)
            CV_Error(Error::OpenGlApiCallError, "Can't Find A Suitable PixelFormat");

        if (!SetPixelFormat(hGLDC, PixelFormat, &pfd))
            CV_Error(Error::OpenGlApiCallError, "Can't Set The PixelFormat");

        hGLRC = wglCreateContext(hGLDC);
        if (!hGLRC)
            CV_Error(Error::OpenGlApiCallError, "Can't Create A GL Rendering Context");

        if (!wglMakeCurrent(hGLDC, hGLRC))
            CV_Error(Error::OpenGlApiCallError, "Can't Activate The GL Rendering Context");

        useGl = true;
    }

    void releaseGlContext(CvWindow& window)
    {
        //CV_FUNCNAME("releaseGlContext");

        AutoLock lock(getWindowMutex());

        if (window.hGLRC)
        {
            wglDeleteContext(window.hGLRC);
            window.hGLRC = NULL;
        }

        if (window.dc)
        {
            ReleaseDC(window.hwnd, window.dc);
            window.dc = NULL;
        }

        window.useGl = false;
    }

    void drawGl(CvWindow& window)
    {
        CV_FUNCNAME("drawGl");

        AutoLock lock(getWindowMutex());

        if (!wglMakeCurrent(window.dc, window.hGLRC))
            CV_Error(Error::OpenGlApiCallError, "Can't Activate The GL Rendering Context");

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        if (window.glDrawCallback)
            window.glDrawCallback(window.glDrawData);

        if (!SwapBuffers(window.dc))
            CV_Error(Error::OpenGlApiCallError, "Can't swap OpenGL buffers");
    }

    void resizeGl(CvWindow& window)
    {
        CV_FUNCNAME("resizeGl");

        AutoLock lock(getWindowMutex());

        if (!wglMakeCurrent(window.dc, window.hGLRC))
            CV_Error(Error::OpenGlApiCallError, "Can't Activate The GL Rendering Context");

        glViewport(0, 0, window.width, window.height);
    }
}

#endif // HAVE_OPENGL

static std::shared_ptr<CvWindow> namedWindow_(const std::string& name, int flags);

CV_IMPL int cvNamedWindow(const char* name, int flags)
{
    CV_FUNCNAME("cvNamedWindow");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    // Check the name in the storage
    auto window = icvFindWindowByName(name);
    if (window)
    {
        return 1;
    }

    window = namedWindow_(name, flags);
    return (bool)window;
}

static std::shared_ptr<CvWindow> namedWindow_(const std::string& name, int flags)
{
    AutoLock lock(getWindowMutex());

    cvInitSystem(0,0);

    HWND hWnd, mainhWnd;
    DWORD defStyle = WS_VISIBLE | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU;
#ifdef HAVE_OPENGL
    bool useGl;
    HDC hGLDC;
    HGLRC hGLRC;
#endif

    CvRect rect;
    icvLoadWindowPos(name.c_str(), rect);

    if (!(flags & CV_WINDOW_AUTOSIZE))//YV add border in order to resize the window
       defStyle |= WS_SIZEBOX;

#ifdef HAVE_OPENGL
    if (flags & CV_WINDOW_OPENGL)
        defStyle |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
#endif

    mainhWnd = CreateWindow(mainHighGUIclassName, name.c_str(), defStyle | WS_OVERLAPPED,
                             rect.x, rect.y, rect.width, rect.height, 0, 0, hg_hinstance, 0);
    if (!mainhWnd)
        CV_Error_(Error::StsError, ("Frame window can not be created: '%s'", name.c_str()));

    ShowWindow(mainhWnd, SW_SHOW);

    //YV- remove one border by changing the style
    hWnd = CreateWindow(highGUIclassName, "", (defStyle & ~WS_SIZEBOX) | WS_CHILD, CW_USEDEFAULT, 0, rect.width, rect.height, mainhWnd, 0, hg_hinstance, 0);
    if (!hWnd)
        CV_Error(Error::StsError, "Frame window can not be created");

#ifndef HAVE_OPENGL
    if (flags & CV_WINDOW_OPENGL)
        CV_Error(Error::OpenGlNotSupported, "Library was built without OpenGL support");
#else
    useGl = false;
    hGLDC = 0;
    hGLRC = 0;

    if (flags & CV_WINDOW_OPENGL)
        createGlContext(hWnd, hGLDC, hGLRC, useGl);
#endif

    ShowWindow(hWnd, SW_SHOW);

    auto window = std::make_shared<CvWindow>(name);

    window->hwnd = hWnd;
    window->frame = mainhWnd;
    window->flags = flags;
    window->image = 0;

#ifndef HAVE_OPENGL
    window->dc = CreateCompatibleDC(0);
#else
    if (!useGl)
    {
        window->dc = CreateCompatibleDC(0);
        window->hGLRC = 0;
        window->useGl = false;
    }
    else
    {
        window->dc = hGLDC;
        window->hGLRC = hGLRC;
        window->useGl = true;
    }

    window->glDrawCallback = 0;
    window->glDrawData = 0;
#endif

    window->last_key = 0;
    window->status = CV_WINDOW_NORMAL;//YV

    window->on_mouse = 0;
    window->on_mouse_param = 0;

    icvSetWindowLongPtr(hWnd, CV_USERDATA, window.get());
    icvSetWindowLongPtr(mainhWnd, CV_USERDATA, window.get());

    auto& g_windows = getWindowsList();
    g_windows.push_back(window);

    // Recalculate window pos
    icvUpdateWindowPos(*window);

    return window;
}

#ifdef HAVE_OPENGL

CV_IMPL void cvSetOpenGlContext(const char* name)
{
    CV_FUNCNAME("cvSetOpenGlContext");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    if (!window->useGl)
        CV_Error(Error::OpenGlNotSupported, "Window doesn't support OpenGL");

    if (!wglMakeCurrent(window->dc, window->hGLRC))
        CV_Error(Error::OpenGlApiCallError, "Can't Activate The GL Rendering Context");
}

CV_IMPL void cvUpdateWindow(const char* name)
{
    CV_FUNCNAME("cvUpdateWindow");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    InvalidateRect(window->hwnd, 0, 0);
}

CV_IMPL void cvSetOpenGlDrawCallback(const char* name, CvOpenGlDrawCallback callback, void* userdata)
{
    CV_FUNCNAME("cvCreateOpenGLCallback");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    if (!window->useGl)
        CV_Error(Error::OpenGlNotSupported, "Window was created without OpenGL context");

    window->glDrawCallback = callback;
    window->glDrawData = userdata;
}

#endif // HAVE_OPENGL

static void icvRemoveWindow(const std::shared_ptr<CvWindow>& window_)
{
    CV_Assert(window_);
    AutoLock lock(getWindowMutex());
    CvWindow& window = *window_;

    RECT wrect={0,0,0,0};

    auto& g_windows = getWindowsList();
    for (auto it = g_windows.begin(); it != g_windows.end(); ++it)
    {
        const std::shared_ptr<CvWindow>& w = *it;
        if (w.get() == &window)
        {
            g_windows.erase(it);
            break;
        }
    }

#ifdef HAVE_OPENGL
    if (window.useGl)
        releaseGlContext(window);
#endif

    if (window.frame)
        GetWindowRect(window.frame, &wrect);
    icvSaveWindowPos(window.name.c_str(), cvRect(wrect.left, wrect.top, wrect.right-wrect.left, wrect.bottom-wrect.top));

    if (window.hwnd)
        icvSetWindowLongPtr(window.hwnd, CV_USERDATA, 0);
    if (window.frame)
        icvSetWindowLongPtr(window.frame, CV_USERDATA, 0);

    if (window.toolbar.toolbar)
        icvSetWindowLongPtr(window.toolbar.toolbar, CV_USERDATA, 0);

    if (window.dc && window.image)
        DeleteObject(SelectObject(window.dc, window.image));

    if (window.dc)
        DeleteDC(window.dc);

    for (auto it = window.toolbar.trackbars.begin(); it != window.toolbar.trackbars.end(); ++it)
    {
        auto trackbar = (*it).get();
        if (trackbar && trackbar->hwnd)
        {
            icvSetWindowLongPtr(trackbar->hwnd, CV_USERDATA, 0);
        }
    }
}


CV_IMPL void cvDestroyWindow(const char* name)
{
    CV_FUNCNAME("cvDestroyWindow");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name string");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    window->destroy();
}


void CvWindow::destroy()
{
    SendMessage(hwnd, WM_CLOSE, 0, 0);
    SendMessage(frame, WM_CLOSE, 0, 0);
    // Do NOT call _remove_window -- CvWindow list will be updated automatically ...
}

static void icvScreenToClient(HWND hwnd, RECT* rect)
{
    POINT p;
    p.x = rect->left;
    p.y = rect->top;
    ScreenToClient(hwnd, &p);
    OffsetRect(rect, p.x - rect->left, p.y - rect->top);
}


/* Calculatess the window coordinates relative to the upper left corner of the mainhWnd window */
static RECT icvCalcWindowRect(CvWindow& window)
{
    RECT crect = { 0 }, trect = { 0 }, rect = { 0 };

    GetClientRect(window.frame, &crect);
    if (window.toolbar.toolbar)
    {
        GetWindowRect(window.toolbar.toolbar, &trect);
        icvScreenToClient(window.frame, &trect);
        SubtractRect(&rect, &crect, &trect);
    }
    else
        rect = crect;

    return rect;
}
static inline RECT icvCalcWindowRect(CvWindow* window) { CV_Assert(window); return icvCalcWindowRect(*window); }


// returns FALSE if there is a problem such as ERROR_IO_PENDING.
static bool icvGetBitmapData(CvWindow& window, SIZE& size, int& channels, void*& data)
{
    GdiFlush();

    HGDIOBJ h = GetCurrentObject(window.dc, OBJ_BITMAP);
    size.cx = size.cy = 0;
    data = 0;

    if (h == NULL)
        return false;

    BITMAP bmp = {};
    if (GetObject(h, sizeof(bmp), &bmp) == 0)
        return false;

    size.cx = abs(bmp.bmWidth);
    size.cy = abs(bmp.bmHeight);

    channels = bmp.bmBitsPixel/8;

    data = bmp.bmBits;

    return true;
}
static bool icvGetBitmapData(CvWindow& window, SIZE& size)
{
    int channels = 0;
    void* data = nullptr;
    return icvGetBitmapData(window, size, channels, data);
}


static void icvUpdateWindowPos(CvWindow& window)
{
    RECT rect = { 0 };

    if ((window.flags & CV_WINDOW_AUTOSIZE) && window.image)
    {
        int i;
        SIZE size = {0,0};
        icvGetBitmapData(window, size);  // TODO check return value?

        // Repeat two times because after the first resizing of the mainhWnd window
        // toolbar may resize too
        for(i = 0; i < (window.toolbar.toolbar ? 2 : 1); i++)
        {
            RECT rmw = { 0 }, rw = icvCalcWindowRect(&window);
            MoveWindow(window.hwnd, rw.left, rw.top,
                rw.right - rw.left, rw.bottom - rw.top, FALSE);
            GetClientRect(window.hwnd, &rw);
            GetWindowRect(window.frame, &rmw);
            // Resize the mainhWnd window in order to make the bitmap fit into the child window
            MoveWindow(window.frame, rmw.left, rmw.top,
                size.cx + (rmw.right - rmw.left) - (rw.right - rw.left),
                size.cy + (rmw.bottom - rmw.top) - (rw.bottom - rw.top), TRUE);
        }
    }

    rect = icvCalcWindowRect(window);
    MoveWindow(window.hwnd, rect.left, rect.top,
               rect.right - rect.left,
               rect.bottom - rect.top, TRUE);
}

static void showImage_(CvWindow& window, const Mat& image);

CV_IMPL void
cvShowImage(const char* name, const CvArr* arr)
{
    CV_FUNCNAME("cvShowImage");

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name");

    std::shared_ptr<CvWindow> window;
    {
        AutoLock lock(getWindowMutex());

        window = icvFindWindowByName(name);
        if (!window)
        {
            cvNamedWindow(name, CV_WINDOW_AUTOSIZE);
            window = icvFindWindowByName(name);
        }
    }

    if (!window || !arr)
        return; // keep silence here.

    CvMat stub = {};
    CvMat* image_c = cvGetMat(arr, &stub);
    Mat image = cv::cvarrToMat(image_c);
#ifdef HAVE_OPENGL
    if (window->useGl)
    {
        cv::imshow(name, image);
        return;
    }
#endif
    return showImage_(*window, image);
}

static void showImage_(CvWindow& window, const Mat& image)
{
    AutoLock lock(window.mutex);

    SIZE size = { 0, 0 };
    int channels = 0;
    void* dst_ptr = 0;
    const int channels0 = 3;
    bool changed_size = false; // philipg

    if (window.image)
    {
        // if there is something wrong with these system calls, we cannot display image...
        if (!icvGetBitmapData(window, size, channels, dst_ptr))
            return;
    }

    if (size.cx != image.cols || size.cy != image.rows || channels != channels0)
    {
        changed_size = true;

        uchar buffer[sizeof(BITMAPINFO) + 255*sizeof(RGBQUAD)];
        BITMAPINFO* binfo = (BITMAPINFO*)buffer;

        DeleteObject(SelectObject(window.dc, window.image));
        window.image = 0;

        size.cx = image.cols;
        size.cy = image.rows;
        channels = channels0;

        FillBitmapInfo(binfo, size.cx, size.cy, channels*8, 1);

        window.image = SelectObject(window.dc,
                CreateDIBSection(window.dc, binfo, DIB_RGB_COLORS, &dst_ptr, 0, 0)
            );
    }

    {
        cv::Mat dst(size.cy, size.cx, CV_8UC3, dst_ptr, (size.cx * channels + 3) & -4);
        convertToShow(image, dst, false);
        CV_Assert(dst.data == (uchar*)dst_ptr);
        cv::flip(dst, dst, 0);
    }

    // only resize window if needed
    if (changed_size)
        icvUpdateWindowPos(window);
    InvalidateRect(window.hwnd, 0, 0);
    // philipg: this is not needed and just slows things down
    //    UpdateWindow(window->hwnd);
}

static void resizeWindow_(CvWindow& window, const Size& size);

CV_IMPL void cvResizeWindow(const char* name, int width, int height)
{
    CV_FUNCNAME("cvResizeWindow");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    return resizeWindow_(*window, Size(width, height));
}

static void resizeWindow_(CvWindow& window, const Size& size)
{
    RECT rmw = { 0 }, rw = { 0 }, rect = { 0 };

    // Repeat two times because after the first resizing of the mainhWnd window
    // toolbar may resize too
    for (int i = 0; i < (window.toolbar.toolbar ? 2 : 1); i++)
    {
        rw = icvCalcWindowRect(window);
        MoveWindow(window.hwnd, rw.left, rw.top,
            rw.right - rw.left, rw.bottom - rw.top, FALSE);
        GetClientRect(window.hwnd, &rw);
        GetWindowRect(window.frame, &rmw);
        // Resize the mainhWnd window in order to make the bitmap fit into the child window
        MoveWindow(window.frame, rmw.left, rmw.top,
            size.width  + (rmw.right - rmw.left) - (rw.right - rw.left),
            size.height + (rmw.bottom - rmw.top) - (rw.bottom - rw.top), TRUE);
    }

    rect = icvCalcWindowRect(window);
    MoveWindow(window.hwnd, rect.left, rect.top,
        rect.right - rect.left, rect.bottom - rect.top, TRUE);
}

static void moveWindow_(CvWindow& window, const Point& pt);

CV_IMPL void cvMoveWindow(const char* name, int x, int y)
{
    CV_FUNCNAME("cvMoveWindow");

    AutoLock lock(getWindowMutex());

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL name");

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    (void)moveWindow_(*window, Point(x, y));
}

static void moveWindow_(CvWindow& window, const Point& pt)
{
    RECT rect = { 0 };
    GetWindowRect(window.frame, &rect);  // TODO check return value
    MoveWindow(window.frame, pt.x, pt.y, rect.right - rect.left, rect.bottom - rect.top, TRUE);
}


static LRESULT CALLBACK
MainWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    auto window_ = icvWindowByHWND(hwnd);
    if (!window_)
        return DefWindowProc(hwnd, uMsg, wParam, lParam);

    CvWindow& window = *window_;

    switch(uMsg)
    {
    case WM_COPY:
        ::SendMessage(window.hwnd, uMsg, wParam, lParam);
        break;

    case WM_DESTROY:

        icvRemoveWindow(window_);
        // Do nothing!!!
        //PostQuitMessage(0);
        break;

    case WM_GETMINMAXINFO:
        if (!(window.flags & CV_WINDOW_AUTOSIZE))
        {
            MINMAXINFO* minmax = (MINMAXINFO*)lParam;
            RECT rect = { 0 };
            LRESULT retval = DefWindowProc(hwnd, uMsg, wParam, lParam);

            minmax->ptMinTrackSize.y = 100;
            minmax->ptMinTrackSize.x = 100;

            if (!window.toolbar.trackbars.empty())
            {
                GetWindowRect(window.toolbar.trackbars[0]->hwnd, &rect);
                minmax->ptMinTrackSize.y += window.toolbar.rows*(rect.bottom - rect.top);
                minmax->ptMinTrackSize.x = MAX(rect.right - rect.left + HG_BUDDY_WIDTH, HG_BUDDY_WIDTH*2);
            }
            return retval;
        }
        break;

    case WM_WINDOWPOSCHANGED:
        {
            WINDOWPOS* pos = (WINDOWPOS*)lParam;

            // Update the toolbar pos/size
            if (window.toolbar.toolbar)
            {
                RECT rect = { 0 };
                GetWindowRect(window.toolbar.toolbar, &rect);
                MoveWindow(window.toolbar.toolbar, 0, 0, pos->cx, rect.bottom - rect.top, TRUE);
            }

            if (!(window.flags & CV_WINDOW_AUTOSIZE))
                icvUpdateWindowPos(window);

            break;
        }

    case WM_WINDOWPOSCHANGING:
       {
          // Snap window to screen edges with multi-monitor support. // Adi Shavit
          LPWINDOWPOS pos = (LPWINDOWPOS)lParam;

          RECT rect = { 0 };
          GetWindowRect(window.frame, &rect);

          HMONITOR hMonitor;
          hMonitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST);

          MONITORINFO mi;
          mi.cbSize = sizeof(mi);
          GetMonitorInfo(hMonitor, &mi);

          const int SNAP_DISTANCE = 15;

          if (abs(pos->x - mi.rcMonitor.left) <= SNAP_DISTANCE)
             pos->x = mi.rcMonitor.left;               // snap to left edge
          else
             if (abs(pos->x + pos->cx - mi.rcMonitor.right) <= SNAP_DISTANCE)
                pos->x = mi.rcMonitor.right - pos->cx; // snap to right edge

          if (abs(pos->y - mi.rcMonitor.top) <= SNAP_DISTANCE)
             pos->y = mi.rcMonitor.top;                 // snap to top edge
          else
             if (abs(pos->y + pos->cy - mi.rcMonitor.bottom) <= SNAP_DISTANCE)
                pos->y = mi.rcMonitor.bottom - pos->cy; // snap to bottom edge
       }

    case WM_ACTIVATE:
        if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE)
            SetFocus(window.hwnd);
        break;

    case WM_MOUSEWHEEL:
    case WM_MOUSEHWHEEL:
       if (window.on_mouse)
       {
          int flags = (wParam & MK_LBUTTON      ? CV_EVENT_FLAG_LBUTTON  : 0)|
                      (wParam & MK_RBUTTON      ? CV_EVENT_FLAG_RBUTTON  : 0)|
                      (wParam & MK_MBUTTON      ? CV_EVENT_FLAG_MBUTTON  : 0)|
                      (wParam & MK_CONTROL      ? CV_EVENT_FLAG_CTRLKEY  : 0)|
                      (wParam & MK_SHIFT        ? CV_EVENT_FLAG_SHIFTKEY : 0)|
                      (GetKeyState(VK_MENU) < 0 ? CV_EVENT_FLAG_ALTKEY   : 0);
          int event = (uMsg == WM_MOUSEWHEEL    ? CV_EVENT_MOUSEWHEEL    : CV_EVENT_MOUSEHWHEEL);

          // Set the wheel delta of mouse wheel to be in the upper word of 'event'
          int delta = GET_WHEEL_DELTA_WPARAM(wParam);
          flags |= (delta << 16);

          POINT pt;
          pt.x = GET_X_LPARAM(lParam);
          pt.y = GET_Y_LPARAM(lParam);
          ::ScreenToClient(hwnd, &pt); // Convert screen coordinates to client coordinates.

          RECT rect = { 0 };
          GetClientRect(window.hwnd, &rect);

          SIZE size = {0,0};
#ifdef HAVE_OPENGL
          if (window.useGl)
          {
              cv::ogl::Texture2D* texObj = static_cast<cv::ogl::Texture2D*>(window.glDrawData);
              size.cx = texObj->cols();
              size.cy = texObj->rows();
          }
          else
          {
              icvGetBitmapData(window, size);
          }
#else
          icvGetBitmapData(window, size);
#endif

          int x = cvRound((float)pt.x*size.cx/MAX(rect.right - rect.left,1));
          int y = cvRound((float)pt.y*size.cy/MAX(rect.bottom - rect.top,1));
          window.on_mouse(event, x, y, flags, window.on_mouse_param);
       }
       break;

    case WM_ERASEBKGND:
        {
            RECT cr = { 0 }, tr = { 0 }, wrc = { 0 };
            HRGN rgn, rgn1, rgn2;
            int ret;
            HDC hdc = (HDC)wParam;
            GetWindowRect(window.hwnd, &cr);
            icvScreenToClient(window.frame, &cr);
            if (window.toolbar.toolbar)
            {
                GetWindowRect(window.toolbar.toolbar, &tr);
                icvScreenToClient(window.frame, &tr);
            }
            else
                tr.left = tr.top = tr.right = tr.bottom = 0;

            GetClientRect(window.frame, &wrc);

            rgn = CreateRectRgn(0, 0, wrc.right, wrc.bottom);
            rgn1 = CreateRectRgn(cr.left, cr.top, cr.right, cr.bottom);
            rgn2 = CreateRectRgn(tr.left, tr.top, tr.right, tr.bottom);
            CV_Assert_N(rgn != 0, rgn1 != 0, rgn2 != 0);

            ret = CombineRgn(rgn, rgn, rgn1, RGN_DIFF);
            ret = CombineRgn(rgn, rgn, rgn2, RGN_DIFF);

            if (ret != NULLREGION && ret != ERROR)
                FillRgn(hdc, rgn, (HBRUSH)icvGetClassLongPtr(hwnd, CV_HBRBACKGROUND));

            DeleteObject(rgn);
            DeleteObject(rgn1);
            DeleteObject(rgn2);
        }
        return 1;
    }

    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}


static LRESULT CALLBACK HighGUIProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    auto window_ = icvWindowByHWND(hwnd);
    if (!window_)
    {
        // This window is not mentioned in HighGUI storage
        // Actually, this should be error except for the case of calls to CreateWindow
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }

    CvWindow& window = *window_;

    // Process the message
    switch(uMsg)
    {
    case WM_COPY:
        {
            if (!::OpenClipboard(hwnd))
                break;

            HDC hDC       = 0;
            HDC memDC     = 0;
            HBITMAP memBM = 0;

            // We'll use a do-while(0){} scope as a single-run breakable scope
            // Upon any error we can jump out of the single-time while scope to clean up the resources.
            do
            {
                if (!::EmptyClipboard())
                    break;

                if (!window.image)
                    break;

                // Get window device context
                if (0 == (hDC = ::GetDC(hwnd)))
                    break;

                // Create another DC compatible with hDC
                if (0 == (memDC = ::CreateCompatibleDC(hDC)))
                    break;

                // Determine the bitmap's dimensions
                SIZE size = {0,0};
                int nchannels = 3;
                void* data = NULL;  // unused
                icvGetBitmapData(window, size, nchannels, data);

                // Create bitmap to draw on and it in the new DC
                if (0 == (memBM = ::CreateCompatibleBitmap(hDC, size.cx, size.cy)))
                    break;

                if (!::SelectObject(memDC, memBM))
                    break;

                // Begin drawing to DC
                if (!::SetStretchBltMode(memDC, COLORONCOLOR))
                    break;

                RGBQUAD table[256];
                if (1 == nchannels)
                {
                    for(int i = 0; i < 256; ++i)
                    {
                        table[i].rgbBlue = (unsigned char)i;
                        table[i].rgbGreen = (unsigned char)i;
                        table[i].rgbRed = (unsigned char)i;
                    }
                    if (!::SetDIBColorTable(window.dc, 0, 255, table))
                        break;
                }

                // The image copied to the clipboard will be in its original size, regardless if the window itself was resized.

                // Render the image to the dc/bitmap (at original size).
                if (!::BitBlt(memDC, 0, 0, size.cx, size.cy, window.dc, 0, 0, SRCCOPY))
                    break;

                // Finally, set bitmap to clipboard
                ::SetClipboardData(CF_BITMAP, memBM);
            } while (0,0); // (0,0) instead of (0) to avoid MSVC compiler warning C4127: "conditional expression is constant"

            //////////////////////////////////////////////////////////////////////////
            // if handle is allocated (i.e. != 0) then clean-up.
            if (memBM) ::DeleteObject(memBM);
            if (memDC) ::DeleteDC(memDC);
            if (hDC)   ::ReleaseDC(hwnd, hDC);
            ::CloseClipboard();
            break;
        }

    case WM_WINDOWPOSCHANGING:
        {
            LPWINDOWPOS pos = (LPWINDOWPOS)lParam;
            RECT rect = icvCalcWindowRect(window);
            pos->x = rect.left;
            pos->y = rect.top;
            pos->cx = rect.right - rect.left;
            pos->cy = rect.bottom - rect.top;
        }
        break;

    case WM_LBUTTONDOWN:
    case WM_RBUTTONDOWN:
    case WM_MBUTTONDOWN:
    case WM_LBUTTONDBLCLK:
    case WM_RBUTTONDBLCLK:
    case WM_MBUTTONDBLCLK:
    case WM_LBUTTONUP:
    case WM_RBUTTONUP:
    case WM_MBUTTONUP:
    case WM_MOUSEMOVE:
        if (window.on_mouse)
        {
            POINT pt;

            int flags = (wParam & MK_LBUTTON ? CV_EVENT_FLAG_LBUTTON : 0)|
                        (wParam & MK_RBUTTON ? CV_EVENT_FLAG_RBUTTON : 0)|
                        (wParam & MK_MBUTTON ? CV_EVENT_FLAG_MBUTTON : 0)|
                        (wParam & MK_CONTROL ? CV_EVENT_FLAG_CTRLKEY : 0)|
                        (wParam & MK_SHIFT ? CV_EVENT_FLAG_SHIFTKEY : 0)|
                        (GetKeyState(VK_MENU) < 0 ? CV_EVENT_FLAG_ALTKEY : 0);
            int event = uMsg == WM_LBUTTONDOWN ? CV_EVENT_LBUTTONDOWN :
                        uMsg == WM_RBUTTONDOWN ? CV_EVENT_RBUTTONDOWN :
                        uMsg == WM_MBUTTONDOWN ? CV_EVENT_MBUTTONDOWN :
                        uMsg == WM_LBUTTONUP ? CV_EVENT_LBUTTONUP :
                        uMsg == WM_RBUTTONUP ? CV_EVENT_RBUTTONUP :
                        uMsg == WM_MBUTTONUP ? CV_EVENT_MBUTTONUP :
                        uMsg == WM_LBUTTONDBLCLK ? CV_EVENT_LBUTTONDBLCLK :
                        uMsg == WM_RBUTTONDBLCLK ? CV_EVENT_RBUTTONDBLCLK :
                        uMsg == WM_MBUTTONDBLCLK ? CV_EVENT_MBUTTONDBLCLK :
                                                   CV_EVENT_MOUSEMOVE;
            if (uMsg == WM_LBUTTONDOWN || uMsg == WM_RBUTTONDOWN || uMsg == WM_MBUTTONDOWN)
                SetCapture(hwnd);
            if (uMsg == WM_LBUTTONUP || uMsg == WM_RBUTTONUP || uMsg == WM_MBUTTONUP)
                ReleaseCapture();

            pt.x = GET_X_LPARAM(lParam);
            pt.y = GET_Y_LPARAM(lParam);

            if (window.flags & CV_WINDOW_AUTOSIZE)
            {
                // As user can't change window size, do not scale window coordinates. Underlying windowing system
                // may prevent full window from being displayed and in this case coordinates should not be scaled.
                window.on_mouse(event, pt.x, pt.y, flags, window.on_mouse_param);
            } else {
                // Full window is displayed using different size. Scale coordinates to match underlying positions.
                RECT rect = { 0 };
                SIZE size = {0, 0};

                GetClientRect(window.hwnd, &rect);

#ifdef HAVE_OPENGL
                if (window.useGl)
                {
                    cv::ogl::Texture2D* texObj = static_cast<cv::ogl::Texture2D*>(window.glDrawData);
                    size.cx = texObj->cols();
                    size.cy = texObj->rows();
                }
                else
                {
                    icvGetBitmapData(window, size);
                }
#else
                icvGetBitmapData(window, size);
#endif

                int x = cvRound((float)pt.x*size.cx/MAX(rect.right - rect.left,1));
                int y = cvRound((float)pt.y*size.cy/MAX(rect.bottom - rect.top,1));
                window.on_mouse(event, x, y, flags, window.on_mouse_param);
            }
        }
        break;

    case WM_PAINT:
        if (window.image != 0)
        {
            int nchannels = 3;
            SIZE size = {0,0};
            PAINTSTRUCT paint;
            HDC hdc;
            RGBQUAD table[256];

            // Determine the bitmap's dimensions
            void* data = 0;  // unused
            icvGetBitmapData(window, size, nchannels, data);

            hdc = BeginPaint(hwnd, &paint);
            SetStretchBltMode(hdc, COLORONCOLOR);

            if (nchannels == 1)
            {
                int i;
                for(i = 0; i < 256; i++)
                {
                    table[i].rgbBlue = (unsigned char)i;
                    table[i].rgbGreen = (unsigned char)i;
                    table[i].rgbRed = (unsigned char)i;
                }
                SetDIBColorTable(window.dc, 0, 255, table);
            }

            if (window.flags & CV_WINDOW_AUTOSIZE)
            {
                BitBlt(hdc, 0, 0, size.cx, size.cy, window.dc, 0, 0, SRCCOPY);
            }
            else
            {
                RECT rect = { 0 };
                GetClientRect(window.hwnd, &rect);
                StretchBlt(hdc, 0, 0, rect.right - rect.left, rect.bottom - rect.top,
                            window.dc, 0, 0, size.cx, size.cy, SRCCOPY);
            }
            //DeleteDC(hdc);
            EndPaint(hwnd, &paint);
        }
#ifdef HAVE_OPENGL
        else if (window.useGl)
        {
            drawGl(window);
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
        }
#endif
        else
        {
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
        }
        return 0;

    case WM_ERASEBKGND:
        if (window.image)
            return 0;
        break;

    case WM_DESTROY:

        icvRemoveWindow(window_);
        // Do nothing!!!
        //PostQuitMessage(0);
        break;

    case WM_SETCURSOR:
        SetCursor((HCURSOR)icvGetClassLongPtr(hwnd, CV_HCURSOR));
        return 0;

    case WM_KEYDOWN:
        window.last_key = (int)wParam;
        return 0;

    case WM_SIZE:
        window.width = LOWORD(lParam);
        window.height = HIWORD(lParam);

#ifdef HAVE_OPENGL
        if (window.useGl)
            resizeGl(window);
#endif
    }

    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}


static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    LRESULT ret;

    if (hg_on_preprocess)
    {
        int was_processed = 0;
        int rethg = hg_on_preprocess(hwnd, uMsg, wParam, lParam, &was_processed);
        if (was_processed)
            return rethg;
    }
    ret = HighGUIProc(hwnd, uMsg, wParam, lParam);

    if (hg_on_postprocess)
    {
        int was_processed = 0;
        int rethg = hg_on_postprocess(hwnd, uMsg, wParam, lParam, &was_processed);
        if (was_processed)
            return rethg;
    }

    return ret;
}


static void icvUpdateTrackbar(CvTrackbar& trackbar, int pos)
{
    const int max_name_len = 10;
    const char* suffix = "";
    char pos_text[32];
    int name_len;

    if (trackbar.data)
        *trackbar.data = pos;

    if (trackbar.pos != pos)
    {
        trackbar.pos = pos;
        if (trackbar.onChangeCallback)
            trackbar.onChangeCallback(pos, trackbar.userdata);
        if (trackbar.notify2)
            trackbar.notify2(pos, trackbar.userdata);
        if (trackbar.notify)
            trackbar.notify(pos);

        name_len = (int)trackbar.name.size();

        // TODO replace C strings manipulation
        if (name_len > max_name_len)
        {
            int start_len = max_name_len*2/3;
            int end_len = max_name_len - start_len - 2;
            memcpy(pos_text, trackbar.name.c_str(), start_len);
            memcpy(pos_text + start_len, "...", 3);
            memcpy(pos_text + start_len + 3, trackbar.name.c_str() + name_len - end_len, end_len + 1);
        }
        else
        {
            memcpy(pos_text, trackbar.name.c_str(), name_len + 1);
        }

        sprintf(pos_text + strlen(pos_text), "%s: %d\n", suffix, pos);
        SetWindowText(trackbar.buddy, pos_text);
    }
}


static LRESULT CALLBACK HGToolbarProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    auto window_ = icvWindowByHWND(hwnd);
    if (!window_)
        return DefWindowProc(hwnd, uMsg, wParam, lParam);

    CvWindow& window = *window_;

    // Control messages processing
    switch(uMsg)
    {
    // Slider processing
    case WM_HSCROLL:
        {
            HWND slider = (HWND)lParam;
            int pos = (int)SendMessage(slider, TBM_GETPOS, 0, 0);
            auto trackbar = icvTrackbarByHWND(slider);

            if (trackbar)
            {
                if (trackbar->pos != pos)
                    icvUpdateTrackbar(*trackbar, pos);
            }

            SetFocus(window.hwnd);
            return 0;
        }

    case WM_NCCALCSIZE:
        {
            LRESULT ret = CallWindowProc(window.toolbar.toolBarProc, hwnd, uMsg, wParam, lParam);
            int rows = (int)SendMessage(hwnd, TB_GETROWS, 0, 0);

            if (window.toolbar.rows != rows)
            {
                SendMessage(window.toolbar.toolbar, TB_BUTTONCOUNT, 0, 0);
                auto& trakbars = window.toolbar.trackbars;

                for (auto it = trakbars.begin(); it != trakbars.end(); ++it)
                {
                    auto trackbar = *it;
                    CV_Assert(trackbar);
                    RECT rect = { 0 };
                    SendMessage(window.toolbar.toolbar, TB_GETITEMRECT,
                               (WPARAM)trackbar->id, (LPARAM)&rect);
                    MoveWindow(trackbar->hwnd, rect.left + HG_BUDDY_WIDTH, rect.top,
                               rect.right - rect.left - HG_BUDDY_WIDTH,
                               rect.bottom - rect.top, FALSE);
                    MoveWindow(trackbar->buddy, rect.left, rect.top,
                               HG_BUDDY_WIDTH, rect.bottom - rect.top, FALSE);
                }
                window.toolbar.rows = rows;
            }
            return ret;
        }
    }

    return CallWindowProc(window.toolbar.toolBarProc, hwnd, uMsg, wParam, lParam);
}


CV_IMPL void
cvDestroyAllWindows(void)
{
    std::vector< std::shared_ptr<CvWindow> > g_windows;
    {
        AutoLock lock(getWindowMutex());
        g_windows = getWindowsList();  // copy
    }
    for (auto it = g_windows.begin(); it != g_windows.end(); ++it)
    {
        auto window_ = *it;
        if (!window_)
            continue;

        {
            CvWindow& window = *window_;

            HWND mainhWnd = window.frame;
            HWND hwnd = window.hwnd;

            SendMessage(hwnd, WM_CLOSE, 0, 0);
            SendMessage(mainhWnd, WM_CLOSE, 0, 0);
        }

        window_.reset();
    }
    // TODO needed?
    {
        AutoLock lock(getWindowMutex());
        getWindowsList().clear();
    }
}

static void showSaveDialog(CvWindow& window)
{
    if (!window.image)
        return;

    SIZE sz;
    int channels;
    void* data;
    if (!icvGetBitmapData(window, sz, channels, data))
        return; // nothing to save

    char szFileName[MAX_PATH] = "";
    // try to use window title as file name
    GetWindowText(window.frame, szFileName, MAX_PATH);

    OPENFILENAME ofn;
    ZeroMemory(&ofn, sizeof(ofn));
#ifdef OPENFILENAME_SIZE_VERSION_400
    // we are not going to use new fields any way
    ofn.lStructSize = OPENFILENAME_SIZE_VERSION_400;
#else
    ofn.lStructSize = sizeof(ofn);
#endif
    ofn.hwndOwner = window.hwnd;
    ofn.lpstrFilter =
#ifdef HAVE_PNG
                      "Portable Network Graphics files (*.png)\0*.png\0"
#endif
                      "Windows bitmap (*.bmp;*.dib)\0*.bmp;*.dib\0"
#ifdef HAVE_JPEG
                      "JPEG files (*.jpeg;*.jpg;*.jpe)\0*.jpeg;*.jpg;*.jpe\0"
#endif
#ifdef HAVE_TIFF
                      "TIFF Files (*.tiff;*.tif)\0*.tiff;*.tif\0"
#endif
#ifdef HAVE_JASPER
                      "JPEG-2000 files (*.jp2)\0*.jp2\0"
#endif
#ifdef HAVE_WEBP
                      "WebP files (*.webp)\0*.webp\0"
#endif
                      "Portable image format (*.pbm;*.pgm;*.ppm;*.pxm;*.pnm)\0*.pbm;*.pgm;*.ppm;*.pxm;*.pnm\0"
#ifdef HAVE_OPENEXR
                      "OpenEXR Image files (*.exr)\0*.exr\0"
#endif
                      "Radiance HDR (*.hdr;*.pic)\0*.hdr;*.pic\0"
                      "Sun raster files (*.sr;*.ras)\0*.sr;*.ras\0"
                      "All Files (*.*)\0*.*\0";
    ofn.lpstrFile = szFileName;
    ofn.nMaxFile = MAX_PATH;
    ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_NOREADONLYRETURN | OFN_NOCHANGEDIR;
#ifdef HAVE_PNG
    ofn.lpstrDefExt = "png";
#else
    ofn.lpstrDefExt = "bmp";
#endif

    if (GetSaveFileName(&ofn))
    {
        cv::Mat tmp;
        cv::flip(cv::Mat(sz.cy, sz.cx, CV_8UC(channels), data, (sz.cx * channels + 3) & -4), tmp, 0);
        cv::imwrite(szFileName, tmp);
    }
}

/*
 * message received. check if it belongs to our windows (frame, hwnd).
 * returns true (and value in keyCode) if a key was pressed.
 * otherwise returns false (indication to continue event loop).
 */
static bool handleMessage(MSG& message, int& keyCode)
{
    std::shared_ptr<CvWindow> window_;
    {
        AutoLock lock(getWindowMutex());
        window_ = icvFindWindowByHandle(message.hwnd);
    }
    if (window_)
    {
        CvWindow& window = *window_;

        switch (message.message)
        {
            case WM_DESTROY:
                // fallthru
            case WM_CHAR:
                DispatchMessage(&message);
                keyCode = (int)message.wParam;
                return true;

            case WM_SYSKEYDOWN:
                if (message.wParam == VK_F10)
                {
                    keyCode = (int)(message.wParam << 16);
                    return true;
                }
                break;

            case WM_KEYDOWN:
                // Intercept Ctrl+C for copy to clipboard
                if ('C' == message.wParam && (::GetKeyState(VK_CONTROL) >> 15))
                {
                    ::SendMessage(message.hwnd, WM_COPY, 0, 0);
                    return false;
                }

                // Intercept Ctrl+S for "save as" dialog
                if ('S' == message.wParam && (::GetKeyState(VK_CONTROL) >> 15))
                {
                    showSaveDialog(window);
                    return false;
                }

                TranslateMessage(&message);
                if ((message.wParam >= VK_F1 && message.wParam <= VK_F24)      ||
                    message.wParam == VK_HOME   || message.wParam == VK_END    ||
                    message.wParam == VK_UP     || message.wParam == VK_DOWN   ||
                    message.wParam == VK_LEFT   || message.wParam == VK_RIGHT  ||
                    message.wParam == VK_INSERT || message.wParam == VK_DELETE ||
                    message.wParam == VK_PRIOR  || message.wParam == VK_NEXT)
                {
                    DispatchMessage(&message);
                    keyCode = (int)(message.wParam << 16);
                    return true;
                }

                // fallthru

            default:
                DispatchMessage(&message);
                break;
        }
    }
    else
    {
        TranslateMessage(&message);
        DispatchMessage(&message);
    }

    return false; // no keyCode to return, keep processing
}

/*
 * process until queue is empty but don't wait.
 */
int pollKey_W32()
{
    CV_TRACE_FUNCTION();
    for(;;)
    {
        MSG message;
        if (PeekMessage(&message, 0, 0, 0, PM_REMOVE) == FALSE)
            return -1;

        int keyCode = -1;
        if (handleMessage(message, keyCode))
            return keyCode;
    }
}

CV_IMPL int
cvWaitKey(int delay)
{
    int64 time0 = cv::getTickCount();
    int64 timeEnd = time0 + (int64)(delay * 0.001f * cv::getTickFrequency());

    for(;;)
    {
        MSG message;

        if ((delay <= 0) && !getWindowsList().empty())
            GetMessage(&message, 0, 0, 0);
        else if (PeekMessage(&message, 0, 0, 0, PM_REMOVE) == FALSE)
        {
            int64 t = cv::getTickCount();
            if (t - timeEnd >= 0)
                return -1;  // no messages and no more time
            Sleep(1);
            continue;
        }

        int keyCode = -1;
        if (handleMessage(message, keyCode))
            return keyCode;
    }
}


static
std::shared_ptr<CvTrackbar> icvFindTrackbarByName(CvWindow& window, const std::string& name)
{
    auto trackbars = window.toolbar.trackbars;
    for (auto it = trackbars.begin(); it != trackbars.end(); ++it)
    {
        auto& trackbar = *it;
        CV_Assert(trackbar);
        if (trackbar->name == name)
            return trackbar;
    }
    return std::shared_ptr<CvTrackbar>();
}
static inline
std::shared_ptr<CvTrackbar> icvFindTrackbarByName(const std::shared_ptr<CvWindow>& window, const std::string& name)
{
    CV_Assert(window);
    return icvFindTrackbarByName(window, name);
}

static
std::shared_ptr<CvTrackbar> createTrackbar_(CvWindow& window, const std::string& trackbar_name,
    int count,
    TrackbarCallback onChange, void* userdata);

static int
icvCreateTrackbar(const char* trackbar_name, const char* window_name,
                  int* val, int count, CvTrackbarCallback on_notify,
                  CvTrackbarCallback2 on_notify2, void* userdata)
{
    CV_FUNCNAME("icvCreateTrackbar");

    AutoLock lock(getWindowMutex());

    if (!window_name || !trackbar_name)
        CV_Error(Error::StsNullPtr, "NULL window or trackbar name");

    if (count < 0)
        CV_Error(Error::StsOutOfRange, "Bad trackbar maximal value");

    auto window = icvFindWindowByName(window_name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", window_name));

    auto trackbar = icvFindTrackbarByName(*window, trackbar_name);
    if (!trackbar)
        trackbar = createTrackbar_(*window, trackbar_name, count, nullptr, userdata);
    CV_Assert(trackbar);

    trackbar->notify = on_notify;
    trackbar->notify2 = on_notify2;
    trackbar->userdata = userdata;
    trackbar->data = val;

    return 1;
}

static void createToolbar_(CvWindow& window)
{
    CV_Assert(!window.toolbar.toolbar);

    const int default_height = 30;

    // CreateToolbarEx is deprecated and forces linking against Comctl32.lib.
    window.toolbar.toolbar = CreateWindowEx(0, TOOLBARCLASSNAME, NULL,
                                WS_CHILD | CCS_TOP | TBSTYLE_WRAPABLE | BTNS_AUTOSIZE | BTNS_BUTTON,
                                0, 0, 0, 0,
                                window.frame, NULL, GetModuleHandle(NULL), NULL);
    // CreateToolbarEx automatically sends this but CreateWindowEx doesn't.
    SendMessage(window.toolbar.toolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);

    RECT rect;
    GetClientRect(window.frame, &rect);
    MoveWindow(window.toolbar.toolbar, 0, 0,
               rect.right - rect.left, default_height, TRUE);
    SendMessage(window.toolbar.toolbar, TB_AUTOSIZE, 0, 0);
    ShowWindow(window.toolbar.toolbar, SW_SHOW);

    window.toolbar.pos = 0;
    window.toolbar.rows = 0;
    window.toolbar.toolBarProc =
        (WNDPROC)icvGetWindowLongPtr(window.toolbar.toolbar, CV_WNDPROC);

    icvUpdateWindowPos(window);

    // Subclassing from toolbar
    icvSetWindowLongPtr(window.toolbar.toolbar, CV_WNDPROC, HGToolbarProc);
    icvSetWindowLongPtr(window.toolbar.toolbar, CV_USERDATA, (void*)&window);

}

static
std::shared_ptr<CvTrackbar> createTrackbar_(CvWindow& window, const std::string& trackbar_name,
    int count,
    TrackbarCallback onChange, void* userdata)
{
    // create toolbar if it is not created yet
    if (!window.toolbar.toolbar)
    {
        createToolbar_(window);
    }

    TBBUTTON tbs = {};

    /* Retrieve current buttons count */
    int bcount = (int)SendMessage(window.toolbar.toolbar, TB_BUTTONCOUNT, 0, 0);

    if (bcount > 1)
    {
        /* If this is not the first button then we need to
        separate it from the previous one */
        tbs.iBitmap = 0;
        tbs.idCommand = bcount; // Set button id to it's number
        tbs.iString = 0;
        tbs.fsStyle = TBSTYLE_SEP;
        tbs.fsState = TBSTATE_ENABLED;
        SendMessage(window.toolbar.toolbar, TB_ADDBUTTONS, 1, (LPARAM)&tbs);

        // Retrieve current buttons count
        bcount = (int)SendMessage(window.toolbar.toolbar, TB_BUTTONCOUNT, 0, 0);
    }

    /* Add a button which we're going to cover with the slider */
    tbs.iBitmap = 0;
    tbs.idCommand = bcount; // Set button id to it's number
    tbs.fsState = TBSTATE_ENABLED;
#if 0/*!defined WIN64 && !defined EM64T*/
    tbs.fsStyle = 0;
    tbs.iString = 0;
#else

#ifndef TBSTYLE_AUTOSIZE
#define TBSTYLE_AUTOSIZE        0x0010
#endif

#ifndef TBSTYLE_GROUP
#define TBSTYLE_GROUP           0x0004
#endif
    //tbs.fsStyle = TBSTYLE_AUTOSIZE;
    tbs.fsStyle = TBSTYLE_GROUP;
    tbs.iString = (INT_PTR)trackbar_text;
#endif
    SendMessage(window.toolbar.toolbar, TB_ADDBUTTONS, 1, (LPARAM)&tbs);

    TBBUTTONINFO tbis = {};

    /* Adjust button size to the slider */
    tbis.cbSize = sizeof(tbis);
    tbis.dwMask = TBIF_SIZE;

    RECT rect = { 0 };
    GetClientRect(window.hwnd, &rect);
    tbis.cx = (unsigned short)(rect.right - rect.left);

    SendMessage(window.toolbar.toolbar, TB_SETBUTTONINFO,
        (WPARAM)tbs.idCommand, (LPARAM)&tbis);

    /* Get button pos */
    SendMessage(window.toolbar.toolbar, TB_GETITEMRECT,
        (WPARAM)tbs.idCommand, (LPARAM)&rect);

    /* Create a slider */
    auto trackbar = std::make_shared<CvTrackbar>(window, trackbar_name);
    trackbar->id = bcount;
    window.toolbar.trackbars.push_back(trackbar);

    auto slider_name = cv::format("Trackbar%p", trackbar.get());
    trackbar->hwnd = CreateWindowEx(0, TRACKBAR_CLASS, slider_name.c_str(),
                        WS_CHILD | WS_VISIBLE | TBS_AUTOTICKS |
                        TBS_FIXEDLENGTH | TBS_HORZ | TBS_BOTTOM,
                        rect.left + HG_BUDDY_WIDTH, rect.top,
                        rect.right - rect.left - HG_BUDDY_WIDTH,
                        rect.bottom - rect.top, window.toolbar.toolbar,
                        (HMENU)(size_t)bcount, hg_hinstance, 0);

    slider_name = cv::format("Buddy%p", trackbar.get());
    trackbar->buddy = CreateWindowEx(0, "STATIC", slider_name.c_str(),
                        WS_CHILD | SS_RIGHT,
                        rect.left, rect.top,
                        HG_BUDDY_WIDTH, rect.bottom - rect.top,
                        window.toolbar.toolbar, 0, hg_hinstance, 0);

    icvSetWindowLongPtr(trackbar->hwnd, CV_USERDATA, (void*)trackbar.get());

    /* Minimize the number of rows */
    SendMessage(window.toolbar.toolbar, TB_SETROWS,
                MAKEWPARAM(1, FALSE), (LPARAM)&rect);

    trackbar->maxval = count;

    /* Adjust slider parameters */
    SendMessage(trackbar->hwnd, TBM_SETRANGEMIN, (WPARAM)TRUE, (LPARAM)0);
    SendMessage(trackbar->hwnd, TBM_SETRANGEMAX, (WPARAM)TRUE, (LPARAM)count);
    SendMessage(trackbar->hwnd, TBM_SETTICFREQ, (WPARAM)1, (LPARAM)0);

    int pos = 0;
    SendMessage(trackbar->hwnd, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)pos);
    SendMessage(window.toolbar.toolbar, TB_AUTOSIZE, 0, 0);

    trackbar->pos = -1;
    icvUpdateTrackbar(*trackbar, pos);
    ShowWindow(trackbar->buddy, SW_SHOW);
    ShowWindow(trackbar->hwnd, SW_SHOW);

    /* Resize the window to reflect the toolbar resizing*/
    icvUpdateWindowPos(window);

    trackbar->onChangeCallback = onChange;
    trackbar->userdata = userdata;

    return trackbar;
}

CV_IMPL int
cvCreateTrackbar(const char* trackbar_name, const char* window_name,
                 int* val, int count, CvTrackbarCallback on_notify)
{
    return icvCreateTrackbar(trackbar_name, window_name, val, count,
        on_notify, 0, 0);
}

CV_IMPL int
cvCreateTrackbar2(const char* trackbar_name, const char* window_name,
                  int* val, int count, CvTrackbarCallback2 on_notify2,
                  void* userdata)
{
    return icvCreateTrackbar(trackbar_name, window_name, val, count,
        0, on_notify2, userdata);
}

CV_IMPL void
cvSetMouseCallback(const char* name, CvMouseCallback on_mouse, void* param)
{
    CV_FUNCNAME("cvSetMouseCallback");

    if (!name)
        CV_Error(Error::StsNullPtr, "NULL window name");

    AutoLock lock(getWindowMutex());

    auto window = icvFindWindowByName(name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", name));

    window->on_mouse = on_mouse;
    window->on_mouse_param = param;
}


CV_IMPL int cvGetTrackbarPos(const char* trackbar_name, const char* window_name)
{
    CV_FUNCNAME("cvGetTrackbarPos");

    AutoLock lock(getWindowMutex());

    if (trackbar_name == 0 || window_name == 0)
        CV_Error(Error::StsNullPtr, "NULL trackbar or window name");

    auto window = icvFindWindowByName(window_name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", window_name));

    auto trackbar = icvFindTrackbarByName(window, trackbar_name);
    if (!trackbar)
        CV_Error_(Error::StsNullPtr, ("NULL trackbar: '%s'", trackbar_name));

    return trackbar->pos;
}


CV_IMPL void cvSetTrackbarPos(const char* trackbar_name, const char* window_name, int pos)
{
    CV_FUNCNAME("cvSetTrackbarPos");

    AutoLock lock(getWindowMutex());

    if (trackbar_name == 0 || window_name == 0)
        CV_Error(Error::StsNullPtr, "NULL trackbar or window name");

    auto window = icvFindWindowByName(window_name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", window_name));

    auto trackbar = icvFindTrackbarByName(window, trackbar_name);
    if (!trackbar)
        CV_Error_(Error::StsNullPtr, ("NULL trackbar: '%s'", trackbar_name));

    {
        if (pos < 0)
            pos = 0;

        if (pos > trackbar->maxval)
            pos = trackbar->maxval;

        SendMessage(trackbar->hwnd, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)pos);
        icvUpdateTrackbar(*trackbar, pos);
    }
}


CV_IMPL void cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval)
{
    CV_FUNCNAME("cvSetTrackbarMax");

    if (trackbar_name == 0 || window_name == 0)
    {
        CV_Error(Error::StsNullPtr, "NULL trackbar or window name");
    }

    AutoLock lock(getWindowMutex());

    auto window = icvFindWindowByName(window_name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", window_name));

    auto trackbar = icvFindTrackbarByName(window, trackbar_name);
    if (!trackbar)
        CV_Error_(Error::StsNullPtr, ("NULL trackbar: '%s'", trackbar_name));

    // FIXIT
    if (maxval >= 0)
    {
        // The position will be min(pos, maxval).
        trackbar->maxval = (trackbar->minval>maxval)?trackbar->minval:maxval;
        SendMessage(trackbar->hwnd, TBM_SETRANGEMAX, (WPARAM)TRUE, (LPARAM)maxval);
    }
}


CV_IMPL void cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval)
{
    CV_FUNCNAME("cvSetTrackbarMin");

    if (trackbar_name == 0 || window_name == 0)
    {
        CV_Error(Error::StsNullPtr, "NULL trackbar or window name");
    }

    AutoLock lock(getWindowMutex());

    auto window = icvFindWindowByName(window_name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", window_name));

    auto trackbar = icvFindTrackbarByName(window, trackbar_name);
    if (!trackbar)
        CV_Error_(Error::StsNullPtr, ("NULL trackbar: '%s'", trackbar_name));

    // FIXIT
    if (minval >= 0)
    {
        // The position will be min(pos, maxval).
        trackbar->minval = (minval<trackbar->maxval)?minval:trackbar->maxval;
        SendMessage(trackbar->hwnd, TBM_SETRANGEMIN, (WPARAM)TRUE, (LPARAM)minval);
    }
}


CV_IMPL void* cvGetWindowHandle(const char* window_name)
{
    CV_FUNCNAME("cvGetWindowHandle");

    AutoLock lock(getWindowMutex());

    if (window_name == 0)
        CV_Error(Error::StsNullPtr, "NULL window name");

    auto window = icvFindWindowByName(window_name);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%s'", window_name));

    return (void*)window->hwnd;
}

// FIXIT: result is not safe to use
CV_IMPL const char* cvGetWindowName(void* window_handle)
{
    CV_FUNCNAME("cvGetWindowName");

    AutoLock lock(getWindowMutex());

    if (window_handle == 0)
        CV_Error(Error::StsNullPtr, "NULL window handle");

    auto window = icvWindowByHWND((HWND)window_handle);
    if (!window)
        CV_Error_(Error::StsNullPtr, ("NULL window: '%p'", window_handle));

    return window->name.c_str();
}


CV_IMPL void
cvSetPreprocessFuncWin32_(const void* callback)
{
    hg_on_preprocess = (CvWin32WindowCallback)callback;
}

CV_IMPL void
cvSetPostprocessFuncWin32_(const void* callback)
{
    hg_on_postprocess = (CvWin32WindowCallback)callback;
}



namespace cv { namespace impl {

using namespace cv::highgui_backend;

class Win32UITrackbar;

class Win32UIWindow
        : public UIWindow
        , public std::enable_shared_from_this<Win32UIWindow>
{
protected:
    const std::string name_;
    std::weak_ptr<CvWindow> window_;
    std::map<std::string, std::shared_ptr<Win32UITrackbar> > trackbars_;
public:
    Win32UIWindow(const std::string& name, const std::shared_ptr<CvWindow>& window)
        : name_(name)
        , window_(window)
    {
        // nothing
    }

    ~Win32UIWindow() CV_OVERRIDE
    {
        if (!window_.expired())
            destroy();
        CV_LOG_DEBUG(NULL, "OpenCV/UI/Win32UI: Win32UIWindow(" << name_ << ") is disposed");
    }

    const std::string& getID() const CV_OVERRIDE { return name_; }

    bool isActive() const CV_OVERRIDE { return !window_.expired(); }

    void destroy() CV_OVERRIDE
    {
        cv::AutoLock lock(getWindowMutex());
        if (!window_.expired())
        {
            auto window = window_.lock();
            if (window)
                window->destroy();
            window_.reset();
        }
    }

    void imshow(InputArray image) CV_OVERRIDE
    {
        auto window_ptr = window_.lock();
        CV_Assert(window_ptr);
        CvWindow& window = *window_ptr;
        Mat image_mat = image.getMat();
        showImage_(window, image_mat);
    }

    double getProperty(int prop) const CV_OVERRIDE
    {
        auto window_ptr = window_.lock();
        CV_Assert(window_ptr);
        CvWindow& window = *window_ptr;
        // see cvGetWindowProperty
        switch ((WindowPropertyFlags)prop)
        {
        case WND_PROP_FULLSCREEN:
            return (double)window.status;

        case WND_PROP_AUTOSIZE:
            return (window.flags & WINDOW_AUTOSIZE) ? 1.0 : 0.0;

        case WND_PROP_ASPECT_RATIO:
            return static_cast<double>(window.width) / window.height;

#ifdef HAVE_OPENGL
        case WND_PROP_OPENGL:
            return window.useGl ? 1.0 : 0.0;
#endif

        case WND_PROP_VISIBLE:
            return 1.0;

        case WND_PROP_TOPMOST:
            return getPropTopmost_(window);

        case WND_PROP_VSYNC:
            return getPropVsync_(window);

        // don't use default, add unsupported cases below:
        // case WND_PROP_UNSUPPORTED:  // fallthru
        //    break;
        }
        return std::numeric_limits<double>::quiet_NaN();
    }

    bool setProperty(int prop, double value) CV_OVERRIDE
    {
        auto window_ptr = window_.lock();
        CV_Assert(window_ptr);
        CvWindow& window = *window_ptr;
        // see cvSetWindowProperty
        switch ((WindowPropertyFlags)prop)
        {
        case WND_PROP_FULLSCREEN:
            if (value != WINDOW_NORMAL && value != WINDOW_FULLSCREEN)  // bad arg
                break;
            setModeWindow_(window, (int)value);
            return true;

        case WND_PROP_TOPMOST:
            return setPropTopmost_(window, value != 0.0);

        case WND_PROP_VSYNC:
            return setPropVsync_(window, value != 0.0);

        // don't use default, add unsupported cases below:
        // case WND_PROP_UNSUPPORTED:  // fallthru
        case WND_PROP_AUTOSIZE:  // fallthru
        case WND_PROP_ASPECT_RATIO:  // fallthru
        case WND_PROP_OPENGL:  // fallthru
        case WND_PROP_VISIBLE:  // fallthru
            break;
        }
        return false;
    }

    void resize(int width, int height) CV_OVERRIDE
    {
        auto window_ptr = window_.lock();
        CV_Assert(window_ptr);
        CvWindow& window = *window_ptr;
        resizeWindow_(window, Size(width, height));
    }

    void move(int x, int y) CV_OVERRIDE
    {
        auto window_ptr = window_.lock();
        CV_Assert(window_ptr);
        CvWindow& window = *window_ptr;
        moveWindow_(window, Point(x, y));
    }

    Rect getImageRect() const CV_OVERRIDE
    {
        auto window_ptr = window_.lock();
        CV_Assert(window_ptr);
        CvWindow& window = *window_ptr;
        return getImageRect_(window);
    }

    void setTitle(const std::string& title) CV_OVERRIDE
    {
        auto window_ptr = window_.lock();
        CV_Assert(window_ptr);
        CvWindow& window = *window_ptr;
        if (!SetWindowText(window.frame, title.c_str()))
            CV_Error_(Error::StsError, ("Failed to set \"%s\" window title to \"%s\"", window.name.c_str(), title.c_str()));
    }

    void setMouseCallback(MouseCallback onMouse, void* userdata /*= 0*/) CV_OVERRIDE
    {
        auto window_ptr = window_.lock();
        CV_Assert(window_ptr);
        CvWindow& window = *window_ptr;
        window.on_mouse = onMouse;
        window.on_mouse_param = userdata;
    }

    std::shared_ptr<UITrackbar> createTrackbar(
        const std::string& name,
        int count,
        TrackbarCallback onChange /*= 0*/,
        void* userdata /*= 0*/
    ) CV_OVERRIDE
    {
        auto window_ptr = window_.lock();
        CV_Assert(window_ptr);
        CvWindow& window = *window_ptr;
        CV_LOG_INFO(NULL, "OpenCV/UI: Creating Win32UI trackbar at '" << name_ << "': '" << name << "'");
        auto trackbar = createTrackbar_(window, name, count, onChange, userdata);
        auto ui_trackbar = std::make_shared<Win32UITrackbar>(name, trackbar, shared_from_this());
        {
            cv::AutoLock lock(getWindowMutex());
            trackbars_.emplace(name, ui_trackbar);
        }
        return std::static_pointer_cast<UITrackbar>(ui_trackbar);
    }

    std::shared_ptr<UITrackbar> findTrackbar(const std::string& name) CV_OVERRIDE
    {
        cv::AutoLock lock(getWindowMutex());
        auto i = trackbars_.find(name);
        if (i != trackbars_.end())
        {
            return std::static_pointer_cast<UITrackbar>(i->second);
        }
        return std::shared_ptr<UITrackbar>();
    }
};  // Win32UIWindow


class Win32UITrackbar : public UITrackbar
{
protected:
    /*const*/ std::string name_;
    std::weak_ptr<CvTrackbar> trackbar_;
    std::weak_ptr<Win32UIWindow> parent_;
    std::map<std::string, std::shared_ptr<Win32UITrackbar> > trackbars_;
public:
    Win32UITrackbar(const std::string& name, const std::shared_ptr<CvTrackbar>& trackbar, const std::shared_ptr<Win32UIWindow>& parent)
        : trackbar_(trackbar)
        , parent_(parent)
    {
        name_ = std::string("<") + name + ">@" + parent->getID();
    }

    ~Win32UITrackbar() CV_OVERRIDE
    {
        if (!trackbar_.expired())
            destroy();
        CV_LOG_DEBUG(NULL, "OpenCV/UI/Win32UI: Win32UITrackbar(" << name_ << ") is disposed");
    }

    const std::string& getID() const CV_OVERRIDE { return name_; }

    bool isActive() const CV_OVERRIDE { return !trackbar_.expired(); }

    void destroy() CV_OVERRIDE
    {
        // nothing (destroyed with parent window, dedicated trackbar removal is not supported)
    }

    int getPos() const CV_OVERRIDE
    {
        auto trackbar_ptr = trackbar_.lock();
        CV_Assert(trackbar_ptr);
        CvTrackbar& trackbar = *trackbar_ptr;
        return trackbar.pos;
    }
    void setPos(int pos) CV_OVERRIDE
    {
        auto trackbar_ptr = trackbar_.lock();
        CV_Assert(trackbar_ptr);
        CvTrackbar& trackbar = *trackbar_ptr;
        SendMessage(trackbar.hwnd, TBM_SETPOS, (WPARAM)TRUE, (LPARAM)pos);
        icvUpdateTrackbar(trackbar, pos);
    }

    cv::Range getRange() const CV_OVERRIDE
    {
        auto trackbar_ptr = trackbar_.lock();
        CV_Assert(trackbar_ptr);
        CvTrackbar& trackbar = *trackbar_ptr;
        return cv::Range(trackbar.minval, trackbar.maxval);
    }

    void setRange(const cv::Range& range) CV_OVERRIDE
    {
        auto trackbar_ptr = trackbar_.lock();
        CV_Assert(trackbar_ptr);
        CvTrackbar& trackbar = *trackbar_ptr;
        CV_CheckLE(range.start, range.end, "Invalid trackbar range");
        trackbar.minval = range.start;
        trackbar.maxval = range.start;
        SendMessage(trackbar.hwnd, TBM_SETRANGEMIN, (WPARAM)TRUE, (LPARAM)trackbar.minval);
        SendMessage(trackbar.hwnd, TBM_SETRANGEMAX, (WPARAM)TRUE, (LPARAM)trackbar.maxval);
    }
};  // Win32UITrackbar


class Win32BackendUI : public UIBackend
{
public:
    ~Win32BackendUI() CV_OVERRIDE
    {
        destroyAllWindows();
    }

    void destroyAllWindows() CV_OVERRIDE
    {
        cvDestroyAllWindows();
    }

    // namedWindow
    virtual std::shared_ptr<UIWindow> createWindow(
        const std::string& winname,
        int flags
    ) CV_OVERRIDE
    {
        CV_LOG_INFO(NULL, "OpenCV/UI: Creating Win32UI window: " << winname << " (" << flags << ")");
        auto window = namedWindow_(winname, flags);
        auto ui_window = std::make_shared<Win32UIWindow>(winname, window);
        return ui_window;
    }

    int waitKeyEx(int delay) CV_OVERRIDE
    {
        return cvWaitKey(delay);
    }
    int pollKey() CV_OVERRIDE
    {
        return pollKey_W32();
    }
};  // Win32BackendUI

static
std::shared_ptr<Win32BackendUI>& getInstance()
{
    static std::shared_ptr<Win32BackendUI> g_instance = std::make_shared<Win32BackendUI>();
    return g_instance;
}

} // namespace impl

#ifndef BUILD_PLUGIN
namespace highgui_backend {

std::shared_ptr<UIBackend> createUIBackendWin32UI()
{
    return impl::getInstance();
}

}  // namespace highgui_backend
#endif

}  // namespace


#ifdef BUILD_PLUGIN

#define ABI_VERSION 0
#define API_VERSION 0
#include "plugin_api.hpp"

static
CvResult cv_getInstance(CV_OUT CvPluginUIBackend* handle) CV_NOEXCEPT
{
    try
    {
        if (!handle)
            return CV_ERROR_FAIL;
        *handle = cv::impl::getInstance().get();
        return CV_ERROR_OK;
    }
    catch (...)
    {
        return CV_ERROR_FAIL;
    }
}

static const OpenCV_UI_Plugin_API plugin_api =
{
    {
        sizeof(OpenCV_UI_Plugin_API), ABI_VERSION, API_VERSION,
        CV_VERSION_MAJOR, CV_VERSION_MINOR, CV_VERSION_REVISION, CV_VERSION_STATUS,
        "Win32 OpenCV UI plugin"
    },
    {
        /*  1*/cv_getInstance
    }
};

const OpenCV_UI_Plugin_API* CV_API_CALL opencv_ui_plugin_init_v0(int requested_abi_version, int requested_api_version, void* /*reserved=NULL*/) CV_NOEXCEPT
{
    if (requested_abi_version == ABI_VERSION && requested_api_version <= API_VERSION)
        return &plugin_api;
    return NULL;
}

#endif  // BUILD_PLUGIN

#endif  // HAVE_WIN32UI