Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 681 lines (558 sloc) 18.644 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
/*
* CPUserDefaults.j
* Foundation
*
* Created by Nicholas Small.
* Copyright 2010, 280 North, Inc.
*
* 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.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

@import "CPBundle.j"
@import "CPData.j"
@import "CPDictionary.j"
@import "CPException.j"
@import "CPKeyedArchiver.j"
@import "CPKeyedUnarchiver.j"
@import "CPNotificationCenter.j"
@import "CPObject.j"
@import "CPRunLoop.j"
@import "CPString.j"
@import "CPURL.j"
@import "CPURLConnection.j"
@import "CPURLRequest.j"


CPArgumentDomain = @"CPArgumentDomain";
CPApplicationDomain = [[[CPBundle mainBundle] infoDictionary] objectForKey:@"CPBundleIdentifier"] || @"CPApplicationDomain";
CPGlobalDomain = @"CPGlobalDomain";
CPLocaleDomain = @"CPLocaleDomain";
CPRegistrationDomain = @"CPRegistrationDomain";

CPUserDefaultsDidChangeNotification = @"CPUserDefaultsDidChangeNotification";

var StandardUserDefaults;

/*!
@ingroup foundation
@class CPUserDefaults

CPUserDefaults provides a way of storing a list of user preferences. Everything you store must be CPCoding compliant because it is stored as CPData.

Unlike in Cocoa, CPUserDefaults is per-host by default because of the method of storage. By default, the localStorage API will be used if the browser
supports it. Otherwise a cookie fallback mechanism is utilized. Be aware that if the user erases the local database or clears their cookies, all the
preferences will be lost. Also be aware that this is not a safe storage method; do not store sensitive data in the defaults database.

The storage method utilized is determined by matching the writing domain to a dictionary of stores, concrete subclasses of the CPUserDefaultsStore abstract
class. This is a deviation from Cocoa. You can create a custom defaults store by subclassing the abstract class and implementing the protocol. Currently the
protocol consists of only two methods: -data and -setData:. The latter needs to store the passed in CPData object in your storage mechanism and the former
needs to return an equivalent CPData object synchronously. You can then configure CPUserDefaults to use your storage mechanism using
-setPersistentStoreClass:forDomain:reloadData:
*/
@implementation CPUserDefaults : CPObject
{
    CPDictionary _domains;
    CPDictionary _stores;

    CPDictionary _searchList;
    BOOL _searchListNeedsReload;
}

/*!
Returns the shared defaults object.
*/
+ (id)standardUserDefaults
{
    if (!StandardUserDefaults)
        StandardUserDefaults = [[CPUserDefaults alloc] init];

    return StandardUserDefaults;
}

/*!
Synchronizes any changes made to the shared user defaults object and releases it from memory.
A subsequent invocation of standardUserDefaults creates a new shared user defaults object with the standard search list.
*/
+ (void)resetStandardUserDefaults
{
    if (StandardUserDefaults)
        [StandardUserDefaults synchronize];

    StandardUserDefaults = nil;
}

/*
@ignore
*/
- (id)init
{
    self = [super init];

    if (self)
    {
        _domains = [CPDictionary dictionary];
        [self _setupArgumentsDomain];

        var defaultStore = [CPUserDefaultsLocalStore supportsLocalStorage] ? CPUserDefaultsLocalStore : CPUserDefaultsCookieStore;

        _stores = [CPDictionary dictionary];
        [self setPersistentStoreClass:defaultStore forDomain:CPGlobalDomain reloadData:YES];
        [self setPersistentStoreClass:defaultStore forDomain:CPApplicationDomain reloadData:YES];
    }

    return self;
}

/*
@ignore
*/
- (void)_setupArgumentsDomain
{
    var args = [CPApp namedArguments],
        keys = [args allKeys],
        count = [keys count],
        i = 0;

    for (; i < count; i++)
    {
        var key = keys[i];
        [self setObject:[args objectForKey:key] forKey:key inDomain:CPArgumentDomain];
    }
}

/*!
Return a default value. The order of domains in the search list is: CPRegistrationDomain, CPGlobalDomain, CPApplicationDomain, CPArgumentDomain.
Calling this method may cause the search list to be recreated if any new values have recently been set. Be aware of the performance ramifications.
*/
- (id)objectForKey:(CPString)aKey
{
    if (_searchListNeedsReload)
        [self _reloadSearchList];

    return [_searchList objectForKey:aKey];
}

/*!
Set a default value in your application domain.
*/
- (void)setObject:(id)anObject forKey:(CPString)aKey
{
    [self setObject:anObject forKey:aKey inDomain:CPApplicationDomain];
}

