1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751
|
// =================================================================================================
// Copyright 2003 Adobe
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
#include "public/include/XMP_Environment.h" // ! This must be the first include!
#include "XMPCore/source/XMPCore_Impl.hpp"
#include "XMPCore/source/XMPUtils.hpp"
#include "third-party/zuid/interfaces/MD5.h"
#include <map>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>
#include <errno.h>
#include <vector>
#include <stdio.h> // For snprintf.
#if ENABLE_CPP_DOM_MODEL
#include "source/UnicodeInlines.incl_cpp"
#include "source/UnicodeConversions.hpp"
#include "XMPMeta2.hpp"
#include "XMPCore/Interfaces/IMetadata_I.h"
#include "XMPCore/Interfaces/IArrayNode_I.h"
#include "XMPCore/Interfaces/ISimpleNode_I.h"
#include "XMPCommon/Interfaces/IUTF8String_I.h"
#include "XMPCore/Interfaces/INameSpacePrefixMap.h"
#include "XMPCore/Interfaces/INodeIterator.h"
using namespace AdobeXMPCore;
using namespace AdobeXMPCommon;
#endif
#if XMP_WinBuild
#pragma warning ( disable : 4800 ) // forcing value to bool 'true' or 'false' (performance warning)
#pragma warning ( disable : 4996 ) // '...' was declared deprecated
#endif
// =================================================================================================
// Local Types and Constants
// =========================
static const char * sBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const XMP_VarString xmlNameSpace = "http://www.w3.org/XML/1998/namespace";
// =================================================================================================
// Local Utilities
// ===============
// -------------------------------------------------------------------------------------------------
// SetINode
// --------------
#if ENABLE_CPP_DOM_MODEL
void XMPUtils::SetNode ( const spINode & node , XMP_StringPtr value, XMP_OptionBits options )
{
if (!node) return;
//TO DO check UTF-8
if ( options & kXMP_DeleteExisting ) {
XMP_ClearOption ( options, kXMP_DeleteExisting );
node->Clear();
}
if ( value != 0 ) {
if ( options & kXMP_PropCompositeMask ) XMP_Throw ( "Composite nodes can't have values", kXMPErr_BadXPath );
if ( !node ) return;
XMP_Assert( node->GetNodeType() == INode::kNTSimple);
spISimpleNode simpleNode = node->ConvertToSimpleNode();
std::string newValue = value;
XMP_Uns8* chPtr = (XMP_Uns8*) newValue.c_str(); // Check for valid UTF-8, replace ASCII controls with a space.
while ( *chPtr != 0 ) {
while ( (*chPtr != 0) && (*chPtr < 0x80) ) {
if ( *chPtr < 0x20 ) {
if ( (*chPtr != kTab) && (*chPtr != kLF) && (*chPtr != kCR) ) *chPtr = 0x20;
}
else if (*chPtr == 0x7F ) {
*chPtr = 0x20;
}
++chPtr;
}
XMP_Assert ( (*chPtr == 0) || (*chPtr >= 0x80) );
if ( *chPtr != 0 ) {
XMP_Uns32 cp = GetCodePoint ( (const XMP_Uns8 **) &chPtr ); // Throws for bad UTF-8.
if ( (cp == 0xFFFE) || (cp == 0xFFFF) ) {
XMP_Throw ( "U+FFFE and U+FFFF are not allowed in XML", kXMPErr_BadUnicode );
}
}
}
if ( XMP_PropIsQualifier(options) && XMP_LitMatch(node->GetNameSpace()->c_str(), xmlNameSpace.c_str()) && XMP_LitMatch(node->GetName()->c_str(), "lang")) NormalizeLangValue ( &newValue );
simpleNode->SetValue(newValue.c_str(), newValue.size());
}
else {
if((node->GetNodeType() == INode::kNTStructure && (options & kXMP_PropValueIsArray)) || (node->GetNodeType() == INode::kNTArray && (options & kXMP_PropValueIsStruct))) {
XMP_Throw ( "Requested and existing composite form mismatch", kXMPErr_BadXPath );
}
node->Clear();
}
} // SetINode
XMP_OptionBits XMPUtils::ConvertNewArrayFormToOldArrayForm (const spcIArrayNode & arrayNode) {
XMP_OptionBits options = 0;
if(!arrayNode) return options;
if( arrayNode->GetArrayForm() == IArrayNode::kAFAlternative) return kXMP_PropArrayIsAlternate;
if( arrayNode->GetArrayForm() == IArrayNode::kAFOrdered) return kXMP_PropArrayIsOrdered;
if( arrayNode->GetArrayForm() == IArrayNode::kAFUnordered) return kXMP_PropArrayIsUnordered;
return 0;
}
spINode XMPUtils::CreateArrayChildNode( const spIArrayNode & arrayNode, XMP_OptionBits options) {
XMP_VarString nodeNameSpace = arrayNode->GetNameSpace()->c_str(), nodeName = arrayNode->GetName()->c_str();
spINode itemNode;
size_t arrayChildCount = arrayNode->ChildCount();
spINode firstChildNode;
if (!arrayChildCount) {
itemNode = XMPUtils::CreateTerminalNode(nodeNameSpace.c_str(), nodeName.c_str(), options);
return itemNode;
}
if(arrayChildCount) firstChildNode = arrayNode->GetNodeAtIndex(1);
XMP_OptionBits childOptions = 0;
if(firstChildNode && firstChildNode->GetNodeType() == INode::kNTArray) {
childOptions = ConvertNewArrayFormToOldArrayForm(firstChildNode->ConvertToArrayNode());
}
if(XMP_PropIsStruct(options) && (!arrayChildCount || firstChildNode->GetNodeType() == INode::kNTStructure ) ) {
itemNode = IStructureNode::CreateStructureNode(nodeNameSpace.c_str(), nodeNameSpace.size(), nodeName.c_str(), nodeName.size() );
}
else if(XMP_PropIsSimple(options) && (!arrayChildCount || firstChildNode->GetNodeType() == INode::kNTSimple ) ) {
itemNode = ISimpleNode::CreateSimpleNode(nodeNameSpace.c_str(), nodeNameSpace.size(), nodeName.c_str(), nodeName.size(), "", 0 );
}
else if((options & kXMP_PropArrayIsAlternate) && (childOptions & kXMP_PropArrayIsAlternate) ) {
itemNode = IArrayNode::CreateAlternativeArrayNode( nodeNameSpace.c_str(), nodeNameSpace.size(), nodeName.c_str(), nodeName.size() );
}
else if((options & kXMP_PropArrayIsOrdered) && (childOptions & kXMP_PropArrayIsOrdered)) {
itemNode = IArrayNode::CreateOrderedArrayNode( nodeNameSpace.c_str(), nodeNameSpace.size(), nodeName.c_str(), nodeName.size() );
}
else if((options & kXMP_PropArrayIsUnordered) && (childOptions & kXMP_PropArrayIsUnordered)) {
itemNode = IArrayNode::CreateUnorderedArrayNode( nodeNameSpace.c_str(), nodeNameSpace.size(), nodeName.c_str(), nodeName.size() );
}
if(!itemNode) XMP_Throw("Array has to be homogeneous", kXMPErr_BadXPath);
return itemNode;
}
void
XMPUtils::DoSetArrayItem ( const spIArrayNode &arrayNode,
XMP_Index itemIndex,
XMP_StringPtr itemValue,
XMP_OptionBits options )
{
XMP_OptionBits itemLoc = options & kXMP_PropArrayLocationMask;
XMP_Index arraySize = static_cast<XMP_Index>( arrayNode->ChildCount() );
XMP_VarString arrayNameSpace = arrayNode->GetNameSpace()->c_str();
XMP_VarString arrayName = arrayNode->GetName()->c_str();
options &= ~kXMP_PropArrayLocationMask;
options = VerifySetOptions ( options, itemValue );
// Now locate or create the item node and set the value. Note the index parameter is one-based!
// The index can be in the range [0..size+1] or "last", normalize it and check the insert flags.
// The order of the normalization checks is important. If the array is empty we end up with an
// index and location to set item size+1.
spINode itemNode;
if ( itemIndex == kXMP_ArrayLastItem ) itemIndex = arraySize;
if ( (itemIndex == 0) && (itemLoc == kXMP_InsertAfterItem) ) {
itemIndex = 1;
itemLoc = kXMP_InsertBeforeItem;
}
if ( (itemIndex == arraySize) && (itemLoc == kXMP_InsertAfterItem) ) {
itemIndex += 1;
itemLoc = 0;
}
if ( (itemIndex == arraySize + 1) && (itemLoc == kXMP_InsertBeforeItem) ) itemLoc = 0;
if ( itemIndex == arraySize + 1 ) {
if ( itemLoc ) XMP_Throw ( "Can't insert before or after implicit new item", kXMPErr_BadIndex );
itemNode = CreateArrayChildNode(arrayNode, options);
arrayNode->InsertNodeAtIndex(itemNode, arraySize + 1);
}
else {
if ( (itemIndex < 1) || (itemIndex > arraySize) ) XMP_Throw ( "Array index out of bounds", kXMPErr_BadIndex );
if ( itemLoc == 0 ) {
itemNode = arrayNode->GetNodeAtIndex( itemIndex )->ConvertToSimpleNode();
}
else {
itemNode = CreateArrayChildNode(arrayNode, options);
if ( itemLoc == kXMP_InsertAfterItem ) ++itemIndex;
arrayNode->InsertNodeAtIndex (itemNode, itemIndex );
}
}
SetNode(itemNode, itemValue, options);
} // DoSetIXMPArrayItem
void XMPUtils::SetImplicitNodeInformation( bool & firstImplicitNodeFound,
spINode &implicitNodeRoot,
spINode &destNode,
XMP_Index &implicitNodeIndex,
XMP_Index index )
{
if(!firstImplicitNodeFound) {
implicitNodeRoot = destNode;
firstImplicitNodeFound = true;
if( index) {
implicitNodeIndex = index;
}
}
}
void XMPUtils::GetNameSpaceAndNameFromStepValue( const std::string & stepStr,
const spcINameSpacePrefixMap & defaultMap,
std::string &stepNameSpace,
std::string &stepName)
{
size_t colonPos = stepStr.find(':');
XMP_VarString prefix = stepStr.substr( 0, colonPos );
stepNameSpace = defaultMap->GetNameSpace( prefix.c_str(), prefix.size() )->c_str();
stepName = stepStr.substr( colonPos + 1);
}
// =================================================================================================
// FindNode
// ========
//
// Follow an expanded path expression to find or create a node. Returns a pointer to the node, and
// optionally an iterator for the node's position in the parent's vector of children or qualifiers.
// The iterator is unchanged if no child node (null) is returned.
spINode XMPUtils::CreateTerminalNode(const char* nameSpace, const char * name, XMP_OptionBits options) {
spINode newNode;
if(XMP_PropIsSimple(options)) {
spISimpleNode simpleNode = ISimpleNode::CreateSimpleNode(nameSpace, AdobeXMPCommon::npos, name, AdobeXMPCommon::npos, NULL, 0 );
newNode = simpleNode;
}
if(XMP_PropIsStruct(options)){
spIStructureNode structNode = IStructureNode::CreateStructureNode(nameSpace, AdobeXMPCommon::npos, name, AdobeXMPCommon::npos);
newNode = structNode;
}
if(XMP_PropIsArray(options)) {
if ( options & kXMP_PropArrayIsAlternate )
newNode = IArrayNode::CreateAlternativeArrayNode( nameSpace, AdobeXMPCommon::npos, name, AdobeXMPCommon::npos );
else if(options & kXMP_PropArrayIsOrdered)
newNode = IArrayNode::CreateOrderedArrayNode( nameSpace, AdobeXMPCommon::npos, name, AdobeXMPCommon::npos );
else
newNode = IArrayNode::CreateUnorderedArrayNode( nameSpace, AdobeXMPCommon::npos, name, AdobeXMPCommon::npos );
}
return newNode;
}
bool XMPUtils::HandleConstAliasStep(const spIMetadata & mDOM,
spINode &destNode,
const XMP_ExpandedXPath & expandedXPath,
XMP_Index *nodeIndex
)
{
destNode = mDOM;
if (expandedXPath.empty()) XMP_Throw("Empty XPath", kXMPErr_BadXPath);
if (!(expandedXPath[kRootPropStep].options & kXMP_StepIsAlias)) {
return false;
}
else {
XMP_AliasMapPos aliasPos = sRegisteredAliasMap->find(expandedXPath[kRootPropStep].step);
XMP_Assert(aliasPos != sRegisteredAliasMap->end());
XMP_VarString namespaceName = aliasPos->second[kSchemaStep].step.c_str();
size_t colonPos = aliasPos->second[kRootPropStep].step.find(":");
XMP_Assert(colonPos != std::string::npos);
XMP_VarString propertyName = aliasPos->second[kRootPropStep].step.substr( colonPos + 1);
destNode = mDOM->GetNode( namespaceName.c_str(), namespaceName.size(), propertyName.c_str(), propertyName.size() );
if (!destNode) return false;
if (aliasPos->second.size() == 2) return true;
XMP_Assert(destNode->GetNodeType() == INode::kNTArray);
if (aliasPos->second[2].options == kXMP_ArrayIndexStep) {
XMP_Assert(aliasPos->second[2].step == "[1]");
destNode = destNode->ConvertToArrayNode()->GetNodeAtIndex( 1 );
INode::eNodeType actualNodeType = destNode->GetNodeType();
if (destNode) {
if (nodeIndex) *nodeIndex = 1;
return true;
}
return false;
}
else if (aliasPos->second[2].options == kXMP_QualSelectorStep) {
XMP_Assert(aliasPos->second[2].step == "[?xml:lang=\"x-default\"]");
spcINodeIterator iter = XMPUtils::GetNodeChildIterator(destNode);
XMP_Index index = 1;
while (iter) {
spcINode node = iter->GetNode();
spcINode qualNode = node->GetQualifier(xmlNameSpace.c_str(), xmlNameSpace.size(), "lang", AdobeXMPCommon::npos );
if (qualNode->GetNodeType() == INode::kNTSimple) {
if (!strcmp("x-default", qualNode->ConvertToSimpleNode()->GetValue()->c_str())){
destNode = AdobeXMPCore_Int::const_pointer_cast<INode>(node);
if (nodeIndex) *nodeIndex = index;
return true;
}
}
index++;
iter =iter->Next();
}
return false;
}
return false;
}
}
bool XMPUtils::HandleAliasStep(const spIMetadata & mDOM,
XMP_ExpandedXPath &expandedXPath,
bool createNodes,
XMP_OptionBits leafOptions /* = 0 */,
spINode &destNode,
XMP_Index *nodeIndex,
bool ignoreLastStep
)
{
destNode = mDOM;
bool isAliasBeingCreated = expandedXPath.size() == 2;
if (expandedXPath.empty()) XMP_Throw("Empty XPath", kXMPErr_BadXPath);
if (!(expandedXPath[kRootPropStep].options & kXMP_StepIsAlias)) {
return false;
}
else {
XMP_AliasMapPos aliasPos = sRegisteredAliasMap->find(expandedXPath[kRootPropStep].step);
XMP_Assert(aliasPos != sRegisteredAliasMap->end());
XMP_VarString namespaceName = aliasPos->second[kSchemaStep].step.c_str();
size_t colonPos = aliasPos->second[kRootPropStep].step.find(":");
XMP_Assert(colonPos != std::string::npos);
XMP_VarString propertyName = aliasPos->second[kRootPropStep].step.substr(colonPos + 1);
destNode = mDOM->GetNode(namespaceName.c_str(), namespaceName.size(), propertyName.c_str(), propertyName.size() );
if (!destNode && !createNodes) return false;
if (aliasPos->second.size() == 2) {
if (destNode) return true;
XMP_OptionBits createOptions = 0;
destNode = mDOM;
if (isAliasBeingCreated) createOptions = leafOptions;
spINode tempNode = CreateTerminalNode(namespaceName.c_str(), propertyName.c_str(), createOptions);
if (!tempNode) return false;
destNode->ConvertToStructureNode()->AppendNode( tempNode );
destNode = tempNode;
if (destNode) return true;
return false;
}
//XMP_Assert(destNode->GetNodeType() == INode::kNTArray);
XMP_Assert(aliasPos->second.size() == 3);
if (aliasPos->second[2].options == kXMP_ArrayIndexStep) {
XMP_Assert(aliasPos->second[2].step == "[1]");
destNode = mDOM->GetNode(namespaceName.c_str(), namespaceName.size(), propertyName.c_str(), propertyName.size() );
if (!destNode && !createNodes) return false;
if (!destNode) {
spINode arrayNode = CreateTerminalNode(namespaceName.c_str(), propertyName.c_str(), kXMP_PropArrayIsOrdered | kXMP_PropValueIsArray);
mDOM->AppendNode(arrayNode);
destNode = arrayNode;
}
if ( destNode->ConvertToArrayNode()->GetNodeAtIndex( 1 ) ) {
destNode = destNode->ConvertToArrayNode()->GetNodeAtIndex( 1 );
if (nodeIndex) *nodeIndex = 1;
return true;
}
else {
spISimpleNode indexNode = ISimpleNode::CreateSimpleNode( namespaceName.c_str(), namespaceName.size(), "[]", AdobeXMPCommon::npos, "", AdobeXMPCommon::npos );
destNode->ConvertToArrayNode()->InsertNodeAtIndex( indexNode, 1 );
destNode = destNode->ConvertToArrayNode()->GetNodeAtIndex( 1 );
return true;
}
return false;
}
else if (aliasPos->second[2].options == kXMP_QualSelectorStep) {
XMP_Assert(aliasPos->second[2].step == "[?xml:lang=\"x-default\"]");
destNode = mDOM->GetNode(namespaceName.c_str(), namespaceName.size(), propertyName.c_str(), propertyName.size() );
if (!destNode && !createNodes) return false;
spINode arrayNode = CreateTerminalNode(namespaceName.c_str(), propertyName.c_str(), kXMP_PropArrayIsAltText | kXMP_PropValueIsArray);
mDOM->AppendNode(arrayNode);
destNode = arrayNode;
spcINodeIterator iter = XMPUtils::GetNodeChildIterator(destNode);
XMP_Index index = 1;
while (iter) {
spcINode node = iter->GetNode();
spcINode qualNode = node->GetQualifier(xmlNameSpace.c_str(), xmlNameSpace.size(), "lang", AdobeXMPCommon::npos );
if (qualNode->GetNodeType() == INode::kNTSimple) {
if (!strcmp("x-default", qualNode->ConvertToSimpleNode()->GetValue()->c_str())){
destNode = AdobeXMPCore_Int::const_pointer_cast<INode>(node);
if (nodeIndex) *nodeIndex = index;
return true;
}
}
index++;
iter = iter->Next();
}
spISimpleNode qualifierNode = ISimpleNode::CreateSimpleNode(xmlNameSpace.c_str(), xmlNameSpace.size(), "lang", AdobeXMPCommon::npos, "x-default" );
if ( destNode->ConvertToArrayNode()->GetNodeAtIndex( 1 ) ) {
destNode = destNode->ConvertToArrayNode()->GetNodeAtIndex( 1 );
if (nodeIndex) *nodeIndex = 1;
destNode->InsertQualifier(qualifierNode);
return true;
}
else {
spISimpleNode indexNode = ISimpleNode::CreateSimpleNode(namespaceName.c_str(), namespaceName.size(), "[]", AdobeXMPCommon::npos );
destNode->ConvertToArrayNode()->InsertNodeAtIndex( indexNode, 1 );
destNode->InsertQualifier(qualifierNode);
destNode = destNode->ConvertToArrayNode()->GetNodeAtIndex( 1 );
return true;
}
}
}
return false;
}
bool XMPUtils:: FindNode ( const spIMetadata & mDOM,
XMP_ExpandedXPath & expPath,
bool createNodes,
XMP_OptionBits leafOptions /* = 0 */,
spINode &retNode,
XMP_Index *nodeIndex ,
bool ignoreLastStep
)
{
// TO DO - Differentiate between failures on last step and steps before that
spINode destNode = mDOM;
spINode parentDestNode = mDOM;
bool firstImplicitNodeFound = false;
bool leafIsNew = false;
spINode implicitNodeRoot;
bool qualifierFlag = false;
XMP_Index implicitNodeIndex ; // used in case first implicit node's parent is an array
XMP_Assert ( (leafOptions == 0) || createNodes );
if ( expPath.empty() ) XMP_Throw ( "Empty XPath", kXMPErr_BadXPath );
auto defaultMap = INameSpacePrefixMap::GetDefaultNameSpacePrefixMap();
size_t pathStartIdx = 1;
if (expPath[kRootPropStep].options & kXMP_StepIsAlias) {
if (!HandleAliasStep(mDOM, expPath, createNodes, leafOptions, destNode,0, 0 )) return false;
pathStartIdx = 2;
}
try{
for (size_t i = pathStartIdx, endIndex = (ignoreLastStep) ? expPath.size() - 1 : expPath.size(); i < endIndex; i++) {
// split the path into prefix and property name
if (!destNode) goto EXIT;
XMP_VarString stepStr = expPath[i].step;
XMP_VarString prevStep = (i == 0) ? "" : expPath[i - 1].step;
spcIUTF8String nameSpace;
XMP_VarString stepName;
switch (expPath[i].options) {
case kXMP_StructFieldStep:
{
size_t colonPos = stepStr.find(':');
XMP_VarString prefix = stepStr.substr(0, colonPos);
// get the namespace from the prefix
nameSpace = defaultMap->GetNameSpace(prefix.c_str(), prefix.size());
stepName = stepStr.substr(colonPos + 1);
if (destNode->GetNodeType() == INode::kNTStructure) {
spIStructureNode tempNode = destNode->ConvertToStructureNode();
parentDestNode = destNode;
destNode = tempNode->GetNode(nameSpace->c_str(), nameSpace->size(), stepStr.c_str() + colonPos + 1, AdobeXMPCommon::npos );
if (destNode) continue;
if (!createNodes) return false;
if (i == (expPath.size() - 1)) {
spINode simpleInsertNode = CreateTerminalNode(nameSpace->c_str(), stepName.c_str(), leafOptions);
tempNode->InsertNode(simpleInsertNode);
destNode = simpleInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex);
}
else {
switch (expPath[i + 1].options) {
case kXMP_StructFieldStep:
{
// TODO : Exit and handle deletetion of implicit node
// TODO : structInsertNode :
spIStructureNode structInsertNode = IStructureNode::CreateStructureNode(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size() );
spIStructureNode parentStructNode = parentDestNode->ConvertToStructureNode();
parentStructNode->InsertNode(structInsertNode);
destNode = structInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex);
}
break;
case kXMP_FieldSelectorStep:
case kXMP_QualSelectorStep:
case kXMP_ArrayLastStep:
case kXMP_ArrayIndexStep:
{
// from where will you get arrayform ? which arrayform to set by default?
spIArrayNode arrayInsertNode = IArrayNode::CreateOrderedArrayNode(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size() );
spIStructureNode parentStructNode = parentDestNode->ConvertToStructureNode();
parentStructNode->InsertNode(arrayInsertNode);
destNode = arrayInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex);
}
break;
case kXMP_QualifierStep:
{
spISimpleNode simpleInsertNode = ISimpleNode::CreateSimpleNode(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size() );
spIStructureNode parentStructNode = parentDestNode->ConvertToStructureNode();
parentStructNode->InsertNode(simpleInsertNode);
destNode = simpleInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex);
}
default:
break;
}
}
}
else {
goto EXIT;
}
}
break;
case kXMP_ArrayIndexStep:
{
// TO DO : type array item
// if array not empty -> see type of first array element
// else if next is array type , arrayitem is array
// if next is struct select type, array item is struct
// if next is type qualifier , array item is simple property
// TODO : HANDLE EXIT CASE
//
// we should check if the previous segment is an array segment
if (destNode->GetNodeType() != INode::kNTArray) {
XMP_Throw("Indexing applied to non-array", kXMPErr_BadXPath);
}
spIArrayNode tempNode = destNode->ConvertToArrayNode();
size_t index = 0;
XMP_Assert((stepStr.length() >= 2) && (*(stepStr.begin()) == '[') && (stepStr[stepStr.length() - 1] == ']'));
for (size_t chNum = 1, chEnd = stepStr.length() - 1; chNum != chEnd; ++chNum) {
XMP_Assert(('0' <= stepStr[chNum]) && (stepStr[chNum] <= '9'));
index = (index * 10) + (stepStr[chNum] - '0');
}
if (index < 1) XMP_Throw("Array index must be larger than one", kXMPErr_BadXPath);
if (nodeIndex) *nodeIndex = static_cast<XMP_Index>(index);
size_t colonPos = prevStep.find(':');
XMP_VarString prefix = prevStep.substr(0, colonPos);
nameSpace = defaultMap->GetNameSpace(prefix.c_str(), prefix.size() );
stepName = kXMP_ArrayItemName;
parentDestNode = destNode;
destNode = tempNode->GetNodeAtIndex(index);
if (destNode) continue;
if (!createNodes) return false;
spIArrayNode parentArrayNode = parentDestNode->ConvertToArrayNode();
if (parentArrayNode->ChildCount() + 1 < index) goto EXIT;
if (i == expPath.size() - 1) {
// to do if array not empty create of type already existing type
/// else create simple node
spINode simpleInsertNode = CreateTerminalNode((nameSpace) ? nameSpace->c_str() : kXMP_NS_XMP, stepName.c_str(), leafOptions);
parentArrayNode->InsertNodeAtIndex(simpleInsertNode, index);
destNode = simpleInsertNode;
if (!firstImplicitNodeFound) {
firstImplicitNodeFound = true;
implicitNodeRoot = destNode;
implicitNodeIndex = static_cast<XMP_Index>(index);
}
}
else {
switch (expPath[i + 1].options) {
case kXMP_StructFieldStep:
{
// TODO : Exit and handle deletetion of implicit node
spIStructureNode structInsertNode = IStructureNode::CreateStructureNode(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size() );
parentArrayNode->InsertNodeAtIndex(structInsertNode, index);
destNode = structInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex, (XMP_Index)index);
}
break;
case kXMP_FieldSelectorStep:
case kXMP_QualSelectorStep:
case kXMP_ArrayLastStep:
case kXMP_ArrayIndexStep:
{
spIArrayNode arrayInsertNode = IArrayNode::CreateOrderedArrayNode(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size());
parentArrayNode->InsertNodeAtIndex(arrayInsertNode, index);
destNode = arrayInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex, (XMP_Index)index);
}
break;
case kXMP_QualifierStep:
{
spISimpleNode simpleInsertNode = ISimpleNode::CreateSimpleNode(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size() );
parentArrayNode->InsertNodeAtIndex(simpleInsertNode, index);
destNode = simpleInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex, (XMP_Index)index);
}
default:
break;
}
}
}
break;
case kXMP_ArrayLastStep:
{
// what is the interpretation of last when array is empty ? creating an array item for index 1 if creatNodes is true
// rest of the things are same as above case
// old implementation has an assertion failing for this case
if (destNode->GetNodeType() != INode::kNTArray) {
XMP_Throw("Indexing applied to non-array", kXMPErr_BadXPath);
}
spIArrayNode tempNode = destNode->ConvertToArrayNode();
size_t colonPos = prevStep.find(':');
XMP_VarString prefix = prevStep.substr(0, colonPos);
nameSpace = defaultMap->GetNameSpace(prefix.c_str(), prefix.size());
stepName = prevStep.substr(colonPos + 1);
spINode parentNode = destNode;
spIArrayNode parentArrayNode = parentNode->ConvertToArrayNode();
if (parentNode && parentNode->GetNodeType() == INode::kNTArray) {
size_t childCount = parentNode->ConvertToArrayNode()->ChildCount();
if (nodeIndex) *nodeIndex = (XMP_Index)childCount + 1;
if (childCount) {
destNode = parentArrayNode->GetNodeAtIndex(childCount);
continue;
}
if (!createNodes) return false;
if (i == expPath.size() - 1) {
spINode simpleInsertNode = CreateTerminalNode(nameSpace->c_str(), stepName.c_str(), leafOptions);
parentArrayNode->InsertNodeAtIndex(simpleInsertNode, 1);
destNode = simpleInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex, (XMP_Index)childCount + 1);
continue;
}
switch (expPath[i + 1].options) {
case kXMP_QualifierStep:
{
spISimpleNode simpleInsertNode = ISimpleNode::CreateSimpleNode(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size());
parentArrayNode->InsertNodeAtIndex(simpleInsertNode, 1);
destNode = simpleInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex, (XMP_Index)childCount + 1);
continue;
}
break;
case kXMP_ArrayIndexStep:
case kXMP_ArrayLastStep:
case kXMP_FieldSelectorStep:
case kXMP_QualSelectorStep:
{
spIArrayNode arrayInsertNode = IArrayNode::CreateOrderedArrayNode(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size() );
parentArrayNode->InsertNodeAtIndex(arrayInsertNode, childCount + 1);
destNode = arrayInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex, (XMP_Index)childCount + 1);
}
break;
case kXMP_StructFieldStep:
{
spIStructureNode structInsertNode = IStructureNode::CreateStructureNode(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size() );
parentArrayNode->InsertNodeAtIndex(structInsertNode, childCount + 1);
destNode = structInsertNode;
SetImplicitNodeInformation(firstImplicitNodeFound, implicitNodeRoot, destNode, implicitNodeIndex, (XMP_Index)childCount + 1);
}
break;
default:
break;
}
}
}
break;
case kXMP_QualifierStep:
{
// if qualifier exists for the parent node, continue
// else create qualifier if createnodes is true
XMP_Assert(stepStr[0] == '?');
stepStr = stepStr.substr(1);
size_t colonPos = stepStr.find(':');
XMP_VarString prefix = stepStr.substr(0, colonPos);
nameSpace = defaultMap->GetNameSpace(prefix.c_str(),prefix.size());
stepName = stepStr.substr(colonPos + 1);
qualifierFlag = true;
parentDestNode = destNode;
destNode = destNode->GetQualifier(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size() );
if (destNode) continue;
if (!createNodes) return false;
spISimpleNode qualifierNode = ISimpleNode::CreateSimpleNode(nameSpace->c_str(), nameSpace->size(), stepName.c_str(), stepName.size() );
parentDestNode->InsertQualifier(qualifierNode);
destNode = qualifierNode;
}
break;
case kXMP_QualSelectorStep:
{
// TODO - check the old behavior - checked - no implicit nodes except in one case
// TODO it is perhaps not required, can be done later
// if next path step is array(index/lastinddex/qualselect/fieldselect) - this will be an arraynode
// if next path step is a struct, this will be an structnode
// if next path step is a qualifier , this will be a simple property
if (destNode->GetNodeType() != INode::kNTArray) {
goto EXIT;
}
spIArrayNode tempNode = destNode->ConvertToArrayNode();
XMP_VarString qualName, qualValue, qualNameSpace;
SplitNameAndValue(stepStr, &qualName, &qualValue);
spINode parentNode = destNode;
size_t colonPos = qualName.find(':');
XMP_VarString prefix = qualName.substr(0, colonPos);
qualNameSpace = defaultMap->GetNameSpace(prefix.c_str(), prefix.size())->c_str();
bool indexFound = false;
if (parentNode && parentNode->GetNodeType() == INode::kNTArray) {
spIArrayNode parentArrayNode = parentNode->ConvertToArrayNode();
size_t arrayChildCount = parentArrayNode->ChildCount();
for (size_t arrayIdx = 1; arrayIdx <= arrayChildCount; arrayIdx++) {
spINode currentArrayItem = parentArrayNode->GetNodeAtIndex(arrayIdx);
spINode qualNode = currentArrayItem->GetQualifier(qualNameSpace.c_str(), qualNameSpace.size(), qualName.c_str() + colonPos + 1, AdobeXMPCommon::npos );
if (!qualNode) continue;
XMP_VarString currentQualValue = qualNode->ConvertToSimpleNode()->GetValue()->c_str();
if (currentQualValue == qualValue) {
indexFound = true;
destNode = parentArrayNode->GetNodeAtIndex(arrayIdx);
break;
}
}
}
if (!indexFound) {
goto EXIT;
}
}
break;
case kXMP_FieldSelectorStep:
{
// what if multiple indices match search criterion ?
// what if parent node isn't an array- exception or return false ?
// same issue what if one or more child nodes aren't structures ?
XMP_VarString fieldName, fieldValue, fieldNameSpace;
SplitNameAndValue(stepStr, &fieldName, &fieldValue);
spINode parentNode = destNode;
size_t colonPos = fieldName.find(':');
XMP_VarString prefix = fieldName.substr(0, colonPos);
fieldNameSpace = defaultMap->GetNameSpace(prefix.c_str(), prefix.size())->c_str();
bool indexFound = false;
if (parentNode && parentNode->GetNodeType() == INode::kNTArray) {
spIArrayNode parentArrayNode = parentNode->ConvertToArrayNode();
size_t arrayChildCount = parentArrayNode->ChildCount();
for (size_t arrayIdx = 1; arrayIdx <= arrayChildCount; arrayIdx++) {
spINode currentItem = parentArrayNode->GetNodeAtIndex(arrayIdx);
if (currentItem->GetNodeType() != INode::kNTStructure) {
goto EXIT;
}
spINode fieldNode = currentItem->ConvertToStructureNode()->GetNode(fieldNameSpace.c_str(), fieldNameSpace.size(), fieldName.c_str() + colonPos + 1, AdobeXMPCommon::npos );
if (!fieldNode || fieldNode->GetNodeType() != INode::kNTSimple) continue;
XMP_VarString currentFieldValue = fieldNode->ConvertToSimpleNode()->GetValue()->c_str();
if (currentFieldValue == fieldValue) {
indexFound = true;
destNode = parentArrayNode->GetNodeAtIndex(arrayIdx);
break;
}
}
}
if (!indexFound) {
goto EXIT;
}
}
break;
default:
break;
}
}
}
catch (...) {
if (firstImplicitNodeFound) {
spINode parentImplicitNode = implicitNodeRoot->GetParent();
if (parentImplicitNode->GetNodeType() == INode::kNTArray) {
parentImplicitNode->ConvertToArrayNode()->RemoveNodeAtIndex( implicitNodeIndex );
}
else if (parentImplicitNode->GetNodeType() == INode::kNTStructure) {
parentImplicitNode->ConvertToStructureNode()->RemoveNode(implicitNodeRoot->GetNameSpace()->c_str(), implicitNodeRoot->GetNameSpace()->size(), implicitNodeRoot->GetName()->c_str(), implicitNodeRoot->GetName()->size() );
}
}
throw;
}
retNode = destNode;
return true;
EXIT:
{
//XMP_Assert ( !destNode || (currNode == *currPos) );
//XMP_Assert ( (destNode!= 0) || (! createNodes) );
if(!destNode) {
if( firstImplicitNodeFound ) {
spINode parentImplicitNode = implicitNodeRoot->GetParent();
if(parentImplicitNode->GetNodeType() == INode::kNTArray) {
parentImplicitNode->ConvertToArrayNode()->RemoveNodeAtIndex( implicitNodeIndex );
}
else if(parentImplicitNode->GetNodeType()== INode::kNTStructure) {
parentImplicitNode->ConvertToStructureNode()->RemoveNode( implicitNodeRoot->GetNameSpace()->c_str(), implicitNodeRoot->GetNameSpace()->size(), implicitNodeRoot->GetName()->c_str(), implicitNodeRoot->GetName()->size() );
}
}
} return false;
}
return false;
} // FindNode
bool XMPUtils::FindCnstNode ( const spIMetadata & mDOM,XMP_ExpandedXPath &expPath , spINode &destNode, XMP_OptionBits *options , XMP_Index * arrayIndex )
{
auto defaultMap = INameSpacePrefixMap::GetDefaultNameSpacePrefixMap();
destNode = mDOM;
bool qualifierFlag = false;
size_t pathStartIdx = 1;
if (expPath[kRootPropStep].options & kXMP_StepIsAlias) {
if (!HandleConstAliasStep(mDOM, destNode, expPath, 0)) return false;
pathStartIdx = 2;
}
for ( size_t i = pathStartIdx, endIndex = expPath.size(); i < endIndex; i++ ) {
// split the path into prefix and property name
if(!destNode) return false;
XMP_VarString stepStr = expPath[i].step;
XMP_VarString prevStep = (i == 0)? "" : expPath[i - 1].step;
spcIUTF8String nameSpace ;
switch( expPath[i].options ) {
case kXMP_StructFieldStep:
{
size_t colonPos = stepStr.find(':');
XMP_VarString prefix = stepStr.substr( 0, colonPos );
// get the namespace from the prefix
nameSpace = defaultMap->GetNameSpace( prefix.c_str(), prefix.size() );
if(destNode->GetNodeType() == INode::kNTStructure) {
spIStructureNode tempNode = destNode->ConvertToStructureNode();
destNode = tempNode->GetNode(nameSpace->c_str(), nameSpace->size(), stepStr.c_str() + colonPos + 1, AdobeXMPCommon::npos );
}
else {
XMP_Throw ( "Named children only allowed for schemas and structs", kXMPErr_BadXPath );
}
}
break;
case kXMP_ArrayIndexStep:
{
// should we check if previous segment is an array segment
if(destNode->GetNodeType() != INode::kNTArray) {
XMP_Throw ( "Indexes allowed for arrays only", kXMPErr_BadXPath );
}
spIArrayNode tempNode = destNode->ConvertToArrayNode();
XMP_Index index = 0;
XMP_Assert ( (stepStr.length() >= 2) && (*( stepStr.begin()) == '[') && (stepStr[stepStr.length()-1] == ']') );
for ( size_t chNum = 1,chEnd = stepStr.length() -1 ; chNum != chEnd; ++chNum ) {
XMP_Assert ( ('0' <= stepStr[chNum]) && (stepStr[chNum] <= '9') );
index = (index * 10) + (stepStr[chNum] - '0');
}
if ( index < 1) XMP_Throw ( "Array index must be larger than one", kXMPErr_BadXPath );
size_t colonPos = prevStep.find(':');
XMP_VarString prefix = prevStep.substr( 0, colonPos );
nameSpace = defaultMap->GetNameSpace( prefix.c_str(), prefix.size() );
destNode = tempNode->GetNodeAtIndex( index);
if(arrayIndex) *arrayIndex = index;
}
break;
case kXMP_ArrayLastStep:
{
if(destNode->GetNodeType() != INode::kNTArray) {
XMP_Throw ( "Indexes allowed for arrays only", kXMPErr_BadXPath );
}
spIArrayNode tempNode = destNode->ConvertToArrayNode();
size_t colonPos = prevStep.find(':');
XMP_VarString prefix = prevStep.substr( 0, colonPos );
nameSpace = defaultMap->GetNameSpace( prefix.c_str(), prefix.size() );
spINode parentNode = destNode;
if(parentNode && parentNode->GetNodeType()== INode::kNTArray) {
size_t childCount = parentNode->ConvertToArrayNode()->ChildCount();
if(!childCount) {
XMP_Throw ( "Array index overflow", kXMPErr_BadXPath );
}
destNode = tempNode->GetNodeAtIndex(childCount);
if(arrayIndex) *arrayIndex = (XMP_Index)childCount;
}
}
break;
case kXMP_QualifierStep:
{
XMP_Assert(stepStr[0]=='?');
stepStr = stepStr.substr(1);
size_t colonPos = stepStr.find(':');
XMP_VarString prefix = stepStr.substr( 0, colonPos);
nameSpace = defaultMap->GetNameSpace( prefix.c_str(), prefix.size() );
qualifierFlag = true;
destNode = destNode->GetQualifier(nameSpace->c_str(), nameSpace->size(), stepStr.c_str() + colonPos + 1, AdobeXMPCommon::npos);
// spINode node = mDOM->GetNode( path);
}
break;
case kXMP_QualSelectorStep:
{
// what if multiple indices match search criterion ?
if(destNode->GetNodeType() != INode::kNTArray) {
XMP_Throw ( "Indexes allowed for arrays only", kXMPErr_BadXPath );
}
spIArrayNode tempNode = destNode->ConvertToArrayNode();
XMP_VarString qualName, qualValue, qualNameSpace;
SplitNameAndValue (stepStr, &qualName, &qualValue );
spINode parentNode = destNode;
size_t colonPos = qualName.find(':');
XMP_VarString prefix = qualName.substr( 0, colonPos);
qualNameSpace = defaultMap->GetNameSpace( prefix.c_str(), prefix.size() )->c_str();
bool indexFound = false;
if(parentNode && parentNode->GetNodeType() == INode::kNTArray) {
spIArrayNode parentArrayNode = parentNode->ConvertToArrayNode();
size_t arrayChildCount = parentArrayNode->ChildCount();
for(size_t arrayIdx = 1; arrayIdx <= arrayChildCount; arrayIdx++) {
spINode currentArrayItem = parentArrayNode->GetNodeAtIndex(arrayIdx);
spINode qualNode = currentArrayItem->GetQualifier(qualNameSpace.c_str(), qualNameSpace.size(), qualName.c_str() + colonPos + 1, AdobeXMPCommon::npos );
if(!qualNode) continue;
XMP_VarString currentQualValue = qualNode->ConvertToSimpleNode()->GetValue()->c_str();
if( currentQualValue == qualValue) {
indexFound = true;
if(arrayIndex) *arrayIndex = (XMP_Index)arrayIdx;
destNode = parentArrayNode->GetNodeAtIndex( arrayIdx);
break;
}
}
}
if(!indexFound) {
return false;
}
}
break;
case kXMP_FieldSelectorStep :
{
// what if multiple indices match search criterion ?
// what if parent node isn't an array- exception or return false ?
// same issue what if one or more child nodes aren't structures ?
XMP_VarString fieldName, fieldValue, fieldNameSpace;
SplitNameAndValue (stepStr, &fieldName, &fieldValue );
spINode parentNode = destNode;
size_t colonPos = fieldName.find(':');
XMP_VarString prefix = fieldName.substr( 0, colonPos);
fieldNameSpace = defaultMap->GetNameSpace( prefix.c_str(), prefix.size() )->c_str();
bool indexFound = false;
if(parentNode && parentNode->GetNodeType() == INode::kNTArray) {
spIArrayNode parentArrayNode = parentNode->ConvertToArrayNode();
size_t arrayChildCount = parentArrayNode->ChildCount();
for(size_t arrayIdx = 1; arrayIdx <= arrayChildCount; arrayIdx++) {
spINode currentItem = parentArrayNode->GetNodeAtIndex(arrayIdx);
if(currentItem->GetNodeType() != INode::kNTStructure) {
return false;
}
spINode fieldNode = currentItem->ConvertToStructureNode()->GetNode(fieldNameSpace.c_str(), fieldNameSpace.size(), fieldName.c_str() + colonPos + 1, AdobeXMPCommon::npos );
if(!fieldNode || fieldNode->GetNodeType() != INode::kNTSimple) continue;
XMP_VarString currentFieldValue = fieldNode->ConvertToSimpleNode()->GetValue()->c_str();
if( currentFieldValue == fieldValue) {
indexFound = true;
if(arrayIndex) *arrayIndex = (XMP_Index)arrayIdx;
destNode = parentArrayNode->GetNodeAtIndex( arrayIdx);
break;
}
}
}
if(!indexFound) {
return false;
}
}
break;
default:
break;
}
}
if(!destNode) return false;
if(!options) return true;
*options = GetIXMPOptions(destNode);
return true;
}
size_t XMPUtils:: GetNodeChildCount(const spcINode & node){
size_t childCount = 0;
if( node->GetNodeType() == INode::kNTArray) {
childCount = node->ConvertToArrayNode()->ChildCount();
}
else if (node->GetNodeType() == INode::kNTStructure) {
childCount = node->ConvertToStructureNode()->ChildCount();
}
return childCount;
}
spcINodeIterator XMPUtils::GetNodeChildIterator(const spcINode & node){
spcINodeIterator childIter;
if( node->GetNodeType() == INode::kNTArray) {
childIter = node->ConvertToArrayNode()->Iterator();
}
else if (node->GetNodeType() == INode::kNTStructure) {
childIter = node->ConvertToStructureNode()->Iterator();
}
return childIter;
}
std::vector<spcINode> XMPUtils:: GetChildVector( const spINode & node) {
std::vector<spcINode> childNodes;
spcINodeIterator childIter = GetNodeChildIterator(node);
for(; childIter; childIter = childIter->Next()) {
childNodes.push_back(childIter->GetNode());
}
return childNodes;
}
XMP_OptionBits XMPUtils:: GetIXMPOptions( const spcINode & node) {
XMP_OptionBits options = 0;
if(!node) return options;
if ( node->HasQualifiers()) {
options |= kXMP_PropHasQualifiers;
// ( destNode->GetQualifier( "
if( node->GetQualifier(xmlNameSpace.c_str(), xmlNameSpace.size(), "lang", AdobeXMPCommon::npos )) {
options |= kXMP_PropHasLang;
}
if( node->GetQualifier("http://www.w3.org/1999/02/22-rdf-syntax-ns#", AdobeXMPCommon::npos, "type", AdobeXMPCommon::npos )) {
options |= kXMP_PropHasType;
}
}
XMP_VarString snamespace = node->GetNameSpace()->c_str();
XMP_VarString sname = node->GetName()->c_str();
spcINode parentNode = node->GetParent();
if (node->IsQualifierNode()){
options |= kXMP_PropIsQualifier;
}
if ( node->GetNodeType() == INode::kNTSimple ) {
if( node->ConvertToSimpleNode()->IsURIType()){
options |= kXMP_PropValueIsURI;
}
}
else if ( node->GetNodeType() == INode::kNTArray) {
spcIArrayNode arrayNode = node->ConvertToArrayNode();
options |= kXMP_PropValueIsArray;
switch(arrayNode->GetArrayForm()) {
case IArrayNode::kAFAlternative:
options |= kXMP_PropArrayIsAlternate;options|= kXMP_PropArrayIsOrdered;
break;
case IArrayNode::kAFOrdered:
options |= kXMP_PropArrayIsOrdered;
break;
case IArrayNode::kAFUnordered:
options |= kXMP_PropArrayIsUnordered;
break;
default:
return false;
break;
}
bool isAltTextArray = (arrayNode->GetArrayForm() == IArrayNode::kAFAlternative );
for( size_t arrayIndex = 1; arrayIndex <= arrayNode->ChildCount(); arrayIndex++) {
spcINode childNode = arrayNode->GetNodeAtIndex(arrayIndex);
if((childNode->GetNodeType() != INode::kNTSimple || !childNode->GetQualifier(xmlNameSpace.c_str(), xmlNameSpace.size(), "lang", AdobeXMPCommon::npos ))) {
isAltTextArray = false;
break;
}
}
if(isAltTextArray) {
options |= kXMP_PropArrayIsAltText;
}
}
else if( node->GetNodeType() == INode::kNTStructure && node->GetParent() ) {
options |= kXMP_PropValueIsStruct;
}
return options;
}
spINode
XMPUtils::FindChildNode ( const spINode &parent,
XMP_StringPtr childName,
XMP_StringPtr childNameSpace,
bool createNodes,
size_t * pos /* = 0 */ )
{
// need to pass childnamespace too
spINode childNode;
XMP_OptionBits parentOptions = XMPUtils::GetIXMPOptions(parent);
if ( ! (parentOptions & (kXMP_SchemaNode | kXMP_PropValueIsStruct)) ) {
if ( parentOptions & kXMP_PropValueIsArray ) {
XMP_Throw ( "Named children not allowed for arrays", kXMPErr_BadXPath );
}
}
spcINodeIterator childIter = XMPUtils::GetNodeChildIterator(parent);
for (size_t idx = 1 ; childIter; childIter = childIter->Next(), ++idx ) {
spcINode currChild = childIter->GetNode();
if (currChild && XMP_LitMatch(currChild->GetName()->c_str(), childName) && XMP_LitMatch(currChild->GetNameSpace()->c_str(), childNameSpace) ) {
childNode = AdobeXMPCore_Int::const_pointer_cast<INode>(currChild);
if(pos) *pos = idx;
break;
}
}
if ( (!childNode) && createNodes ) {
childNode = ISimpleNode::CreateSimpleNode(childNameSpace, AdobeXMPCommon::npos, childName, AdobeXMPCommon::npos );
parent->ConvertToStructureNode()->InsertNode( childNode );
}
XMP_Assert ( (childNode ) || (! createNodes) );
return childNode;
} // FindChildNode
spcIUTF8String XMPUtils::GetNodeValue( const spINode & node) {
if (node && node->GetNodeType() == INode::kNTSimple) {
return node->ConvertToSimpleNode()->GetValue();
}
return spIUTF8String();
}
XMP_Index XMPUtils::LookupFieldSelector_v2(const spIArrayNode & arrayNode, XMP_VarString fieldName, XMP_VarString fieldValue) {
XMP_Index destIdx = -1;
if (arrayNode->GetNodeType() != INode::kNTArray) return destIdx;
for (XMP_Index index = 1, indexLim = (XMP_Index)arrayNode->ChildCount(); index <= indexLim; ++index) {
spINode childNode = arrayNode->GetNodeAtIndex(index);
if (childNode->GetNodeType() != INode::kNTStructure) {
XMP_Throw("Field selector must be used on array of struct", kXMPErr_BadXPath);
}
for (spcINodeIterator childNodeIter = XMPUtils::GetNodeChildIterator(childNode); childNodeIter; childNodeIter = childNodeIter->Next()) {
spcINode currentField = childNodeIter->GetNode();
if (!XMP_LitMatch(currentField->GetName()->c_str(), fieldName.c_str())) continue;
if (currentField->GetNodeType() != INode::kNTSimple) continue;
XMP_VarString currentFieldValue = currentField->ConvertToSimpleNode()->GetValue()->c_str();
if (currentFieldValue == fieldValue) {
return index;
}
}
}
return destIdx;
}
#endif
// -------------------------------------------------------------------------------------------------
// ANSI Time Functions
// -------------------
//
// A bit of hackery to use the best available time functions. Mac, UNIX and iOS have thread safe versions
// of gmtime and localtime.
#if XMP_MacBuild | XMP_UNIXBuild | XMP_iOSBuild | XMP_AndroidBuild
typedef time_t ansi_tt;
typedef struct tm ansi_tm;
#define ansi_time time
#define ansi_mktime mktime
#define ansi_difftime difftime
#define ansi_gmtime gmtime_r
#define ansi_localtime localtime_r
#elif XMP_WinBuild
// ! VS.Net 2003 (VC7) does not provide thread safe versions of gmtime and localtime.
// ! VS.Net 2005 (VC8) inverts the parameters for the safe versions of gmtime and localtime.
typedef time_t ansi_tt;
typedef struct tm ansi_tm;
#define ansi_time time
#define ansi_mktime mktime
#define ansi_difftime difftime
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
#define ansi_gmtime(tt,tm) gmtime_s ( tm, tt )
#define ansi_localtime(tt,tm) localtime_s ( tm, tt )
#else
static inline void ansi_gmtime ( const ansi_tt * ttTime, ansi_tm * tmTime )
{
ansi_tm * tmx = gmtime ( ttTime ); // ! Hope that there is no race!
if ( tmx == 0 ) XMP_Throw ( "Failure from ANSI C gmtime function", kXMPErr_ExternalFailure );
*tmTime = *tmx;
}
static inline void ansi_localtime ( const ansi_tt * ttTime, ansi_tm * tmTime )
{
ansi_tm * tmx = localtime ( ttTime ); // ! Hope that there is no race!
if ( tmx == 0 ) XMP_Throw ( "Failure from ANSI C localtime function", kXMPErr_ExternalFailure );
*tmTime = *tmx;
}
#endif
#endif
// -------------------------------------------------------------------------------------------------
// VerifyDateTimeFlags
// -------------------
static void
VerifyDateTimeFlags ( XMP_DateTime * dt )
{
if ( (dt->year != 0) || (dt->month != 0) || (dt->day != 0) ) dt->hasDate = true;
if ( (dt->hour != 0) || (dt->minute != 0) || (dt->second != 0) || (dt->nanoSecond != 0) ) dt->hasTime = true;
if ( (dt->tzSign != 0) || (dt->tzHour != 0) || (dt->tzMinute != 0) ) dt->hasTimeZone = true;
if ( dt->hasTimeZone ) dt->hasTime = true; // ! Don't combine with above line, UTC has zero values.
} // VerifyDateTimeFlags
// -------------------------------------------------------------------------------------------------
// IsLeapYear
// ----------
static bool
IsLeapYear ( long year )
{
if ( year < 0 ) year = -year + 1; // Fold the negative years, assuming there is a year 0.
if ( (year % 4) != 0 ) return false; // Not a multiple of 4.
if ( (year % 100) != 0 ) return true; // A multiple of 4 but not a multiple of 100.
if ( (year % 400) == 0 ) return true; // A multiple of 400.
return false; // A multiple of 100 but not a multiple of 400.
} // IsLeapYear
// -------------------------------------------------------------------------------------------------
// DaysInMonth
// -----------
static int
DaysInMonth ( XMP_Int32 year, XMP_Int32 month )
{
static short daysInMonth[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
int days = daysInMonth [ month ];
if ( (month == 2) && IsLeapYear ( year ) ) days += 1;
return days;
} // DaysInMonth
// -------------------------------------------------------------------------------------------------
// AdjustTimeOverflow
// ------------------
static void
AdjustTimeOverflow ( XMP_DateTime * time )
{
enum { kBillion = 1000*1000*1000L };
// ----------------------------------------------------------------------------------------------
// To be safe against pathalogical overflow we first adjust from month to second, then from
// nanosecond back up to month. This leaves each value closer to zero before propagating into it.
// For example if the hour and minute are both near max, adjusting minutes first can cause the
// hour to overflow.
// ! Photoshop 8 creates "time only" values with zeros for year, month, and day.
if ( (time->year != 0) || (time->month != 0) || (time->day != 0) ) {
while ( time->month < 1 ) {
time->year -= 1;
time->month += 12;
}
while ( time->month > 12 ) {
time->year += 1;
time->month -= 12;
}
while ( time->day < 1 ) {
time->month -= 1;
if ( time->month < 1 ) { // ! Keep the months in range for indexing daysInMonth!
time->year -= 1;
time->month += 12;
}
time->day += DaysInMonth ( time->year, time->month ); // ! Decrement month before so index here is right!
}
while ( time->day > DaysInMonth ( time->year, time->month ) ) {
time->day -= DaysInMonth ( time->year, time->month ); // ! Increment month after so index here is right!
time->month += 1;
if ( time->month > 12 ) {
time->year += 1;
time->month -= 12;
}
}
}
while ( time->hour < 0 ) {
time->day -= 1;
time->hour += 24;
}
while ( time->hour >= 24 ) {
time->day += 1;
time->hour -= 24;
}
while ( time->minute < 0 ) {
time->hour -= 1;
time->minute += 60;
}
while ( time->minute >= 60 ) {
time->hour += 1;
time->minute -= 60;
}
while ( time->second < 0 ) {
time->minute -= 1;
time->second += 60;
}
while ( time->second >= 60 ) {
time->minute += 1;
time->second -= 60;
}
while ( time->nanoSecond < 0 ) {
time->second -= 1;
time->nanoSecond += kBillion;
}
while ( time->nanoSecond >= kBillion ) {
time->second += 1;
time->nanoSecond -= kBillion;
}
while ( time->second < 0 ) {
time->minute -= 1;
time->second += 60;
}
while ( time->second >= 60 ) {
time->minute += 1;
time->second -= 60;
}
while ( time->minute < 0 ) {
time->hour -= 1;
time->minute += 60;
}
while ( time->minute >= 60 ) {
time->hour += 1;
time->minute -= 60;
}
while ( time->hour < 0 ) {
time->day -= 1;
time->hour += 24;
}
while ( time->hour >= 24 ) {
time->day += 1;
time->hour -= 24;
}
if ( (time->year != 0) || (time->month != 0) || (time->day != 0) ) {
while ( time->month < 1 ) { // Make sure the months are OK first, for DaysInMonth.
time->year -= 1;
time->month += 12;
}
while ( time->month > 12 ) {
time->year += 1;
time->month -= 12;
}
while ( time->day < 1 ) {
time->month -= 1;
if ( time->month < 1 ) {
time->year -= 1;
time->month += 12;
}
time->day += DaysInMonth ( time->year, time->month );
}
while ( time->day > DaysInMonth ( time->year, time->month ) ) {
time->day -= DaysInMonth ( time->year, time->month );
time->month += 1;
if ( time->month > 12 ) {
time->year += 1;
time->month -= 12;
}
}
}
} // AdjustTimeOverflow
// -------------------------------------------------------------------------------------------------
// GatherInt
// ---------
//
// Gather into a 64-bit value in order to easily check for overflow. Using a 32-bit value and
// checking for negative isn't reliable, the "*10" part can wrap around to a low positive value.
static XMP_Int32
GatherInt ( XMP_StringPtr strValue, size_t * _pos, const char * errMsg )
{
size_t pos = *_pos;
XMP_Int64 value = 0;
enum { kMaxSInt32 = 0x7FFFFFFF };
for ( char ch = strValue[pos]; ('0' <= ch) && (ch <= '9'); ++pos, ch = strValue[pos] ) {
value = (value * 10) + (ch - '0');
if ( value > kMaxSInt32 ) XMP_Throw ( errMsg, kXMPErr_BadValue );
}
if ( pos == *_pos ) XMP_Throw ( errMsg, kXMPErr_BadParam );
*_pos = pos;
return (XMP_Int32)value;
} // GatherInt
// -------------------------------------------------------------------------------------------------
static void FormatFullDateTime ( XMP_DateTime & tempDate, char * buffer, size_t bufferLen )
{
AdjustTimeOverflow ( &tempDate ); // Make sure all time parts are in range.
if ( tempDate.nanoSecond == 0 ) {
// Output YYYY-MM-DDThh:mm:ssTZD.
snprintf ( buffer, bufferLen, "%.4d-%02d-%02dT%02d:%02d:%02d", // AUDIT: Callers pass sizeof(buffer).
tempDate.year, tempDate.month, tempDate.day,
tempDate.hour, tempDate.minute, tempDate.second );
} else {
// Output YYYY-MM-DDThh:mm:ss.sTZD.
snprintf ( buffer, bufferLen, "%.4d-%02d-%02dT%02d:%02d:%02d.%09d", // AUDIT: Callers pass sizeof(buffer).
tempDate.year, tempDate.month, tempDate.day,
tempDate.hour, tempDate.minute, tempDate.second, tempDate.nanoSecond );
buffer[bufferLen - 1] = 0; // AUDIT warning C6053: make sure string is terminated. buffer is already filled with 0 from caller
for ( size_t i = strlen(buffer)-1; buffer[i] == '0'; --i ) buffer[i] = 0; // Trim excess digits.
}
} // FormatFullDateTime
// -------------------------------------------------------------------------------------------------
// DecodeBase64Char
// ----------------
// The decode mapping:
//
// encoded encoded raw
// char value value
// ------- ------- -----
// A .. Z 0x41 .. 0x5A 0 .. 25
// a .. z 0x61 .. 0x7A 26 .. 51
// 0 .. 9 0x30 .. 0x39 52 .. 61
// + 0x2B 62
// / 0x2F 63
static unsigned char
DecodeBase64Char ( XMP_Uns8 ch )
{
if ( ('A' <= ch) && (ch <= 'Z') ) {
ch = ch - 'A';
} else if ( ('a' <= ch) && (ch <= 'z') ) {
ch = ch - 'a' + 26;
} else if ( ('0' <= ch) && (ch <= '9') ) {
ch = ch - '0' + 52;
} else if ( ch == '+' ) {
ch = 62;
} else if ( ch == '/' ) {
ch = 63;
} else if ( (ch == ' ') || (ch == kTab) || (ch == kLF) || (ch == kCR) ) {
ch = 0xFF; // Will be ignored by the caller.
} else {
XMP_Throw ( "Invalid base-64 encoded character", kXMPErr_BadParam );
}
return ch;
} // DecodeBase64Char ();
// -------------------------------------------------------------------------------------------------
// EstimateSizeForJPEG
// -------------------
//
// Estimate the serialized size for the subtree of an XMP_Node. Support for PackageForJPEG.
static size_t
EstimateSizeForJPEG ( const XMP_Node * xmpNode )
{
size_t estSize = 0;
size_t nameSize = xmpNode->name.size();
bool includeName = (! XMP_PropIsArray ( xmpNode->parent->options ));
if ( XMP_PropIsSimple ( xmpNode->options ) ) {
if ( includeName ) estSize += (nameSize + 3); // Assume attribute form.
estSize += xmpNode->value.size();
} else if ( XMP_PropIsArray ( xmpNode->options ) ) {
// The form of the value portion is: <rdf:Xyz><rdf:li>...</rdf:li>...</rdf:Xyx>
if ( includeName ) estSize += (2*nameSize + 5);
size_t arraySize = xmpNode->children.size();
estSize += 9 + 10; // The rdf:Xyz tags.
estSize += arraySize * (8 + 9); // The rdf:li tags.
for ( size_t i = 0; i < arraySize; ++i ) {
estSize += EstimateSizeForJPEG ( xmpNode->children[i] );
}
} else {
// The form is: <headTag rdf:parseType="Resource">...fields...</tailTag>
if ( includeName ) estSize += (2*nameSize + 5);
estSize += 25; // The rdf:parseType="Resource" attribute.
size_t fieldCount = xmpNode->children.size();
for ( size_t i = 0; i < fieldCount; ++i ) {
estSize += EstimateSizeForJPEG ( xmpNode->children[i] );
}
}
return estSize;
}
#if ENABLE_CPP_DOM_MODEL
// -------------------------------------------------------------------------------------------------
// EstimateSizeForJPEG
// -------------------
//
// Estimate the serialized size for the subtree of an XMP_Node. Support for PackageForJPEG.
static size_t
EstimateSizeForJPEG(const spINode &xmpNode)
{
size_t estSize = 0;
auto defaultMap = INameSpacePrefixMap::GetDefaultNameSpacePrefixMap();
size_t nameSize = xmpNode->GetName()->size() + 1 ;
nameSize += defaultMap->GetPrefix(xmpNode->GetNameSpace()->c_str(), xmpNode->GetNameSpace()->size())->size();
XMP_OptionBits xmpNodeOptions = XMPUtils::GetIXMPOptions(xmpNode);
bool includeName = (xmpNode->GetParent()->GetNodeType() != INode::kNTArray);
if (XMP_PropIsSimple(xmpNodeOptions)) {
if (includeName) estSize += (nameSize + 3); // Assume attribute form.
estSize += xmpNode->ConvertToSimpleNode()->GetValue()->size();
}
else if (XMP_PropIsArray(xmpNodeOptions)) {
// The form of the value portion is: <rdf:Xyz><rdf:li>...</rdf:li>...</rdf:Xyx>
if (includeName) estSize += (2 * nameSize + 5);
spIArrayNode structNode = xmpNode->ConvertToArrayNode();
size_t arraySize = structNode->ChildCount();
estSize += 9 + 10; // The rdf:Xyz tags.
estSize += arraySize * (8 + 9); // The rdf:li tags.
for (auto structIter = structNode->Iterator(); structIter; structIter = structIter->Next()) {
estSize += EstimateSizeForJPEG(structIter->GetNode());
}
}
else {
// The form is: <headTag rdf:parseType="Resource">...fields...</tailTag>
if (includeName) estSize += (2 * nameSize + 5);
spIStructureNode structNode = xmpNode->ConvertToStructureNode();
estSize += 25; // The rdf:parseType="Resource" attribute.
size_t fieldCount = structNode->ChildCount();
for (auto structIter = structNode->Iterator(); structIter; structIter = structIter->Next()) {
estSize += EstimateSizeForJPEG(structIter->GetNode());
}
}
return estSize;
}
#endif
// -------------------------------------------------------------------------------------------------
// MoveOneProperty
// ---------------
static bool MoveOneProperty ( XMPMeta & stdXMP, XMPMeta * extXMP,
XMP_StringPtr schemaURI, XMP_StringPtr propName )
{
XMP_Node * propNode = 0;
XMP_NodePtrPos stdPropPos;
XMP_Node * stdSchema = FindSchemaNode ( &stdXMP.tree, schemaURI, kXMP_ExistingOnly, 0 );
if ( stdSchema != 0 ) {
propNode = FindChildNode ( stdSchema, propName, kXMP_ExistingOnly, &stdPropPos );
}
if ( propNode == 0 ) return false;
XMP_Node * extSchema = FindSchemaNode ( &extXMP->tree, schemaURI, kXMP_CreateNodes );
propNode->parent = extSchema;
extSchema->options &= ~kXMP_NewImplicitNode;
extSchema->children.push_back ( propNode );
stdSchema->children.erase ( stdPropPos );
DeleteEmptySchema ( stdSchema );
return true;
} // MoveOneProperty
// -------------------------------------------------------------------------------------------------
// MoveOneProperty
// ---------------
#if ENABLE_CPP_DOM_MODEL
static bool MoveOneProperty(XMPMeta2 & stdXMP, XMPMeta2 * extXMP,
XMP_StringPtr schemaURI, XMP_StringPtr propName)
{
spINode rootNode = stdXMP.mDOM;
if (!rootNode) return false;
spINode propNode = rootNode->ConvertToStructureNode()->GetNode(schemaURI, AdobeXMPCommon::npos, propName, AdobeXMPCommon::npos);
if (!propNode) return false;
spINode clonedNode = propNode->Clone();
spIStructureNode rootNode2 = extXMP->mDOM;
if (rootNode2->GetNode(schemaURI, AdobeXMPCommon::npos, propName, AdobeXMPCommon::npos )) {
rootNode2->RemoveNode(schemaURI, AdobeXMPCommon::npos, propName, AdobeXMPCommon::npos);
}
rootNode2->AppendNode(clonedNode);
rootNode->ConvertToStructureNode()->RemoveNode( schemaURI, AdobeXMPCommon::npos, propName, AdobeXMPCommon::npos );
return true;
} // MoveOneProperty
#endif
// -------------------------------------------------------------------------------------------------
// CreateEstimatedSizeMap
// ----------------------
#ifndef Trace_PackageForJPEG
#define Trace_PackageForJPEG 0
#endif
typedef std::pair < XMP_VarString*, XMP_VarString* > StringPtrPair;
typedef std::pair < const char *, const char * > StringPtrPair2;
typedef std::multimap < size_t, StringPtrPair > PropSizeMap;
typedef std::multimap < size_t, StringPtrPair2 > PropSizeMap2;
static void CreateEstimatedSizeMap ( XMPMeta & stdXMP, PropSizeMap * propSizes )
{
#if Trace_PackageForJPEG
printf ( " Creating top level property map:\n" );
#endif
for ( size_t s = stdXMP.tree.children.size(); s > 0; --s ) {
XMP_Node * stdSchema = stdXMP.tree.children[s-1];
for ( size_t p = stdSchema->children.size(); p > 0; --p ) {
XMP_Node * stdProp = stdSchema->children[p-1];
if ( (stdSchema->name == kXMP_NS_XMP_Note) &&
(stdProp->name == "xmpNote:HasExtendedXMP") ) continue; // ! Don't move xmpNote:HasExtendedXMP.
size_t propSize = EstimateSizeForJPEG ( stdProp );
StringPtrPair namePair ( &stdSchema->name, &stdProp->name );
PropSizeMap::value_type mapValue ( propSize, namePair );
(void) propSizes->insert ( propSizes->upper_bound ( propSize ), mapValue );
#if Trace_PackageForJPEG
printf ( " %d bytes, %s in %s\n", propSize, stdProp->name.c_str(), stdSchema->name.c_str() );
#endif
}
}
} // CreateEstimatedSizeMap
#if ENABLE_CPP_DOM_MODEL
static void CreateEstimatedSizeMap(XMPMeta2 & stdXMP, PropSizeMap2 * propSizes)
{
#if Trace_PackageForJPEG
printf(" Creating top level property map:\n");
#endif
spIStructureNode rootNode = stdXMP.mDOM;
for (auto rootIter = rootNode->Iterator(); rootIter; rootIter = rootIter->Next()) {
const spINode & node = rootIter->GetNode();
if (!strcmp(node->GetNameSpace()->c_str(), kXMP_NS_XMP_Note) && !strcmp(node->GetName()->c_str(), "HasExtendedXMP")) continue;
size_t propSize = EstimateSizeForJPEG(node);
StringPtrPair2 namePair(node->GetNameSpace()->c_str(), node->GetName()->c_str());
PropSizeMap2::value_type mapValue(propSize, namePair);
(void)propSizes->insert(propSizes->upper_bound(propSize), mapValue);
#if Trace_PackageForJPEG
printf(" %d bytes, %s in %s\n", propSize, stdProp->name.c_str(), stdSchema->name.c_str());
#endif
}
} // CreateEstimatedSizeMap
#endif
#if ENABLE_CPP_DOM_MODEL
// -------------------------------------------------------------------------------------------------
// MoveLargestProperty
// -------------------
static size_t MoveLargestProperty(XMPMeta2 & stdXMP, XMPMeta2 * extXMP, PropSizeMap2 & propSizes)
{
XMP_Assert(!propSizes.empty());
#if 0
// *** Xocde 2.3 on Mac OS X 10.4.7 seems to have a bug where this does not pick the last
// *** item in the map. We'll just avoid it on all platforms until thoroughly tested.
PropSizeMap::iterator lastPos = propSizes.end();
--lastPos; // Move to the actual last item.
#else
PropSizeMap2::iterator lastPos = propSizes.begin();
PropSizeMap2::iterator nextPos = lastPos;
for (++nextPos; nextPos != propSizes.end(); ++nextPos) lastPos = nextPos;
#endif
size_t propSize = lastPos->first;
const char * schemaURI = lastPos->second.first;
const char * propName = lastPos->second.second;
#if Trace_PackageForJPEG
printf(" Move %s, %d bytes\n", propName, propSize);
#endif
bool moved = MoveOneProperty(stdXMP, extXMP, schemaURI, propName);
XMP_Assert(moved);
propSizes.erase(lastPos);
return propSize;
} // MoveLargestProperty
#endif
// -------------------------------------------------------------------------------------------------
// MoveLargestProperty
// -------------------
static size_t MoveLargestProperty ( XMPMeta & stdXMP, XMPMeta * extXMP, PropSizeMap & propSizes )
{
XMP_Assert ( ! propSizes.empty() );
#if 0
// *** Xocde 2.3 on Mac OS X 10.4.7 seems to have a bug where this does not pick the last
// *** item in the map. We'll just avoid it on all platforms until thoroughly tested.
PropSizeMap::iterator lastPos = propSizes.end();
--lastPos; // Move to the actual last item.
#else
PropSizeMap::iterator lastPos = propSizes.begin();
PropSizeMap::iterator nextPos = lastPos;
for ( ++nextPos; nextPos != propSizes.end(); ++nextPos ) lastPos = nextPos;
#endif
size_t propSize = lastPos->first;
const char * schemaURI = lastPos->second.first->c_str();
const char * propName = lastPos->second.second->c_str();
#if Trace_PackageForJPEG
printf ( " Move %s, %d bytes\n", propName, propSize );
#endif
#if XMP_DebugBuild
bool moved =
#endif
MoveOneProperty ( stdXMP, extXMP, schemaURI, propName );
XMP_Assert ( moved );
propSizes.erase ( lastPos );
return propSize;
} // MoveLargestProperty
// =================================================================================================
// Class Static Functions
// ======================
// -------------------------------------------------------------------------------------------------
// Initialize
// ----------
/* class static */ bool
XMPUtils::Initialize()
{
if ( WhiteSpaceStrPtr == NULL ) {
WhiteSpaceStrPtr = new std::string();
WhiteSpaceStrPtr->append( " \t\n\r" );
}
return true;
} // Initialize
// -------------------------------------------------------------------------------------------------
// Terminate
// ---------
/* class static */ void
XMPUtils::Terminate() RELEASE_NO_THROW
{
delete WhiteSpaceStrPtr;
WhiteSpaceStrPtr = NULL;
return;
} // Terminate
// -------------------------------------------------------------------------------------------------
// ComposeArrayItemPath
// --------------------
//
// Return "arrayName[index]".
/* class static */ void
XMPUtils::ComposeArrayItemPath ( XMP_StringPtr schemaNS,
XMP_StringPtr arrayName,
XMP_Index itemIndex,
XMP_VarString * _fullPath )
{
XMP_Assert ( schemaNS != 0 ); // Enforced by wrapper.
XMP_Assert ( (arrayName != 0) && (*arrayName != 0) ); // Enforced by wrapper.
XMP_Assert ( _fullPath != 0 ); // Enforced by wrapper.
XMP_ExpandedXPath expPath; // Just for side effects to check namespace and basic path.
ExpandXPath ( schemaNS, arrayName, &expPath );
if ( (itemIndex < 0) && (itemIndex != kXMP_ArrayLastItem) ) XMP_Throw ( "Array index out of bounds", kXMPErr_BadParam );
size_t reserveLen = strlen(arrayName) + 2 + 32; // Room plus padding.
XMP_VarString fullPath; // ! Allow for arrayName to be the incoming _fullPath.c_str().
fullPath.reserve ( reserveLen );
fullPath = arrayName;
if ( itemIndex == kXMP_ArrayLastItem ) {
fullPath += "[last()]";
} else {
// AUDIT: Using sizeof(buffer) for the snprintf length is safe.
char buffer [32]; // A 32 byte buffer is plenty, even for a 64-bit integer.
snprintf ( buffer, sizeof(buffer), "[%d]", itemIndex );
fullPath += buffer;
}
*_fullPath = fullPath;
} // ComposeArrayItemPath
// -------------------------------------------------------------------------------------------------
// ComposeStructFieldPath
// ----------------------
//
// Return "structName/ns:fieldName".
/* class static */ void
XMPUtils::ComposeStructFieldPath ( XMP_StringPtr schemaNS,
XMP_StringPtr structName,
XMP_StringPtr fieldNS,
XMP_StringPtr fieldName,
XMP_VarString * _fullPath )
{
XMP_Assert ( (schemaNS != 0) && (fieldNS != 0) ); // Enforced by wrapper.
XMP_Assert ( (structName != 0) && (*structName != 0) ); // Enforced by wrapper.
XMP_Assert ( (fieldName != 0) && (*fieldName != 0) ); // Enforced by wrapper.
XMP_Assert ( _fullPath != 0 ); // Enforced by wrapper.
XMP_ExpandedXPath expPath; // Just for side effects to check namespace and basic path.
ExpandXPath ( schemaNS, structName, &expPath );
XMP_ExpandedXPath fieldPath;
ExpandXPath ( fieldNS, fieldName, &fieldPath );
if ( fieldPath.size() != 2 ) XMP_Throw ( "The fieldName must be simple", kXMPErr_BadXPath );
size_t reserveLen = strlen(structName) + fieldPath[kRootPropStep].step.size() + 1;
XMP_VarString fullPath; // ! Allow for arrayName to be the incoming _fullPath.c_str().
fullPath.reserve ( reserveLen );
fullPath = structName;
fullPath += '/';
fullPath += fieldPath[kRootPropStep].step;
*_fullPath = fullPath;
} // ComposeStructFieldPath
// -------------------------------------------------------------------------------------------------
// ComposeQualifierPath
// --------------------
//
// Return "propName/?ns:qualName".
/* class static */ void
XMPUtils::ComposeQualifierPath ( XMP_StringPtr schemaNS,
XMP_StringPtr propName,
XMP_StringPtr qualNS,
XMP_StringPtr qualName,
XMP_VarString * _fullPath )
{
XMP_Assert ( (schemaNS != 0) && (qualNS != 0) ); // Enforced by wrapper.
XMP_Assert ( (propName != 0) && (*propName != 0) ); // Enforced by wrapper.
XMP_Assert ( (qualName != 0) && (*qualName != 0) ); // Enforced by wrapper.
XMP_Assert ( _fullPath != 0 ); // Enforced by wrapper.
XMP_ExpandedXPath expPath; // Just for side effects to check namespace and basic path.
ExpandXPath ( schemaNS, propName, &expPath );
XMP_ExpandedXPath qualPath;
ExpandXPath ( qualNS, qualName, &qualPath );
if ( qualPath.size() != 2 ) XMP_Throw ( "The qualifier name must be simple", kXMPErr_BadXPath );
size_t reserveLen = strlen(propName) + qualPath[kRootPropStep].step.size() + 2;
XMP_VarString fullPath; // ! Allow for arrayName to be the incoming _fullPath.c_str().
fullPath.reserve ( reserveLen );
fullPath = propName;
fullPath += "/?";
fullPath += qualPath[kRootPropStep].step;
*_fullPath = fullPath;
} // ComposeQualifierPath
// -------------------------------------------------------------------------------------------------
// ComposeLangSelector
// -------------------
//
// Return "arrayName[?xml:lang="lang"]".
// *** #error "handle quotes in the lang - or verify format"
/* class static */ void
XMPUtils::ComposeLangSelector ( XMP_StringPtr schemaNS,
XMP_StringPtr arrayName,
XMP_StringPtr _langName,
XMP_VarString * _fullPath )
{
XMP_Assert ( schemaNS != 0 ); // Enforced by wrapper.
XMP_Assert ( (arrayName != 0) && (*arrayName != 0) ); // Enforced by wrapper.
XMP_Assert ( (_langName != 0) && (*_langName != 0) ); // Enforced by wrapper.
XMP_Assert ( _fullPath != 0 ); // Enforced by wrapper.
XMP_ExpandedXPath expPath; // Just for side effects to check namespace and basic path.
ExpandXPath ( schemaNS, arrayName, &expPath );
XMP_VarString langName ( _langName );
NormalizeLangValue ( &langName );
size_t reserveLen = strlen(arrayName) + langName.size() + 14;
XMP_VarString fullPath; // ! Allow for arrayName to be the incoming _fullPath.c_str().
fullPath.reserve ( reserveLen );
fullPath = arrayName;
fullPath += "[?xml:lang=\"";
fullPath += langName;
fullPath += "\"]";
*_fullPath = fullPath;
} // ComposeLangSelector
// -------------------------------------------------------------------------------------------------
// ComposeFieldSelector
// --------------------
//
// Return "arrayName[ns:fieldName="fieldValue"]".
// *** #error "handle quotes in the value"
/* class static */ void
XMPUtils::ComposeFieldSelector ( XMP_StringPtr schemaNS,
XMP_StringPtr arrayName,
XMP_StringPtr fieldNS,
XMP_StringPtr fieldName,
XMP_StringPtr fieldValue,
XMP_VarString * _fullPath )
{
XMP_Assert ( (schemaNS != 0) && (fieldNS != 0) && (fieldValue != 0) ); // Enforced by wrapper.
XMP_Assert ( (*arrayName != 0) && (*fieldName != 0) ); // Enforced by wrapper.
XMP_Assert ( _fullPath != 0 ); // Enforced by wrapper.
XMP_ExpandedXPath expPath; // Just for side effects to check namespace and basic path.
ExpandXPath ( schemaNS, arrayName, &expPath );
XMP_ExpandedXPath fieldPath;
ExpandXPath ( fieldNS, fieldName, &fieldPath );
if ( fieldPath.size() != 2 ) XMP_Throw ( "The fieldName must be simple", kXMPErr_BadXPath );
size_t reserveLen = strlen(arrayName) + fieldPath[kRootPropStep].step.size() + strlen(fieldValue) + 5;
XMP_VarString fullPath; // ! Allow for arrayName to be the incoming _fullPath.c_str().
fullPath.reserve ( reserveLen );
fullPath = arrayName;
fullPath += '[';
fullPath += fieldPath[kRootPropStep].step;
fullPath += "=\"";
fullPath += fieldValue;
fullPath += "\"]";
*_fullPath = fullPath;
} // ComposeFieldSelector
// -------------------------------------------------------------------------------------------------
// ConvertFromBool
// ---------------
/* class static */ void
XMPUtils::ConvertFromBool ( bool binValue,
XMP_VarString * strValue )
{
XMP_Assert ( strValue != 0 ); // Enforced by wrapper.
if ( binValue ) {
*strValue = kXMP_TrueStr;
} else {
*strValue = kXMP_FalseStr;
}
} // ConvertFromBool
// -------------------------------------------------------------------------------------------------
// ConvertFromInt
// --------------
/* class static */ void
XMPUtils::ConvertFromInt ( XMP_Int32 binValue,
XMP_StringPtr format,
XMP_VarString * strValue )
{
XMP_Assert ( (format != 0) && (strValue != 0) ); // Enforced by wrapper.
strValue->erase();
if ( *format == 0 ) format = "%d";
// AUDIT: Using sizeof(buffer) for the snprintf length is safe.
char buffer [32]; // Big enough for a 64-bit integer;
snprintf ( buffer, sizeof(buffer), format, binValue );
*strValue = buffer;
} // ConvertFromInt
// -------------------------------------------------------------------------------------------------
// ConvertFromInt64
// ----------------
/* class static */ void
XMPUtils::ConvertFromInt64 ( XMP_Int64 binValue,
XMP_StringPtr format,
XMP_VarString * strValue )
{
XMP_Assert ( (format != 0) && (strValue != 0) ); // Enforced by wrapper.
strValue->erase();
if ( *format == 0 ) format = "%lld";
// AUDIT: Using sizeof(buffer) for the snprintf length is safe.
char buffer [32]; // Big enough for a 64-bit integer;
snprintf ( buffer, sizeof(buffer), format, binValue );
*strValue = buffer;
} // ConvertFromInt64
// -------------------------------------------------------------------------------------------------
// ConvertFromFloat
// ----------------
/* class static */ void
XMPUtils::ConvertFromFloat ( double binValue,
XMP_StringPtr format,
XMP_VarString * strValue )
{
XMP_Assert ( (format != 0) && (strValue != 0) ); // Enforced by wrapper.
strValue->erase();
if ( *format == 0 ) format = "%f";
// AUDIT: Using sizeof(buffer) for the snprintf length is safe.
char buffer [64]; // Ought to be plenty big enough.
snprintf ( buffer, sizeof(buffer), format, binValue );
*strValue = buffer;
} // ConvertFromFloat
// -------------------------------------------------------------------------------------------------
// ConvertFromDate
// ---------------
//
// Format a date-time string according to ISO 8601 and http://www.w3.org/TR/NOTE-datetime:
// YYYY
// YYYY-MM
// YYYY-MM-DD
// YYYY-MM-DDThh:mmTZD
// YYYY-MM-DDThh:mm:ssTZD
// YYYY-MM-DDThh:mm:ss.sTZD
//
// YYYY = four-digit year
// MM = two-digit month (01=January, etc.)
// DD = two-digit day of month (01 through 31)
// hh = two digits of hour (00 through 23)
// mm = two digits of minute (00 through 59)
// ss = two digits of second (00 through 59)
// s = one or more digits representing a decimal fraction of a second
// TZD = time zone designator (Z or +hh:mm or -hh:mm)
//
// Note that ISO 8601 does not seem to allow years less than 1000 or greater than 9999. We allow
// any year, even negative ones. The year is formatted as "%.4d". The TZD is also optional in XMP,
// even though required in the W3C profile. Finally, Photoshop 8 (CS) sometimes created time-only
// values so we tolerate that.
/* class static */ void
XMPUtils::ConvertFromDate ( const XMP_DateTime & _inValue,
XMP_VarString * strValue )
{
XMP_Assert ( strValue != 0 ); // Enforced by wrapper.
char buffer [100]; // Plenty long enough.
memset( buffer, 0, 100);
// Pick the format, use snprintf to format into a local buffer, assign to static output string.
// Don't use AdjustTimeOverflow at the start, that will wipe out zero month or day values.
// ! Photoshop 8 creates "time only" values with zeros for year, month, and day.
XMP_DateTime binValue = _inValue;
VerifyDateTimeFlags ( &binValue );
// Temporary fix for bug 1269463, silently fix out of range month or day.
if ( binValue.month == 0 ) {
if ( (binValue.day != 0) || binValue.hasTime ) binValue.month = 1;
} else {
if ( binValue.month < 1 ) binValue.month = 1;
if ( binValue.month > 12 ) binValue.month = 12;
}
if ( binValue.day == 0 ) {
if ( binValue.hasTime ) binValue.day = 1;
} else {
if ( binValue.day < 1 ) binValue.day = 1;
if ( binValue.day > 31 ) binValue.day = 31;
}
// Now carry on with the original logic.
if ( binValue.month == 0 ) {
// Output YYYY if all else is zero, otherwise output a full string for the quasi-bogus
// "time only" values from Photoshop CS.
if ( (binValue.day == 0) && (! binValue.hasTime) ) {
snprintf ( buffer, sizeof(buffer), "%.4d", binValue.year ); // AUDIT: Using sizeof for snprintf length is safe.
} else if ( (binValue.year == 0) && (binValue.day == 0) ) {
FormatFullDateTime ( binValue, buffer, sizeof(buffer) );
} else {
XMP_Throw ( "Invalid partial date", kXMPErr_BadParam);
}
} else if ( binValue.day == 0 ) {
// Output YYYY-MM.
if ( (binValue.month < 1) || (binValue.month > 12) ) XMP_Throw ( "Month is out of range", kXMPErr_BadParam);
if ( binValue.hasTime ) XMP_Throw ( "Invalid partial date, non-zeros after zero month and day", kXMPErr_BadParam);
snprintf ( buffer, sizeof(buffer), "%.4d-%02d", binValue.year, binValue.month ); // AUDIT: Using sizeof for snprintf length is safe.
} else if ( ! binValue.hasTime ) {
// Output YYYY-MM-DD.
if ( (binValue.month < 1) || (binValue.month > 12) ) XMP_Throw ( "Month is out of range", kXMPErr_BadParam);
if ( (binValue.day < 1) || (binValue.day > 31) ) XMP_Throw ( "Day is out of range", kXMPErr_BadParam);
snprintf ( buffer, sizeof(buffer), "%.4d-%02d-%02d", binValue.year, binValue.month, binValue.day ); // AUDIT: Using sizeof for snprintf length is safe.
} else {
FormatFullDateTime ( binValue, buffer, sizeof(buffer) );
}
strValue->assign ( buffer );
if ( binValue.hasTimeZone ) {
if ( (binValue.tzHour < 0) || (binValue.tzHour > 23) ||
(binValue.tzMinute < 0 ) || (binValue.tzMinute > 59) ||
(binValue.tzSign < -1) || (binValue.tzSign > +1) ||
((binValue.tzSign == 0) && ((binValue.tzHour != 0) || (binValue.tzMinute != 0))) ) {
XMP_Throw ( "Invalid time zone values", kXMPErr_BadParam );
}
if ( binValue.tzSign == 0 ) {
*strValue += 'Z';
} else {
snprintf ( buffer, sizeof(buffer), "+%02d:%02d", binValue.tzHour, binValue.tzMinute ); // AUDIT: Using sizeof for snprintf length is safe.
if ( binValue.tzSign < 0 ) buffer[0] = '-';
*strValue += buffer;
}
}
} // ConvertFromDate
// -------------------------------------------------------------------------------------------------
// ConvertToBool
// -------------
//
// Formally the string value should be "True" or "False", but we should be more flexible here. Map
// the string to lower case. Allow any of "true", "false", "t", "f", "1", or "0".
/* class static */ bool
XMPUtils::ConvertToBool ( XMP_StringPtr strValue )
{
if ( (strValue == 0) || (*strValue == 0) ) XMP_Throw ( "Empty convert-from string", kXMPErr_BadValue );
bool result = false;
XMP_VarString strObj ( strValue );
for ( XMP_VarStringPos ch = strObj.begin(); ch != strObj.end(); ++ch ) {
if ( ('A' <= *ch) && (*ch <= 'Z') ) *ch += 0x20;
}
if ( (strObj == "true") || (strObj == "t") || (strObj == "1") ) {
result = true;
} else if ( (strObj == "false") || (strObj == "f") || (strObj == "0") ) {
result = false;
} else {
XMP_Throw ( "Invalid Boolean string", kXMPErr_BadParam );
}
return result;
} // ConvertToBool
// -------------------------------------------------------------------------------------------------
// ConvertToInt
// ------------
/* class static */ XMP_Int32
XMPUtils::ConvertToInt ( XMP_StringPtr strValue )
{
if ( (strValue == 0) || (*strValue == 0) ) XMP_Throw ( "Empty convert-from string", kXMPErr_BadValue );
int count;
char nextCh;
XMP_Int32 result;
if ( ! XMP_LitNMatch ( strValue, "0x", 2 ) ) {
count = sscanf ( strValue, "%d%c", &result, &nextCh );
} else {
count = sscanf ( strValue, "%x%c", &result, &nextCh );
}
if ( count != 1 ) XMP_Throw ( "Invalid integer string", kXMPErr_BadParam );
return result;
} // ConvertToInt
// -------------------------------------------------------------------------------------------------
// ConvertToInt64
// --------------
/* class static */ XMP_Int64
XMPUtils::ConvertToInt64 ( XMP_StringPtr strValue )
{
if ( (strValue == 0) || (*strValue == 0) ) XMP_Throw ( "Empty convert-from string", kXMPErr_BadValue );
int count;
char nextCh;
XMP_Int64 result;
if ( ! XMP_LitNMatch ( strValue, "0x", 2 ) ) {
// when int64_t is defined as a long, we get a warning.
long long value;
count = sscanf ( strValue, "%lld%c", &value, &nextCh );
result = value;
} else {
unsigned long long uvalue;
count = sscanf ( strValue, "%llx%c", &uvalue, &nextCh );
result = uvalue; // bad unsigned -> signed
}
if ( count != 1 ) XMP_Throw ( "Invalid integer string", kXMPErr_BadParam );
return result;
} // ConvertToInt64
// -------------------------------------------------------------------------------------------------
// ConvertToFloat
// --------------
/* class static */ double
XMPUtils::ConvertToFloat ( XMP_StringPtr strValue )
{
if ( (strValue == 0) || (*strValue == 0) ) XMP_Throw ( "Empty convert-from string", kXMPErr_BadValue );
XMP_VarString oldLocale; // Try to make sure number conversion uses '.' as the decimal point.
XMP_StringPtr oldLocalePtr = setlocale ( LC_ALL, 0 );
if ( oldLocalePtr != 0 ) {
oldLocale.assign ( oldLocalePtr ); // Save the locale to be reset when exiting.
setlocale ( LC_ALL, "C" );
}
errno = 0;
char * numEnd;
double result = strtod ( strValue, &numEnd );
int errnoSave = errno; // The setlocale call below might change errno.
if ( ! oldLocale.empty() ) setlocale ( LC_ALL, oldLocale.c_str() ); // ! Reset locale before possible throw!
if ( (errnoSave != 0) || (*numEnd != 0) ) XMP_Throw ( "Invalid float string", kXMPErr_BadParam );
return result;
} // ConvertToFloat
// -------------------------------------------------------------------------------------------------
// ConvertToDate
// -------------
//
// Parse a date-time string according to ISO 8601 and http://www.w3.org/TR/NOTE-datetime:
// YYYY
// YYYY-MM
// YYYY-MM-DD
// YYYY-MM-DDThh:mmTZD
// YYYY-MM-DDThh:mm:ssTZD
// YYYY-MM-DDThh:mm:ss.sTZD
//
// YYYY = four-digit year
// MM = two-digit month (01=January, etc.)
// DD = two-digit day of month (01 through 31)
// hh = two digits of hour (00 through 23)
// mm = two digits of minute (00 through 59)
// ss = two digits of second (00 through 59)
// s = one or more digits representing a decimal fraction of a second
// TZD = time zone designator (Z or +hh:mm or -hh:mm)
//
// Note that ISO 8601 does not seem to allow years less than 1000 or greater than 9999. We allow
// any year, even negative ones. The year is formatted as "%.4d". The TZD is also optional in XMP,
// even though required in the W3C profile. Finally, Photoshop 8 (CS) sometimes created time-only
// values so we tolerate that.
// *** Put the ISO format comments in the header documentation.
/* class static */ void
XMPUtils::ConvertToDate ( XMP_StringPtr strValue,
XMP_DateTime * binValue )
{
if ( (strValue == 0) || (*strValue == 0) ) XMP_Throw ( "Empty convert-from string", kXMPErr_BadValue);
size_t pos = 0;
XMP_Int32 temp;
XMP_Assert ( sizeof(*binValue) == sizeof(XMP_DateTime) );
// (Exempi) UNSAFE. You don't memset a C++ object.
*binValue = XMP_DateTime();
//(void) memset ( binValue, 0, sizeof(*binValue) ); // AUDIT: Safe, using sizeof destination.
size_t strSize = strlen ( strValue );
bool timeOnly = ( (strValue[0] == 'T') ||
((strSize >= 2) && (strValue[1] == ':')) ||
((strSize >= 3) && (strValue[2] == ':')) );
if ( ! timeOnly ) {
binValue->hasDate = true;
if ( strValue[0] == '-' ) pos = 1;
temp = GatherInt ( strValue, &pos, "Invalid year in date string" ); // Extract the year.
if ( (strValue[pos] != 0) && (strValue[pos] != '-') ) XMP_Throw ( "Invalid date string, after year", kXMPErr_BadParam );
if ( strValue[0] == '-' ) temp = -temp;
binValue->year = temp;
if ( strValue[pos] == 0 ) return;
++pos;
temp = GatherInt ( strValue, &pos, "Invalid month in date string" ); // Extract the month.
if ( (strValue[pos] != 0) && (strValue[pos] != '-') ) XMP_Throw ( "Invalid date string, after month", kXMPErr_BadParam );
if ( binValue->year != 0 && temp < 1 ) temp = 1;
if ( temp > 12 ) temp = 12;
binValue->month = temp;
if ( strValue[pos] == 0 ) return;
++pos;
temp = GatherInt ( strValue, &pos, "Invalid day in date string" ); // Extract the day.
if ( (strValue[pos] != 0) && (strValue[pos] != 'T') ) XMP_Throw ( "Invalid date string, after day", kXMPErr_BadParam );
if ( temp > 31 ) temp = 31;
binValue->day = temp;
if ( strValue[pos] == 0 ) return;
// Allow year, month, and day to all be zero; implies the date portion is missing.
if ( (binValue->year != 0) || (binValue->month != 0) || (binValue->day != 0) ) {
// Temporary fix for bug 1269463, silently fix out of range month or day.
// if ( (binValue->month < 1) || (binValue->month > 12) ) XMP_Throw ( "Month is out of range", kXMPErr_BadParam );
// if ( (binValue->day < 1) || (binValue->day > 31) ) XMP_Throw ( "Day is out of range", kXMPErr_BadParam );
if ( binValue->month < 1 ) binValue->month = 1;
// if ( binValue->month > 12 ) binValue->month = 12;
if ( binValue->day < 1 ) binValue->day = 1;
// if ( binValue->day > 31 ) binValue->day = 31;
}
}
// If we get here there is more of the string, otherwise we would have returned above.
if ( strValue[pos] == 'T' ) {
++pos;
} else if ( ! timeOnly ) {
XMP_Throw ( "Invalid date string, missing 'T' after date", kXMPErr_BadParam );
}
binValue->hasTime = true;
temp = GatherInt ( strValue, &pos, "Invalid hour in date string" ); // Extract the hour.
if ( strValue[pos] != ':' ) XMP_Throw ( "Invalid date string, after hour", kXMPErr_BadParam );
if ( temp > 23 ) temp = 23; // *** 1269463: XMP_Throw ( "Hour is out of range", kXMPErr_BadParam );
binValue->hour = temp;
// Don't check for done, we have to work up to the time zone.
++pos;
temp = GatherInt ( strValue, &pos, "Invalid minute in date string" ); // And the minute.
if ( (strValue[pos] != ':') && (strValue[pos] != 'Z') &&
(strValue[pos] != '+') && (strValue[pos] != '-') && (strValue[pos] != 0) ) XMP_Throw ( "Invalid date string, after minute", kXMPErr_BadParam );
if ( temp > 59 ) temp = 59; // *** 1269463: XMP_Throw ( "Minute is out of range", kXMPErr_BadParam );
binValue->minute = temp;
// Don't check for done, we have to work up to the time zone.
if ( strValue[pos] == ':' ) {
++pos;
temp = GatherInt ( strValue, &pos, "Invalid whole seconds in date string" ); // Extract the whole seconds.
if ( (strValue[pos] != '.') && (strValue[pos] != 'Z') &&
(strValue[pos] != '+') && (strValue[pos] != '-') && (strValue[pos] != 0) ) {
XMP_Throw ( "Invalid date string, after whole seconds", kXMPErr_BadParam );
}
if ( temp > 59 ) temp = 59; // *** 1269463: XMP_Throw ( "Whole second is out of range", kXMPErr_BadParam );
binValue->second = temp;
// Don't check for done, we have to work up to the time zone.
if ( strValue[pos] == '.' ) {
++pos;
size_t digits = pos; // Will be the number of digits later.
temp = GatherInt ( strValue, &pos, "Invalid fractional seconds in date string" ); // Extract the fractional seconds.
if ( (strValue[pos] != 'Z') && (strValue[pos] != '+') && (strValue[pos] != '-') && (strValue[pos] != 0) ) {
XMP_Throw ( "Invalid date string, after fractional second", kXMPErr_BadParam );
}
digits = pos - digits;
for ( ; digits > 9; --digits ) temp = temp / 10;
for ( ; digits < 9; ++digits ) temp = temp * 10;
if ( temp >= 1000*1000*1000 ) XMP_Throw ( "Fractional second is out of range", kXMPErr_BadParam );
binValue->nanoSecond = temp;
// Don't check for done, we have to work up to the time zone.
}
}
if ( strValue[pos] == 0 ) return;
binValue->hasTimeZone = true;
if ( strValue[pos] == 'Z' ) {
++pos;
} else {
if ( strValue[pos] == '+' ) {
binValue->tzSign = kXMP_TimeEastOfUTC;
} else if ( strValue[pos] == '-' ) {
binValue->tzSign = kXMP_TimeWestOfUTC;
} else {
XMP_Throw ( "Time zone must begin with 'Z', '+', or '-'", kXMPErr_BadParam );
}
++pos;
temp = GatherInt ( strValue, &pos, "Invalid time zone hour in date string" ); // Extract the time zone hour.
if ( strValue[pos] != ':' ) XMP_Throw ( "Invalid date string, after time zone hour", kXMPErr_BadParam );
if ( temp > 23 ) XMP_Throw ( "Time zone hour is out of range", kXMPErr_BadParam );
binValue->tzHour = temp;
++pos;
temp = GatherInt ( strValue, &pos, "Invalid time zone minute in date string" ); // Extract the time zone minute.
if ( temp > 59 ) XMP_Throw ( "Time zone minute is out of range", kXMPErr_BadParam );
binValue->tzMinute = temp;
}
if ( strValue[pos] != 0 ) XMP_Throw ( "Invalid date string, extra chars at end", kXMPErr_BadParam );
} // ConvertToDate
// -------------------------------------------------------------------------------------------------
// EncodeToBase64
// --------------
//
// Encode a string of raw data bytes in base 64 according to RFC 2045. For the encoding definition
// see section 6.8 in <http://www.ietf.org/rfc/rfc2045.txt>. Although it isn't needed for RDF, we
// do insert a linefeed character as a newline for every 76 characters of encoded output.
/* class static */ void
XMPUtils::EncodeToBase64 ( XMP_StringPtr rawStr,
XMP_StringLen rawLen,
XMP_VarString * encodedStr )
{
if ( (rawStr == 0) && (rawLen != 0) ) XMP_Throw ( "Null raw data buffer", kXMPErr_BadParam );
XMP_Assert ( encodedStr != 0 ); // Enforced by wrapper.
encodedStr->erase();
if ( rawLen == 0 ) return;
char encChunk[4];
unsigned long in, out;
unsigned char c1, c2, c3;
unsigned long merge;
const size_t outputSize = (rawLen / 3) * 4; // Approximate, might be small.
encodedStr->reserve ( outputSize );
// ----------------------------------------------------------------------------------------
// Each 6 bits of input produces 8 bits of output, so 3 input bytes become 4 output bytes.
// Process the whole chunks of 3 bytes first, then deal with any remainder. Be careful with
// the loop comparison, size-2 could be negative!
for ( in = 0, out = 0; (in+2) < rawLen; in += 3, out += 4 ) {
c1 = rawStr[in];
c2 = rawStr[in+1];
c3 = rawStr[in+2];
merge = (c1 << 16) + (c2 << 8) + c3;
encChunk[0] = sBase64Chars [ merge >> 18 ];
encChunk[1] = sBase64Chars [ (merge >> 12) & 0x3F ];
encChunk[2] = sBase64Chars [ (merge >> 6) & 0x3F ];
encChunk[3] = sBase64Chars [ merge & 0x3F ];
if ( out >= 76 ) {
encodedStr->append ( 1, kLF );
out = 0;
}
encodedStr->append ( encChunk, 4 );
}
// ------------------------------------------------------------------------------------------
// The output must always be a multiple of 4 bytes. If there is a 1 or 2 byte input remainder
// we need to create another chunk. Zero pad with bits to a 6 bit multiple, then add one or
// two '=' characters to pad out to 4 bytes.
switch ( rawLen - in ) {
case 0: // Done, no remainder.
break;
case 1: // One input byte remains.
c1 = rawStr[in];
merge = c1 << 16;
encChunk[0] = sBase64Chars [ merge >> 18 ];
encChunk[1] = sBase64Chars [ (merge >> 12) & 0x3F ];
encChunk[2] = encChunk[3] = '=';
if ( out >= 76 ) encodedStr->append ( 1, kLF );
encodedStr->append ( encChunk, 4 );
break;
case 2: // Two input bytes remain.
c1 = rawStr[in];
c2 = rawStr[in+1];
merge = (c1 << 16) + (c2 << 8);
encChunk[0] = sBase64Chars [ merge >> 18 ];
encChunk[1] = sBase64Chars [ (merge >> 12) & 0x3F ];
encChunk[2] = sBase64Chars [ (merge >> 6) & 0x3F ];
encChunk[3] = '=';
if ( out >= 76 ) encodedStr->append ( 1, kLF );
encodedStr->append ( encChunk, 4 );
break;
}
} // EncodeToBase64
// -------------------------------------------------------------------------------------------------
// DecodeFromBase64
// ----------------
//
// Decode a string of raw data bytes from base 64 according to RFC 2045. For the encoding definition
// see section 6.8 in <http://www.ietf.org/rfc/rfc2045.txt>. RFC 2045 talks about ignoring all "bad"
// input but warning about non-whitespace. For XMP use we ignore space, tab, LF, and CR. Any other
// bad input is rejected.
/* class static */ void
XMPUtils::DecodeFromBase64 ( XMP_StringPtr encodedStr,
XMP_StringLen encodedLen,
XMP_VarString * rawStr )
{
if ( (encodedStr == 0) && (encodedLen != 0) ) XMP_Throw ( "Null encoded data buffer", kXMPErr_BadParam );
XMP_Assert ( rawStr != 0 ); // Enforced by wrapper.
rawStr->erase();
if ( encodedLen == 0 ) return;
unsigned char ch, rawChunk[3];
unsigned long inStr, inChunk, inLimit, merge, padding;
XMP_StringLen outputSize = (encodedLen / 4) * 3; // Only a close approximation.
rawStr->reserve ( outputSize );
// ----------------------------------------------------------------------------------------
// Each 8 bits of input produces 6 bits of output, so 4 input bytes become 3 output bytes.
// Process all but the last 4 data bytes first, then deal with the final chunk. Whitespace
// in the input must be ignored. The first loop finds where the last 4 data bytes start and
// counts the number of padding equal signs.
padding = 0;
for ( inStr = 0, inLimit = encodedLen; (inStr < 4) && (inLimit > 0); ) {
inLimit -= 1; // ! Don't do in the loop control, the decr/test order is wrong.
ch = encodedStr[inLimit];
if ( ch == '=' ) {
padding += 1; // The equal sign padding is a data byte.
} else if ( DecodeBase64Char(ch) == 0xFF ) {
continue; // Ignore whitespace, don't increment inStr.
} else {
inStr += 1;
}
}
// ! Be careful to count whitespace that is immediately before the final data. Otherwise
// ! middle portion will absorb the final data and mess up the final chunk processing.
while ( (inLimit > 0) && (DecodeBase64Char(encodedStr[inLimit-1]) == 0xFF) ) --inLimit;
if ( inStr == 0 ) return; // Nothing but whitespace.
if ( padding > 2 ) XMP_Throw ( "Invalid encoded string", kXMPErr_BadParam );
// -------------------------------------------------------------------------------------------
// Now process all but the last chunk. The limit ensures that we have at least 4 data bytes
// left when entering the output loop, so the inner loop will succeed without overrunning the
// end of the data. At the end of the outer loop we might be past inLimit though.
inStr = 0;
while ( inStr < inLimit ) {
merge = 0;
for ( inChunk = 0; inChunk < 4; ++inStr ) { // ! Yes, increment inStr on each pass.
ch = DecodeBase64Char ( encodedStr [inStr] );
if ( ch == 0xFF ) continue; // Ignore whitespace.
merge = (merge << 6) + ch;
inChunk += 1;
}
rawChunk[0] = (unsigned char) (merge >> 16);
rawChunk[1] = (unsigned char) ((merge >> 8) & 0xFF);
rawChunk[2] = (unsigned char) (merge & 0xFF);
rawStr->append ( (char*)rawChunk, 3 );
}
// -------------------------------------------------------------------------------------------
// Process the final, possibly partial, chunk of data. The input is always a multiple 4 bytes,
// but the raw data can be any length. The number of padding '=' characters determines if the
// final chunk has 1, 2, or 3 raw data bytes.
XMP_Assert ( inStr < encodedLen );
merge = 0;
for ( inChunk = 0; inChunk < 4-padding; ++inStr ) { // ! Yes, increment inStr on each pass.
ch = DecodeBase64Char ( encodedStr[inStr] );
if ( ch == 0xFF ) continue; // Ignore whitespace.
merge = (merge << 6) + ch;
inChunk += 1;
}
if ( padding == 2 ) {
rawChunk[0] = (unsigned char) (merge >> 4);
rawStr->append ( (char*)rawChunk, 1 );
} else if ( padding == 1 ) {
rawChunk[0] = (unsigned char) (merge >> 10);
rawChunk[1] = (unsigned char) ((merge >> 2) & 0xFF);
rawStr->append ( (char*)rawChunk, 2 );
} else {
rawChunk[0] = (unsigned char) (merge >> 16);
rawChunk[1] = (unsigned char) ((merge >> 8) & 0xFF);
rawChunk[2] = (unsigned char) (merge & 0xFF);
rawStr->append ( (char*)rawChunk, 3 );
}
} // DecodeFromBase64
// -------------------------------------------------------------------------------------------------
// PackageForJPEG
// --------------
/* class static */ void
XMPUtils::PackageForJPEG ( const XMPMeta & origXMP,
XMP_VarString * stdStr,
XMP_VarString * extStr,
XMP_VarString * digestStr )
{
#if ENABLE_CPP_DOM_MODEL
if(sUseNewCoreAPIs) {
const XMPMeta2 & orig = dynamic_cast<const XMPMeta2 &>(origXMP);
return XMPUtils::PackageForJPEG(orig, stdStr, extStr, digestStr);
}
#endif
XMP_Assert ( (stdStr != 0) && (extStr != 0) && (digestStr != 0) ); // ! Enforced by wrapper.
enum { kStdXMPLimit = 65000 };
static const char * kPacketTrailer = "<?xpacket end=\"w\"?>";
static size_t kTrailerLen = strlen ( kPacketTrailer );
XMP_VarString tempStr;
XMPMeta stdXMP, extXMP;
XMP_OptionBits keepItSmall = kXMP_UseCompactFormat | kXMP_OmitAllFormatting;
stdStr->erase();
extStr->erase();
digestStr->erase();
// Try to serialize everything. Note that we're making internal calls to SerializeToBuffer, so
// we'll be getting back the pointer and length for its internal string.
origXMP.SerializeToBuffer ( &tempStr, keepItSmall, 1, "", "", 0 );
#if Trace_PackageForJPEG
printf ( "\nXMPUtils::PackageForJPEG - Full serialize %d bytes\n", tempStr.size() );
#endif
if ( tempStr.size() > kStdXMPLimit ) {
// Couldn't fit everything, make a copy of the input XMP and make sure there is no xmp:Thumbnails property.
stdXMP.tree.options = origXMP.tree.options;
stdXMP.tree.name = origXMP.tree.name;
stdXMP.tree.value = origXMP.tree.value;
CloneOffspring ( &origXMP.tree, &stdXMP.tree );
if ( stdXMP.DoesPropertyExist ( kXMP_NS_XMP, "Thumbnails" ) ) {
stdXMP.DeleteProperty ( kXMP_NS_XMP, "Thumbnails" );
stdXMP.SerializeToBuffer ( &tempStr, keepItSmall, 1, "", "", 0 );
#if Trace_PackageForJPEG
printf ( " Delete xmp:Thumbnails, %d bytes left\n", tempStr.size() );
#endif
}
}
if ( tempStr.size() > kStdXMPLimit ) {
// Still doesn't fit, move all of the Camera Raw namespace. Add a dummy value for xmpNote:HasExtendedXMP.
stdXMP.SetProperty ( kXMP_NS_XMP_Note, "HasExtendedXMP", "123456789-123456789-123456789-12", 0 );
XMP_NodePtrPos crSchemaPos;
XMP_Node * crSchema = FindSchemaNode ( &stdXMP.tree, kXMP_NS_CameraRaw, kXMP_ExistingOnly, &crSchemaPos );
if ( crSchema != 0 ) {
crSchema->parent = &extXMP.tree;
extXMP.tree.children.push_back ( crSchema );
stdXMP.tree.children.erase ( crSchemaPos );
stdXMP.SerializeToBuffer ( &tempStr, keepItSmall, 1, "", "", 0 );
#if Trace_PackageForJPEG
printf ( " Move Camera Raw schema, %d bytes left\n", tempStr.size() );
#endif
}
}
if ( tempStr.size() > kStdXMPLimit ) {
// Still doesn't fit, move photoshop:History.
bool moved = MoveOneProperty ( stdXMP, &extXMP, kXMP_NS_Photoshop, "photoshop:History" );
if ( moved ) {
stdXMP.SerializeToBuffer ( &tempStr, keepItSmall, 1, "", "", 0 );
#if Trace_PackageForJPEG
printf ( " Move photoshop:History, %d bytes left\n", tempStr.size() );
#endif
}
}
if ( tempStr.size() > kStdXMPLimit ) {
// Still doesn't fit, move top level properties in order of estimated size. This is done by
// creating a multi-map that maps the serialized size to the string pair for the schema URI
// and top level property name. Since maps are inherently ordered, a reverse iteration of
// the map can be done to move the largest things first. We use a double loop to keep going
// until the serialization actually fits, in case the estimates are off.
PropSizeMap propSizes;
CreateEstimatedSizeMap ( stdXMP, &propSizes );
#if Trace_PackageForJPEG
if ( ! propSizes.empty() ) {
printf ( " Top level property map, smallest to largest:\n" );
PropSizeMap::iterator mapPos = propSizes.begin();
PropSizeMap::iterator mapEnd = propSizes.end();
for ( ; mapPos != mapEnd; ++mapPos ) {
size_t propSize = mapPos->first;
const char * schemaName = mapPos->second.first->c_str();
const char * propName = mapPos->second.second->c_str();
printf ( " %d bytes, %s in %s\n", propSize, propName, schemaName );
}
}
#endif
#if 0 // Trace_PackageForJPEG *** Xcode 2.3 on 10.4.7 has bugs in backwards iteration
if ( ! propSizes.empty() ) {
printf ( " Top level property map, largest to smallest:\n" );
PropSizeMap::iterator mapPos = propSizes.end();
PropSizeMap::iterator mapBegin = propSizes.begin();
for ( --mapPos; true; --mapPos ) {
size_t propSize = mapPos->first;
const char * schemaName = mapPos->second.first->c_str();
const char * propName = mapPos->second.second->c_str();
printf ( " %d bytes, %s in %s\n", propSize, propName, schemaName );
if ( mapPos == mapBegin ) break;
}
}
#endif
// Outer loop to make sure enough is actually moved.
while ( (tempStr.size() > kStdXMPLimit) && (! propSizes.empty()) ) {
// Inner loop, move what seems to be enough according to the estimates.
size_t tempLen = tempStr.size();
while ( (tempLen > kStdXMPLimit) && (! propSizes.empty()) ) {
size_t propSize = MoveLargestProperty ( stdXMP, &extXMP, propSizes );
XMP_Assert ( propSize > 0 );
if ( propSize > tempLen ) propSize = tempLen; // ! Don't go negative.
tempLen -= propSize;
}
// Reserialize the remaining standard XMP.
stdXMP.SerializeToBuffer ( &tempStr, keepItSmall, 1, "", "", 0 );
}
}
if ( tempStr.size() > kStdXMPLimit ) {
// Still doesn't fit, throw an exception and let the client decide what to do.
// ! This should never happen with the policy of moving any and all top level properties.
XMP_Throw ( "Can't reduce XMP enough for JPEG file", kXMPErr_TooLargeForJPEG );
}
// Set the static output strings.
if ( extXMP.tree.children.empty() ) {
// Just have the standard XMP.
*stdStr = tempStr;
} else {
// Have extended XMP. Serialize it, compute the digest, reset xmpNote:HasExtendedXMP, and
// reserialize the standard XMP.
extXMP.SerializeToBuffer ( &tempStr, (keepItSmall | kXMP_OmitPacketWrapper), 0, "", "", 0 );
*extStr = tempStr;
MD5_CTX context;
XMP_Uns8 digest [16];
MD5Init ( &context );
MD5Update ( &context, (XMP_Uns8*)tempStr.c_str(), (XMP_Uns32)tempStr.size() );
MD5Final ( digest, &context );
digestStr->reserve ( 32 );
for ( size_t i = 0; i < 16; ++i ) {
XMP_Uns8 byte = digest[i];
digestStr->push_back ( kHexDigits [ byte>>4 ] );
digestStr->push_back ( kHexDigits [ byte&0xF ] );
}
stdXMP.SetProperty ( kXMP_NS_XMP_Note, "HasExtendedXMP", digestStr->c_str(), 0 );
stdXMP.SerializeToBuffer ( &tempStr, keepItSmall, 1, "", "", 0 );
*stdStr = tempStr;
}
// Adjust the standard XMP padding to be up to 2KB.
#if XMP_DebugBuild
XMP_Assert ( (stdStr->size() > kTrailerLen) && (stdStr->size() <= kStdXMPLimit) );
const char * packetEnd = stdStr->c_str() + stdStr->size() - kTrailerLen;
XMP_Assert ( XMP_LitMatch ( packetEnd, kPacketTrailer ) );
#endif
size_t extraPadding = kStdXMPLimit - stdStr->size(); // ! Do this before erasing the trailer.
if ( extraPadding > 2047 ) extraPadding = 2047;
stdStr->erase ( stdStr->size() - kTrailerLen );
stdStr->append ( extraPadding, ' ' );
stdStr->append ( kPacketTrailer );
} // PackageForJPEG
#if ENABLE_CPP_DOM_MODEL
// -------------------------------------------------------------------------------------------------
// PackageForJPEG
// --------------
/* class static */ void
XMPUtils::PackageForJPEG(const XMPMeta2 & origXMP,
XMP_VarString * stdStr,
XMP_VarString * extStr,
XMP_VarString * digestStr)
{
XMP_Assert((stdStr != 0) && (extStr != 0) && (digestStr != 0)); // ! Enforced by wrapper.
enum { kStdXMPLimit = 65000 };
static const char * kPacketTrailer = "<?xpacket end=\"w\"?>";
static size_t kTrailerLen = strlen(kPacketTrailer);
XMP_VarString tempStr;
XMPMeta2 stdXMP, extXMP;
XMP_OptionBits keepItSmall = kXMP_UseCompactFormat | kXMP_OmitAllFormatting;
stdStr->erase();
extStr->erase();
digestStr->erase();
// Try to serialize everything. Note that we're making internal calls to SerializeToBuffer, so
// we'll be getting back the pointer and length for its internal string.
origXMP.SerializeToBuffer(&tempStr, keepItSmall, 1, "", "", 0);
#if Trace_PackageForJPEG
printf("\nXMPUtils::PackageForJPEG - Full serialize %d bytes\n", tempStr.size());
#endif
if (tempStr.size() > kStdXMPLimit) {
// Couldn't fit everything, make a copy of the input XMP and make sure there is no xmp:Thumbnails property.
stdXMP.mDOM = origXMP.mDOM->Clone()->ConvertToMetadata();
if (stdXMP.DoesPropertyExist(kXMP_NS_XMP, "Thumbnails")) {
stdXMP.DeleteProperty(kXMP_NS_XMP, "Thumbnails");
stdXMP.SerializeToBuffer(&tempStr, keepItSmall, 1, "", "", 0);
#if Trace_PackageForJPEG
printf(" Delete xmp:Thumbnails, %d bytes left\n", tempStr.size());
#endif
}
}
if (tempStr.size() > kStdXMPLimit) {
// Still doesn't fit, move all of the Camera Raw namespace. Add a dummy value for xmpNote:HasExtendedXMP.
stdXMP.SetProperty(kXMP_NS_XMP_Note, "HasExtendedXMP", "123456789-123456789-123456789-12", 0);
spIStructureNode currRootNode = stdXMP.mDOM;
std::vector<XMP_VarString> nodes;
for (auto rootPropIter = currRootNode->Iterator(); rootPropIter; rootPropIter = rootPropIter->Next()) {
auto rootPropNodeCloned = rootPropIter->GetNode()->Clone();
if (strcmp(rootPropNodeCloned->GetNameSpace()->c_str(), kXMP_NS_CameraRaw ) ) continue;
extXMP.mDOM->AppendNode(rootPropNodeCloned);
nodes.push_back(rootPropNodeCloned->GetName()->c_str());
}
for (size_t childIdx = 0, childLim = nodes.size(); childIdx != childLim; ++childIdx) {
stdXMP.mDOM->RemoveNode(kXMP_NS_CameraRaw, AdobeXMPCommon::npos, nodes[childIdx].c_str(), nodes[childIdx].size() );
}
if (nodes.size() != 0) {
stdXMP.SerializeToBuffer(&tempStr, keepItSmall, 1, "", "", 0);
#if Trace_PackageForJPEG
printf(" Move Camera Raw schema, %d bytes left\n", tempStr.size());
#endif
}
}
if (tempStr.size() > kStdXMPLimit) {
// Still doesn't fit, move photoshop:History.
bool moved = MoveOneProperty(stdXMP, &extXMP, kXMP_NS_Photoshop, "History");
if (moved) {
stdXMP.SerializeToBuffer(&tempStr, keepItSmall, 1, "", "", 0);
#if Trace_PackageForJPEG
printf(" Move photoshop:History, %d bytes left\n", tempStr.size());
#endif
}
}
if (tempStr.size() > kStdXMPLimit) {
// Still doesn't fit, move top level properties in order of estimated size. This is done by
// creating a multi-map that maps the serialized size to the string pair for the schema URI
// and top level property name. Since maps are inherently ordered, a reverse iteration of
// the map can be done to move the largest things first. We use a double loop to keep going
// until the serialization actually fits, in case the estimates are off.
PropSizeMap2 propSizes;
CreateEstimatedSizeMap(stdXMP, &propSizes);
#if Trace_PackageForJPEG
if (!propSizes.empty()) {
printf(" Top level property map, smallest to largest:\n");
PropSizeMap::iterator mapPos = propSizes.begin();
PropSizeMap::iterator mapEnd = propSizes.end();
for (; mapPos != mapEnd; ++mapPos) {
size_t propSize = mapPos->first;
const char * schemaName = mapPos->second.first->c_str();
const char * propName = mapPos->second.second->c_str();
printf(" %d bytes, %s in %s\n", propSize, propName, schemaName);
}
}
#endif
#if 0 // Trace_PackageForJPEG *** Xcode 2.3 on 10.4.7 has bugs in backwards iteration
if (!propSizes.empty()) {
printf(" Top level property map, largest to smallest:\n");
PropSizeMap::iterator mapPos = propSizes.end();
PropSizeMap::iterator mapBegin = propSizes.begin();
for (--mapPos; true; --mapPos) {
size_t propSize = mapPos->first;
const char * schemaName = mapPos->second.first->c_str();
const char * propName = mapPos->second.second->c_str();
printf(" %d bytes, %s in %s\n", propSize, propName, schemaName);
if (mapPos == mapBegin) break;
}
}
#endif
// Outer loop to make sure enough is actually moved.
while ((tempStr.size() > kStdXMPLimit) && (!propSizes.empty())) {
// Inner loop, move what seems to be enough according to the estimates.
size_t tempLen = tempStr.size();
while ((tempLen > kStdXMPLimit) && (!propSizes.empty())) {
size_t propSize = MoveLargestProperty(stdXMP, &extXMP, propSizes);
XMP_Assert(propSize > 0);
if (propSize > tempLen) propSize = tempLen; // ! Don't go negative.
tempLen -= propSize;
}
// Reserialize the remaining standard XMP.
stdXMP.SerializeToBuffer(&tempStr, keepItSmall, 1, "", "", 0);
}
}
if (tempStr.size() > kStdXMPLimit) {
// Still doesn't fit, throw an exception and let the client decide what to do.
// ! This should never happen with the policy of moving any and all top level properties.
XMP_Throw("Can't reduce XMP enough for JPEG file", kXMPErr_TooLargeForJPEG);
}
// Set the static output strings.
if (!extXMP.mDOM->ChildCount()) {
// Just have the standard XMP.
*stdStr = tempStr;
}
else {
// Have extended XMP. Serialize it, compute the digest, reset xmpNote:HasExtendedXMP, and
// reserialize the standard XMP.
extXMP.SerializeToBuffer(&tempStr, (keepItSmall | kXMP_OmitPacketWrapper), 0, "", "", 0);
*extStr = tempStr;
MD5_CTX context;
XMP_Uns8 digest[16];
MD5Init(&context);
MD5Update(&context, (XMP_Uns8*)tempStr.c_str(), (XMP_Uns32)tempStr.size());
MD5Final(digest, &context);
digestStr->reserve(32);
for (size_t i = 0; i < 16; ++i) {
XMP_Uns8 byte = digest[i];
digestStr->push_back(kHexDigits[byte >> 4]);
digestStr->push_back(kHexDigits[byte & 0xF]);
}
stdXMP.SetProperty(kXMP_NS_XMP_Note, "HasExtendedXMP", digestStr->c_str(), 0);
stdXMP.SerializeToBuffer(&tempStr, keepItSmall, 1, "", "", 0);
*stdStr = tempStr;
}
// Adjust the standard XMP padding to be up to 2KB.
XMP_Assert((stdStr->size() > kTrailerLen) && (stdStr->size() <= kStdXMPLimit));
const char * packetEnd = stdStr->c_str() + stdStr->size() - kTrailerLen;
XMP_Assert(XMP_LitMatch(packetEnd, kPacketTrailer));
size_t extraPadding = kStdXMPLimit - stdStr->size(); // ! Do this before erasing the trailer.
if (extraPadding > 2047) extraPadding = 2047;
stdStr->erase(stdStr->size() - kTrailerLen);
stdStr->append(extraPadding, ' ');
stdStr->append(kPacketTrailer);
} // PackageForJPEG
#endif
// -------------------------------------------------------------------------------------------------
// MergeFromJPEG
// -------------
//
// Copy all of the top level properties from extendedXMP to fullXMP, replacing any duplicates.
// Delete the xmpNote:HasExtendedXMP property from fullXMP.
/* class static */ void
XMPUtils::MergeFromJPEG ( XMPMeta * fullXMP,
const XMPMeta & extendedXMP )
{
XMP_OptionBits apFlags = (kXMPTemplate_ReplaceExistingProperties | kXMPTemplate_IncludeInternalProperties);
XMPUtils::ApplyTemplate ( fullXMP, extendedXMP, apFlags );
fullXMP->DeleteProperty ( kXMP_NS_XMP_Note, "HasExtendedXMP" );
} // MergeFromJPEG
// -------------------------------------------------------------------------------------------------
// CurrentDateTime
// ---------------
/* class static */ void
XMPUtils::CurrentDateTime ( XMP_DateTime * xmpTime )
{
XMP_Assert ( xmpTime != 0 ); // ! Enforced by wrapper.
ansi_tt binTime = ansi_time(0);
if ( binTime == -1 ) XMP_Throw ( "Failure from ANSI C time function", kXMPErr_ExternalFailure );
ansi_tm currTime;
ansi_localtime ( &binTime, &currTime );
xmpTime->year = currTime.tm_year + 1900;
xmpTime->month = currTime.tm_mon + 1;
xmpTime->day = currTime.tm_mday;
xmpTime->hasDate = true;
xmpTime->hour = currTime.tm_hour;
xmpTime->minute = currTime.tm_min;
xmpTime->second = currTime.tm_sec;
xmpTime->nanoSecond = 0;
xmpTime->hasTime = true;
xmpTime->tzSign = 0;
xmpTime->tzHour = 0;
xmpTime->tzMinute = 0;
xmpTime->hasTimeZone = false; // ! Needed for SetTimeZone.
XMPUtils::SetTimeZone ( xmpTime );
} // CurrentDateTime
// -------------------------------------------------------------------------------------------------
// SetTimeZone
// -----------
//
// Sets just the time zone part of the time. Useful for determining the local time zone or for
// converting a "zone-less" time to a proper local time. The ANSI C time functions are smart enough
// to do all the right stuff, as long as we call them properly!
/* class static */ void
XMPUtils::SetTimeZone ( XMP_DateTime * xmpTime )
{
XMP_Assert ( xmpTime != 0 ); // ! Enforced by wrapper.
VerifyDateTimeFlags ( xmpTime );
if ( xmpTime->hasTimeZone ) {
XMP_Throw ( "SetTimeZone can only be used on zone-less times", kXMPErr_BadParam );
}
// Create ansi_tt form of the input time. Need the ansi_tm form to make the ansi_tt form.
ansi_tt ttTime;
ansi_tm tmLocal, tmUTC;
if ( (xmpTime->year == 0) && (xmpTime->month == 0) && (xmpTime->day == 0) ) {
ansi_tt now = ansi_time(0);
if ( now == -1 ) XMP_Throw ( "Failure from ANSI C time function", kXMPErr_ExternalFailure );
ansi_localtime ( &now, &tmLocal );
} else {
tmLocal.tm_year = xmpTime->year - 1900;
while ( tmLocal.tm_year < 70 ) tmLocal.tm_year += 4; // ! Some versions of mktime barf on years before 1970.
tmLocal.tm_mon = xmpTime->month - 1;
tmLocal.tm_mday = xmpTime->day;
}
tmLocal.tm_hour = xmpTime->hour;
tmLocal.tm_min = xmpTime->minute;
tmLocal.tm_sec = xmpTime->second;
tmLocal.tm_isdst = -1; // Don't know if daylight time is in effect.
ttTime = ansi_mktime ( &tmLocal );
if ( ttTime == -1 ) XMP_Throw ( "Failure from ANSI C mktime function", kXMPErr_ExternalFailure );
// Convert back to a localized ansi_tm time and get the corresponding UTC ansi_tm time.
ansi_localtime ( &ttTime, &tmLocal );
ansi_gmtime ( &ttTime, &tmUTC );
// Get the offset direction and amount.
ansi_tm tmx = tmLocal; // ! Note that mktime updates the ansi_tm parameter, messing up difftime!
ansi_tm tmy = tmUTC;
tmx.tm_isdst = tmy.tm_isdst = 0;
ansi_tt ttx = ansi_mktime ( &tmx );
ansi_tt tty = ansi_mktime ( &tmy );
double diffSecs;
if ( (ttx != -1) && (tty != -1) ) {
diffSecs = ansi_difftime ( ttx, tty );
} else {
#if XMP_MacBuild | XMP_iOSBuild
// Looks like Apple's mktime is buggy - see W1140533. But the offset is visible.
diffSecs = tmLocal.tm_gmtoff;
#else
// Win and UNIX don't have a visible offset. Make sure we know about the failure,
// then try using the current date/time as a close fallback.
ttTime = ansi_time(0);
if ( ttTime == -1 ) XMP_Throw ( "Failure from ANSI C time function", kXMPErr_ExternalFailure );
ansi_localtime ( &ttTime, &tmx );
ansi_gmtime ( &ttTime, &tmy );
tmx.tm_isdst = tmy.tm_isdst = 0;
ttx = ansi_mktime ( &tmx );
tty = ansi_mktime ( &tmy );
if ( (ttx == -1) || (tty == -1) ) XMP_Throw ( "Failure from ANSI C mktime function", kXMPErr_ExternalFailure );
diffSecs = ansi_difftime ( ttx, tty );
#endif
}
if ( diffSecs > 0.0 ) {
xmpTime->tzSign = kXMP_TimeEastOfUTC;
} else if ( diffSecs == 0.0 ) {
xmpTime->tzSign = kXMP_TimeIsUTC;
} else {
xmpTime->tzSign = kXMP_TimeWestOfUTC;
diffSecs = -diffSecs;
}
xmpTime->tzHour = XMP_Int32 ( diffSecs / 3600.0 );
xmpTime->tzMinute = XMP_Int32 ( (diffSecs / 60.0) - (xmpTime->tzHour * 60.0) );
xmpTime->hasTimeZone = xmpTime->hasTime = true;
// *** Save the tm_isdst flag in a qualifier?
XMP_Assert ( (0 <= xmpTime->tzHour) && (xmpTime->tzHour <= 23) );
XMP_Assert ( (0 <= xmpTime->tzMinute) && (xmpTime->tzMinute <= 59) );
XMP_Assert ( (-1 <= xmpTime->tzSign) && (xmpTime->tzSign <= +1) );
XMP_Assert ( (xmpTime->tzSign == 0) ? ((xmpTime->tzHour == 0) && (xmpTime->tzMinute == 0)) :
((xmpTime->tzHour != 0) || (xmpTime->tzMinute != 0)) );
} // SetTimeZone
// -------------------------------------------------------------------------------------------------
// ConvertToUTCTime
// ----------------
/* class static */ void
XMPUtils::ConvertToUTCTime ( XMP_DateTime * time )
{
XMP_Assert ( time != 0 ); // ! Enforced by wrapper.
VerifyDateTimeFlags ( time );
if ( ! time->hasTimeZone ) return; // Do nothing if there is no current time zone.
XMP_Assert ( (0 <= time->tzHour) && (time->tzHour <= 23) );
XMP_Assert ( (0 <= time->tzMinute) && (time->tzMinute <= 59) );
XMP_Assert ( (-1 <= time->tzSign) && (time->tzSign <= +1) );
XMP_Assert ( (time->tzSign == 0) ? ((time->tzHour == 0) && (time->tzMinute == 0)) :
((time->tzHour != 0) || (time->tzMinute != 0)) );
if ( time->tzSign == kXMP_TimeEastOfUTC ) {
// We are before (east of) GMT, subtract the offset from the time.
time->hour -= time->tzHour;
time->minute -= time->tzMinute;
} else if ( time->tzSign == kXMP_TimeWestOfUTC ) {
// We are behind (west of) GMT, add the offset to the time.
time->hour += time->tzHour;
time->minute += time->tzMinute;
}
AdjustTimeOverflow ( time );
time->tzSign = time->tzHour = time->tzMinute = 0;
} // ConvertToUTCTime
// -------------------------------------------------------------------------------------------------
// ConvertToLocalTime
// ------------------
/* class static */ void
XMPUtils::ConvertToLocalTime ( XMP_DateTime * time )
{
XMP_Assert ( time != 0 ); // ! Enforced by wrapper.
VerifyDateTimeFlags ( time );
if ( ! time->hasTimeZone ) return; // Do nothing if there is no current time zone.
XMP_Assert ( (0 <= time->tzHour) && (time->tzHour <= 23) );
XMP_Assert ( (0 <= time->tzMinute) && (time->tzMinute <= 59) );
XMP_Assert ( (-1 <= time->tzSign) && (time->tzSign <= +1) );
XMP_Assert ( (time->tzSign == 0) ? ((time->tzHour == 0) && (time->tzMinute == 0)) :
((time->tzHour != 0) || (time->tzMinute != 0)) );
ConvertToUTCTime ( time ); // The existing time zone might not be the local one.
time->hasTimeZone = false; // ! Needed for SetTimeZone.
SetTimeZone ( time ); // Fill in the local timezone offset, then adjust the time.
if ( time->tzSign > 0 ) {
// We are before (east of) GMT, add the offset to the time.
time->hour += time->tzHour;
time->minute += time->tzMinute;
} else if ( time->tzSign < 0 ) {
// We are behind (west of) GMT, subtract the offset from the time.
time->hour -= time->tzHour;
time->minute -= time->tzMinute;
}
AdjustTimeOverflow ( time );
} // ConvertToLocalTime
// -------------------------------------------------------------------------------------------------
// CompareDateTime
// ---------------
/* class static */ int
XMPUtils::CompareDateTime ( const XMP_DateTime & _in_left,
const XMP_DateTime & _in_right )
{
int result = 0;
XMP_DateTime left = _in_left;
XMP_DateTime right = _in_right;
VerifyDateTimeFlags ( &left );
VerifyDateTimeFlags ( &right );
// Can't compare if one has a date and the other does not.
if ( left.hasDate != right.hasDate ) return 0; // Throw?
if ( left.hasTimeZone & right.hasTimeZone ) {
// If both times have zones then convert them to UTC, otherwise assume the same zone.
ConvertToUTCTime ( &left );
ConvertToUTCTime ( &right );
}
if ( left.hasDate ) {
XMP_Assert ( right.hasDate );
if ( left.year < right.year ) {
result = -1;
} else if ( left.year > right.year ) {
result = +1;
} else if ( left.month < right.month ) {
result = -1;
} else if ( left.month > right.month ) {
result = +1;
} else if ( left.day < right.day ) {
result = -1;
} else if ( left.day > right.day ) {
result = +1;
}
if ( result != 0 ) return result;
}
if ( left.hasTime & right.hasTime ) {
// Ignore the time parts if either value is date-only.
if ( left.hour < right.hour ) {
result = -1;
} else if ( left.hour > right.hour ) {
result = +1;
} else if ( left.minute < right.minute ) {
result = -1;
} else if ( left.minute > right.minute ) {
result = +1;
} else if ( left.second < right.second ) {
result = -1;
} else if ( left.second > right.second ) {
result = +1;
} else if ( left.nanoSecond < right.nanoSecond ) {
result = -1;
} else if ( left.nanoSecond > right.nanoSecond ) {
result = +1;
} else {
result = 0;
}
}
return result;
} // CompareDateTime
// =================================================================================================
std::string * XMPUtils::WhiteSpaceStrPtr = NULL;
std::string& XMPUtils::Trim( std::string& string )
{
size_t pos = string.find_last_not_of( *WhiteSpaceStrPtr );
if ( pos != std::string::npos ) {
string.erase( pos + 1 );
pos = string.find_first_not_of( *WhiteSpaceStrPtr );
if(pos != std::string::npos) string.erase(0, pos);
} else {
string.erase( string.begin(), string.end() );
}
return string;
}
#if ENABLE_CPP_DOM_MODEL
#include "XMPCore/XMPCoreErrorCodes.h"
void XMPUtils::MapXMPErrorToIError( XMP_Int32 xmpErrorCode, IError::eErrorDomain & domain, IError::eErrorCode & code ) {
switch ( xmpErrorCode ) {
case kXMPErr_Unknown:
case kXMPErr_TBD:
code = kGECUnknownFailure;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_Unavailable:
case kXMPErr_Unimplemented:
code = kGECNotImplemented;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_BadObject:
case kXMPErr_BadParam:
case kXMPErr_BadValue:
code = kGECParametersNotAsExpected;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_AssertFailure:
case kXMPErr_EnforceFailure:
code = kGECAssertionFailure;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_InternalFailure:
code = kGECInternalFailure;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_Deprecated:
code = kGECDeprecatedFunctionCall;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_ExternalFailure:
code = kGECExternalFailure;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_UserAbort:
case kXMPErr_ProgressAbort:
code = kGECUserAbort;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_StdException:
code = kGECStandardException;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_UnknownException:
code = kGECUnknownExceptionCaught;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_NoMemory:
code = kMMECAllocationFailure;
domain = IError_base::kEDMemoryManagement;
break;
case kXMPErr_BadSchema:
code = kDMECBadSchema;
domain = IError_base::kEDDataModel;
break;
case kXMPErr_BadXPath:
code = kDMECBadXPath;
domain = IError_base::kEDDataModel;
break;
case kXMPErr_BadOptions:
code = kDMECBadOptions;
domain = IError_base::kEDDataModel;
break;
case kXMPErr_BadIndex:
code = kGECIndexOutOfBounds;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_BadIterPosition:
code = kDMECBadIterPosition;
domain = IError_base::kEDDataModel;
break;
case kXMPErr_BadParse:
code = kPECBadXMP;
domain = IError_base::kEDParser;
break;
case kXMPErr_BadSerialize:
code = kSECSizeExceed;
domain = IError_base::kEDSerializer;
break;
case kXMPErr_BadFileFormat:
case kXMPErr_NoFileHandler:
case kXMPErr_TooLargeForJPEG:
case kXMPErr_NoFile:
case kXMPErr_FilePermission:
case kXMPErr_DiskSpace:
case kXMPErr_ReadError:
case kXMPErr_WriteError:
case kXMPErr_BadBlockFormat:
case kXMPErr_FilePathNotAFile:
case kXMPErr_RejectedFileExtension:
code = kGECNotImplemented;
domain = IError_base::kEDGeneral;
break;
case kXMPErr_BadXML:
code = kPECBadXML;
domain = IError_base::kEDParser;
break;
case kXMPErr_BadRDF:
code = kPECBadRDF;
domain = IError_base::kEDParser;
break;
case kXMPErr_BadXMP:
code = kPECBadXMP;
domain = IError_base::kEDParser;
break;
case kXMPErr_EmptyIterator:
code = kDMECEmptyIterator;
domain = IError_base::kEDDataModel;
break;
case kXMPErr_BadUnicode:
code = kDMECBadUnicode;
domain = IError_base::kEDDataModel;
break;
case kXMPErr_BadTIFF:
case kXMPErr_BadJPEG:
case kXMPErr_BadPSD:
case kXMPErr_BadPSIR:
case kXMPErr_BadIPTC:
case kXMPErr_BadMPEG:
default:
code = kGECNotImplemented;
domain = IError_base::kEDGeneral;
break;
}
}
#endif
// =================================================================================================
|