📄 drcontroller.m
字号:
#import <Foundation/Foundation.h>#import <AppKit/AppKit.h>#import <stdio.h>#import <mach/mach.h>#import <servers/bootstrap.h>#include <unistd.h>#import "DRController.h"#import "ConversionJob.h"#import "NSFileManager-Extensions.h"#import "DragFromWell.h"// the first part of this file contains the routines needed to ask another Cocoa app// to do something. In this case, we ask PStill to convert a PostScript file into PDF.#define PStillFilterServer ([NSString \ stringWithFormat:@"PStillFilterServer-%@",\ [[NSProcessInfo processInfo] hostName]])@protocol PStillVended// 0 = succes anything else = failure// caller's responsibility to make sure outputFile is writeable and not// existing!- (int)convertFile:(NSString *)inputFile toPDFFile:(NSString *)outputFile deleteInput:(BOOL)deleteInput;// you can also convert many files to one single PDF with this one:- (int)convertFiles:(NSArray *)fullPathsToFiles toPDFFile:(NSString *)outputFile deleteInput:(BOOL)deleteInput;// when licensing is done, this will return YES, otherwise NO- (BOOL)applicationReadyForInput;// for jobs to show a preview from a thread- (void) showImageFile:(NSString *)file width:(int)width height:(int)height isEPS:(BOOL)isEPS rotation:(int)rotation pageNumber:(int)pageNumber;@end#define USAGE NSLog(@"This Print Filter requires PStill for Mac OS X by Stone Design and Frank Siegert. Visit www.stone.com to download and full information.")#define WAKE_UP_WAIT 5static id<PStillVended> lookupPStillDOServer(void) { port_t sendMachPort; NSDistantObject *rootProxy = nil; id<PStillVended> result; // First, try look up PStill;s DO object in the bootstrap server. // This is where the app registers it by default. if ((BOOTSTRAP_SUCCESS == bootstrap_look_up(bootstrap_port, (char *)([PStillFilterServer cString]), &sendMachPort)) && (PORT_NULL != sendMachPort)) { NSConnection *conn = [NSConnection connectionWithReceivePort: [NSPort port] sendPort:[NSMachPort portWithMachPort:sendMachPort]]; rootProxy = [conn rootProxy]; } // If the previous call failed, the following might succeed if the user // logged in is running Terminal with the PublicDOServices user default // set. if (!rootProxy) { rootProxy = [NSConnection rootProxyForConnectionWithRegisteredName: PStillFilterServer host:@""]; } // We could also try to launch PStill at this point, using // the NSWorkspace protocol. if (!rootProxy) { if (![[NSWorkspace sharedWorkspace] launchApplication:@"PStill"]) { USAGE; return nil; } sleep(WAKE_UP_WAIT); rootProxy = [NSConnection rootProxyForConnectionWithRegisteredName:PStillFilterServer host:@""]; } if (!rootProxy) { fprintf(stderr,"Can't connect to PStill\n"); return nil; } [rootProxy setProtocolForProxy:@protocol(PStillVended)]; result = (id<PStillVended>)rootProxy; return result;}BOOL convertFiles(NSArray *inputFiles, NSString *outputFile) { id<PStillVended> theProxy = lookupPStillDOServer(); // if we can't find it, bail: if (theProxy != nil) { // if she's not launched, we wait until she's licensed or they // give up on licensing: while (![theProxy applicationReadyForInput]) { [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; } if (([inputFiles count]==1 && [theProxy convertFile:[inputFiles objectAtIndex:0] toPDFFile:outputFile deleteInput:NO] == 0)) { return YES; } else if ([theProxy convertFiles:inputFiles toPDFFile:outputFile deleteInput:NO]) { return YES; } else { NSLog(@"Couldn't convert %@",[inputFiles objectAtIndex:0]); } } else { NSLog(@"Couldn't connect to PStill"); } return NO;}@implementation DRController// Launching a URL in the user's favorite browser is this simple in Cocoa:- (IBAction)gotoStoneSite:(id)sender { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.stone.com/"]];}- (IBAction)showDOCtorSourceAction:(id)sender { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.stone.com/DOCtor/"]];}// when the Application launches, set the state of the interface to match the user's preferences:- (void)awakeFromNib { [openInCreateSwitch setState:![[NSUserDefaults standardUserDefaults] boolForKey:@"DontOpenInCreate"]];}- (IBAction)changeOpenInCreateAction:(id)sender;{ [[NSUserDefaults standardUserDefaults] setBool:![openInCreateSwitch state] forKey:@"DontOpenInCreate"];}- (IBAction)showGPLAction:(id)sender {// In Interface Builder, you can set the identifier on each tab view// this allows you to programmatically select a given Tab: [tabView selectTabViewItemWithIdentifier:@"GPL"]; // Don't forget to order the window front in case it's hidden: [[tabView window] makeKeyAndOrderFront:self];}- (void)revealInFinder:(NSString *)path { BOOL isDir; if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) { if (isDir) [[NSWorkspace sharedWorkspace] selectFile:nil inFileViewerRootedAtPath:path]; else [[NSWorkspace sharedWorkspace] selectFile:path inFileViewerRootedAtPath:nil]; }}- (IBAction)showSourceAction:(id)sender { NSString *antiword = [[[NSBundle mainBundle]pathForResource:@"antiword" ofType:@""]stringByAppendingPathComponent:@"antiword.0.32.tar.gz"]; [self revealInFinder:antiword]; }- (IBAction)toggleDrawer:(id)sender { if ([drawer state]== NSDrawerClosedState) [drawer openOnEdge:NSMinYEdge]; else if ([drawer state] == NSDrawerOpenState) [drawer close:nil];}- (IBAction)showLogAction:(id)sender { [[textLogView window] makeKeyAndOrderFront:self];}// drag & drop routines// a standard way to name output files, based on an input name:- (NSString *)safeFileName:(NSString *)input { NSString *truncString = [NSString stringWithFormat:@"%C",138]; NSRange r = [input rangeOfString:truncString]; if (r.length) { return ([NSString stringWithFormat:@"%@-%@", [input substringToIndex:r.location],[input substringFromIndex:r.location + r.length]]); } return input;}- (NSString *)fileForInput:(NSString *)docFile extension:(NSString *)extension { NSFileManager *fm = [NSFileManager defaultManager]; NSString *safe = [self safeFileName:[docFile lastPathComponent]]; return [fm nextUniqueNameUsing:[[fm temporaryDirectory] stringByAppendingPathComponent:[[safe stringByDeletingPathExtension]stringByAppendingPathExtension:extension]]];}- (NSString *)psFileForDocFile:docFile { return [self fileForInput:docFile extension:@"ps"];}- (NSString *)pdfFileForDocFile:docFile { return [self fileForInput:docFile extension:@"pdf"];}- (BOOL)convertFile:(NSString *)docFile toFile:(NSString *)psFile { // call antiword with a ConversionJob instance: ConversionJob *job = [[ConversionJob allocWithZone:[self zone]] initWithInputFile:(NSString *)docFile outputFile:(NSString *)psFile landscape:[portraitLandscapeMatrix selectedTag] paperName:[paperSizePopUp titleOfSelectedItem]]; // pending : QUEUES // we may go threaded later... return [job doExecution:self];}- (BOOL)openFile:(NSString *)pdfFile { NSWorkspace *wm = [NSWorkspace sharedWorkspace]; if (([[NSUserDefaults standardUserDefaults] boolForKey:@"DontOpenInCreate"]) || ![wm openFile:pdfFile withApplication:@"Create" andDeactivate:YES]) { return [wm openFile:pdfFile]; } return NO;}// Ask PStill to do convert the file:- (BOOL)pstillConvert:(NSString *)ps toFile:(NSString *)pdf { return convertFiles([NSArray arrayWithObject:ps], pdf);}// Once the job finishes, this is called - let's give the user some feedback:- (void)taskTerminated:(BOOL)success outputFile:(NSString *)outpout { if (success) { NSString *pdfFile = [self pdfFileForDocFile:outpout]; [well setFile:outpout]; [statusField setStringValue:@"Success - click image to reveal in Finder"]; // We have a valid PS file - let's begin the next step of translation to PDF: if ([self pstillConvert:outpout toFile:pdfFile]) { // success! Let's give some feedback and open the file: [well setFile:pdfFile]; [self openFile:pdfFile]; } else { [statusField setStringValue:@"PStill had trouble - see PStill's Log"]; } } else { [well setFile:@""]; [statusField setStringValue:@"Converted failed - see Log!"]; }}- (id)logText { return textLogView;}- (BOOL)convertAndOpenFile:(NSString *)docFile { NSString *psFile = [self psFileForDocFile:docFile]; [self convertFile:docFile toFile:psFile]; return YES;}// In order for your app to open files that are dragged upon the dock tile, you need to do two things// 1. Implement - application: openFile: in your NSApplications's delegate class// 2. In PB, specify valid Document Types in Target inspector, Application settings- (BOOL)application:(NSApplication *)sender openFile:(NSString *)path{ return [self convertAndOpenFile:path];}#define OK_VERSION_TITLE NSLocalizedStringFromTable(@"Your Software is up-to-date",@"DOC",@"title of software is up to date alert")#define OK_VERSION_MSG NSLocalizedStringFromTable(@"You have the most recent version of %@.", @"DOC",@"message of software is up to date alert")#define NEW_VERSION_TITLE NSLocalizedStringFromTable(@"A New Version is Available",@"DOC",@"title of software is NOT up to date alert")#define NEW_VERSION_MSG NSLocalizedStringFromTable(@"A new version of %@ is available (version %@). Would you like to download the new version now?", @"DOC",@"message of software is NOT up to date message")#define OK NSLocalizedStringFromTable(@"OK",@"DOC",@"ok")#define CANCEL NSLocalizedStringFromTable(@"Cancel",@"DOC",@"cancel")#define NO_NET_TITLE NSLocalizedStringFromTable(@"No network connection", @"DOC", @"title of no network alert")#define NO_NET_MSG NSLocalizedStringFromTable(@"Try again later when your computer is connected to the Internet.", @"DOC", @"message when no network connection available")- (void)checkForNewVersion:(id)sender{ NSString *currVersionNumber = [[[NSBundle bundleForClass:[self class]] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; NSURL *url = [NSURL URLWithString:@"http://www.stone.com/versionlist.xml"]; NSDictionary *productVersionDict = [NSDictionary dictionaryWithContentsOfURL:url]; NSString *appName = [[NSProcessInfo processInfo] processName]; NSString *latestVersionNumber = [productVersionDict valueForKey:appName]; if (url == nil) { NSRunAlertPanel(NO_NET_TITLE,NO_NET_MSG,OK, nil,nil); } else { if([latestVersionNumber isEqualTo: currVersionNumber]) { // tell user software is up to date NSRunAlertPanel(OK_VERSION_TITLE,OK_VERSION_MSG,OK, nil,nil,appName); } else { // tell user to download a new version int button = NSRunAlertPanel(NEW_VERSION_TITLE,NEW_VERSION_MSG, OK, CANCEL, nil,appName,latestVersionNumber); if(NSOKButton == button) { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.stone.com/NewDownload.html#DOCtor"]]; } } }}@end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -