William Bowling is sharing code with you
Bitbucket is a code hosting site. Unlimited public and private repositories. Free for small teams.
Don't show this again1 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 | //
// AIPreferenceContainer.m
// Adium
//
// Created by Evan Schoenberg on 1/8/08.
//
#import "AIPreferenceContainer.h"
#import "AIPreferenceController.h"
#import <Adium/AIListObject.h>
#import <Adium/AILoginControllerProtocol.h>
#import <AIUtilities/AIApplicationAdditions.h>
#import <AIUtilities/AIDictionaryAdditions.h>
#import <AIUtilities/AIStringAdditions.h>
#import <Adium/AIAccount.h>
@interface AIPreferenceContainer ()
- (id)initForGroup:(NSString *)inGroup object:(AIListObject *)inObject;
- (void)save;
@property (readonly, nonatomic) NSMutableDictionary *prefs;
- (void) loadGlobalPrefs;
//Lazily sets up our pref dict if needed
- (void) setPrefValue:(id)val forKey:(id)key;
@end
#define SAVE_OBJECT_PREFS_DELAY 10.0
/* XXX Remove me */
#ifdef DEBUG_BUILD
#define PREFERENCE_CONTAINER_DEBUG
#endif
static NSMutableDictionary *objectPrefs = nil;
static NSTimer *timer_savingOfObjectCache = nil;
static NSMutableDictionary *accountPrefs = nil;
static NSTimer *timer_savingOfAccountCache = nil;
/*!
* @brief Preference Container
*
* A single AIPreferenceContainer instance provides read/write access preferences to a specific preference group, either
* for the global preferences or for a specific object.
*
* All contacts share a single plist on-disk, loaded into a single mutable dictionary in-memory, objectPrefs.
* All accounts share a single plist on-disk, loaded into a single mutable dictionary in-memory, accountPrefs.
* These global dictionaries provide per-object preference dictionaries, keyed by the object's internalObjectID.
*
* Individual instances of AIPreferenceContainer make use of this shared store. Saving of changes is batched for all changes made during a
* SAVE_OBJECT_PREFS_DELAY interval across all instances of AIPreferenceContainer for a given global dictionary. Because creating
* the data representation of a large dictionary and writing it out can be time-consuming (certainly less than a second, but still long
* enough to cause a perceptible delay for a user actively typing or interacting with Adium), saving is performed on a thread.
*/
@implementation AIPreferenceContainer
+ (AIPreferenceContainer *)preferenceContainerForGroup:(NSString *)inGroup object:(AIListObject *)inObject
{
return [[[self alloc] initForGroup:inGroup object:inObject] autorelease];
}
+ (void)preferenceControllerWillClose
{
//If a save of the object prefs is pending, perform it immediately since we are quitting
if (timer_savingOfObjectCache) {
[objectPrefs writeToPath:[adium.loginController userDirectory]
withName:@"ByObjectPrefs"];
/* There's no guarantee that 'will close' is called in the same run loop as the actual program termination.
* We've done our final save, though; don't let the timer fire again.
*/
[timer_savingOfObjectCache invalidate];
[timer_savingOfObjectCache release]; timer_savingOfObjectCache = nil;
}
//If a save of the account prefs is pending, perform it immediately since we are quitting
if (timer_savingOfAccountCache) {
[accountPrefs writeToPath:[adium.loginController userDirectory]
withName:@"AccountPrefs"];
/* There's no guarantee that 'will close' is called in the same run loop as the actual program termination.
* We've done our final save, though; don't let the timer fire again.
*/
[timer_savingOfAccountCache invalidate];
[timer_savingOfAccountCache release]; timer_savingOfObjectCache = nil;
}
}
- (id)initForGroup:(NSString *)inGroup object:(AIListObject *)inObject
{
if ((self = [super init])) {
group = [inGroup retain];
object = [inObject retain];
if (object) {
if ([object isKindOfClass:[AIAccount class]]) {
myGlobalPrefs = &accountPrefs;
myTimerForSavingGlobalPrefs = &timer_savingOfAccountCache;
globalPrefsName = @"AccountPrefs";
} else {
myGlobalPrefs = &objectPrefs;
myTimerForSavingGlobalPrefs = &timer_savingOfObjectCache;
globalPrefsName = @"ByObjectPrefs";
}
}
}
return self;
}
- (void)dealloc
{
[defaults release]; defaults = nil;
[group release];
[object release];
[globalPrefsName release]; globalPrefsName = nil;
[super dealloc];
}
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey
{
return NO;
}
#pragma mark Defaults
@synthesize defaults;
/*!
* @brief Register defaults
*
* These defaults will be added to any existing defaults; if there is overlap between keys, the new key-value pair will be used.
*/
- (void)registerDefaults:(NSDictionary *)inDefaults
{
if (!defaults) defaults = [[NSMutableDictionary alloc] init];
[defaults addEntriesFromDictionary:inDefaults];
//Clear the cached defaults dictionary so it will be recreated as needed
[prefsWithDefaults release]; prefsWithDefaults = nil;
}
#pragma mark Get and set
- (void) loadGlobalPrefs
{
NSAssert(*myGlobalPrefs == nil, @"Attempting to load global prefs when they're already loaded");
NSString *objectPrefsPath = [[adium.loginController.userDirectory stringByAppendingPathComponent:globalPrefsName] stringByAppendingPathExtension:@"plist"];
NSString *errorString = nil;
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:objectPrefsPath
options:NSUncachedRead
error:&error];
if (error) {
NSLog(@"Error reading data for preferences file %@: %@ (%@ %ld: %@)", objectPrefsPath, error,
[error domain], [error code], [error userInfo]);
AILogWithSignature(@"Error reading data for preferences file %@: %@ (%@ %i: %@)", objectPrefsPath, error,
[error domain], [error code], [error userInfo]);
if ([[NSFileManager defaultManager] fileExistsAtPath:objectPrefsPath]) {
while (!data) {
AILogWithSignature(@"Preferences file %@'s attributes: %@. Reattempting to read the file...", globalPrefsName, [[NSFileManager defaultManager] fileAttributesAtPath:objectPrefsPath traverseLink:NO]);
data = [NSData dataWithContentsOfFile:objectPrefsPath
options:NSUncachedRead
error:&error];
if (error) {
AILogWithSignature(@"Error reading data for preferences file %@: %@ (%@ %i: %@)", objectPrefsPath, error,
[error domain], [error code], [error userInfo]);
}
}
}
}
//We want to load a mutable dictioanry of mutable dictionaries.
if (data) {
*myGlobalPrefs = [[NSPropertyListSerialization propertyListFromData:data
mutabilityOption:NSPropertyListMutableContainers
format:NULL
errorDescription:&errorString] retain];
}
/* Log any error */
if (errorString) {
NSLog(@"Error reading preferences file %@: %@", objectPrefsPath, errorString);
AILogWithSignature(@"Error reading preferences file %@: %@", objectPrefsPath, errorString);
}
#ifdef PREFERENCE_CONTAINER_DEBUG
AILogWithSignature(@"I read in %@ with %i items", globalPrefsName, [*myGlobalPrefs count]);
#endif
/* If we don't get a dictionary, create a new one */
if (!*myGlobalPrefs) {
/* This wouldn't be an error if this were a new Adium installation; the below is temporary debug logging. */
NSLog(@"WARNING: Unable to parse preference file %@ (data was %@)", objectPrefsPath, data);
AILogWithSignature(@"WARNING: Unable to parse preference file %@ (data was %@)", objectPrefsPath, data);
*myGlobalPrefs = [[NSMutableDictionary alloc] init];
}
}
- (void) setPrefValue:(id)value forKey:(id)key
{
NSAssert([NSThread currentThread] == [NSThread mainThread], @"AIPreferenceContainer is not threadsafe! Don't set prefs from non-main threads");
NSMutableDictionary *prefDict = self.prefs;
if (object && !prefDict) {
//For compatibility with having loaded individual object prefs from previous version of Adium, we key by the safe filename string
NSString *globalPrefsKey = [object.internalObjectID safeFilenameString];
prefs = [[NSMutableDictionary alloc] init];
[*myGlobalPrefs setObject:prefs
forKey:globalPrefsKey];
}
[self.prefs setValue:value forKey:key];
}
/*!
* @brief Return a dictionary of our preferences, loading it from disk as needed
*/
- (NSMutableDictionary *)prefs
{
if (!prefs) {
NSString *userDirectory = adium.loginController.userDirectory;
if (object) {
if (!(*myGlobalPrefs))
[self loadGlobalPrefs];
//For compatibility with having loaded individual object prefs from previous version of Adium, we key by the safe filename string
NSString *globalPrefsKey = [object.internalObjectID safeFilenameString];
prefs = [[*myGlobalPrefs objectForKey:globalPrefsKey] retain];
} else {
prefs = [[NSMutableDictionary dictionaryAtPath:userDirectory
withName:group
create:YES] retain];
}
}
return prefs;
}
/*!
* @brief Return a dictionary of preferences and defaults, appropriately merged together
*/
- (NSDictionary *)dictionary
{
if (!prefsWithDefaults) {
//Add our own preferences to the defaults dictionary to get a dict with the set keys overriding the default keys
if (defaults) {
prefsWithDefaults = [defaults mutableCopy];
NSDictionary *prefDict = self.prefs;
if (prefDict)
[prefsWithDefaults addEntriesFromDictionary:prefDict];
} else {
prefsWithDefaults = [self.prefs retain];
}
}
return prefsWithDefaults;
}
/*!
* @brief Set value for key
*
* This sets and saves a preference for the given key
*/
- (void)setValue:(id)value forKey:(NSString *)key
{
BOOL valueChanged = YES;
/* Comparing pointers, numbers, and strings is far cheapear than writing out to disk;
* check to see if we don't need to change anything at all. However, we still want to post notifications
* for observers that we were set.
*/
id oldValue = [self valueForKey:key];
if ((!value && !oldValue) || (value && oldValue && [value isEqual:oldValue]))
valueChanged = NO;
[self willChangeValueForKey:key];
if (valueChanged) {
//Clear the cached defaults dictionary so it will be recreated as needed
if (value)
[prefsWithDefaults setValue:value forKey:key];
else {
[prefsWithDefaults autorelease]; prefsWithDefaults = nil;
}
[self setPrefValue:value forKey:key];
}
[self didChangeValueForKey:key];
//Now tell the preference controller
if (!preferenceChangeDelays) {
[adium.preferenceController informObserversOfChangedKey:key inGroup:group object:object];
if (valueChanged)
[self save];
}
}
- (id)valueForKey:(NSString *)key
{
return [[self dictionary] valueForKey:key];
}
/*!
* @brief Get a preference, possibly ignoring the defaults
*
* @param key The key
* @param ignoreDefaults If YES, the preferences are accessed diretly, without including the default values
*/
- (id)valueForKey:(NSString *)key ignoringDefaults:(BOOL)ignoreDefaults
{
if (ignoreDefaults)
return [self.prefs valueForKey:key];
else
return [self valueForKey:key];
}
- (id)defaultValueForKey:(NSString *)key
{
return [[self defaults] valueForKey:key];
}
/*!
* @brief Set all preferences for this group
*
* All existing preferences are removed for this group; the passed dictionary becomes the new preferences
*/
- (void)setPreferences:(NSDictionary *)inPreferences
{
[self setPreferenceChangedNotificationsEnabled:NO];
[self setValuesForKeysWithDictionary:inPreferences];
[self setPreferenceChangedNotificationsEnabled:YES];
}
- (void)setPreferenceChangedNotificationsEnabled:(BOOL)inEnabled
{
if (inEnabled)
preferenceChangeDelays--;
else
preferenceChangeDelays++;
if (preferenceChangeDelays == 0) {
[adium.preferenceController informObserversOfChangedKey:nil inGroup:group object:object];
[self save];
}
}
#pragma mark Saving
- (void)performObjectPrefsSave:(NSTimer *)inTimer
{
NSDictionary *immutablePrefsToWrite = [[[NSDictionary alloc] initWithDictionary:inTimer.userInfo copyItems:YES] autorelease];
/* Data verification */
#ifdef PREFERENCE_CONTAINER_DEBUG
// {
// NSData *data = [NSData dataWithContentsOfFile:[adium.loginController.userDirectory stringByAppendingPathComponent:[globalPrefsName stringByAppendingPathExtension:@"plist"]]];
// NSString *errorString = nil;
// NSDictionary *theDict = [NSPropertyListSerialization propertyListFromData:data
// mutabilityOption:NSPropertyListMutableContainers
// format:NULL
// errorDescription:&errorString];
// if (theDict && [theDict count] > 0 && [immutablePrefsToWrite count] == 0)
// {
// NSLog(@"Writing out an empty ByObjectPrefs when we have an existing non-empty one!");
// *((int*)0xdeadbeef) = 42;
// }
// }
#endif
#warning figure this out
if ([immutablePrefsToWrite count] > 0) {
[immutablePrefsToWrite asyncWriteToPath:adium.loginController.userDirectory withName:globalPrefsName];
} else {
NSLog(@"Attempted to write an empty ByObject Prefs. Uh oh!");
*((int*)0xdeadbeef) = 42;
}
if (inTimer == timer_savingOfObjectCache) {
[timer_savingOfObjectCache release]; timer_savingOfObjectCache = nil;
} else if (inTimer == timer_savingOfAccountCache) {
[timer_savingOfAccountCache release]; timer_savingOfAccountCache = nil;
}
}
/*!
* @brief Save to disk
*/
- (void)save
{
if (object) {
//For an object's pref changes, batch all changes in a SAVE_OBJECT_PREFS_DELAY second period. We'll force an immediate save if Adium quits.
if (*myTimerForSavingGlobalPrefs) {
[*myTimerForSavingGlobalPrefs setFireDate:[NSDate dateWithTimeIntervalSinceNow:SAVE_OBJECT_PREFS_DELAY]];
} else {
#ifdef PREFERENCE_CONTAINER_DEBUG
// This shouldn't be happening at all.
if (!*myGlobalPrefs) {
NSLog(@"Attempted to detach to save for %@ [%@], but info was nil.", self, globalPrefsName);
AILogWithSignature(@"Attempted to detach to save for %@ [%@], but info was nil.", self, globalPrefsName);
}
#endif
*myTimerForSavingGlobalPrefs = [[NSTimer scheduledTimerWithTimeInterval:SAVE_OBJECT_PREFS_DELAY
target:self
selector:@selector(performObjectPrefsSave:)
userInfo:*myGlobalPrefs
repeats:NO] retain];
}
} else {
//Save the preference change immediately
[self.prefs writeToPath:adium.loginController.userDirectory withName:group];
}
}
- (void)setGroup:(NSString *)inGroup
{
if (group != inGroup) {
[group release];
group = [inGroup retain];
}
}
#pragma mark Debug
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@ %p: Group %@, object %@>", NSStringFromClass([self class]), self, group, object];
}
@end
|