/*!
Return a default value from a specific domain. If you know
which domain you'd like to use you should always use this method
because it doesn't have to hit the search list.
*/
- (id)objectForKey:(CPString)aKey inDomain:(CPString)aDomain
{
    var domain = [_domains objectForKey:aDomain];

    if (!domain)
        return nil;

    return [domain objectForKey:aKey];
}

/*!
Set a default value in the domain you pass in. If the domain is CPApplicationDomain or CPGlobalDomain,
the defaults store will eventually be persisted. You can call -forceFlush to force a persist.
*/
- (void)setObject:(id)anObject forKey:(CPString)aKey inDomain:(CPString)aDomain
{
    if (!aKey || !aDomain)
        return;

    var domain = [_domains objectForKey:aDomain];
    if (!domain)
    {
        domain = [CPDictionary dictionary];
        [_domains setObject:domain forKey:aDomain];
    }

    [domain setObject:anObject forKey:aKey];
    _searchListNeedsReload = YES;
    [self domainDidChange:aDomain];
}

/*!
Removes the value of the specified default key in the standard application domain.
Removing a default has no effect on the value returned by the objectForKey: method if the same key exists in a domain that precedes the standard application domain in the search list.
*/
- (void)removeObjectForKey:(CPString)aKey
{
    [self removeObjectForKey:aKey inDomain:CPApplicationDomain];
}

/*!
Removes the value of the specified default key in the specified domain.
*/
- (void)removeObjectForKey:(CPString)aKey inDomain:(CPString)aDomain
{
    if (!aKey || !aDomain)
        return;

    var domain = [_domains objectForKey:aDomain];
    if (!domain)
        return;

    [domain removeObjectForKey:aKey];
    _searchListNeedsReload = YES;
    [self domainDidChange:aDomain];
}

/*!
Adds the contents the specified dictionary to the registration domain.

If there is no registration domain, one is created using the specified dictionary, and CPRegistrationDomain is added to the end of the search list.
The contents of the registration domain are not written to disk; you need to call this method each time your application starts. You can place a plist file in the application's Resources directory and call registerDefaultsWithContentsOfFile:

@param aDictionary The dictionary of keys and values you want to register.
*/
- (void)registerDefaults:(CPDictionary)aDictionary
{
    var keys = [aDictionary allKeys],
        count = [keys count],
        i = 0;

    for (; i < count; i++)
    {
        var key = keys[i];
        [self setObject:[aDictionary objectForKey:key] forKey:key inDomain:CPRegistrationDomain];
    }
}

/*!
This is just a convenience method to load a plist resource and register all the values it contains as defaults.

NOTE: This sends a synchronous request. If you don't want to do that, create a dictionary any way you want (including loading a plist)
and pass it to -registerDefaults:
*/
- (void)registerDefaultsFromContentsOfFile:(CPURL)aURL
{
    var contents = [CPURLConnection sendSynchronousRequest:[CPURLRequest requestWithURL:aURL] returningResponse:nil],
        data = [CPData dataWithRawString:[contents rawString]],
        plist = [data plistObject];

    [self registerDefaults:plist];
}

/*
@ignore
*/
- (void)_reloadSearchList
{
    _searchListNeedsReload = NO;

    var dicts = [CPRegistrationDomain, CPGlobalDomain, CPApplicationDomain, CPArgumentDomain],
        count = [dicts count],
        i = 0;

    _searchList = [CPDictionary dictionary];

    for (; i < count; i++)
    {
        var domain = [_domains objectForKey:dicts[i]];
        if (!domain)
            continue;

        var keys = [domain allKeys],
            keysCount = [keys count],
            j = 0;

        for (; j < keysCount; j++)
        {
            var key = keys[j];
            [_searchList setObject:[domain objectForKey:key] forKey:key];
        }
    }
}

// Synchronization

/*!
Returns an array of currently volatile domain names.
*/
- (CPArray)volatileDomainNames
{
    return [CPArgumentDomain, CPLocaleDomain, CPRegistrationDomain];
}

/*!
Returns an array of currently persistent domain names.
*/
- (CPArray)persistentDomainNames
{
    return [CPGlobalDomain, CPApplicationDomain];
}

/*!
Returns the currently used instance of CPUserDefaultStore concrete subclass for the given domain name.
*/
- (CPUserDefaultsStore)persistentStoreForDomain:(CPString)aDomain
{
    return [_stores objectForKey:aDomain];
}

