Advertisement
Guest User

CIALBrowserViewController.m

a guest
Jun 17th, 2012
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 39.17 KB | None | 0 0
  1. //
  2. //  BrowserViewController.m
  3. //  Browser
  4. //
  5.  
  6.  
  7. @interface CIALBrowserViewController ()
  8. - (void)addBookmark;
  9. - (void)updateLoadingStatus;
  10. - (void)longPressRecognized:(UILongPressGestureRecognizer *)gestureRecognizer;
  11.  
  12. - (void)goBack:(id)sender;
  13. - (void)goForward:(id)sender;
  14. - (void)reloadOrStop:(id)sender;
  15. - (void)loadURL:(NSURL *)url;
  16.  
  17. - (void)dismiss:(id)sender;
  18. @end
  19.  
  20. @implementation CIALBrowserViewController
  21.  
  22. @synthesize bookmarkPopoverController = _bookmarkPopoverController;
  23. @synthesize addBookmarkPopoverController = _addBookmarkPopoverController;
  24. @synthesize actionActionSheet = _actionActionSheet;
  25. @synthesize modal = _modal;
  26. @synthesize enabledSafari = _enabledSafari;
  27.  
  28. + (CIALBrowserViewController *)modalBrowserViewControllerWithURL:(NSURL *)url
  29. {
  30.     CIALBrowserViewController *controller = [[[self alloc] initWithURL:url] autorelease];
  31.     controller.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
  32.     controller.modal = YES;
  33.     return controller;
  34. }
  35.  
  36. /* DELETEME: default is nil
  37. - (id)init {
  38.     self = [super init];
  39.     if (self) {
  40.         _urlToLoad = nil;
  41.         req = nil;
  42.     }
  43.     return self;
  44. }
  45. */
  46.  
  47. - (id)initWithURL:(NSURL *)url  {
  48.     self = [super init];
  49.     if (self) {
  50.         [self setURL:url];
  51.     }
  52.     return self;
  53. }
  54.  
  55. - (void)loadView {
  56.     self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
  57.     self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
  58.     self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  59.     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  60.         // Toolbar
  61.         toolBar = [[[UIToolbar alloc] initWithFrame:CGRectZero] autorelease];
  62.         navigationBar.tintColor = [UIColor darkGrayColor];
  63.         self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
  64.         toolBar.barStyle = UIBarStyleDefault;
  65.         [toolBar sizeToFit];
  66.         toolBar.autoresizesSubviews = NO;
  67.         toolBar.frame = CGRectMake(0,
  68.                                    0,
  69.                                    self.view.frame.size.width,
  70.                                    toolBar.frame.size.height);
  71.         toolBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
  72.        
  73.         NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:9];
  74.         UIBarButtonItem *flexibleSpaceButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
  75.                                                                                                   target:nil
  76.                                                                                                   action:nil] autorelease];
  77.         backButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/browserBack.png"]
  78.                                                            style:UIBarButtonItemStylePlain
  79.                                                           target:self
  80.                                                           action:@selector(goBack:)] autorelease];
  81.         forwardButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/browserForward.png"]
  82.                                                               style:UIBarButtonItemStylePlain
  83.                                                              target:self
  84.                                                              action:@selector(goForward:)] autorelease];
  85.         UIBarButtonItem *bookmarkButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks
  86.                                                                                              target:self
  87.                                                                                              action:@selector(viewBookmark:)] autorelease];
  88.         actionButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
  89.                                                                           target:self
  90.                                                                           action:@selector(actionButton:)] autorelease];
  91.        
  92.        
  93.         locationField = [[UITextField alloc] initWithFrame:CGRectMake(37,7,246,31)];
  94.         locationField.delegate = self;
  95.         locationField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  96.         locationField.textColor = [UIColor colorWithRed:102.0/255 green:102.0/255 blue:102.0/255 alpha:1.0];
  97.         locationField.textAlignment = UITextAlignmentLeft;
  98.         locationField.borderStyle = UITextBorderStyleRoundedRect;
  99.         locationField.font = [UIFont fontWithName:@"Helvetica" size:15];
  100.         locationField.autocorrectionType = UITextAutocorrectionTypeNo;
  101.         locationField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
  102.         locationField.clearsOnBeginEditing = NO;
  103.         locationField.autocapitalizationType = UITextAutocapitalizationTypeNone;
  104.         locationField.autocorrectionType = UITextAutocorrectionTypeNo;
  105.         locationField.keyboardType = UIKeyboardTypeURL;
  106.         locationField.returnKeyType = UIReturnKeyGo;        
  107.         locationField.clearButtonMode = UITextFieldViewModeWhileEditing;
  108.         [self.navigationItem setTitleView:locationField];
  109.         // reloadButton
  110.         stopReloadButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
  111.         stopReloadButton.bounds = CGRectMake(0, 0, 26, 30);
  112.         [stopReloadButton setImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewReload.png"] forState:UIControlStateNormal];
  113.         [stopReloadButton setImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewReload.png"] forState:UIControlStateHighlighted];
  114.         stopReloadButton.showsTouchWhenHighlighted = NO;
  115.         [stopReloadButton addTarget:self action:@selector(reloadOrStop:) forControlEvents:UIControlEventTouchUpInside];
  116.         locationField.rightView = stopReloadButton;
  117.         locationField.rightViewMode = UITextFieldViewModeUnlessEditing;
  118.  
  119.         UIBarButtonItem *textFieldItem = [[[UIBarButtonItem alloc] initWithCustomView:locationField] autorelease];
  120.  
  121.         [buttons addObject:flexibleSpaceButtonItem];
  122.         [buttons addObject:backButtonItem];
  123.         [buttons addObject:flexibleSpaceButtonItem];
  124.         [buttons addObject:bookmarkButtonItem];
  125.         [buttons addObject:flexibleSpaceButtonItem];
  126.         [buttons addObject:textFieldItem];
  127.         [buttons addObject:flexibleSpaceButtonItem];
  128.         [buttons addObject:actionButtonItem];
  129.         [buttons addObject:flexibleSpaceButtonItem];
  130.         [buttons addObject:forwardButtonItem];
  131.        
  132.         /*
  133.         if (self.isModal) {
  134.             NSString *closeTitle = CIALBrowserLocalizedString(@"Close", nil);
  135.             closeButtonItem = [[UIBarButtonItem alloc] initWithTitle:closeTitle style:UIBarButtonItemStyleBordered target:self action:@selector(dismiss:)];
  136.             navigationItem.rightBarButtonItem = closeButtonItem;
  137.             [buttons addObject:closeButtonItem];
  138.         } else {
  139.             [buttons addObject:flexibleSpaceButtonItem];
  140.         }
  141.          */
  142.        
  143.         [toolBar setItems:buttons];
  144.         [self.view addSubview:toolBar];
  145.        
  146.         // webView
  147.         webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, toolBar.frame.size.height , self.view.frame.size.width, self.view.frame.size.height - toolBar.frame.size.height)];
  148.         webView.scalesPageToFit = YES;
  149.         webView.contentMode = UIViewContentModeScaleToFill;
  150.         webView.multipleTouchEnabled = YES;
  151.         webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  152.         [self.view addSubview:webView];
  153.         [webView release];
  154.     } else {
  155.         navigationItem = [[UINavigationItem alloc] initWithTitle:nil];
  156.         // titleView
  157.         locationField = [[UITextField alloc] initWithFrame:CGRectMake(37,7,300,31)];
  158.         locationField.delegate = self;
  159.         locationField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  160.         locationField.textColor = [UIColor colorWithRed:102.0/255 green:102.0/255 blue:102.0/255 alpha:1.0];
  161.         locationField.textAlignment = UITextAlignmentLeft;
  162.         locationField.borderStyle = UITextBorderStyleRoundedRect;
  163.         locationField.font = [UIFont fontWithName:@"Helvetica" size:15];
  164.         locationField.autocorrectionType = UITextAutocorrectionTypeNo;
  165.         locationField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
  166.         locationField.clearsOnBeginEditing = NO;
  167.        
  168.         locationField.autocapitalizationType = UITextAutocapitalizationTypeNone;
  169.         locationField.autocorrectionType = UITextAutocorrectionTypeNo;
  170.         locationField.keyboardType = UIKeyboardTypeURL;
  171.         locationField.returnKeyType = UIReturnKeyGo;
  172.        
  173.         locationField.clearButtonMode = UITextFieldViewModeWhileEditing;
  174.        
  175.         // reloadButton
  176.         stopReloadButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
  177.         stopReloadButton.bounds = CGRectMake(0, 0, 26, 30);
  178.         [stopReloadButton setImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewReload.png"] forState:UIControlStateNormal];
  179.         [stopReloadButton setImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewReload.png"] forState:UIControlStateHighlighted];
  180.         stopReloadButton.showsTouchWhenHighlighted = NO;
  181.         [stopReloadButton addTarget:self action:@selector(reloadOrStop:) forControlEvents:UIControlEventTouchUpInside];
  182.         locationField.rightView = stopReloadButton;
  183.         locationField.rightViewMode = UITextFieldViewModeUnlessEditing;
  184.        
  185.         navigationItem.titleView = locationField;
  186.        
  187.         if (self.isModal) {
  188.             NSString *closeTitle = CIALBrowserLocalizedString(@"Close", nil);
  189.             closeButtonItem = [[UIBarButtonItem alloc] initWithTitle:closeTitle style:UIBarButtonItemStyleBordered target:self action:@selector(dismiss:)];
  190.             navigationItem.rightBarButtonItem = closeButtonItem;
  191.         }
  192.        
  193.         navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
  194.         self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
  195.         navigationBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  196.         [navigationBar setItems:[NSArray arrayWithObject:navigationItem]];
  197.         [self.view addSubview:navigationBar];
  198.         [navigationBar release];
  199.        
  200.         // Toolbar
  201.         toolBar = [[[UIToolbar alloc] initWithFrame:CGRectZero] autorelease];
  202.         toolBar.barStyle = UIBarStyleDefault;
  203.         toolBar.tintColor = [UIColor darkGrayColor];
  204.         [toolBar sizeToFit];
  205.         toolBar.autoresizesSubviews = NO;
  206.         toolBar.frame = CGRectMake(0,
  207.                                    self.view.frame.size.height-toolBar.frame.size.height,
  208.                                    self.view.frame.size.width,
  209.                                    toolBar.frame.size.height);
  210.         toolBar.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
  211.        
  212.         NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:9];
  213.         UIBarButtonItem *flexibleSpaceButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
  214.                                                                                                   target:nil
  215.                                                                                                   action:nil] autorelease];
  216.         backButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/browserBack.png"]
  217.                                                            style:UIBarButtonItemStylePlain
  218.                                                           target:self
  219.                                                           action:@selector(goBack:)] autorelease];
  220.         forwardButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"CIALBrowser.bundle/images/browserForward.png"]
  221.                                                               style:UIBarButtonItemStylePlain
  222.                                                              target:self
  223.                                                              action:@selector(goForward:)] autorelease];
  224.         actionButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
  225.                                                                           target:self
  226.                                                                           action:@selector(actionButton:)] autorelease];
  227.         UIBarButtonItem *bookmarkButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks
  228.                                                                                              target:self
  229.                                                                                              action:@selector(viewBookmark:)] autorelease];
  230.        
  231.         [buttons addObject:flexibleSpaceButtonItem];
  232.         [buttons addObject:backButtonItem];
  233.         [buttons addObject:flexibleSpaceButtonItem];
  234.         [buttons addObject:actionButtonItem];
  235.         [buttons addObject:flexibleSpaceButtonItem];
  236.         [buttons addObject:bookmarkButtonItem];
  237.         [buttons addObject:flexibleSpaceButtonItem];
  238.         [buttons addObject:forwardButtonItem];
  239.         [buttons addObject:flexibleSpaceButtonItem];
  240.        
  241.         [toolBar setItems:buttons];
  242.         [self.view addSubview:toolBar];
  243.        
  244.         // webView
  245.         webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, navigationBar.frame.size.height , self.view.frame.size.width, self.view.frame.size.height - navigationBar.frame.size.height - toolBar.frame.size.height)];
  246.         webView.scalesPageToFit = YES;
  247.         webView.contentMode = UIViewContentModeScaleToFill;
  248.         webView.multipleTouchEnabled = YES;
  249.         webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  250.         [self.view addSubview:webView];
  251.         [webView release];
  252.     }
  253.  
  254.     // Create a long press recognizer for handling links long press
  255.     UnpreventableUILongPressGestureRecognizer *longPressRecognizer = [[UnpreventableUILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressRecognized:)];
  256.     longPressRecognizer.allowableMovement = 20;
  257.     longPressRecognizer.minimumPressDuration = 1.0f;
  258.     [webView addGestureRecognizer:longPressRecognizer];
  259.     [longPressRecognizer release];
  260. }
  261.  
  262. - (void)dealloc {
  263.     // Stop the spinner
  264.     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  265.    
  266.     webView.delegate = nil;
  267.     [webView release],webView = nil;
  268.     [backButtonItem release],backButtonItem = nil;
  269.     [forwardButtonItem release],forwardButtonItem = nil;
  270.     [bookmarkButton release],bookmarkButton = nil;
  271.     [stopReloadButton release],stopReloadButton = nil;
  272.     [locationField release],locationField = nil;
  273.     [closeButtonItem release], closeButtonItem = nil;
  274.     [navigationBar release],navigationBar = nil;
  275.     [_urlToLoad release],_urlToLoad = nil;
  276.     [_urlToHandle release],_urlToHandle = nil;
  277.    
  278.     self.actionActionSheet = nil;
  279.    
  280.     [super dealloc];
  281. }
  282.  
  283. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  284.     // On iPad, allow any orientation
  285.     // On iPhone/iPod Touch, allow any orientation but upside down portrait
  286.     BOOL allowRotate = YES;
  287.     if ((UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) && (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))  {
  288.         allowRotate = NO;
  289.     }
  290.     if ([_longPressActionSheet isVisible]) {
  291.         allowRotate = NO;
  292.     }
  293.     return allowRotate;
  294. }
  295.  
  296. - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
  297.     // The height of the toolbar is changing according to orientation, resize the webview occording to this
  298.     if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) {
  299.         if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
  300.             webView.frame = CGRectMake(0, navigationBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - navigationBar.frame.size.height - toolBar.frame.size.height);
  301.         } else {
  302.             webView.frame = CGRectMake(0, navigationBar.frame.size.height, self.view.frame.size.height, self.view.frame.size.width - navigationBar.frame.size.height - toolBar.frame.size.height);
  303.         }
  304.     }
  305. }
  306.  
  307. #pragma mark -
  308.  
  309. - (void) viewDidLoad {
  310.     [super viewDidLoad];
  311.     self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
  312.    
  313.     webView.delegate = self;
  314.    
  315.     [self updateLoadingStatus];
  316.    
  317.     if (_urlToLoad) {
  318.         [self loadURL:_urlToLoad];
  319.     } else {
  320.         [locationField becomeFirstResponder];
  321.     }
  322. }
  323.  
  324. #pragma mark -
  325.  
  326. - (void)loadURL:(NSURL *)url {
  327.     if (!webView) {
  328.         [self setURL:url];
  329.         return;
  330.     }
  331.    
  332.     if (!url) return;
  333.    
  334.     locationField.text = url.absoluteString;
  335.    
  336.     [webView loadRequest:[NSURLRequest requestWithURL:url]];
  337. }
  338.  
  339. - (void)goBack:(id) sender {
  340.     [webView goBack];
  341.    
  342.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLocationField) object:nil];
  343.     [self performSelector:@selector(updateLocationField) withObject:nil afterDelay:1.];
  344. }
  345.  
  346. - (void)goForward:(id) sender {
  347.     [webView goForward];
  348.    
  349.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLocationField) object:nil];
  350.     [self performSelector:@selector(updateLocationField) withObject:nil afterDelay:1.];
  351. }
  352.  
  353. - (void)reloadOrStop:(id) sender {
  354.     if (webView.loading)
  355.         [webView stopLoading];
  356.     else [webView reload];
  357. }
  358.  
  359. - (NSURL *)url {
  360.     NSURL *url = [NSURL URLWithString:locationField.text];
  361.     if (!url.scheme.length && locationField.text.length) url = [NSURL URLWithString:[@"http://" stringByAppendingString:locationField.text]];
  362.     return url;
  363. }
  364.  
  365. #pragma mark -
  366. #pragma mark UITextField delegate
  367.  
  368. - (void)setURL:(NSURL *)url
  369. {
  370.     NSString *urlString = url.absoluteString;
  371.     if ([urlString length]) {
  372.         if (!url.scheme.length) {
  373.             url = [NSURL URLWithString:[@"http://" stringByAppendingString:urlString]];
  374.         }
  375.         [_urlToLoad release];
  376.         _urlToLoad = [url copy];
  377.     }
  378. }
  379.  
  380. - (BOOL) textFieldShouldReturn:(UITextField *) textField {
  381.     NSURL *url = [NSURL URLWithString:locationField.text];
  382.    
  383.     // if user didn't enter "http", add it the the url
  384.     if (!url.scheme.length) {
  385.         url = [NSURL URLWithString:[@"http://" stringByAppendingString:locationField.text]];
  386.     }
  387.    
  388.     [self loadURL:url];
  389.    
  390.     [locationField resignFirstResponder];
  391.    
  392.     return YES;
  393. }
  394.  
  395. #pragma mark -
  396.  
  397. - (void) updateLocationField {
  398.     NSString *location = webView.request.URL.absoluteString;
  399.     if (location.length)
  400.         locationField.text = webView.request.URL.absoluteString;
  401. }
  402.  
  403. - (void) updateLoadingStatus {
  404.     UIImage *image = nil;
  405.     if (webView.loading) {
  406.         image = [UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewStop.png"];
  407.        
  408.         [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  409.     } else {
  410.         image = [UIImage imageNamed:@"CIALBrowser.bundle/images/AddressViewReload.png"];
  411.        
  412.         [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  413.     }
  414.    
  415.     [stopReloadButton setImage:image forState:UIControlStateNormal];
  416.    
  417.     // update status of back/forward buttons
  418.     backButtonItem.enabled = [webView canGoBack];
  419.     forwardButtonItem.enabled = [webView canGoForward];
  420. }
  421.  
  422. #pragma mark -
  423. #pragma mark UIWebView delegate
  424.  
  425. - (BOOL)webView:(UIWebView *) sender shouldStartLoadWithRequest:(NSURLRequest *) request navigationType:(UIWebViewNavigationType) navigationType {
  426.     if ([request.URL.absoluteString isEqual:@"about:blank"])
  427.         return NO;
  428.     [req release];
  429.     req = (NSMutableURLRequest *)[request retain];
  430.    
  431.     return YES;
  432. }
  433.  
  434. - (void) webViewDidStartLoad:(UIWebView *) sender {
  435.     [self updateLoadingStatus];
  436. }
  437.  
  438. - (void) webViewDidFinishLoad:(UIWebView *) sender {
  439.     // Disable the defaut actionSheet when doing a long press
  440.     [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.webkitTouchCallout='none';"];
  441.     [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
  442.    
  443.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLocationField) object:nil];
  444.     [self performSelector:@selector(updateLocationField) withObject:nil afterDelay:1.];
  445.    
  446.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLoadingStatus) object:nil];
  447.     [self performSelector:@selector(updateLoadingStatus) withObject:nil afterDelay:1.];
  448. }
  449.  
  450. - (void) webView:(UIWebView *)sender didFailLoadWithError:(NSError *) error {
  451.     switch ([error code]) {
  452.         case kCFURLErrorCancelled :
  453.         {
  454.             // Do nothing in this case
  455.             break;
  456.         }
  457.         default:
  458.         {
  459.             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:CIALBrowserLocalizedString(@"Error",@"")
  460.                                                             message:[error localizedDescription]
  461.                                                            delegate:nil
  462.                                                   cancelButtonTitle:CIALBrowserLocalizedString(@"OK",@"")
  463.                                                   otherButtonTitles:nil];
  464.             [alert show];    
  465.             [alert release];
  466.             break;
  467.         }
  468.     }
  469.    
  470.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLocationField) object:nil];
  471.     [self performSelector:@selector(updateLocationField) withObject:nil afterDelay:1.];
  472.    
  473.     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateLoadingStatus) object:nil];
  474.     [self performSelector:@selector(updateLoadingStatus) withObject:nil afterDelay:1.];
  475. }
  476.  
  477. #pragma mark actions -
  478.  
  479. - (void)dismiss:(id)sender
  480. {
  481.     [self dismissModalViewControllerAnimated:YES];
  482. }
  483.  
  484.  
  485. #pragma mark -
  486. #pragma mark UIBarButtonItem functions
  487.  
  488. - (void)viewBookmark:(UIBarButtonItem *)button {
  489.     // Make other popover disappear
  490.     if ([self.actionActionSheet isVisible]) {
  491.         [self.actionActionSheet dismissWithClickedButtonIndex:self.actionActionSheet.cancelButtonIndex
  492.                                                      animated:YES];
  493.     }
  494.    
  495.     if ([self.addBookmarkPopoverController isPopoverVisible]) {
  496.         [self.addBookmarkPopoverController dismissPopoverAnimated:YES];
  497.     }
  498.  
  499.     if (printInteraction != nil) {
  500.         [printInteraction dismissAnimated:YES];
  501.         printInteraction = nil;
  502.     }
  503.  
  504.     // Create the popover or make it disappear if needed
  505.     if (self.bookmarkPopoverController.popoverVisible) {
  506.         [self.bookmarkPopoverController dismissPopoverAnimated:YES];
  507.         self.bookmarkPopoverController = nil;
  508.     } else {
  509.         ViewBookmarkViewController * viewBookmarkViewController = [[[ViewBookmarkViewController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
  510.         viewBookmarkViewController.delegate = self;
  511.         [viewBookmarkViewController setBookmark:[webView stringByEvaluatingJavaScriptFromString:@"document.title"]
  512.                                         url:self.url];
  513.         UINavigationController *navController = [[[UINavigationController alloc] initWithRootViewController:viewBookmarkViewController] autorelease];
  514.         navController.navigationBar.tintColor = [UIColor darkGrayColor];
  515.         navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  516.        
  517.         if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  518.             self.bookmarkPopoverController = [[[UIPopoverController alloc] initWithContentViewController:navController] autorelease];
  519.             [self.bookmarkPopoverController presentPopoverFromBarButtonItem:button
  520.                                                    permittedArrowDirections:UIPopoverArrowDirectionDown|UIPopoverArrowDirectionUp
  521.                                                                    animated:YES];
  522.         } else {
  523.             [self presentModalViewController:navController animated:YES];
  524.         }
  525.     }
  526.  
  527. }
  528.  
  529. - (void)addBookmark {
  530.     AddBookmarkViewController * addBookmarkViewController = [[[AddBookmarkViewController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
  531.     [addBookmarkViewController setBookmark:[webView stringByEvaluatingJavaScriptFromString:@"document.title"]
  532.                                        url:self.url];
  533.     addBookmarkViewController.delegate = self;
  534.     UINavigationController *navController = [[[UINavigationController alloc] initWithRootViewController:addBookmarkViewController] autorelease];
  535.    
  536.     navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  537.    
  538.     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  539.         self.addBookmarkPopoverController = [[[UIPopoverController alloc] initWithContentViewController:navController] autorelease];
  540.         self.addBookmarkPopoverController.popoverContentSize = CGSizeMake(320.0, 150.0);
  541.         [self.addBookmarkPopoverController presentPopoverFromBarButtonItem:actionButtonItem
  542.                                                permittedArrowDirections:UIPopoverArrowDirectionDown|UIPopoverArrowDirectionUp
  543.                                                                animated:YES];
  544.     } else {
  545.         [self presentModalViewController:navController animated:YES];
  546.     }
  547. }
  548.  
  549. - (void)actionButton:(UIBarButtonItem *)button {
  550.     if ([self.bookmarkPopoverController isPopoverVisible]) {
  551.         [self.bookmarkPopoverController dismissPopoverAnimated:YES];
  552.     }
  553.     if ([self.addBookmarkPopoverController isPopoverVisible]) {
  554.         [self.addBookmarkPopoverController dismissPopoverAnimated:YES];
  555.         // addBookmarkPopoverController is created by this actionSheet
  556.         // if this button is tapped, make the popover disappear and don't create the actionSheet
  557.         return;
  558.     }
  559.    
  560.     if (printInteraction != nil) {
  561.         [printInteraction dismissAnimated:YES];
  562.         printInteraction = nil;
  563.         // printInteraction is created by this actionSheet
  564.         // if this button is tapped, make it disappear and don't create the actionSheet
  565.         return;
  566.     }
  567.    
  568.     // Create the actionSheet or make it disappear if needed
  569.     if (!self.actionActionSheet) {
  570.         self.actionActionSheet = [[UIActionSheet alloc] initWithTitle:[_urlToHandle.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
  571.                                                          delegate:self
  572.                                                 cancelButtonTitle:nil
  573.                                            destructiveButtonTitle:nil
  574.                                                 otherButtonTitles:nil];
  575.         self.actionActionSheet.actionSheetStyle = UIActionSheetStyleDefault;
  576.        
  577.         copyButtonIndex = -1;
  578.         openLinkButtonIndex = -1;
  579.         addBookmarkButtonIndex = [self.actionActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Add bookmark",nil)];
  580.        
  581.         if (self.enabledSafari) {
  582.             openWithSafariButtonIndex = [self.actionActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Open with Safari",@"")];
  583.         } else {
  584.             openWithSafariButtonIndex = -1;
  585.         }
  586.        
  587.         if ([MFMailComposeViewController canSendMail]) {
  588.             sendUrlButtonIndex = [self.actionActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Mail Link to this Page",@"")];
  589.         }
  590.        
  591.         Class printInteractionController = NSClassFromString(@"UIPrintInteractionController");
  592.         if ((printInteractionController != nil) && [printInteractionController isPrintingAvailable]) {
  593.             printButtonIndex = [self.actionActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Print",@"")];
  594.         } else {
  595.             printButtonIndex = -1;
  596.         }
  597.        
  598.         if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  599.             self.actionActionSheet.cancelButtonIndex = -1;
  600.         } else {
  601.             self.actionActionSheet.cancelButtonIndex = [_actionActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Cancel",@"")];
  602.         }
  603.     }
  604.     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  605.         if (_actionActionSheet.visible) {
  606.             [_actionActionSheet dismissWithClickedButtonIndex:_actionActionSheet.cancelButtonIndex
  607.                                                      animated:YES];
  608.         } else {
  609.             [_actionActionSheet showFromBarButtonItem:button animated:YES];
  610.         }
  611.     } else {
  612.         [_actionActionSheet showInView:self.view];
  613.     }
  614. }
  615.  
  616. #pragma mark -
  617. #pragma mark UIActionSheet delegate
  618.  
  619. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  620.     if (copyButtonIndex == buttonIndex) {
  621.         NSLog(@"url : %@",_urlToHandle);
  622.         NSString *urlString;
  623.         if (req != nil) {
  624.             urlString = [req.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  625.         } else {
  626.             urlString = [_urlToHandle.absoluteString  stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  627.         }
  628.        
  629.         UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
  630.        
  631.         [pasteBoard setValue:urlString forPasteboardType:@"public.utf8-plain-text"];
  632.     } else if (openLinkButtonIndex == buttonIndex) {
  633.         NSLog(@"url : %@",_urlToHandle);
  634.         [self loadURL:_urlToHandle];
  635.         _urlToHandle = nil;
  636.     } else if (addBookmarkButtonIndex == buttonIndex) {
  637.         [self addBookmark];
  638.     } else if (openWithSafariButtonIndex == buttonIndex) {
  639.         [[UIApplication sharedApplication] openURL:self.url];
  640.     } else if (sendUrlButtonIndex == buttonIndex) {
  641.         MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
  642.         [mailViewController setSubject:[webView stringByEvaluatingJavaScriptFromString:@"document.title"]];
  643.         [mailViewController setMessageBody:[self.url absoluteString]
  644.                                     isHTML:NO];
  645.        
  646.         mailViewController.mailComposeDelegate = self;
  647.        
  648.         if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  649.             mailViewController.modalPresentationStyle = UIModalPresentationPageSheet;
  650.         }
  651.        
  652.         [self presentModalViewController:mailViewController animated:YES];
  653.         [mailViewController release];
  654.     } else if (printButtonIndex == buttonIndex) {
  655.         Class printInteractionController = NSClassFromString(@"UIPrintInteractionController");
  656.        
  657.         if ((printInteractionController != nil) && [printInteractionController isPrintingAvailable])
  658.         {
  659.             printInteraction = [printInteractionController sharedPrintController];
  660.             printInteraction.delegate = self;
  661.            
  662.             UIPrintInfo *printInfo = [NSClassFromString(@"UIPrintInfo") printInfo];
  663.            
  664.             printInfo.duplex = UIPrintInfoDuplexLongEdge;
  665.             printInfo.outputType = UIPrintInfoOutputGeneral;
  666.             printInfo.jobName = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
  667.            
  668.             printInteraction.printInfo = printInfo;
  669.             printInteraction.showsPageRange = YES;
  670.            
  671.             UIViewPrintFormatter *formatter = [webView viewPrintFormatter];
  672.             printInteraction.printFormatter = formatter;
  673.            
  674.             [printInteraction presentFromBarButtonItem:actionButtonItem
  675.                                               animated:YES
  676.                                      completionHandler:
  677.              ^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
  678.              }
  679.              ];
  680.         }
  681.     }
  682.    
  683.     if (req != nil) {
  684.         [req release];
  685.         req = nil;
  686.     }    
  687. }
  688.  
  689. - (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
  690. {
  691.     if (actionSheet == _longPressActionSheet)
  692.     {
  693.         _longPressActionSheet = nil;
  694.     }
  695. }
  696.  
  697. #pragma mark -
  698. #pragma mark MFMailComposeViewController delegates
  699.  
  700. - (void)mailComposeController:(MFMailComposeViewController*)controller
  701.           didFinishWithResult:(MFMailComposeResult)result
  702.                         error:(NSError*)error {
  703.     [self dismissModalViewControllerAnimated:YES];
  704.    
  705.     NSString *mailError = nil;
  706.    
  707.     switch (result) {
  708.         case MFMailComposeResultSent:
  709.             break;
  710.         case MFMailComposeResultFailed:
  711.             mailError = CIALBrowserLocalizedString(@"Failed sending email, please try again...",@"");
  712.             break;
  713.         default:
  714.             break;
  715.     }
  716.    
  717.     if (mailError != nil) {
  718.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
  719.                                                         message:mailError
  720.                                                        delegate:nil
  721.                                               cancelButtonTitle:@"OK"
  722.                                               otherButtonTitles:nil];
  723.         [alert show];
  724.         [alert release];
  725.     }
  726. }
  727.  
  728. #pragma mark -
  729. #pragma mark UIPrintInteractionControllerDelegate
  730. - (void)printInteractionControllerDidDismissPrinterOptions:(UIPrintInteractionController *)printInteractionController {
  731.     NSLog(@"printInteractionControllerDidDismissPrinterOptions");
  732.     printInteraction = nil;
  733. }
  734.  
  735. #pragma mark -
  736. #pragma mark UILongPressGestureRecognizer handling
  737.  
  738. - (void)longPressRecognized:(UILongPressGestureRecognizer *)gestureRecognizer {
  739.     if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
  740.         CGPoint point = [gestureRecognizer locationInView:webView];
  741.        
  742.         // convert point from view to HTML coordinate system
  743.         CGSize viewSize = [webView frame].size;
  744.         CGSize windowSize = [webView windowSize];
  745.        
  746.         CGFloat f = windowSize.width / viewSize.width;
  747.         if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.) {
  748.             point.x = point.x * f;
  749.             point.y = point.y * f;
  750.         } else {
  751.             // On iOS 4 and previous, document.elementFromPoint is not taking
  752.             // offset into account, we have to handle it
  753.             CGPoint offset = [webView scrollOffset];
  754.             point.x = point.x * f + offset.x;
  755.             point.y = point.y * f + offset.y;
  756.         }
  757.                
  758.         // Load the JavaScript code from the Resources and inject it into the web page
  759.         NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"CIALBrowser" ofType:@"bundle"]];
  760.  
  761.         NSString *path = [bundle pathForResource:@"JSTools" ofType:@"js"];
  762.         NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  763.         [webView stringByEvaluatingJavaScriptFromString: jsCode];
  764.        
  765.         // get the Tags at the touch location
  766.         NSString *tags = [webView stringByEvaluatingJavaScriptFromString:
  767.                           [NSString stringWithFormat:@"MyAppGetHTMLElementsAtPoint(%i,%i);",(NSInteger)point.x,(NSInteger)point.y]];
  768.        
  769.         NSString *tagsHREF = [webView stringByEvaluatingJavaScriptFromString:
  770.                               [NSString stringWithFormat:@"MyAppGetLinkHREFAtPoint(%i,%i);",(NSInteger)point.x,(NSInteger)point.y]];
  771.        
  772.         NSString *tagsSRC = [webView stringByEvaluatingJavaScriptFromString:
  773.                              [NSString stringWithFormat:@"MyAppGetLinkSRCAtPoint(%i,%i);",(NSInteger)point.x,(NSInteger)point.y]];
  774.         NSLog(@"tags : %@",tags);
  775.         NSLog(@"href : %@",tagsHREF);
  776.         NSLog(@"src : %@",tagsSRC);
  777.        
  778.         NSString *url = nil;
  779.         if ([tags rangeOfString:@",IMG,"].location != NSNotFound) {
  780.             url = tagsSRC;
  781.         }
  782.         if ([tags rangeOfString:@",A,"].location != NSNotFound) {
  783.             url = tagsHREF;
  784.         }
  785.         NSLog(@"url : %@",url);
  786.        
  787.         NSArray *urlArray = [[url lowercaseString] componentsSeparatedByString:@"/"];
  788.         NSString *urlBase = nil;
  789.         if ([urlArray count] > 2) {
  790.             urlBase = [urlArray objectAtIndex:2];
  791.         }
  792.        
  793.         if ((url != nil) &&
  794.             ([url length] != 0)) {
  795.             // Release any previous request
  796.             [req release], req = nil;
  797.             // Save URL for the request
  798.             _urlToHandle = [[NSURL alloc] initWithString:url];
  799.            
  800.             // ask user what to do
  801.             _longPressActionSheet = [[UIActionSheet alloc] initWithTitle:[_urlToHandle.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
  802.                                                                 delegate:self
  803.                                                        cancelButtonTitle:nil
  804.                                                   destructiveButtonTitle:nil
  805.                                                        otherButtonTitles:nil];
  806.             _longPressActionSheet.actionSheetStyle = UIActionSheetStyleDefault;
  807.            
  808.             openLinkButtonIndex = [_longPressActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Open",@"")];
  809.             copyButtonIndex = [_longPressActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Copy",@"")];
  810.            
  811.             if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  812.                 CGPoint touchPosition = [gestureRecognizer locationInView:webView];
  813.                 [_longPressActionSheet showFromRect:CGRectMake(touchPosition.x, touchPosition.y, 1, 1)
  814.                                              inView:webView
  815.                                            animated:YES];
  816.             } else {
  817.                 _longPressActionSheet.cancelButtonIndex = [_longPressActionSheet addButtonWithTitle:CIALBrowserLocalizedString(@"Cancel",@"")];
  818.                 [_longPressActionSheet showInView:self.view];
  819.             }
  820.             [_longPressActionSheet release];
  821.         }        
  822.     }
  823. }
  824.  
  825. #pragma mark -
  826. #pragma mark Bookmark delegates
  827.  
  828. - (void)openThisURL:(NSURL *)url {
  829.     [self loadURL:url];
  830. }
  831.  
  832. - (void)dismissViewBookmMarkViewController:(ViewBookmarkViewController *)viewController {
  833.     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  834.         [self.bookmarkPopoverController dismissPopoverAnimated:YES];
  835.     } else {
  836.         [viewController dismissModalViewControllerAnimated:YES];
  837.     }
  838. }
  839.  
  840. #pragma mark -
  841. #pragma mark addBookmark delegates
  842.  
  843. - (void)dismissAddBookmMarkViewController:(AddBookmarkViewController *)viewController {
  844.     if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  845.         [self.addBookmarkPopoverController dismissPopoverAnimated:YES];
  846.     } else {
  847.         [viewController dismissModalViewControllerAnimated:YES];
  848.     }
  849. }
  850.  
  851. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement