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
|
/** Implementation for NSUserDefaults for GNUstep
Copyright (C) 1995-2016 Free Software Foundation, Inc.
Written by: Georg Tuparev <Tuparev@EMBL-Heidelberg.de>
EMBL & Academia Naturalis,
Heidelberg, Germany
Modified by: Richard Frith-Macdonald <rfm@gnu.org>
This file is part of the GNUstep Base Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
<title>NSUserDefaults class reference</title>
$Date$ $Revision$
*/
#import "common.h"
#define EXPOSE_NSUserDefaults_IVARS 1
#include <sys/stat.h>
#include <sys/types.h>
#import "Foundation/NSUserDefaults.h"
#import "Foundation/NSArchiver.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSData.h"
#import "Foundation/NSDate.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSDistributedLock.h"
#import "Foundation/NSException.h"
#import "Foundation/NSFileManager.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSNotification.h"
#import "Foundation/NSPathUtilities.h"
#import "Foundation/NSProcessInfo.h"
#import "Foundation/NSPropertyList.h"
#import "Foundation/NSRunLoop.h"
#import "Foundation/NSSet.h"
#import "Foundation/NSThread.h"
#import "Foundation/NSTimer.h"
#import "Foundation/NSValue.h"
#import "GNUstepBase/GSLocale.h"
#import "GNUstepBase/NSProcessInfo+GNUstepBase.h"
#import "GNUstepBase/NSString+GNUstepBase.h"
#import "NSKVOInternal.h"
#if defined(_WIN32)
#import "win32/NSString+Win32Additions.h"
#include <winnls.h>
/* Fake interface to avoid compiler warnings
*/
@interface NSUserDefaultsWin32 : NSUserDefaults
@end
#endif
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#import "GSPrivate.h"
/* Wait for access */
#define _MAX_COUNT 5 /* Max 10 sec. */
/*************************************************************************
*** Class variables
*************************************************************************/
static SEL nextObjectSel;
static SEL objectForKeySel;
static SEL addSel;
static Class NSArrayClass;
static Class NSDataClass;
static Class NSDateClass;
static Class NSDictionaryClass;
static Class NSNumberClass;
static Class NSMutableDictionaryClass;
static Class NSStringClass;
static NSString *GSPrimaryDomain = @"GSPrimaryDomain";
static NSString *defaultsFile = @".GNUstepDefaults";
static NSUserDefaults *sharedDefaults = nil;
static NSDictionary *argumentsDictionary = nil;
static NSString *bundleIdentifier = nil;
static NSString *processName = nil;
static NSRecursiveLock *classLock = nil;
static NSLock *syncLock = nil;
static BOOL initializing = NO;
/* Flag to say whether the sharedDefaults variable has been set up by a
* call to the +standardUserDefaults method. If this is YES but the variable
* is nil then there was a problem initialising the shared object and we
* have no defaults available.
*/
static BOOL hasSharedDefaults = NO;
/* Caching some default flag values. Until the standard defaults have
* been loaded, these values are taken from the process arguments.
*/
static BOOL flags[GSUserDefaultMaxFlag] = { 0 };
/* An instance of the GSPersistentDomain class is used to encapsulate
* a single persistent domain (represented as a property list file in
* the defaults directory.
* Instances are generally created without contents, and the contents
* are lazily loaded from disk when the domain is needed (either because
* it is in the defaults system search list, or because the method to
* obtain a copy of the domain contents is called).
*/
@interface GSPersistentDomain : NSObject
{
NSString *name;
NSString *path;
NSUserDefaults *owner;
NSMutableDictionary *contents;
NSMutableSet *added;
NSMutableSet *modified;
NSMutableSet *removed;
BOOL loaded;
}
- (NSDictionary*) contents;
- (void) empty;
- (id) initWithName: (NSString*)n
owner: (NSUserDefaults*)o;
- (NSString*) name;
- (id) objectForKey: (NSString*)aKey;
- (BOOL) setObject: (id)anObject forKey: (NSString*)aKey;
- (BOOL) setContents: (NSDictionary*)domain;
- (BOOL) synchronize;
@end
static NSString *
lockPath(NSString *defaultsDatabase, BOOL verbose)
{
NSString *path;
NSFileManager *mgr;
unsigned desired;
NSDictionary *attr;
BOOL isDir;
/* We use a subdirectory (.lck) of the defaults directory in which to
* create/destroy the distributed lock used to ensure that defaults
* are not simultanously updated by multiple processes.
* The use of a subdirectory means that locking/unlocking the distributed
* lock will not change the timestamp on the defaults database directory
* itsself, so we can use that date to see if any defaults files have
* been added or removed.
*/
path = defaultsDatabase;
mgr = [NSFileManager defaultManager];
#if !(defined(S_IRUSR) && defined(S_IWUSR) && defined(S_IXUSR) \
&& defined(S_IRGRP) && defined(S_IXGRP) \
&& defined(S_IROTH) && defined(S_IXOTH))
desired = 0755;
#else
desired = (S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
#endif
attr = [NSDictionary dictionaryWithObjectsAndKeys:
NSUserName(), NSFileOwnerAccountName,
[NSNumberClass numberWithUnsignedLong: desired], NSFilePosixPermissions,
nil];
if ([mgr fileExistsAtPath: path isDirectory: &isDir] == NO)
{
if ([mgr createDirectoryAtPath: path
withIntermediateDirectories: YES
attributes: attr
error: NULL] == NO)
{
if (verbose)
NSLog(@"Defaults path '%@' does not exist - failed to create it.",
path);
return nil;
}
else
{
if (verbose)
NSLog(@"Defaults path '%@' did not exist - created it", path);
isDir = YES;
}
}
if (isDir == NO)
{
if (verbose)
NSLog(@"ERROR - Defaults path '%@' is not a directory!", path);
return nil;
}
path = [path stringByAppendingPathComponent: @".lck"];
if ([mgr fileExistsAtPath: path isDirectory: &isDir] == NO)
{
if ([mgr createDirectoryAtPath: path
withIntermediateDirectories: YES
attributes: attr
error: NULL] == NO)
{
if (verbose)
NSLog(@"Defaults path '%@' does not exist - failed to create it.",
path);
return nil;
}
else
{
if (verbose)
NSLog(@"Defaults path '%@' did not exist - created it", path);
isDir = YES;
}
}
if (isDir == NO)
{
if (verbose)
NSLog(@"ERROR - Defaults path '%@' is not a directory!", path);
return nil;
}
path = [path stringByAppendingPathComponent: defaultsFile];
path = [path stringByAppendingPathExtension: @"lck"];
return path;
}
static void
updateCache(NSUserDefaults *self)
{
if (self == sharedDefaults)
{
NSArray *debug;
/**
* If there is an array NSUserDefault called GNU-Debug,
* we add its contents to the set of active debug levels.
*/
debug = [self arrayForKey: @"GNU-Debug"];
if (debug != nil)
{
unsigned c = [debug count];
NSMutableSet *s;
s = [[NSProcessInfo processInfo] debugSet];
while (c-- > 0)
{
NSString *level = [debug objectAtIndex: c];
[s addObject: level];
}
}
/* NB the following flags are first set up, in the +initialize method.
*/
flags[GSMacOSXCompatible]
= [self boolForKey: @"GSMacOSXCompatible"];
flags[GSOldStyleGeometry]
= [self boolForKey: @"GSOldStyleGeometry"];
flags[GSLogSyslog]
= [self boolForKey: @"GSLogSyslog"];
flags[GSLogThread]
= [self boolForKey: @"GSLogThread"];
flags[GSLogOffset]
= [self boolForKey: @"GSLogOffset"];
flags[NSWriteOldStylePropertyLists]
= [self boolForKey: @"NSWriteOldStylePropertyLists"];
flags[GSExceptionStackTrace]
= [self boolForKey: @"GSExceptionStackTrace"];
}
}
static void
setPermissions(NSString *file)
{
NSFileManager *mgr = [NSFileManager defaultManager];
NSDictionary *attr;
uint32_t desired;
uint32_t attributes;
attr = [mgr fileAttributesAtPath: file
traverseLink: YES];
attributes = [attr filePosixPermissions];
#if !(defined(S_IRUSR) && defined(S_IWUSR))
desired = 0600;
#else
desired = (S_IRUSR|S_IWUSR);
#endif
if (attributes != desired)
{
NSMutableDictionary *enforced_attributes;
NSNumber *permissions;
enforced_attributes
= [NSMutableDictionary dictionaryWithDictionary:
[mgr fileAttributesAtPath: file
traverseLink: YES]];
permissions = [NSNumberClass numberWithUnsignedLong: desired];
[enforced_attributes setObject: permissions
forKey: NSFilePosixPermissions];
[mgr changeFileAttributes: enforced_attributes
atPath: file];
}
}
static BOOL
writeDictionary(NSDictionary *dict, NSString *file)
{
if ([file length] == 0)
{
NSLog(@"Defaults database filename is empty when writing");
}
else if (nil == dict)
{
NSFileManager *mgr = [NSFileManager defaultManager];
return [mgr removeFileAtPath: file handler: nil];
}
else
{
NSData *data;
NSString *err;
err = nil;
data = [NSPropertyListSerialization dataFromPropertyList: dict
format: NSPropertyListXMLFormat_v1_0
errorDescription: &err];
if (data == nil)
{
NSLog(@"Failed to serialize defaults database for writing: %@", err);
}
else if ([data writeToFile: file atomically: YES] == NO)
{
NSLog(@"Failed to write defaults database to file: %@", file);
}
else
{
setPermissions(file);
return YES;
}
}
return NO;
}
/**
* Returns the list of languages retrieved from the operating system, in
* decreasing order of preference. Returns an empty array if the information
* could not be retrieved.
*/
static NSArray *
systemLanguages()
{
NSMutableArray *names = [NSMutableArray arrayWithCapacity: 10];
#if defined(_WIN32)
NSEnumerator *enumerator;
NSArray *languages;
NSString *locale;
BOOL ret;
unsigned long numberOfLanguages = 0;
unsigned long length = 7;
unsigned long factor = sizeof(wchar_t);
wchar_t *buffer = malloc(length * factor);
if (!buffer)
{
return names;
}
/* Returns a wchar_t list of languages in the form ll-CC, where ll is the
* two-letter language code, and CC is the two-letter country code.
*/
ret = GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &numberOfLanguages,
buffer, &length);
if (!ret)
{
length = 0;
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER
&& GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &numberOfLanguages,
NULL, &length))
{
wchar_t *oldBuffer = buffer;
buffer = realloc(buffer, length * factor);
if (!buffer)
{
free(oldBuffer);
return names;
}
ret = GetUserPreferredUILanguages(MUI_LANGUAGE_NAME,
&numberOfLanguages, buffer, &length);
if (!ret)
{
free(buffer);
return names;
}
}
}
languages = [NSString arrayFromWCharList: buffer length: length];
enumerator = [languages objectEnumerator];
free(buffer);
while (nil != (locale = [enumerator nextObject]))
{
/* Replace "-" Separator with "_" */
locale = [locale stringByReplacingOccurrencesOfString: @"-"
withString: @"_"];
[names addObjectsFromArray: GSLanguagesFromLocale(locale)];
}
#elif defined(__ANDROID__)
/* When running on Android, the process must be correctly initialized
* with GSInitializeProcessAndroid (See NSProcessInfo).
*
* If the minimum API level is 24 or higher, the user-prefered locales
* are retrieved from the Android system and passed as GSAndroidLocaleList
* process argument
*/
NSArray *args = [[NSProcessInfo processInfo] arguments];
NSEnumerator *enumerator = [args objectEnumerator];
NSString *key = nil;
NSString *localeList = nil;
[enumerator nextObject]; // Skip process name.
while (nil != (key = [enumerator nextObject]))
{
if ([key isEqualToString: @"-GSAndroidLocaleList"])
{
localeList = [enumerator nextObject];
break;
}
}
// The locale list is a comma-separated list of locales of form ll-CC
if (localeList != nil)
{
NSString *locale;
NSArray *locales = [localeList componentsSeparatedByString: @","];
enumerator = [locales objectEnumerator];
while (nil != (locale = [enumerator nextObject]))
{
[names addObjectsFromArray: GSLanguagesFromLocale(locale)];
}
}
#else
/* Add the languages listed in the LANGUAGE environment variable
* (a non-POSIX GNU extension)
*/
{
NSString *env;
env = [[[NSProcessInfo processInfo] environment] objectForKey: @"LANGUAGE"];
if (env != nil && [env length] > 0)
{
NSArray *array = [env componentsSeparatedByString: @":"];
NSEnumerator *enumerator = [array objectEnumerator];
NSString *locale;
while (nil != (locale = [enumerator nextObject]))
{
[names addObjectsFromArray: GSLanguagesFromLocale(locale)];
}
}
}
// If LANGUAGES did not yield any languages, try LC_MESSAGES
if ([names count] == 0)
{
NSString *locale = GSDefaultLanguageLocale();
if (locale != nil)
{
[names addObjectsFromArray: GSLanguagesFromLocale(locale)];
}
}
#endif
return names;
}
static NSMutableArray *
newLanguages(NSArray *oldNames)
{
NSMutableArray *newNames;
NSEnumerator *enumerator;
NSString *language;
newNames = [NSMutableArray arrayWithCapacity: 5];
if (oldNames == nil || [oldNames count] == 0)
{
oldNames = systemLanguages();
}
// If the user default was not set, and the system languages couldn't
// be retrieved, try the GNUstep environment variable LANGUAGES
if (oldNames == nil || [oldNames count] == 0)
{
NSString *env;
env = [[[NSProcessInfo processInfo] environment]
objectForKey: @"LANGUAGES"];
if (env != nil)
{
oldNames = [env componentsSeparatedByString: @";"];
}
}
enumerator = [oldNames objectEnumerator];
while (nil != (language = [enumerator nextObject]))
{
language = [language stringByTrimmingSpaces];
if ([language length] > 0 && NO == [newNames containsObject: language])
{
[newNames addObject: language];
}
}
/* Check if "English" is included. We do this to make sure all the
* required language constants are set somewhere if they aren't set
* in the default language.
*/
if (NO == [newNames containsObject: @"English"])
{
[newNames addObject: @"English"];
}
return newNames;
}
/*************************************************************************
*** Private method definitions
*************************************************************************/
@interface NSUserDefaults (Private)
+ (void) _createArgumentDictionary: (NSArray*)args;
- (void) _changePersistentDomain: (NSString*)domainName;
- (NSString*) _directory;
- (BOOL) _lockDefaultsFile: (BOOL*)wasLocked;
- (BOOL) _readDefaults;
- (BOOL) _readOnly;
- (void) _unlockDefaultsFile;
@end
/**
* <p>
* NSUserDefaults provides an interface to the defaults system,
* which allows an application access to global and/or application
* specific defaults set by the user. A particular instance of
* NSUserDefaults, standardUserDefaults, is provided as a
* convenience. Most of the information described below
* pertains to the standardUserDefaults. It is unlikely
* that you would want to instantiate your own userDefaults
* object, since it would not be set up in the same way as the
* standardUserDefaults.
* </p>
* <p>
* Defaults are managed based on <em>domains</em>. Certain
* domains, such as <code>NSGlobalDomain</code>, are
* persistent. These domains have defaults that are stored
* externally. Other domains are volatile. The defaults in
* these domains remain in effect only during the existence of
* the application and may in fact be different for
* applications running at the same time. When asking for a
* default value from standardUserDefaults, NSUserDefaults
* looks through the various domains in a particular order.
* </p>
* <deflist>
* <term><code>GSPrimaryDomain</code> ... volatile</term>
* <desc>
* Contains values set at runtime and intended to supercede any values
* set in other domains. This should be used with great care since it
* overrides values which may have been set explicitly by the user.
* </desc>
* <term><code>NSArgumentDomain</code> ... volatile</term>
* <desc>
* Contains defaults read from the arguments provided
* to the application at startup.<br />
* Pairs of arguments are used for this, with the first argument in
* each pair being the name of a default (with a hyphen prepended)
* and the second argument of the pair being the value of the default.<br />
* NB. In GNUstep special arguments of the form <code>--GNU-Debug=...</code>
* are used to enable debugging. Despite beginning with a hyphen, these
* are not treated as default keys.
* </desc>
* <term>Application (name of the current process) ... persistent</term>
* <desc>
* Contains application specific defaults, such as window positions.
* This is the domain used by the -setObject:forKey: method and is
* the domain normally used when setting preferences for an application.
* </desc>
* <term><code>NSGlobalDomain</code> ... persistent</term>
* <desc>
* Global defaults applicable to all applications.
* </desc>
* <term>Language (name based on users's language) ... volatile</term>
* <desc>
* Constants that help with localization to the users's
* language.
* </desc>
* <term><code>GSConfigDomain</code> ... volatile</term>
* <desc>
* Information retrieved from the GNUstep configuration system.
* Usually the system wide and user specific GNUstep.conf files,
* or from information compiled in when the base library was
* built.<br />
* In addition to this standard configuration information, this
* domain contains all values from property lists store in the
* GlobalDefaults subdirectory or from the GlobalDefaults.plist file
* stored in the same directory as the system wide GNUstep.conf
* file.
* </desc>
* <term><code>NSRegistrationDomain</code> ... volatile</term>
* <desc>
* Temporary defaults set up by the application.
* </desc>
* </deflist>
* <p>
* The <em>NSLanguages</em> default value is used to set up the
* constants for localization. GNUstep will also look for the
* <code>LANGUAGES</code> environment variable if it is not set
* in the defaults system. If it exists, it consists of an
* array of languages that the user prefers. At least one of
* the languages should have a corresponding localization file
* (typically located in the <file>Languages</file> directory
* of the GNUstep resources).
* </p>
* <p>
* As a special extension, on systems that support locales
* (e.g. GNU/Linux and Solaris), GNUstep will use information
* from the user specified locale, if the <em>NSLanguages</em>
* default value is not found. Typically the locale is
* specified in the environment with the <code>LANG</code>
* environment variable.
* </p>
* <p>
* The first change to a persistent domain after a -synchronize
* will cause an NSUserDefaultsDidChangeNotification to be posted
* (as will any change caused by reading new values from disk),
* so your application can keep track of changes made to the
* defaults by other software.
* </p>
* <p>
* NB. The GNUstep implementation differs from the Apple one in
* that it is thread-safe while Apple's (as of MacOS-X 10.1) is not.
* </p>
*/
@implementation NSUserDefaults: NSObject
+ (void) atExit
{
DESTROY(sharedDefaults);
DESTROY(bundleIdentifier);
DESTROY(processName);
DESTROY(argumentsDictionary);
DESTROY(classLock);
DESTROY(syncLock);
}
/* Opt-out off automatic willChange/didChange notifications
* as the KVO behaviour for NSUserDefaults is slightly different.
*
* We do not notify observers of changes that do not actually
* change the value of a key (the value is equal to the old value).
*
* https://developer.apple.com/documentation/foundation/nsuserdefaults#2926902
* "You can use key-value observing to be notified of any updates to
* a particular default value. You can also register as an observer for
* NSUserDefaultsDidChangeNotification on the defaultCenter notification center
* in order to be notified of all updates to a local defaults database."
*/
+ (BOOL) automaticallyNotifiesObserversForKey: (NSString*)key
{
return NO;
}
+ (void) initialize
{
static BOOL beenHere = NO;
if (NO == beenHere && self == [NSUserDefaults class])
{
ENTER_POOL
NSEnumerator *enumerator;
NSArray *args;
NSString *key;
beenHere = YES;
initializing = YES;
nextObjectSel = @selector(nextObject);
objectForKeySel = @selector(objectForKey:);
addSel = @selector(addEntriesFromDictionary:);
/*
* Cache class info for more rapid testing of the types of defaults.
*/
NSArrayClass = [NSArray class];
NSDataClass = [NSData class];
NSDateClass = [NSDate class];
NSDictionaryClass = [NSDictionary class];
NSNumberClass = [NSNumber class];
NSMutableDictionaryClass = [NSMutableDictionary class];
NSStringClass = [NSString class];
argumentsDictionary = [NSDictionary new];
[self registerAtExit];
processName = [[[NSProcessInfo processInfo] processName] copy];
key = [GSPrivateInfoDictionary(nil) objectForKey: @"CFBundleIdentifier"];
if (NO == [key isKindOfClass: [NSString class]])
{
/* No bundle identifier found: use the process name instead.
*/
key = processName;
if (NO == [key isKindOfClass: [NSString class]])
{
fprintf(stderr, "+[NSUserDefaults initialize] unable to"
" determine bundle identifier or process name.\n");
key = nil;
}
}
bundleIdentifier = [key copy];
/* Initialise the defaults flags to take values from the
* process arguments. These are otherwise set in updateCache()
* We do this early on so that the boolean argument settings can
* be used while parsing property list values of other args in
* the +_createArgumentDictionary: method.
*/
args = [[NSProcessInfo processInfo] arguments];
enumerator = [args objectEnumerator];
[enumerator nextObject]; // Skip process name.
while (nil != (key = [enumerator nextObject]))
{
if ([key hasPrefix: @"-"] == YES && [key isEqual: @"-"] == NO)
{
id val;
/* Anything beginning with a '-' is a defaults key and we
* must strip the '-' from it.
*/
key = [key substringFromIndex: 1];
while (nil != (val = [enumerator nextObject]))
{
if ([val hasPrefix: @"-"] == YES && [val isEqual: @"-"] == NO)
{
key = val;
}
else if ([key isEqualToString: @"GSMacOSXCompatible"])
{
flags[GSMacOSXCompatible] = [val boolValue];
}
else if ([key isEqualToString: @"GSOldStyleGeometry"])
{
flags[GSOldStyleGeometry] = [val boolValue];
}
else if ([key isEqualToString: @"GSLogSyslog"])
{
flags[GSLogSyslog] = [val boolValue];
}
else if ([key isEqualToString: @"GSLogThread"])
{
flags[GSLogThread] = [val boolValue];
}
else if ([key isEqualToString: @"GSLogOffset"])
{
flags[GSLogOffset] = [val boolValue];
}
else if ([key isEqual: @"NSWriteOldStylePropertyLists"])
{
flags[NSWriteOldStylePropertyLists] = [val boolValue];
}
else if ([key isEqual: @"GSExceptionStackTrace"])
{
flags[GSExceptionStackTrace] = [val boolValue];
}
}
}
}
/* The classLock must be created after setting up the flags[] array,
* so once it exists we know we can used them safely.
*/
classLock = [NSRecursiveLock new];
/* This lock protects locking the defaults file.
*/
syncLock = [NSLock new];
[self _createArgumentDictionary: args];
LEAVE_POOL
initializing = NO;
}
}
+ (void) resetStandardUserDefaults
{
NSDictionary *regDefs = nil;
[classLock lock];
NS_DURING
{
if (nil != sharedDefaults)
{
/* Extract the registration domain from the old defaults.
*/
regDefs = AUTORELEASE(RETAIN([sharedDefaults->_tempDomains
objectForKey: NSRegistrationDomain]));
[sharedDefaults->_tempDomains
removeObjectForKey: NSRegistrationDomain];
/* To ensure that we don't try to synchronise the old defaults to disk
* after creating the new ones, remove as housekeeping notification
* observer.
*/
[[NSNotificationCenter defaultCenter] removeObserver: sharedDefaults];
/* Ensure changes are written, and no changes left so we can't end up
* writing old changes to the new defaults.
*/
[sharedDefaults synchronize];
DESTROY(sharedDefaults->_changedDomains);
DESTROY(sharedDefaults);
}
hasSharedDefaults = NO;
[classLock unlock];
}
NS_HANDLER
{
[classLock unlock];
[localException raise];
}
NS_ENDHANDLER
if (nil != regDefs)
{
[self standardUserDefaults];
if (sharedDefaults != nil)
{
[sharedDefaults->_tempDomains setObject: regDefs
forKey: NSRegistrationDomain];
}
}
}
/* Create a locale dictionary when we have absolutely no information
about the locale. This method should go away, since it will never
be called in a properly installed system. */
+ (NSDictionary *) _unlocalizedDefaults
{
NSDictionary *registrationDefaults;
NSArray *ampm;
NSArray *long_day;
NSArray *long_month;
NSArray *short_day;
NSArray *short_month;
NSArray *earlyt;
NSArray *latert;
NSArray *hour_names;
NSArray *ymw_names;
ampm = [NSArray arrayWithObjects: @"AM", @"PM", nil];
short_month = [NSArray arrayWithObjects:
@"Jan",
@"Feb",
@"Mar",
@"Apr",
@"May",
@"Jun",
@"Jul",
@"Aug",
@"Sep",
@"Oct",
@"Nov",
@"Dec",
nil];
long_month = [NSArray arrayWithObjects:
@"January",
@"February",
@"March",
@"April",
@"May",
@"June",
@"July",
@"August",
@"September",
@"October",
@"November",
@"December",
nil];
short_day = [NSArray arrayWithObjects:
@"Sun",
@"Mon",
@"Tue",
@"Wed",
@"Thu",
@"Fri",
@"Sat",
nil];
long_day = [NSArray arrayWithObjects:
@"Sunday",
@"Monday",
@"Tuesday",
@"Wednesday",
@"Thursday",
@"Friday",
@"Saturday",
nil];
earlyt = [NSArray arrayWithObjects:
@"prior",
@"last",
@"past",
@"ago",
nil];
latert = [NSArray arrayWithObjects: @"next", nil];
ymw_names = [NSArray arrayWithObjects: @"year", @"month", @"week", nil];
hour_names = [NSArray arrayWithObjects:
[NSArray arrayWithObjects: @"0", @"midnight", nil],
[NSArray arrayWithObjects: @"12", @"noon", @"lunch", nil],
[NSArray arrayWithObjects: @"10", @"morning", nil],
[NSArray arrayWithObjects: @"14", @"afternoon", nil],
[NSArray arrayWithObjects: @"19", @"dinner", nil],
nil];
registrationDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
ampm, NSAMPMDesignation,
long_month, NSMonthNameArray,
long_day, NSWeekDayNameArray,
short_month, NSShortMonthNameArray,
short_day, NSShortWeekDayNameArray,
@"DMYH", NSDateTimeOrdering,
[NSArray arrayWithObject: @"tomorrow"], NSNextDayDesignations,
[NSArray arrayWithObject: @"nextday"], NSNextNextDayDesignations,
[NSArray arrayWithObject: @"yesterday"], NSPriorDayDesignations,
[NSArray arrayWithObject: @"today"], NSThisDayDesignations,
earlyt, NSEarlierTimeDesignations,
latert, NSLaterTimeDesignations,
hour_names, NSHourNameDesignations,
ymw_names, NSYearMonthWeekDesignations,
nil];
return registrationDefaults;
}
+ (NSUserDefaults*) standardUserDefaults
{
NSUserDefaults *defs;
BOOL added_lang;
BOOL added_locale;
BOOL setup;
id lang;
NSArray *nL;
NSArray *uL;
NSEnumerator *enumerator;
/* If the shared instance is already available ... return it.
*/
[classLock lock];
defs = RETAIN(sharedDefaults);
setup = hasSharedDefaults;
[classLock unlock];
if (YES == setup)
{
return AUTORELEASE(defs);
}
NS_DURING
{
/* Create new NSUserDefaults (NOTE: Not added to the autorelease pool!)
* NB. The following code avoids deadlocks by creating a minimally
* initialised instance, locking that instance, locking the class-wide
* lock, installing the instance as the new shared defaults, unlocking
* the class wide lock, completing the setup of the instance, and then
* unlocking the instance. This means we already have the shared
* instance locked ourselves at the point when it first becomes
* visible to other threads.
*/
#if defined(_WIN32)
{
NSString *path = GSDefaultsRootForUser(NSUserName());
NSRange r = [path rangeOfString: @":REGISTRY:"];
if (r.length > 0)
{
defs = [[NSUserDefaultsWin32 alloc] init];
}
else
{
defs = [[self alloc] init];
}
}
#else
defs = [[self alloc] init];
#endif
/* Install the new defaults as the shared copy, but lock it so that
* we can complete setup without other threads interfering.
*/
if (nil != defs)
{
[defs->_lock lock];
[classLock lock];
if (NO == hasSharedDefaults)
{
hasSharedDefaults = YES;
ASSIGN(sharedDefaults, defs);
}
else
{
/* Already set up by another thread.
*/
[defs->_lock unlock];
DESTROY(defs);
}
[classLock unlock];
}
if (nil == defs)
{
const unsigned retryCount = 100;
const NSTimeInterval retryInterval = 0.1;
unsigned i;
for (i = 0; i < retryCount; i++)
{
[NSThread sleepForTimeInterval: retryInterval];
[classLock lock];
defs = RETAIN(sharedDefaults);
setup = hasSharedDefaults;
[classLock unlock];
if (YES == setup)
{
NS_VALRETURN(AUTORELEASE(defs));
}
RELEASE(defs);
}
NSLog(@"WARNING - unable to create shared user defaults!\n");
NS_VALRETURN(nil);
}
/*
* Set up search list (excluding language list, which we don't know yet)
*/
[defs->_searchList addObject: GSPrimaryDomain];
[defs->_searchList addObject: NSArgumentDomain];
if (bundleIdentifier)
{
[defs->_searchList addObject: bundleIdentifier];
[defs persistentDomainForName: bundleIdentifier];
}
[defs->_searchList addObject: NSGlobalDomain];
[defs persistentDomainForName: NSGlobalDomain];
[defs->_searchList addObject: GSConfigDomain];
[defs->_searchList addObject: NSRegistrationDomain];
/* Load persistent data into the new instance.
*/
[defs synchronize];
/*
* Look up user languages list and insert language specific domains
* into search list before NSRegistrationDomain
*/
uL = [defs stringArrayForKey: @"NSLanguages"];
nL = newLanguages(uL);
if (NO == [uL isEqual: nL])
{
[self setUserLanguages: nL];
}
enumerator = [nL objectEnumerator];
while ((lang = [enumerator nextObject]))
{
unsigned index = [defs->_searchList count] - 1;
[defs->_searchList insertObject: lang atIndex: index];
}
/* Set up language constants */
/* We lookup gnustep-base resources manually here to prevent
* bootstrap problems. NSBundle's lookup routines depend on having
* NSUserDefaults already bootstrapped, but we're still
* bootstrapping here! So we can't really use NSBundle without
* incurring massive bootstrap complications (btw, most of the times
* we're here as a consequence of [NSBundle +initialize] creating
* the gnustep-base bundle! So trying to use the gnustep-base
* bundle here wouldn't really work.).
*/
/*
* We are looking for:
*
* GNUSTEP_LIBRARY/Libraries/gnustep-base/Versions/<interfaceVersion>/Resources/Languages/<language>
*
* We iterate over <language>, and for each <language> we iterate over GNUSTEP_LIBRARY.
*/
{
/* These variables are reused for all languages so we set them up
* once here and then reuse them.
*/
NSFileManager *fm = [NSFileManager defaultManager];
NSString *tail = [[[[[@"Libraries"
stringByAppendingPathComponent: @"gnustep-base"]
stringByAppendingPathComponent: @"Versions"]
stringByAppendingPathComponent:
OBJC_STRINGIFY(GNUSTEP_BASE_MAJOR_VERSION.GNUSTEP_BASE_MINOR_VERSION)]
stringByAppendingPathComponent: @"Resources"]
stringByAppendingPathComponent: @"Languages"];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSLibraryDirectory, NSAllDomainsMask, YES);
added_lang = NO;
added_locale = NO;
enumerator = [nL objectEnumerator];
while ((lang = [enumerator nextObject]))
{
NSDictionary *dict = nil;
NSString *path = nil;
NSString *alt;
NSEnumerator *pathEnumerator;
/* The language name could be an ISO language identifier rather
* than an OpenStep name (OSX has moved to using them), so we
* try converting as an alternative key for lookup.
*/
alt = GSLanguageFromLocale(lang);
pathEnumerator = [paths objectEnumerator];
while ((path = [pathEnumerator nextObject]) != nil)
{
path = [[path stringByAppendingPathComponent: tail]
stringByAppendingPathComponent: lang];
if ([fm fileExistsAtPath: path])
{
break; /* Path found! */
}
if (nil != alt)
{
path = [[path stringByAppendingPathComponent: tail]
stringByAppendingPathComponent: alt];
if ([fm fileExistsAtPath: path])
{
break; /* Path found! */
}
}
}
if (path != nil)
{
dict = [NSDictionary dictionaryWithContentsOfFile: path];
}
if (dict != nil)
{
[defs setVolatileDomain: dict forName: lang];
added_lang = YES;
}
else if (added_locale == NO)
{
/* The resources for the language that we were looking for
* were not found. If this was the currently set locale
* in the C library, try to get the same information from
* the C library. This would usually happen for the
* language that was added to the list of languages
* precisely because it is the currently set locale in the
* C library.
*/
NSString *locale = GSDefaultLanguageLocale();
if (locale != nil)
{
NSString *i18n = GSLanguageFromLocale(locale);
/* See if we can get the dictionary from i18n
* functions. I don't think that the i18n routines
* can handle more than one locale, so we don't try to
* look 'lang' up but just get what we get and use it
* if it matches 'lang' ... but tell me if I'm wrong
* ...
*/
if ([lang isEqual: i18n] || [alt isEqualToString: i18n])
{
/* We set added_locale to YES to avoid so that we
* won't do this C library locale lookup again
* later on.
*/
added_locale = YES;
dict = GSDomainFromDefaultLocale ();
if (dict != nil)
{
[defs setVolatileDomain: dict forName: lang];
/* We do not set added_lang to YES here
* because we want the basic hardcoded defaults
* to be used in that case.
*/
}
}
}
}
}
}
if (added_lang == NO)
{
/* No language information found ... probably because the base
* library is being used 'standalone' without resources.
* We need to use hard-coded defaults.
*/
/* FIXME - should we set this as volatile domain for English ? */
[defs registerDefaults: [self _unlocalizedDefaults]];
}
updateCache(sharedDefaults);
[defs->_lock unlock];
}
NS_HANDLER
{
if (nil != defs)
{
[defs->_lock unlock];
RELEASE(defs);
}
[localException raise];
}
NS_ENDHANDLER
return AUTORELEASE(defs);
}
+ (NSArray*) userLanguages
{
return [[self standardUserDefaults] stringArrayForKey: @"NSLanguages"];
}
+ (void) setUserLanguages: (NSArray*)languages
{
NSUserDefaults *defs;
NSMutableDictionary *dict;
defs = [self standardUserDefaults];
dict = [[defs volatileDomainForName: GSPrimaryDomain] mutableCopy];
if (languages == nil) // Remove the entry
{
[dict removeObjectForKey: @"NSLanguages"];
}
else
{
if (nil == dict)
{
dict = [NSMutableDictionary new];
}
languages = newLanguages(languages);
[dict setObject: languages forKey: @"NSLanguages"];
}
[defs removeVolatileDomainForName: GSPrimaryDomain];
[defs setVolatileDomain: dict forName: GSPrimaryDomain];
RELEASE(dict);
}
- (id) init
{
return [self initWithUser: NSUserName()];
}
/* Deprecated method ... which shoudl be merged into - initWithUser:
*/
- (id) initWithContentsOfFile: (NSString*)path
{
NSFileManager *mgr = [NSFileManager defaultManager];
NSRange r;
BOOL flag;
self = [super init];
if (path == nil || [path isEqual: @""] == YES)
{
path = [GSDefaultsRootForUser(NSUserName())
stringByAppendingPathComponent: defaultsFile];
}
r = [path rangeOfString: @":INTERNAL:"];
#if defined(_WIN32)
if (r.length == 0)
{
r = [path rangeOfString: @":REGISTRY:"];
}
#endif
if (r.length == 0)
{
path = [path stringByStandardizingPath];
_defaultsDatabase = [[path stringByDeletingLastPathComponent] copy];
if (YES == [mgr fileExistsAtPath: _defaultsDatabase isDirectory: &flag]
&& YES == flag)
{
path = lockPath(_defaultsDatabase, NO);
if (nil != path)
{
_fileLock = [[NSDistributedLock alloc] initWithPath: path];
}
}
}
_lock = [NSRecursiveLock new];
if (YES == [self _readOnly])
{
// Load read-only defaults.
ASSIGN(_lastSync, [NSDateClass date]);
[self _readDefaults];
}
// Create an empty search list
_searchList = [[NSMutableArray alloc] initWithCapacity: 10];
_persDomains = [[NSMutableDictionaryClass alloc] initWithCapacity: 10];
// Create volatile defaults and add the Argument and the Registration domains
_tempDomains = [[NSMutableDictionaryClass alloc] initWithCapacity: 10];
[_tempDomains setObject: argumentsDictionary forKey: NSArgumentDomain];
[_tempDomains
setObject: [NSMutableDictionaryClass dictionaryWithCapacity: 10]
forKey: NSRegistrationDomain];
[_tempDomains setObject: GNUstepConfig(nil) forKey: GSConfigDomain];
updateCache(self);
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(synchronize)
name: @"GSHousekeeping"
object: nil];
return self;
}
- (id) initWithUser: (NSString*)userName
{
NSString *path;
path = [GSDefaultsRootForUser(userName)
stringByAppendingPathComponent: defaultsFile];
return [self initWithContentsOfFile: path];
}
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver: self];
RELEASE(_lastSync);
RELEASE(_searchList);
RELEASE(_persDomains);
RELEASE(_tempDomains);
RELEASE(_changedDomains);
RELEASE(_dictionaryRep);
RELEASE(_defaultsDatabase);
RELEASE(_fileLock);
RELEASE(_lock);
[super dealloc];
}
- (NSString*) description
{
NSMutableString *desc = nil;
[_lock lock];
NS_DURING
{
desc = [NSMutableString stringWithFormat: @"%@", [super description]];
[desc appendFormat: @" SearchList: %@", _searchList];
[desc appendFormat: @" Persistent: %@", _persDomains];
[desc appendFormat: @" Temporary: %@", _tempDomains];
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
return desc;
}
- (void) addSuiteNamed: (NSString*)aName
{
NSUInteger index;
if (aName == nil)
{
[NSException raise: NSInvalidArgumentException
format: @"attempt to add suite with nil name"];
}
[_lock lock];
NS_DURING
{
DESTROY(_dictionaryRep);
[_searchList removeObject: aName];
index = [_searchList indexOfObject: bundleIdentifier];
index = (index == NSNotFound) ? 0 : (index + 1);
aName = [aName copy];
[_searchList insertObject: aName atIndex: index];
// Ensure that any persistent domain with the specified name is loaded.
[self persistentDomainForName: aName];
updateCache(self);
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
RELEASE(aName);
}
- (NSArray*) arrayForKey: (NSString*)defaultName
{
id obj = [self objectForKey: defaultName];
if (obj != nil && [obj isKindOfClass: NSArrayClass])
return obj;
return nil;
}
- (BOOL) boolForKey: (NSString*)defaultName
{
id obj = [self objectForKey: defaultName];
if (obj != nil && ([obj isKindOfClass: NSStringClass]
|| [obj isKindOfClass: NSNumberClass]))
{
return [obj boolValue];
}
return NO;
}
- (NSData*) dataForKey: (NSString*)defaultName
{
id obj = [self objectForKey: defaultName];
if (obj != nil && [obj isKindOfClass: NSDataClass])
return obj;
return nil;
}
- (NSDictionary*) dictionaryForKey: (NSString*)defaultName
{
id obj = [self objectForKey: defaultName];
if (obj != nil && [obj isKindOfClass: NSDictionaryClass])
{
return obj;
}
return nil;
}
- (double) doubleForKey: (NSString*)defaultName
{
id obj = [self objectForKey: defaultName];
if (obj != nil && ([obj isKindOfClass: NSStringClass]
|| [obj isKindOfClass: NSNumberClass]))
{
return [obj doubleValue];
}
return 0.0;
}
- (float) floatForKey: (NSString*)defaultName
{
id obj = [self objectForKey: defaultName];
if (obj != nil && ([obj isKindOfClass: NSStringClass]
|| [obj isKindOfClass: NSNumberClass]))
{
return [obj floatValue];
}
return 0.0;
}
- (NSInteger) integerForKey: (NSString*)defaultName
{
id obj = [self objectForKey: defaultName];
if (obj != nil && ([obj isKindOfClass: NSStringClass]
|| [obj isKindOfClass: NSNumberClass]))
{
return [obj integerValue];
}
return 0;
}
- (id) objectForKey: (NSString*)defaultName
{
id object = nil;
[_lock lock];
NS_DURING
{
NSUInteger count = [_searchList count];
IMP pImp;
IMP tImp;
NSUInteger index;
GS_BEGINITEMBUF(items, count, NSObject*)
pImp = [_persDomains methodForSelector: objectForKeySel];
tImp = [_tempDomains methodForSelector: objectForKeySel];
[_searchList getObjects: items];
for (index = 0; index < count; index++)
{
NSObject *dN = items[index];
GSPersistentDomain *pd;
NSDictionary *td;
pd = (*pImp)(_persDomains, objectForKeySel, dN);
if (pd != nil && (object = [pd objectForKey: defaultName]))
break;
td = (*tImp)(_tempDomains, objectForKeySel, dN);
if (td != nil && (object = [td objectForKey: defaultName]))
break;
}
RETAIN(object);
GS_ENDITEMBUF();
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
return AUTORELEASE(object);
}
- (void) removeObjectForKey: (NSString*)defaultName
{
[_lock lock];
NS_DURING
{
GSPersistentDomain *pd;
pd = [_persDomains objectForKey: bundleIdentifier];
if (nil != pd)
{
id old = [self objectForKey: defaultName];
if ([pd setObject: nil forKey: defaultName])
{
id new;
[self _changePersistentDomain: bundleIdentifier];
new = [self objectForKey: defaultName];
/* Emit only a KVO notification when the value has actually
* changed, meaning -objectForKey: would return a different
* value than before.
*/
if ([new hash] != [old hash])
{
[self _notifyObserversOfChangeForKey: defaultName
oldValue: old
newValue: new];
}
}
else
{
/* We always notify observers of a change, even if the value
* itself is unchanged.
*/
[[NSNotificationCenter defaultCenter]
postNotificationName: NSUserDefaultsDidChangeNotification
object: self];
}
}
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
}
- (void) setBool: (BOOL)value forKey: (NSString*)defaultName
{
NSNumber *n = [NSNumberClass numberWithBool: value];
[self setObject: n forKey: defaultName];
}
- (void) setDouble: (double)value forKey: (NSString*)defaultName
{
NSNumber *n = [NSNumberClass numberWithDouble: value];
[self setObject: n forKey: defaultName];
}
- (void) setFloat: (float)value forKey: (NSString*)defaultName
{
NSNumber *n = [NSNumberClass numberWithFloat: value];
[self setObject: n forKey: defaultName];
}
- (void) setInteger: (NSInteger)value forKey: (NSString*)defaultName
{
NSNumber *n = [NSNumberClass numberWithInteger: value];
[self setObject: n forKey: defaultName];
}
static BOOL isPlistObject(id o)
{
if ([o isKindOfClass: NSStringClass] == YES)
{
return YES;
}
if ([o isKindOfClass: NSDataClass] == YES)
{
return YES;
}
if ([o isKindOfClass: NSDateClass] == YES)
{
return YES;
}
if ([o isKindOfClass: NSNumberClass] == YES)
{
return YES;
}
if ([o isKindOfClass: NSArrayClass] == YES)
{
NSEnumerator *e = [o objectEnumerator];
id tmp;
while ((tmp = [e nextObject]) != nil)
{
if (isPlistObject(tmp) == NO)
{
return NO;
}
}
return YES;
}
if ([o isKindOfClass: NSDictionaryClass] == YES)
{
NSEnumerator *e = [o keyEnumerator];
id tmp;
while ((tmp = [e nextObject]) != nil)
{
if (isPlistObject(tmp) == NO)
{
return NO;
}
tmp = [(NSDictionary*)o objectForKey: tmp];
if (isPlistObject(tmp) == NO)
{
return NO;
}
}
return YES;
}
return NO;
}
- (void) setObject: (id)value forKey: (NSString*)defaultName
{
if (nil == value)
{
[self removeObjectForKey: defaultName];
return;
}
if ([defaultName isKindOfClass: [NSString class]] == NO
|| [defaultName length] == 0)
{
[NSException raise: NSInvalidArgumentException
format: @"attempt to set object with bad key (%@)", defaultName];
}
if (isPlistObject(value) == NO)
{
[NSException raise: NSInvalidArgumentException
format: @"attempt to set non property list object (%@) for key (%@)",
value, defaultName];
}
value = [value copy];
[_lock lock];
NS_DURING
{
GSPersistentDomain *pd;
id old;
pd = [_persDomains objectForKey: bundleIdentifier];
if (nil == pd)
{
pd = [[GSPersistentDomain alloc] initWithName: bundleIdentifier
owner: self];
[_persDomains setObject: pd forKey: bundleIdentifier];
RELEASE(pd);
}
// Make sure to search all domains and not only the process domain
old = [self objectForKey: defaultName];
if ([pd setObject: value forKey: defaultName])
{
id new;
/* New value must be fetched from all domains, as there might be
* a registered default if value is nil, or the value is
* superseded by GSPrimary or NSArgumentDomain
*/
new = [self objectForKey: defaultName];
[self _changePersistentDomain: bundleIdentifier];
// Emit only a KVO notification when the value has actually changed
if ([new hash] != [old hash])
{
[self _notifyObserversOfChangeForKey: defaultName
oldValue: old
newValue: new];
}
}
else
{
/* We always notify observers of a change, even if the value
* itself is unchanged.
*/
[[NSNotificationCenter defaultCenter]
postNotificationName: NSUserDefaultsDidChangeNotification
object: self];
}
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
RELEASE(value);
}
- (void) setValue: (id)value forKey: (NSString*)defaultName
{
[self setObject: value forKey: (NSString*)defaultName];
}
- (NSArray*) stringArrayForKey: (NSString*)defaultName
{
id arr = [self arrayForKey: defaultName];
if (arr != nil)
{
NSEnumerator *enumerator = [arr objectEnumerator];
id obj;
while ((obj = [enumerator nextObject]))
{
if ([obj isKindOfClass: NSStringClass] == NO)
{
return nil;
}
}
return arr;
}
return nil;
}
- (NSString*) stringForKey: (NSString*)defaultName
{
id obj = [self objectForKey: defaultName];
if (obj != nil && [obj isKindOfClass: NSStringClass])
return obj;
return nil;
}
- (NSArray*) searchList
{
NSArray *copy = nil;
[_lock lock];
NS_DURING
{
copy = [_searchList copy];
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
return AUTORELEASE(copy);
}
- (void) setSearchList: (NSArray*)newList
{
[_lock lock];
NS_DURING
{
if (NO == [_searchList isEqual: newList])
{
NSEnumerator *e;
NSString *n;
DESTROY(_dictionaryRep);
RELEASE(_searchList);
_searchList = [newList mutableCopy];
/* Ensure that any domains we need are loaded.
*/
e = [_searchList objectEnumerator];
while (nil != (n = [e nextObject]))
{
[self persistentDomainForName: n];
}
updateCache(self);
}
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
}
- (NSDictionary*) persistentDomainForName: (NSString*)domainName
{
NSDictionary *copy = nil;
[_lock lock];
NS_DURING
{
GSPersistentDomain *pd;
pd = [_persDomains objectForKey: domainName];
if (nil != pd)
{
copy = [[pd contents] copy];
}
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
return AUTORELEASE(copy);
}
- (NSArray*) persistentDomainNames
{
NSArray *keys = nil;
[_lock lock];
NS_DURING
{
keys = [_persDomains allKeys];
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
return keys;
}
- (void) removePersistentDomainForName: (NSString*)domainName
{
[_lock lock];
NS_DURING
{
GSPersistentDomain *pd;
pd = [_persDomains objectForKey: domainName];
if (nil != pd)
{
[pd empty];
if (NO == [domainName isEqualToString: NSGlobalDomain])
{
/* Remove the domain entirely.
*/
[_persDomains removeObjectForKey: domainName];
}
[self _changePersistentDomain: domainName];
}
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
}
- (void) setPersistentDomain: (NSDictionary*)domain
forName: (NSString*)domainName
{
NSDictionary *dict;
[_lock lock];
NS_DURING
{
GSPersistentDomain *pd;
dict = [_tempDomains objectForKey: domainName];
if (dict != nil)
{
[NSException raise: NSInvalidArgumentException
format: @"a volatile domain called %@ exists", domainName];
}
pd = [_persDomains objectForKey: domainName];
if (nil == pd)
{
pd = [[GSPersistentDomain alloc] initWithName: domainName
owner: self];
[_persDomains setObject: pd forKey: domainName];
RELEASE(pd);
}
[pd setContents: domain];
[self _changePersistentDomain: domainName];
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
}
- (id) valueForKey: (NSString*)aKey
{
return [self objectForKey: aKey];
}
- (BOOL) wantToReadDefaultsSince: (NSDate*)lastSyncDate
{
if (nil == lastSyncDate)
{
return YES;
}
else
{
NSFileManager *mgr;
NSDictionary *attr;
mgr = [NSFileManager defaultManager];
attr = [mgr fileAttributesAtPath: _defaultsDatabase traverseLink: YES];
if (attr == nil)
{
return YES;
}
else
{
NSDate *mod;
/*
* If the database was modified since the last synchronisation
* we need to read it.
*/
mod = [attr objectForKey: NSFileModificationDate];
if (mod != nil && [lastSyncDate laterDate: mod] != lastSyncDate)
{
return YES;
}
}
}
return NO;
}
- (BOOL) synchronize
{
NSDate *saved;
BOOL isLocked = NO;
BOOL wasLocked = NO;
BOOL result = YES;
BOOL haveChange = NO;
[_lock lock];
saved = _lastSync;
_lastSync = [NSDate new]; // Record timestamp of this sync.
NS_DURING
{
/* If we haven't changed anything, we only need to synchronise if
* the on-disk database has been changed by someone else.
*/
if (_changedDomains != nil
|| YES == [self wantToReadDefaultsSince: saved])
{
/* If we want to write but are currently read-only, try to
* create the path to make things writable.
*/
if (_changedDomains != nil && YES == [self _readOnly])
{
NSString *path = lockPath(_defaultsDatabase, NO);
if (nil != path)
{
_fileLock = [[NSDistributedLock alloc] initWithPath: path];
}
}
if ([self _lockDefaultsFile: &wasLocked] == NO)
{
result = NO;
}
else
{
NSEnumerator *enumerator;
NSString *domainName;
isLocked = YES;
haveChange = [self _readDefaults];
if (YES == haveChange)
{
DESTROY(_dictionaryRep);
}
if (_changedDomains != nil)
{
haveChange = YES;
if (NO == [self _readOnly])
{
GSPersistentDomain *domain;
NSFileManager *mgr;
mgr = [NSFileManager defaultManager];
enumerator = [_changedDomains objectEnumerator];
DESTROY(_changedDomains); // Retained by enumerator.
while ((domainName = [enumerator nextObject]) != nil)
{
domain = [_persDomains objectForKey: domainName];
if (domain != nil) // Domain was added or changed
{
[domain synchronize];
}
else // Domain was removed
{
NSString *path;
path = [[_defaultsDatabase
stringByAppendingPathComponent: domainName]
stringByAppendingPathExtension: @"plist"];
[mgr removeFileAtPath: path handler: nil];
}
}
}
}
if (YES == haveChange)
{
updateCache(self);
}
if (YES == isLocked && NO == wasLocked)
{
isLocked = NO;
[self _unlockDefaultsFile];
}
}
}
}
NS_HANDLER
{
RELEASE(_lastSync);
_lastSync = saved;
if (YES == isLocked && NO == wasLocked)
{
isLocked = NO;
[self _unlockDefaultsFile];
}
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
if (YES == result)
{
RELEASE(saved);
}
else
{
RELEASE(_lastSync);
_lastSync = saved;
}
// Check and if not existent add the Application and the Global domains
if (bundleIdentifier && [_persDomains objectForKey: bundleIdentifier] == nil)
{
GSPersistentDomain *pd;
pd = [[GSPersistentDomain alloc] initWithName: bundleIdentifier
owner: self];
[_persDomains setObject: pd forKey: bundleIdentifier];
RELEASE(pd);
[self _changePersistentDomain: bundleIdentifier];
}
if ([_persDomains objectForKey: NSGlobalDomain] == nil)
{
GSPersistentDomain *pd;
pd = [[GSPersistentDomain alloc] initWithName: NSGlobalDomain
owner: self];
[_persDomains setObject: pd forKey: NSGlobalDomain];
RELEASE(pd);
[self _changePersistentDomain: NSGlobalDomain];
}
[_lock unlock];
if (haveChange)
{
[[NSNotificationCenter defaultCenter]
postNotificationName: NSUserDefaultsDidChangeNotification
object: self];
}
return result;
}
- (void) removeVolatileDomainForName: (NSString*)domainName
{
[_lock lock];
NS_DURING
{
DESTROY(_dictionaryRep);
[_tempDomains removeObjectForKey: domainName];
if ([_searchList containsObject: domainName])
{
updateCache(self);
}
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
}
- (void) setVolatileDomain: (NSDictionary*)domain
forName: (NSString*)domainName
{
id dict;
[_lock lock];
NS_DURING
{
dict = [_persDomains objectForKey: domainName];
if (dict != nil)
{
[NSException raise: NSInvalidArgumentException
format: @"a persistent domain called %@ exists", domainName];
}
dict = [_tempDomains objectForKey: domainName];
if (dict != nil)
{
[NSException raise: NSInvalidArgumentException
format: @"the volatile domain %@ already exists", domainName];
}
DESTROY(_dictionaryRep);
domain = [domain mutableCopy];
[_tempDomains setObject: domain forKey: domainName];
RELEASE(domain);
if ([_searchList containsObject: domainName])
{
updateCache(self);
}
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
}
- (NSDictionary*) volatileDomainForName: (NSString*)domainName
{
NSDictionary *copy = nil;
[_lock lock];
NS_DURING
{
copy = [[_tempDomains objectForKey: domainName] copy];
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
return AUTORELEASE(copy);
}
- (NSArray*) volatileDomainNames
{
NSArray *keys = nil;
[_lock lock];
NS_DURING
{
keys = [_tempDomains allKeys];
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
return keys;
}
- (NSDictionary*) dictionaryRepresentation
{
NSDictionary *rep;
[_lock lock];
NS_DURING
{
if (_dictionaryRep == nil)
{
NSEnumerator *enumerator;
NSMutableDictionary *dictRep;
id obj;
id dict;
IMP nImp;
IMP pImp;
IMP tImp;
IMP addImp;
pImp = [_persDomains methodForSelector: objectForKeySel];
tImp = [_tempDomains methodForSelector: objectForKeySel];
enumerator = [_searchList reverseObjectEnumerator];
nImp = [enumerator methodForSelector: nextObjectSel];
dictRep = [NSMutableDictionaryClass alloc];
dictRep = [dictRep initWithCapacity: 512];
addImp = [dictRep methodForSelector: addSel];
while ((obj = (*nImp)(enumerator, nextObjectSel)) != nil)
{
GSPersistentDomain *pd;
pd = (*pImp)(_persDomains, objectForKeySel, obj);
if (nil != pd)
{
dict = [pd contents];
}
else
{
dict = (*tImp)(_tempDomains, objectForKeySel, obj);
}
if (nil != dict)
{
(*addImp)(dictRep, addSel, dict);
}
}
_dictionaryRep = GS_IMMUTABLE(dictRep);
}
rep = AUTORELEASE(RETAIN(_dictionaryRep));
[_lock unlock];
}
NS_HANDLER
{
rep = nil;
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
return rep;
}
- (void) registerDefaults: (NSDictionary*)newVals
{
NSMutableDictionary *regDefs;
[_lock lock];
NS_DURING
{
regDefs = [_tempDomains objectForKey: NSRegistrationDomain];
if (regDefs == nil)
{
regDefs = [NSMutableDictionaryClass
dictionaryWithCapacity: [newVals count]];
[_tempDomains setObject: regDefs forKey: NSRegistrationDomain];
}
DESTROY(_dictionaryRep);
[regDefs addEntriesFromDictionary: newVals];
updateCache(self);
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
}
- (void) removeSuiteNamed: (NSString*)aName
{
if (aName == nil)
{
[NSException raise: NSInvalidArgumentException
format: @"attempt to remove suite with nil name"];
}
[_lock lock];
NS_DURING
{
DESTROY(_dictionaryRep);
[_searchList removeObject: aName];
updateCache(self);
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
}
@end
BOOL
GSPrivateDefaultsFlag(GSUserDefaultFlagType type)
{
if (nil == classLock)
{
if (initializing)
{
fprintf(stderr, "GSPrivateDefaultsFlag(%d) called within"
" +[NSUserDefaults initialize] always returns NO.\n",
(int)type);
}
else
{
/* The order of +initialise of NSUserDefaults is such that our
* flags[] array is set up directly from the process arguments
* before classLock is created, so once that variable exists
* this function may be used safely.
*/
[NSUserDefaults class];
if (NO == hasSharedDefaults)
{
[NSUserDefaults standardUserDefaults];
}
}
}
return flags[type];
}
/* Slightly faster than
* [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]
* Avoiding the autorelease of the standard defaults turns out to be
* a modest but significant gain when making heavy use of methods which
* need localisation.
*/
NSDictionary *GSPrivateDefaultLocale()
{
NSDictionary *locale = nil;
NSUserDefaults *defs = nil;
if (nil == classLock)
{
[NSUserDefaults standardUserDefaults];
}
[classLock lock];
NS_DURING
{
if (sharedDefaults == nil)
{
[NSUserDefaults standardUserDefaults];
}
ASSIGN(defs, sharedDefaults);
[classLock unlock];
}
NS_HANDLER
{
[classLock unlock];
[localException raise];
}
NS_ENDHANDLER
locale = [defs dictionaryRepresentation];
RELEASE(defs);
return locale;
}
@implementation NSUserDefaults (Private)
+ (void) _createArgumentDictionary: (NSArray*)args
{
NSEnumerator *enumerator;
NSMutableDictionary *argDict = nil;
BOOL done;
id key, val;
[classLock lock];
NS_DURING
{
enumerator = [args objectEnumerator];
argDict = [NSMutableDictionaryClass dictionaryWithCapacity: 2];
[enumerator nextObject]; // Skip process name.
done = ((key = [enumerator nextObject]) == nil) ? YES : NO;
while (done == NO)
{
/* Any value with a leading '-' may be the name of a default
* in the argument domain.
* NB. Testing on OSX shows that this includes a single '-'
* (where the key is an empty string), but GNUstep disallows
* en empty string as a key (so it can be a value).
*/
if ([key hasPrefix: @"-"] == YES
&& [key isEqual: @"-"] == NO)
{
/* Strip the '-' before the defaults key, and get the
* corresponding value (the next argument).
*/
key = [key substringFromIndex: 1];
val = [enumerator nextObject];
if (nil == val)
{
/* No more arguments and no value ... arg is not set.
*/
done = YES;
continue;
}
else if ([val hasPrefix: @"-"] == YES
&& [val isEqual: @"-"] == NO)
{
/* Value is actually an argument key ...
* current key is not used (behavior matches OSX).
* NB. GNUstep allows a '-' as the value for a default,
* but OSX does not.
*/
key = val;
continue;
}
else
{ // Real parameter
/* Parsing the argument as a property list is very
delicate. We *MUST NOT* crash here just because a
strange parameter (such as `(load "test.scm")`) is
passed, otherwise the whole library is useless in a
foreign environment. */
NSObject *plist_val;
NS_DURING
{
NSData *data;
data = [val dataUsingEncoding: NSUTF8StringEncoding];
plist_val = [NSPropertyListSerialization
propertyListFromData: data
mutabilityOption: NSPropertyListMutableContainers
format: 0
errorDescription: 0];
if (nil == plist_val)
{
plist_val = val;
}
}
NS_HANDLER
{
plist_val = val;
}
NS_ENDHANDLER
/* Make sure we don't crash being caught adding nil to
a dictionary. */
if (plist_val == nil)
{
plist_val = val;
}
[argDict setObject: plist_val forKey: key];
}
}
done = ((key = [enumerator nextObject]) == nil);
}
ASSIGNCOPY(argumentsDictionary, argDict);
[classLock unlock];
}
NS_HANDLER
{
[classLock unlock];
[localException raise];
}
NS_ENDHANDLER
}
- (void) _changePersistentDomain: (NSString*)domainName
{
BOOL haveChange = NO;
NSAssert(nil != domainName, NSInvalidArgumentException);
[_lock lock];
NS_DURING
{
DESTROY(_dictionaryRep);
if (_changedDomains == nil)
{
_changedDomains = [[NSMutableArray alloc] initWithObjects: &domainName
count: 1];
}
else if ([_changedDomains containsObject: domainName] == NO)
{
[_changedDomains addObject: domainName];
}
if ([_searchList containsObject: domainName])
{
updateCache(self);
}
haveChange = YES;
[_lock unlock];
}
NS_HANDLER
{
[_lock unlock];
[localException raise];
}
NS_ENDHANDLER
if (haveChange)
{
[[NSNotificationCenter defaultCenter]
postNotificationName: NSUserDefaultsDidChangeNotification
object: self];
}
}
- (NSString*) _directory
{
return _defaultsDatabase;
}
static BOOL isLocked = NO;
- (BOOL) _lockDefaultsFile: (BOOL*)wasLocked
{
[syncLock lock];
NS_DURING
{
*wasLocked = isLocked;
if (NO == isLocked && _fileLock != nil)
{
NSDate *started = [NSDateClass date];
while ([_fileLock tryLock] == NO)
{
NSDate *lockDate;
/*
* In case we have tried and failed to break the lock,
* we give up after a while ... 66 seconds should give
* us three lock breaks if we do them at 20 second
* intervals.
*/
if ([started timeIntervalSinceNow] < -66.0)
{
fprintf(stderr, "Failed to lock user defaults database"
" even after breaking old locks!\n");
break;
}
ENTER_POOL
/* If lockDate is nil, we should be able to lock again ... but we
* wait a little anyway ... so that in the case of a locking
* problem we do an idle wait rather than a busy one.
*/
if ((lockDate = [_fileLock lockDate]) != nil
&& [lockDate timeIntervalSinceNow] < -20.0)
{
NSLog(@"NSUserDefaults file lock at %@ is dated %@ ... break",
_fileLock, lockDate);
[_fileLock breakLock];
}
else
{
[NSThread sleepForTimeInterval: 0.1];
}
LEAVE_POOL;
}
isLocked = YES;
}
[syncLock unlock];
}
NS_HANDLER
{
[syncLock unlock];
[localException raise];
}
NS_ENDHANDLER
return isLocked;
}
- (BOOL) _readDefaults
{
NSFileManager *mgr = [NSFileManager defaultManager];
NSEnumerator *enumerator;
NSString *domainName;
BOOL haveChange = NO;
static BOOL beenHere = NO;
if (NO == beenHere)
{
NSString *npath = _defaultsDatabase;
NSString *opath = _defaultsDatabase;
beenHere = YES;
/* The default domain name for a program changed from being the name
* of the executable to being the bundle identifier (if available).
* If the domain file does not exist for the new name but does exist
* for the old name, we move the file to the modern location.
*/
opath = [npath stringByAppendingPathComponent: processName];
opath = [opath stringByAppendingPathExtension: @"plist"];
npath = [npath stringByAppendingPathComponent: bundleIdentifier];
npath = [npath stringByAppendingPathExtension: @"plist"];
if (NO == [mgr isReadableFileAtPath: npath]
&& YES == [mgr isReadableFileAtPath: opath])
{
[mgr movePath: opath toPath: npath handler: nil];
}
}
enumerator = [[mgr
directoryContentsAtPath: _defaultsDatabase] objectEnumerator];
while (nil != (domainName = [enumerator nextObject]))
{
if (NO == [[domainName pathExtension] isEqual: @"plist"])
{
/* We only treat files with a .plist extension as being
* defaults domain files.
*/
continue;
}
domainName = [domainName stringByDeletingPathExtension];
/* We may want to know what domains are being loaded.
*/
NSDebugMLog(@"domain name: %@", domainName);
/* We only look at files which do not represent domains in the
* _changedDomains list, since our internal information on the
* domains in that list overrides anything on disk.
*/
if (NO == [_changedDomains containsObject: domainName])
{
GSPersistentDomain *pd;
pd = [_persDomains objectForKey: domainName];
if (nil == pd)
{
/* We had no record of this domain, so we create a new
* instance for it and add it to the dictionary of all
* persistent domains.
*/
pd = [GSPersistentDomain alloc];
pd = [pd initWithName: domainName
owner: self];
[_persDomains setObject: pd forKey: domainName];
RELEASE(pd);
haveChange = YES;
}
if (YES == [_searchList containsObject: domainName])
{
/* This domain is in the search list ... so we must
* synchronize to load the domain contents into memory
* so a lookup will work.
*/
if (YES == [pd synchronize])
{
haveChange = YES;
}
}
}
}
return haveChange;
}
- (BOOL) _readOnly
{
return (nil == _fileLock) ? YES : NO;
}
- (void) _unlockDefaultsFile
{
[syncLock lock];
NS_DURING
{
if (YES == isLocked)
{
[_fileLock unlock];
}
}
NS_HANDLER
{
fprintf(stderr, "Warning ... someone broke our lock (%s) ... and may have"
" interfered with updating defaults data in file.",
[lockPath(_defaultsDatabase, NO) UTF8String]);
}
NS_ENDHANDLER
isLocked = NO;
[syncLock unlock];
}
@end
@implementation GSPersistentDomain
- (NSDictionary*) contents
{
if (NO == loaded)
{
[self synchronize];
}
return contents;
}
- (void) dealloc
{
DESTROY(added);
DESTROY(removed);
DESTROY(modified);
DESTROY(contents);
DESTROY(name);
DESTROY(path);
[super dealloc];
}
- (void) empty
{
if (NO == loaded)
{
[self synchronize];
}
if ([contents count] > 0)
{
NSEnumerator *e;
NSString *k;
e = [[contents allKeys] objectEnumerator];
while (nil != (k = [e nextObject]))
{
[self setObject: nil forKey: k];
}
[self synchronize];
}
}
- (id) initWithName: (NSString*)n
owner: (NSUserDefaults*)o
{
if (nil != (self = [super init]))
{
owner = o; // Not retained
name = [n copy];
path = RETAIN([[[owner _directory] stringByAppendingPathComponent: name]
stringByAppendingPathExtension: @"plist"]);
contents = [NSMutableDictionary new];
added = [NSMutableSet new];
removed = [NSMutableSet new];
modified = [NSMutableSet new];
}
return self;
}
- (NSString*) name
{
return name;
}
- (id) objectForKey: (NSString*)aKey
{
return [contents objectForKey: aKey];
}
- (BOOL) setContents: (NSDictionary*)domain
{
BOOL changed = NO;
if (NO == [contents isEqual: domain])
{
NSEnumerator *e;
NSString *k;
e = [[contents allKeys] objectEnumerator];
while (nil != (k = [e nextObject]))
{
if ([domain objectForKey: k] == nil)
{
[self setObject: nil forKey: k];
}
}
e = [domain keyEnumerator];
while (nil != (k = [e nextObject]))
{
[self setObject: [domain objectForKey: k] forKey: k];
}
changed = YES;
}
return changed;
}
- (BOOL) setObject: (id)anObject forKey: (NSString*)aKey
{
if (nil == anObject)
{
if (nil == [contents objectForKey: aKey])
{
return NO;
}
if ([added member: aKey])
{
[added removeObject: aKey];
}
else if ([modified member: aKey])
{
[modified removeObject: aKey];
[removed addObject: aKey];
}
else
{
[removed addObject: aKey];
}
[contents removeObjectForKey: aKey];
return YES;
}
else
{
id old = [contents objectForKey: aKey];
if ([anObject isEqual: old])
{
return NO;
}
if ([removed member: aKey])
{
[modified addObject: aKey];
[removed removeObject: aKey];
}
else if (nil == [modified member: aKey] && nil == [added member: aKey])
{
if (nil == old)
{
[added addObject: aKey];
}
else
{
[modified addObject: aKey];
}
}
[contents setObject: anObject forKey: aKey];
return YES;
}
}
- (BOOL) synchronize
{
BOOL isLocked = NO;
BOOL wasLocked = NO;
BOOL shouldLock = NO;
BOOL defaultsChanged = NO;
BOOL hasLocalChanges = NO;
if ([removed count] || [added count] || [modified count])
{
hasLocalChanges = YES;
}
if (YES == hasLocalChanges && NO == [owner _readOnly])
{
shouldLock = YES;
}
if (YES == shouldLock && YES == [owner _lockDefaultsFile: &wasLocked])
{
isLocked = YES;
}
NS_DURING
{
NSFileManager *mgr;
NSMutableDictionary *disk;
mgr = [NSFileManager defaultManager];
disk = nil;
if ([mgr isReadableFileAtPath: path])
{
NSData *data;
data = [NSData dataWithContentsOfFile: path];
if (nil != data)
{
id o;
o = [NSPropertyListSerialization
propertyListWithData: data
options: NSPropertyListImmutable
format: 0
error: 0];
if ([o isKindOfClass: [NSDictionary class]])
{
disk = AUTORELEASE([o mutableCopy]);
}
}
}
if (nil == disk)
{
disk = [NSMutableDictionary dictionary];
}
loaded = YES;
if (NO == [contents isEqual: disk])
{
defaultsChanged = YES;
if (YES == hasLocalChanges)
{
NSEnumerator *e;
NSString *k;
e = [removed objectEnumerator];
while (nil != (k = [e nextObject]))
{
[disk removeObjectForKey: k];
}
e = [added objectEnumerator];
while (nil != (k = [e nextObject]))
{
[disk setObject: [contents objectForKey: k] forKey: k];
}
e = [modified objectEnumerator];
while (nil != (k = [e nextObject]))
{
[disk setObject: [contents objectForKey: k] forKey: k];
}
}
ASSIGN(contents, disk);
}
if (YES == hasLocalChanges)
{
BOOL written = NO;
if (NO == [owner _readOnly])
{
if (YES == isLocked)
{
if (0 == [contents count])
{
/* Remove empty defaults dictionary.
*/
written = writeDictionary(nil, path);
}
else
{
/* Write dictionary to file.
*/
written = writeDictionary(contents, path);
}
}
}
if (YES == written)
{
[added removeAllObjects];
[removed removeAllObjects];
[modified removeAllObjects];
}
}
if (YES == isLocked && NO == wasLocked)
{
isLocked = NO;
[owner _unlockDefaultsFile];
}
}
NS_HANDLER
{
fprintf(stderr, "problem synchronising defaults domain '%s': %s\n",
[name UTF8String], [[localException description] UTF8String]);
if (YES == isLocked && NO == wasLocked)
{
[owner _unlockDefaultsFile];
}
}
NS_ENDHANDLER
return defaultsChanged;
}
@end
|