/*!
Set the CPUserDefaultStore concrete subclass that should be instantiated for use
in persisting the given domain name.

@param aStoreClass The concrete subclass of CPUserDefaultsStore to use to store the defaults database for this domain
@param aDomain The name of the domain for which you want to change the storage mechanism
@param reloadData Empty the cached defaults for this domain and reload them from the new storage mechanism
*/
- (CPUserDefaultsStore)setPersistentStoreClass:(Class)aStoreClass forDomain:(CPString)aDomain reloadData:(BOOL)aFlag
{
    var currentStore = [_stores objectForKey:aDomain];
    if (currentStore && [currentStore class] === aStoreClass)
        return currentStore;

    var store = [[aStoreClass alloc] init];
    [store setDomain:aDomain];
    [_stores setObject:store forKey:aDomain];

    if (aFlag)
        [self reloadDataFromStoreForDomain:aDomain];

    return store;
}

/*!
@ignore
*/
- (void)reloadDataFromStoreForDomain:(CPString)aDomain
{
    var data = [[self persistentStoreForDomain:aDomain] data],
        domain = data ? [CPKeyedUnarchiver unarchiveObjectWithData:data] : nil;

    [_domains setObject:domain forKey:aDomain];

    _searchListNeedsReload = YES;
}

/*!
@ignore
*/
- (void)domainDidChange:(CPString)aDomain
{
    if (aDomain === CPGlobalDomain || aDomain === CPApplicationDomain)
        [[CPRunLoop currentRunLoop] performSelector:@selector(synchronize) target:self argument:nil order:0 modes:[CPDefaultRunLoopMode]];

    [[CPNotificationCenter defaultCenter] postNotificationName:CPUserDefaultsDidChangeNotification object:self];
}

/*!
Force write out of defaults database immediately.
*/
- (void)synchronize
{
    var globalDomain = [_domains objectForKey:CPGlobalDomain];
    if (globalDomain)
    {
        var data = [CPKeyedArchiver archivedDataWithRootObject:globalDomain];
        [[self persistentStoreForDomain:CPGlobalDomain] setData:data];
    }

    var appDomain = [_domains objectForKey:CPApplicationDomain];
    if (appDomain)
    {
        var data = [CPKeyedArchiver archivedDataWithRootObject:appDomain];
        [[self persistentStoreForDomain:CPApplicationDomain] setData:data];
    }
}

#pragma mark Getting Default Values

/*!
Returns the array value associated with the specified key.
*/
- (CPArray)arrayForKey:(CPString)aKey
{
    var value = [self objectForKey:aKey];
    if ([value isKindOfClass:CPArray])
        return value;

    return nil;
}

/*!
Returns the Boolean value associated with the specified key.
*/
- (BOOL)boolForKey:(CPString)aKey
{
    var value = [self objectForKey:aKey];
    if ([value respondsToSelector:@selector(boolValue)])
        return [value boolValue];

    return NO;
}


/*!
Returns the data object associated with the specified key.
*/
- (CPData)dataForKey:(CPString)aKey
{
    var value = [self objectForKey:aKey];
    if ([value isKindOfClass:CPData])
        return value;

    return nil;
}

/*!
Returns the Boolean value associated with the specified key.
*/
- (CPDictionary)dictionaryForKey:(CPString)aKey
{
    var value = [self objectForKey:aKey];
    if ([value isKindOfClass:CPDictionary])
        return value;

    return nil;
}

/*!
Returns the float value associated with the specified key.
*/
- (float)floatForKey:(CPString)aKey
{
    var value = [self objectForKey:aKey];
    if (value === nil)
        return 0;

    if ([value respondsToSelector:@selector(floatValue)])
        value = [value floatValue];

    return parseFloat(value);
}

/*!
Returns the integer value associated with the specified key.
*/
- (int)integerForKey:(CPString)aKey
{
    var value = [self objectForKey:aKey];
    if (value === nil)
        return 0;

    if ([value respondsToSelector:@selector(intValue)])
        value = [value intValue];

    return parseInt(value);
}

/*!
Returns the double value associated with the specified key.
*/
- (double)doubleForKey:(CPString)aKey
{
    return [self floatForKey:aKey];
}

/*!
Returns the string value associated with the specified key.
*/
- (CPString)stringForKey:(CPString)aKey
{
    var value = [self objectForKey:aKey];

    if ([value isKindOfClass:CPString])
        return value;

    else if ([value respondsToSelector:@selector(stringValue)])
        return [value stringValue];

    return nil;
}

/*!
Returns the string array value associated with the specified key.
*/
- (CPArray)stringArrayForKey:(CPString)aKey
{
    var value = [self objectForKey:aKey];
    if (![value isKindOfClass:CPArray])
        return nil;

    for (var i = 0, count = [value count]; i < count; i++)
        if (![value[i] isKindOfClass:CPString])
            return nil;

    return value;
}

