/* # Created by Matteo Rattotti on 13/03/06. # Copyright (c) 2006 - 2008 Shiny Frog. All rights reserved. # Contact matteo.rattotti@shinyfrog.net for any problem # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or any later version. # This program 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 General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import "netFixerAppDelegate.h" #import #import "webImpressor.h" @implementation netFixerAppDelegate - (void)applicationWillFinishLaunching:(NSNotification *)aNotification{ /* Setting base extension */ extension = @".png"; /* Setting delegate for event GetUrl when someone click on protocol netfixer: */ [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL]; /* Making fake window */ NSRect rect = NSMakeRect(-16000,-16000,100,100); NSWindow *win = [NSWindow alloc]; [win initWithContentRect:rect styleMask:NSBorderlessWindowMask backing:2 defer:0]; /* Making webView */ wb = [[WebView alloc]initWithFrame:rect]; [[[wb mainFrame] frameView] setAllowsScrolling:NO]; /* Adding webView to fake window */ [win setContentView:wb]; /* Setting delegar for loading frame */ loadDelegate = [[webImpressor alloc]init]; [wb setFrameLoadDelegate:loadDelegate]; /*Passing the well for stopping it when the impressor has finished*/ [loadDelegate setProgWell:progWell]; } - (void)awakeFromNib{ [self loadPref]; /* Adding toolbar to the windows */ [self addToolbar:mainWin]; /*Updating slider value*/ [delayField setStringValue: [NSString stringWithFormat:@"%i", [delaySlider intValue]]]; /*Updating export path value*/ if([self savePathValue] != nil){ [savePathField setStringValue:[self savePathValue]]; } } - (void)loadUrl:(NSString *)url{ NSMutableString* urlmod = [NSMutableString stringWithString:url]; [urlmod replaceOccurrencesOfString:@" " withString:@"" options:nil range:NSMakeRange(0, [url length])]; /* load url and save image ;) */ [[wb mainFrame]loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlmod]]]; } - (IBAction)shotIt:(id)sender{ /* Getting url to be shooted*/ NSString *url = [adrField stringValue]; /*cutIndex for exact matched Filename creation, start after (http://) for default*/ int cutIndex = 7; if([url isEqualToString:@""] == 1){ /* Error if someone try to shot without fill url field*/ NSAlert *a = [NSAlert alertWithMessageText:@"Please insert a website URL!" defaultButton:@"ok" alternateButton:nil otherButton:nil informativeTextWithFormat:@""]; [a runModal]; return; } else if([url hasPrefix:@"/"] == 1){ url = [@"file:///" stringByAppendingString:url]; cutIndex = 9; } else if([url hasPrefix:@"file:///"] == 1 && [url hasPrefix:@"file:////"] != 1){ NSMutableString *tmpUrl = [NSMutableString stringWithString:[url substringFromIndex:8]]; url = [@"file:////" stringByAppendingString:tmpUrl]; cutIndex = 9; } else if([url hasPrefix:@"file:////"] == 1 && [url hasPrefix:@"file://///"] != 1){ NSMutableString *tmpUrl = [NSMutableString stringWithString:[url substringFromIndex:9]]; url = [@"file:////" stringByAppendingString:tmpUrl]; cutIndex = 9; } //Last case, it is a common website else if([url hasPrefix:@"http://"] != 1){ url = [@"http://" stringByAppendingString:url]; } /* /* Filename creation */ NSMutableString* filename = [NSMutableString stringWithString:[url substringFromIndex:cutIndex]]; [filename replaceOccurrencesOfString:@"/" withString:@"." options:nil range:NSMakeRange(0, [url length] - cutIndex)]; /* Base name for the shot */ NSString* basename = [filename stringByAppendingString:extension]; int res; NSString *exportPath; if(![self savePathValue] == nil){ exportPath = [[[self savePathValue] stringByAppendingString:@"/"]stringByAppendingString: basename]; res = 1; } else{ /* NSSave panel for output */ NSSavePanel* sp = [NSSavePanel savePanel]; [sp setCanCreateDirectories:1]; [sp setMessage:@"Where to save the shotted site?"]; res = [sp runModalForDirectory:@"~/" file: basename]; if (res == 1){ exportPath = [sp filename]; } } if (res == 1){ /*Starting well*/ [progWell startAnimation:self]; /* Setting output filename */ [loadDelegate setFileName:exportPath]; /* Loading url in wb*/ [self loadUrl:url]; } /*End of save panel*/ } - (void)changeTab:(id)sender{ if([[sender label]isEqualToString:@"Shoot it!"]){ [tabView selectTabViewItemAtIndex:0]; } else if ([[sender label]isEqualToString:@"Settings!"]){ [tabView selectTabViewItemAtIndex:1]; } } - (IBAction)setFormat:(id)sender{ NSString* format = [sender titleOfSelectedItem]; if([format isEqualToString:@"png"]){[loadDelegate setFormat: NSPNGFileType];extension = @".png";} else if([format isEqualToString:@"jpg"]){[loadDelegate setFormat: NSJPEGFileType]; extension = @".jpg";} else if([format isEqualToString:@"tiff"]){[loadDelegate setFormat: NSTIFFFileType];extension = @".tif";} else if([format isEqualToString:@"gif"]){[loadDelegate setFormat: NSGIFFileType];extension = @".gif";} else if([format isEqualToString:@"bmp"]){[loadDelegate setFormat: NSBMPFileType];extension = @".bmp";} } - (IBAction)setSize:(id)sender{ //NSString* size = [[sender selectedCell]title]; NSString* size = [sender titleOfSelectedItem]; NSArray* rectSize = [size componentsSeparatedByString:@"x"]; float width = [[rectSize objectAtIndex:0]floatValue]; float height = [[rectSize objectAtIndex:1]floatValue]; NSRect rect = NSMakeRect(0,0,width,height); NSSize csize = NSMakeSize(width, height); [loadDelegate setCanvas:rect canvasSize:csize]; } - (IBAction)setSavePath:(id)sender{ /* Creating open panel and setting prefs */ int result; NSOpenPanel *oPanel = [NSOpenPanel openPanel]; [oPanel setCanChooseFiles:NO]; [oPanel setCanChooseDirectories:YES]; [oPanel setCanCreateDirectories:YES]; [oPanel setAllowsMultipleSelection:NO]; /*end open panel setting*/ result = [oPanel runModalForDirectory:NSHomeDirectory() file:nil types:nil]; if (result == NSOKButton) { /* Getting directory target and stripping HOME path */ NSArray *filesToOpen = [oPanel filenames]; NSString* path = [filesToOpen objectAtIndex:0]; //NSRange home = [path rangeOfString:NSHomeDirectory()]; [savePathField setStringValue:path];//[path substringFromIndex:home.length+1]]; //[savePathField setToolTip:[path substringFromIndex:home.location]]; [[NSUserDefaults standardUserDefaults] setObject:[savePathField stringValue] forKey:@"netfixerExportPath"]; } } - (IBAction)unsetSavePath:(id)sender{ [savePathField setStringValue:@""]; [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"netfixerExportPath"]; } - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag { [mainWin makeKeyAndOrderFront:self]; return 1; } - (void)applicationWillTerminate:(NSNotification *)aNotification { [self savePref]; } #pragma mark Preferences - (void)savePref{ int size = [sizeList indexOfSelectedItem]; int output = [outputPopup indexOfSelectedItem]; [[NSUserDefaults standardUserDefaults] setInteger:size forKey:@"canvasSize"]; [[NSUserDefaults standardUserDefaults] setInteger:output forKey:@"outputType"]; //NSLog(@"Save: size -> %d \n output -> %d", size, output); } - (void)loadPref{ int size = [[NSUserDefaults standardUserDefaults] integerForKey:@"canvasSize"]; int output = [[NSUserDefaults standardUserDefaults] integerForKey:@"outputType"]; //NSLog(@"Load: size -> %d \n output -> %d", size, output); [sizeList selectItemAtIndex:size]; [outputPopup selectItemAtIndex:output]; } - (int)delayValue{ return [delaySlider intValue]; } - (void)updateAddrFieldAfterRedirect:(NSString *)url{ [adrField setStringValue:url]; } - (NSString *)savePathValue{ return [[NSUserDefaults standardUserDefaults] stringForKey:@"netfixerExportPath"]; } #pragma mark Toolbar settings #define TB_shot @"tb_shotItem" #define TB_id @"tb_toolbar" #define TB_pref @"tb_prefItem" - (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar { /* Item default in the toolbar */ return [NSArray arrayWithObjects: NSToolbarFlexibleSpaceItemIdentifier, // flexible space TB_shot, // Shot TB_pref, NSToolbarFlexibleSpaceItemIdentifier, // flexible space //NSToolbarCustomizeToolbarItemIdentifier,// customize item nil]; } - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar{ /* item allowed in the toolbar */ return [NSArray arrayWithObjects: TB_shot, NSToolbarFlexibleSpaceItemIdentifier, // flexible space TB_pref, NSToolbarCustomizeToolbarItemIdentifier,// customize item nil]; } - (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted{ NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease]; if ([itemIdent isEqual: TB_shot]){ /* Shot icon definition */ [toolbarItem setLabel: @"Shoot it!"]; [toolbarItem setPaletteLabel: @"Shoot it!"]; [toolbarItem setToolTip: @"Shoot a selected site"]; [toolbarItem setImage: [NSImage imageNamed: @"shot.png"]]; [toolbarItem setTarget: self]; [toolbarItem setAction: @selector(changeTab:)]; return toolbarItem; } if ([itemIdent isEqual: TB_pref]){ /* Shot icon definition */ [toolbarItem setLabel: @"Settings!"]; [toolbarItem setPaletteLabel: @"Settings!"]; [toolbarItem setToolTip: @"Settings for Nexfixer"]; [toolbarItem setImage: [NSImage imageNamed: @"pref.png"]]; [toolbarItem setTarget: self]; [toolbarItem setAction: NSSelectorFromString(@"changeTab:")]; return toolbarItem; } return nil; } - (void)addToolbar:(NSWindow *)win{ // costruisco la nuova istanza della toolbar // la faccio autorelease perche' sara' poi ritenuta dalla finestra NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: TB_id] autorelease]; // imposto le proprieta' di base della toolbar // permetto che l'utente la modifichi [toolbar setAllowsUserCustomization: YES]; // lascio che conservi lo stato tra successivi lanci [toolbar setAutosavesConfiguration: YES]; // dico che mostri solo le icone //[toolbar setDisplayMode: NSToolbarDisplayModeIconOnly]; [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel]; // dico che il delegato della toolbar e' il documento stesso [toolbar setDelegate: self]; // attacco la toolbar alla finestra [ win setToolbar: toolbar ]; } #pragma mark Url delegate handler - (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent { [mainWin makeKeyAndOrderFront:self]; /* This function respond to a GURL event, so after we catch the url we can do all what we want */ NSString *url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; // now you can create an NSURL and grab the necessary parts for example url = [url substringFromIndex:9]; [adrField setStringValue:url]; //NSLog(url); } /* Goodly features, netfixer bookmarklet javascript:%20var%20baseUrl%20=%20'netfixer:';%20var%20url=baseUrl; var%20currentUrl=document.location.href;url=url%20+%20currentUrl;%20location.href=url; */ @end