Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 486 lines (377 sloc) 15.779 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
//
// IGKLaunchController.m
// Ingredients
//
// Created by Alex Gordon on 10/02/2010.
// Written in 2010 by Fileability.
//

#import "IGKLaunchController.h"
#import "IGKScraper.h"
#import "IGKApplicationDelegate.h"
#import "IGKWordMembership.h"
#import "FUCoreDataStore.h"

@interface IGKLaunchController ()

- (void)addDocsetsInPath:(NSString *)docsets toArray:(NSMutableArray *)docsetPaths set:(NSMutableSet *)docsetsSet developerDirectory:(NSString *)devDir;
- (void)stopIndexing;
- (void)finishedLoading;

@end


@implementation IGKLaunchController

@synthesize appController;

- (NSString *)checkForOrSetDeveloperDirectory
{
//Check /Developer exists
BOOL rootDevExists = [[NSFileManager defaultManager] fileExistsAtPath:@"/Developer"];
if (rootDevExists)
return @"/Developer";

//Otherwise, ask the user to point us to their developer directory
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setTitle:@"Choose developer directory"];
[openPanel setMessage:@"Please choose a developer directory."];
[openPanel setCanChooseFiles:NO];
[openPanel setCanChooseDirectories:YES];

NSInteger result = [openPanel runModal];

if (result != NSFileHandlingPanelOKButton)
{
//If they clicked cancel, make do with what we have (if anything)
return nil;
}

NSString *path = [[openPanel URL] path];

//Sanity check path. If it really is a Developer directory, it should have a Library/version.plist
NSString *versionPlistPath = [path stringByAppendingPathComponent:@"Library/version.plist"];
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:versionPlistPath];
if (!exists)
{
return nil;
}

//Seems legit
return path;
}

- (void)applyDeveloperDirectory:(NSString *)devPath
{
[[NSClassFromString(@"IGKPreferencesController") sharedPreferencesController] addDeveloperDirectoryPath:devPath];
}
- (NSArray *)developerDirectoryDescriptionsFromDefaults
{
return [[NSUserDefaults standardUserDefaults] valueForKey:@"developerDirectories"];
}

- (void)saveDocsetPrefs
{
[[NSClassFromString(@"IGKPreferencesController") sharedPreferencesController] saveChanges];
[[NSClassFromString(@"IGKPreferencesController") sharedPreferencesController] reloadTableViews];
}

- (BOOL)launch
{
NSMutableSet *docsetPathsSet = [[NSMutableSet alloc] init];
NSMutableArray *docsetPaths = [[NSMutableArray alloc] init];

//Alloc/Init a shared instance if needed
[NSClassFromString(@"IGKPreferencesController") sharedPreferencesController];

if ([[self developerDirectoryDescriptionsFromDefaults] count] == 0)
{
//First we have to make sure we have a developer directory
NSString *devdir = [self checkForOrSetDeveloperDirectory];

if (!devdir)
return NO;

//Save the new dev directory into preferences
[self applyDeveloperDirectory:devdir];
}

for (NSString *sharedPath in NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSAllDomainsMask, YES))
{
NSString *docsetSharedPath = [sharedPath stringByAppendingPathComponent:@"Developer/Shared/Documentation/DocSets"];
if ([[NSFileManager defaultManager] fileExistsAtPath:docsetSharedPath])
{
[self addDocsetsInPath:docsetSharedPath
toArray:docsetPaths
set:docsetPathsSet
developerDirectory:@"Shared"];
}
        
        docsetSharedPath = [sharedPath stringByAppendingPathComponent:@"Developer/Documentation/DocSets"];
if ([[NSFileManager defaultManager] fileExistsAtPath:docsetSharedPath])
{
[self addDocsetsInPath:docsetSharedPath
toArray:docsetPaths
set:docsetPathsSet
developerDirectory:@"Shared"];
}
}


for (NSDictionary *description in [self developerDirectoryDescriptionsFromDefaults])
{
NSString *devdir = [description valueForKey:@"path"];

if (![[NSFileManager defaultManager] fileExistsAtPath:devdir])
continue;

//Sanity check path. If it really is a Developer directory, it should have a Library/version.plist
NSString *versionPlistPath = [devdir stringByAppendingPathComponent:@"Library/version.plist"];
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:versionPlistPath];
if (!exists)
continue;



//Add the default documentation
[self addDocsetsInPath:[devdir stringByAppendingPathComponent:@"/Documentation/DocSets/"]
toArray:docsetPaths
set:docsetPathsSet
developerDirectory:devdir];

NSString *platformsPath = [devdir stringByAppendingPathComponent:@"/Platforms/"];
NSError *error = nil;
NSArray *platforms = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:platformsPath error:&error];
if (!error)
{
for (NSString *platform in platforms)
{
NSString *platformPath = [platformsPath stringByAppendingPathComponent:platform];
NSString *platformDocsetsPath = [platformPath stringByAppendingPathComponent:@"/Developer/Documentation/DocSets"];

[self addDocsetsInPath:platformDocsetsPath
toArray:docsetPaths
set:docsetPathsSet
developerDirectory:devdir];
}
}
}

/*
[self addDocsetsInPath:@"/Library/Developer/Shared/Documentation/DocSets/"
toArray:docsetPaths
set:docsetPathsSet
developerDirectory:@"Other"];
*/

dbQueue = dispatch_get_main_queue();

totalPathsCount = 0;

scrapers = [[NSMutableArray alloc] init];


BOOL areValidScrapers = NO;
for (NSDictionary *container in docsetPaths)
{
NSString *devDir = [container valueForKey:@"developerDirectory"];

for (NSString *docsetPath in [container valueForKey:@"docsetPaths"])
{
IGKScraper *scraper = [[IGKScraper alloc] initWithDocsetURL:[NSURL fileURLWithPath:docsetPath]
managedObjectContext:[appController backgroundManagedObjectContext]
launchController:self
dbQueue:dbQueue
developerDirectory:devDir];
if ([scraper findPaths])
{
areValidScrapers = YES;
pathReportsExpected++;
[scrapers addObject:scraper];
}
}
}

//If there's nothing to scrape
if (areValidScrapers == NO || ![scrapers count])
{
[self saveDocsetPrefs];
return NO;
}

[[NSNotificationCenter defaultCenter] postNotificationName:@"IGKWillIndexedPaths" object:self];

for (IGKScraper *scraper in scrapers)
{
[scraper findPathCount];
}

[self saveDocsetPrefs];
return YES;
}

- (void)reportPathCount:(NSUInteger)pathCount
{
pathReportsReceived += 1;
totalPathsCount += pathCount;

NSLog(@"Getting path report: %d / %d", pathCount, totalPathsCount);

//If we're still expecting paths, return for now
if (pathReportsReceived < pathReportsExpected)
return;

if (totalPathsCount == 0)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[self stopIndexing];
});

return;
}

//Otherwise send the path count
NSLog(@"## Total number of paths: %d", totalPathsCount);
for (IGKScraper *scraper in scrapers)
{
[scraper index];
}
}