/*!
Returns the CPURL value associated with the specified key.
*/
- (CPURL)URLForKey:(CPString)aKey
{
    var value = [self objectForKey:aKey];
    if ([value isKindOfClass:CPURL])
        return value;

    if ([value isKindOfClass:CPString])
        return [CPURL URLWithString:value];

    return nil;
}

#pragma mark Setting Default Values

/*!
Sets the value of the specified default key to the specified Boolean value.
A cast will be attempted with -boolValue.
*/
- (void)setBool:(BOOL)aValue forKey:(CPString)aKey
{
    if ([aValue respondsToSelector:@selector(boolValue)])
        [self setObject:[aValue boolValue] forKey:aKey];
}

/*!
Sets the value of the specified default key to the specified float value.
A cast will be attempted with -floatValue and parseFloat().
*/
- (void)setFloat:(float)aValue forKey:(CPString)aKey
{
    if ([aValue respondsToSelector:@selector(aValue)])
        aValue = [aValue floatValue];

    [self setObject:parseFloat(aValue) forKey:aKey];
}

/*!
Sets the value of the specified default key to the double value.
*/
- (void)setDouble:(double)aValue forKey:(CPString)aKey
{
    [self setFloat:aValue forKey:aKey];
}

/*!
Sets the value of the specified default key to the specified integer value.
A cast will be attempted with -intValue and parseInt().
*/
- (void)setInteger:(int)aValue forKey:(CPString)aKey
{
    if ([aValue respondsToSelector:@selector(intValue)])
        aValue = [aValue intValue];

    [self setObject:parseInt(aValue) forKey:aKey];
}

/*!
Sets the value of the specified default key to the specified URL.
The adjustments made in Cocoa are not present here.
*/
- (void)setURL:(CPURL)aValue forKey:(CPString)aKey
{
    if ([aValue isKindOfClass:CPString])
        aValue = [CPURL URLWithString:aValue];

    [self setObject:aValue forKey:aKey];
}

@end

@implementation CPUserDefaultsStore : CPObject
{
    CPString _domain @accessors(property=domain);
}

- (CPData)data
{
    _CPRaiseInvalidAbstractInvocation(self, _cmd);
    return nil;
}

- (void)setData:(CPData)aData
{
    _CPRaiseInvalidAbstractInvocation(self, _cmd);
}

@end

@implementation CPUserDefaultsCookieStore : CPUserDefaultsStore
{
    CPCookie _cookie;
}

- (void)setDomain:(CPString)aDomain
{
    if (_domain === aDomain)
        return;

    _domain = aDomain;

    _cookie = [[CPCookie alloc] initWithName:_domain];
}

- (CPData)data
{
    var result = [_cookie value];
    if (!result || [result length] < 1)
        return nil;

    return [CPData dataWithRawString:decodeURIComponent(result)];
}

- (void)setData:(CPData)aData
{
    [_cookie setValue:encodeURIComponent([aData rawString]) expires:[CPDate distantFuture] domain:window.location.href.hostname];
}

@end

var CPUserDefaultsLocalStoreTestKey = "9961800812587769-Cappuccino-Storage-Test";

@implementation CPUserDefaultsLocalStore : CPUserDefaultsStore
{
}

+ (BOOL)supportsLocalStorage
{
    if (!window.localStorage)
        return NO;

    try
    {
        // Just because localStorage exists does not mean it works. In particular it might be disabled
        // as it is when Safari's private browsing mode is active.
        localStorage.setItem(CPUserDefaultsLocalStoreTestKey, "1");
        if (localStorage.getItem(CPUserDefaultsLocalStoreTestKey) != "1")
            return NO;
        localStorage.removeItem(CPUserDefaultsLocalStoreTestKey);
    }
    catch (e)
    {
        return NO;
    }
    return YES;
}

- (id)init
{
    if (![[self class] supportsLocalStorage])
    {
        [CPException raise:@"UnsupportedFeature" reason:@"Browser does not support localStorage for CPUserDefaultsLocalStore"];
        return self = nil;
    }

    return self = [super init];
}

- (CPData)data
{
    var result = localStorage.getItem(_domain);
    if (!result || [result length] < 1)
        return nil;

    return [CPData dataWithRawString:decodeURIComponent(result)];
}

- (void)setData:(CPData)aData
{
    try
    {
        localStorage.setItem(_domain, encodeURIComponent([aData rawString]));
    }
    catch (e)
    {
        CPLog.warn("Unable to write to local storage: " + e);
    }
}

@end
Something went wrong with that request. Please try again.