// // AppDelegate.m // Perforce // // Created by Adam Czubernat on 07.05.2013. // Copyright (c) 2013 Perforce Software, Inc. All rights reserved. // #import "AppDelegate.h" #import "P4Workspace.h" #import "P4Defaults.h" #import "P4WorkspaceDefaults.h" #import "MainWindowController.h" @interface AppDelegate () { MainWindowController *windowController; SEL launchAction; id launchObject; BOOL loggingIn; } - (void)automaticLogin; - (void)showLoginPanel; - (void)loadWorkspace; - (void)performWorkspaceAction:(SEL)selector withObject:(id)object; - (void)handleOpenEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent; - (void)handleServices:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error; @end @implementation AppDelegate - (void)applicationWillFinishLaunching:(NSNotification *)notification { // Set URL handler NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager]; [appleEventManager setEventHandler:self andSelector:@selector(handleOpenEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL]; // Register as default URL scheme handler CFStringRef bundleID = (__bridge CFStringRef)[[NSBundle mainBundle] bundleIdentifier]; LSSetDefaultHandlerForURLScheme((__bridge CFStringRef)@"p4", bundleID); } - (void)applicationDidFinishLaunching:(NSNotification *)notification { // Check if launched as service NSAppleEventDescriptor *event = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent]; BOOL launchedAsService = [event eventID] == kAEOpenApplication && [[event paramDescriptorForKeyword:keyAEPropData] enumCodeValue] == keyAELaunchedAsServiceItem; // Update services [NSApp setServicesProvider:self]; NSUpdateDynamicServices(); // Set the exception handler PSDebugInstallCrashHandler(); // Log app info NSDictionary *info = [[NSBundle mainBundle] infoDictionary]; NSString *appName = [info objectForKey:@"CFBundleExecutable"]; NSString *appVersion = [info objectForKey:@"CFBundleShortVersionString"]; NSString *appBuild = [info objectForKey:@"CFBundleVersion"]; NSString *appBuildDate = [info objectForKey:@"BuildDate"]; PSLogStore(@"AppVersion", @"%@ v%@ (%@)", appName, appVersion, appBuild); PSLogStore(@"BuildDate", @"%@", appBuildDate); // Load default values [NSUserDefaults loadDefaultsWithName:@"UserDefaults"]; NSString *lastWorkspace = [P4Defaults sharedInstance].workspace; windowController = [[MainWindowController alloc] init]; // Check if show window if (launchedAsService) { PSLog(@"Launching with service"); [windowController window]; } else { PSLog(@"Launching normally"); [windowController showWindow:nil]; } if (lastWorkspace.length) { [self automaticLogin]; if ([windowController.window isVisible]) [windowController showLoading:@"Connecting..."]; } else { [windowController showWindow:nil]; [self showLoginPanel]; } } //- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { // return YES; //} - (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)windows { if (!windows) { [windowController showWindow:self]; if (loggingIn) [windowController showLoading:@"Connecting..."]; } return YES; } #pragma mark - Private - (void)automaticLogin { PSLog(@"Automatic login..."); loggingIn = YES; P4Credentials *credentials = [[P4Credentials alloc] init]; credentials.username = [P4Defaults sharedInstance].username; credentials.address = [P4Defaults sharedInstance].host; credentials.resumeSession = YES; // Connect to host [[P4Workspace sharedInstance] connectWithCredentials:credentials response:^(P4Operation *operation, NSArray *response) { if (operation.errors) { PSLog(@"Failed to connect"); [self showLoginPanel]; return; } // Try login last session [[P4Workspace sharedInstance] loginWithCredentials:credentials response:^(P4Operation *operation, NSArray *response) { if (operation.errors) { PSLog(@"Failed logging-in using last session"); PSLog(@"Automatic login using SSO..."); // Try SSO login [[P4Workspace sharedInstance] loginWithSSO:credentials response:^(P4Operation *operation, NSArray *response) { if (operation.errors) { PSLog(@"Failed to login using SSO"); [self showLoginPanel]; return; } PSLog(@"Logged-in using SSO"); [self loadWorkspace]; }]; return; } PSLog(@"Logged-in using last session"); [self loadWorkspace]; }]; }]; } - (void)showLoginPanel { loggingIn = NO; [windowController dismissLoading]; if (![windowController.window isVisible]) [windowController showWindow:nil]; [windowController connect:nil]; } - (void)loadWorkspace { NSString *workspace = [P4Defaults sharedInstance].workspace; [[P4Workspace sharedInstance] setWorkspace:workspace response:^(P4Operation *operation, NSArray *response) { loggingIn = NO; [windowController dismissLoading]; if (operation.errors) { PSLog(@"Couldn't use last workspace %@", workspace); [self showLoginPanel]; [windowController showWorkspaceSelection:nil]; } else { PSLog(@"Connected to last workspace: %@", workspace); PSLogStore(@"Workspace info", @"%@", response); // Save last workspace details [P4WorkspaceDefaults setWorkspace:workspace]; [windowController reload]; if (launchAction != @selector(openFile:)) [windowController loadPath:@"//"]; // Perform dispatched service action if (launchAction) { PSLog(@"Service: dispatched action -%@ %@", NSStringFromSelector(launchAction), launchObject); [windowController performSelectorOnMainThread:launchAction withObject:launchObject waitUntilDone:NO]; launchAction = nil; launchObject = nil; } } }]; } - (void)performWorkspaceAction:(SEL)selector withObject:(id)object { if ([[P4Workspace sharedInstance] isLoggedIn] && [[P4Workspace sharedInstance] workspace]) { PSLog(@"Service: action -%@ %@", NSStringFromSelector(selector), object); [windowController performSelectorOnMainThread:selector withObject:object waitUntilDone:NO]; } else { launchAction = selector; launchObject = object; } } #pragma mark - URL Event handler - (void)handleOpenEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent { NSString *url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; PSLog(@"Opening external URL:\n%@", url); [self performWorkspaceAction:@selector(openFile:) withObject:url]; } - (void)handleServices:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString *__autoreleasing *)error { PSLog(@"Service: %@", userData); NSArray *files = nil; if ([[pboard types] containsObject:NSFilenamesPboardType]){ files = [pboard propertyListForType:NSFilenamesPboardType]; } else if ([userData hasPrefix:@"com.adobe.illustrator"]) { NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource: @"tell application id \"com.adobe.illustrator\"\n" "set theFilePath to file path of front document\n" "end tell"]; NSDictionary *errorDict = nil; NSAppleEventDescriptor *descriptor = [appleScript executeAndReturnError:&errorDict]; NSURL *url = [NSURL URLWithString:[descriptor stringValue]]; NSString *path = [url path]; if(path) { files = [NSArray arrayWithObject:path]; } else { files = [NSArray array]; } if (!files.count) { PSLog(@"Error > Failed to run illustrator script %@\n%@", userData, errorDict); [windowController showErrors:@[ [NSError errorWithFormat:@"Failed to run illustrator script %@\n%@.\nIllustrator failed to return \nCheck if your file name contains illegal characters.", userData, errorDict] ]]; } } if (!files.count) return PSLog(@"Error > Failed to retrieve urls from service %@ %@", userData, pboard); // Parse urls if ([userData hasPrefix:@"com.apple.finder.folder"]) { // Add '/' to directory paths files = [files valueForKey:@"directoryPath"]; } if ([userData hasPrefix:@"com.apple.finder.symlink"]) { // Resolve symlinks files = [files arrayUsingBlock:^id(NSString *file, NSUInteger idx) { NSURL *url = [NSURL fileURLWithPath:file]; NSNumber *isSymlink = nil; [url getResourceValue:&isSymlink forKey:NSURLIsSymbolicLinkKey error:NULL]; if (isSymlink.boolValue) { NSString *dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath:url.path error:NULL]; url = [NSURL fileURLWithPath:dest]; } NSNumber *isDir = nil; [url getResourceValue:&isDir forKey:NSURLIsDirectoryKey error:NULL]; if (isDir.boolValue) return [url.path directoryPath]; return url.path; }]; } if ([userData hasSuffix:@"edit"]) [self performWorkspaceAction:[files.firstObject hasSuffix:@"/"] ? @selector(editAllFiles:) : @selector(editFiles:) withObject:files]; else if ([userData hasSuffix:@"submit"]) [self performWorkspaceAction:[files.firstObject hasSuffix:@"/"] ? @selector(submitAllFiles:) : @selector(submitFiles:) withObject:files]; else if ([userData hasSuffix:@"open"]) [self performWorkspaceAction:@selector(openFile:) withObject:files.firstObject]; else PSLog(@"Error > Unrecognized service %@", userData); } @end