//This will be called from the main thread
- (void)reportPath
{
pathsCounter++;

if (pathsCounter >= totalPathsCount)
{
NSLog(@"Saving %@", [appController backgroundManagedObjectContext]);

//[[NSNotificationCenter defaultCenter] postNotificationName:@"IGKWillSaveIndex" object:self];

[self performSelector:@selector(saveDatabaseAndStopIndexing) withObject:nil afterDelay:1.0];
}
else
{
//A new path

//There's around 200 pixels in the progress bar. We only want to send a notification for each one
if ((pathsCounter % ((totalPathsCount / 100) ?: 1)) == 0)
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"IGKHasIndexedNewPaths" object:self];
}
}
}
- (void)saveDatabaseAndStopIndexing
{
//Save our changes
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

[[appController backgroundManagedObjectContext] save:nil];
[[appController backgroundManagedObjectContext] reset];

[self stopIndexing];
});
}
- (void)stopIndexing
{
//Save our changes
[self finishedLoading];

dispatch_async(dispatch_get_main_queue(), ^{

//All paths have been reported
[[NSNotificationCenter defaultCenter] postNotificationName:@"IGKHasIndexedAllPaths" object:self];
        
        [self showFoundNoPathsError];
    });
}
- (void)showFoundNoPathsError
{
    /*
NSEntityDescription *docRecordEntity = [NSEntityDescription entityForName:@"DocRecord" inManagedObjectContext:[appController managedObjectContext]];
NSFetchRequest *fetchEverything = [[NSFetchRequest alloc] init];
[fetchEverything setEntity:docRecordEntity];
[fetchEverything setFetchLimit:20];
*/
    
    NSManagedObjectContext *ctx = [appController managedObjectContext];
dispatch_queue_t queue = [appController backgroundQueue];

if (!queue)
return;
/*
dispatch_sync(queue, ^{
//Oh god, Core Data was *NOT* meant to be used like this
NSEntityDescription *docRecordEntity = [NSEntityDescription entityForName:@"DocRecord" inManagedObjectContext:ctx];
NSPropertyDescription *nameProperty = [[docRecordEntity propertiesByName] valueForKey:@"name"];
NSFetchRequest *fetchEverything = [[NSFetchRequest alloc] init];
[fetchEverything setEntity:docRecordEntity];
[fetchEverything setResultType:NSDictionaryResultType];
[fetchEverything setReturnsDistinctResults:YES];
[fetchEverything setPropertiesToFetch:[NSArray arrayWithObject:nameProperty]];
//NSArray *objects = [ctx executeFetchRequest:fetchEverything error:nil];
//NSLog(@"All names: %d", [objects count]);
NSUInteger c = [ctx countForFetchRequest:fetchEverything error:nil];
if (c < 10)
{
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Ingredients could not find any documentation to index."];
[alert setInformativeText:@"This is usually because Xcode has not downloaded documentation. Try going to Xcode's Documentation preferences and making sure the docsets you want have been downloaded.\n\nThis can also happen if you're using a newly released version of Xcode and Ingredients has not yet been updated to support it."];
[alert addButtonWithTitle:@"Quit"];
NSInteger answer = [alert runModal];
NSString *appSupportPath = [@"~/Library/Application Support/Ingredients/" stringByExpandingTildeInPath];
[[NSFileManager defaultManager] removeItemAtPath:appSupportPath error:nil];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"docsets"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"ShutdownBad"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"storeVersion"];
[[NSUserDefaults standardUserDefaults] synchronize];
[NSApp terminate:nil];
}
});*/
}

- (void)finishedLoading
{
NSManagedObjectContext *ctx = [appController backgroundManagedObjectContext];
dispatch_queue_t queue = [appController backgroundQueue];
NSLog(@"FINISHED LOADING: %d", queue);
if (!queue)
return;

dispatch_async(queue, ^{

//Oh god, Core Data was *NOT* meant to be used like this
NSEntityDescription *docRecordEntity = [NSEntityDescription entityForName:@"DocRecord" inManagedObjectContext:ctx];
NSPropertyDescription *nameProperty = [[docRecordEntity propertiesByName] valueForKey:@"name"];

NSFetchRequest *fetchEverything = [[NSFetchRequest alloc] init];
[fetchEverything setEntity:docRecordEntity];
[fetchEverything setResultType:NSDictionaryResultType];
[fetchEverything setReturnsDistinctResults:YES];
[fetchEverything setPropertiesToFetch:[NSArray arrayWithObject:nameProperty]];


id fu = [ctx fffffffuuuuuuuuuuuu];

[[fu database] executeUpdate:@"CREATE INDEX IF NOT EXISTS fileability_docrecord_name ON ZDOCRECORD (ZNAME COLLATE NOCASE)"];

FMResultSet *rset = [[fu database] executeQuery:@"SELECT DISTINCT ZNAME FROM ZDOCRECORD" withArgumentsInArray:[NSArray array]];
//id objects = [fu magicObjectsForResultSet:rset];

NSMutableArray *names = [[NSMutableArray alloc] init];
while ([rset next])
{
id name = [rset stringForColumnIndex:0];
if (name)
[names addObject:name];
}


[rset close];
/*
NSArray *objects = [ctx executeFetchRequest:fetchEverything error:nil];
*/
NSLog(@"[names count] = %d", [names count]);
        if ([names count] < 10)
        {
            dispatch_sync(dispatch_get_main_queue(), ^(void) {
            
                NSAlert *alert = [[NSAlert alloc] init];
                [alert setMessageText:@"Ingredients could not find any documentation to index."];
                [alert setInformativeText:@"This is usually because Xcode has not downloaded documentation. Try going to Xcode's Documentation preferences and making sure the docsets you want have been downloaded.\n\nThis can also happen if you're using a newly released version of Xcode and Ingredients has not yet been updated to support it."];
                [alert addButtonWithTitle:@"Quit"];
                
                NSInteger answer = [alert runModal];
                
                NSString *appSupportPath = [@"~/Library/Application Support/Ingredients/" stringByExpandingTildeInPath];
                /*
[[NSFileManager defaultManager] removeItemAtPath:appSupportPath error:nil];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"docsets"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"ShutdownBad"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"storeVersion"];
[[NSUserDefaults standardUserDefaults] synchronize];
*/
                [NSApp terminate:nil];
                    return;
            });
        }
                
NSLog(@"All names: %d", [names count]);

IGKWordMembership *wordMembershipManager = [IGKWordMembership sharedManagerWithCapacity:[names count]];
NSCharacterSet *uppercaseCharacters = [NSCharacterSet uppercaseLetterCharacterSet];
for (NSString *name in names)
{
if (![name length])
continue;

unichar firstLetter = [name characterAtIndex:0];

//To avoid littering the documents with links, we only want to include names that start with an uppercase letter
if (firstLetter < 'A' || firstLetter > 'Z')
continue;

[wordMembershipManager addWord:name];
}

NSLog(@"Unique uppercase names: %d", [[wordMembershipManager valueForKey:@"words"] count]);
});

}

- (double)fraction
{
return (double)pathsCounter / (double)totalPathsCount;
}

- (void)addDocsetsInPath:(NSString *)docsets toArray:(NSMutableArray *)docsetPaths set:(NSMutableSet *)docsetsSet developerDirectory:(NSString *)devDir
{
NSError *error = nil;
NSArray *paths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:docsets error:&error];
if (error)
return;

if (![paths count])
return;

NSMutableArray *docsetPathsArray = [[NSMutableArray alloc] initWithCapacity:[paths count]];

NSMutableDictionary *container = [[NSMutableDictionary alloc] init];
[container setValue:devDir forKey:@"developerDirectory"];
[container setValue:docsetPathsArray forKey:@"docsetPaths"];

for (NSString *path in paths)
{
if ([path isEqual:@"com.apple.ADC_Reference_Library.DeveloperTools.docset"])
continue;

path = [docsets stringByAppendingPathComponent:path];
if (![path length] || ![[path pathExtension] isEqual:@"docset"])
continue;

if ([docsetsSet containsObject:path])
continue;
        
[docsetPathsArray addObject:path];
[docsetsSet addObject:path];
}

if (![docsetPathsArray count])
return;

[docsetPaths addObject:container];
}

- (void)finalize
{
dispatch_release(dbQueue);
[super finalize];
}

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