1 #include "CyteKit/UCPlatform.h"
2 #include "CyteKit/WebViewController.h"
4 #include "CyteKit/MFMailComposeViewController-MailToURL.h"
6 #include "iPhonePrivate.h"
8 #include "CyteKit/IndirectDelegate.h"
9 #include "CyteKit/Localize.h"
10 #include "CyteKit/WebViewController.h"
11 #include "CyteKit/PerlCompatibleRegEx.hpp"
12 #include "CyteKit/WebThreadLocked.hpp"
14 //#include <QuartzCore/CALayer.h>
15 // XXX: fix the minimum requirement
16 extern NSString * const kCAFilterNearest;
18 #include <WebCore/WebCoreThread.h>
20 #import <WebKit/WebKitErrors.h>
21 #import <WebKit/WebPreferences.h>
23 #include <WebKit/DOMCSSPrimitiveValue.h>
24 #include <WebKit/DOMCSSStyleDeclaration.h>
25 #include <WebKit/DOMDocument.h>
26 #include <WebKit/DOMHTMLBodyElement.h>
27 #include <WebKit/DOMRGBColor.h>
30 #include <objc/runtime.h>
33 #define DefaultTimeout_ 120.0
35 #define ShowInternals 0
39 #define lprintf(args...) fprintf(stderr, args)
41 JSValueRef (*$JSObjectCallAsFunction)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *);
43 // XXX: centralize these special class things to some file or mechanism?
44 static Class $MFMailComposeViewController;
46 float CYScrollViewDecelerationRateNormal;
48 @interface WebView (Apple)
49 - (void) _setLayoutInterval:(float)interval;
50 - (void) _setAllowsMessaging:(BOOL)allows;
53 @interface WebFrame (Cydia)
54 - (void) cydia$updateHeight;
57 @implementation WebFrame (Cydia)
59 - (NSString *) description {
60 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[[([self provisionalDataSource] ?: [self dataSource]) request] URL] absoluteString]];
63 - (void) cydia$updateHeight {
64 [[[self frameElement] style]
66 value:[NSString stringWithFormat:@"%dpx",
67 [[[self DOMDocument] body] scrollHeight]]
73 /* Indirect Delegate {{{ */
74 @implementation IndirectDelegate
80 - (void) setDelegate:(id)delegate {
84 - (id) initWithDelegate:(id)delegate {
89 - (IMP) methodForSelector:(SEL)sel {
90 if (IMP method = [super methodForSelector:sel])
92 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
96 - (BOOL) respondsToSelector:(SEL)sel {
97 if ([super respondsToSelector:sel])
100 // XXX: WebThreadCreateNSInvocation returns nil
103 fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
106 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
109 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
110 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
114 fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
117 if (delegate_ != nil)
118 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
121 // XXX: I fucking hate Apple so very very bad
122 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
125 - (void) forwardInvocation:(NSInvocation *)inv {
126 SEL sel = [inv selector];
127 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
128 [inv invokeWithTarget:delegate_];
134 @implementation CyteWebViewController
137 #include "CyteKit/UCInternal.h"
140 + (void) _initialize {
141 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
145 js = dlopen("/System/Library/Frameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
147 js = dlopen("/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
149 $JSObjectCallAsFunction = reinterpret_cast<JSValueRef (*)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(js, "JSObjectCallAsFunction"));
151 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
152 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
154 if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
155 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
156 else // XXX: this actually might be fast on some older systems: we should look into this
157 CYScrollViewDecelerationRateNormal = 0.998;
160 - (bool) retainsNetworkActivityIndicator {
164 - (void) releaseNetworkActivityIndicator {
165 if ([loading_ count] != 0) {
166 [loading_ removeAllObjects];
168 if ([self retainsNetworkActivityIndicator])
169 [delegate_ releaseNetworkActivityIndicator];
175 NSLog(@"[CyteWebViewController dealloc]");
178 [self releaseNetworkActivityIndicator];
183 - (NSString *) description {
184 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[request_ URL] absoluteString]];
187 - (CyteWebView *) webView {
188 return (CyteWebView *) [self view];
191 - (NSURL *) URLWithURL:(NSURL *)url {
195 - (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy referrer:(NSString *)referrer {
196 NSMutableURLRequest *request([NSMutableURLRequest
197 requestWithURL:[self URLWithURL:url]
199 timeoutInterval:DefaultTimeout_
202 [request setValue:referrer forHTTPHeaderField:@"Referer"];
207 - (void) setRequest:(NSURLRequest *)request {
208 _assert(request_ == nil);
212 - (void) setURL:(NSURL *)url {
213 [self setURL:url withReferrer:nil];
216 - (void) setURL:(NSURL *)url withReferrer:(NSString *)referrer {
217 [self setRequest:[self requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy referrer:referrer]];
220 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
221 [self loadRequest:[self requestWithURL:url cachePolicy:policy referrer:nil]];
224 - (void) loadURL:(NSURL *)url {
225 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
228 - (void) loadRequest:(NSURLRequest *)request {
230 NSLog(@"loadRequest:%@", request);
236 WebThreadLocked lock;
237 [[self webView] loadRequest:request];
240 - (void) reloadURLWithCache:(BOOL)cache {
244 NSMutableURLRequest *request([request_ mutableCopy]);
245 [request setCachePolicy:(cache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData)];
249 if (cache || [request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
250 [self loadRequest:request_];
252 UIAlertView *alert = [[[UIAlertView alloc]
253 initWithTitle:UCLocalize("RESUBMIT_FORM")
256 cancelButtonTitle:UCLocalize("CANCEL")
258 UCLocalize("SUBMIT"),
262 [alert setContext:@"submit"];
267 - (void) reloadData {
271 [self dispatchEvent:@"CydiaReloadData"];
273 [self reloadURLWithCache:YES];
276 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
279 function_ = function;
281 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
284 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
287 function_ = function;
289 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
292 - (void) removeButton {
293 custom_ = [NSNull null];
294 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
297 - (void) scrollToBottomAnimated:(NSNumber *)animated {
298 CGSize size([scroller_ contentSize]);
299 CGPoint offset([scroller_ contentOffset]);
300 CGRect frame([scroller_ frame]);
302 if (size.height - offset.y < frame.size.height + 20.f) {
303 CGRect rect = {{0, size.height-1}, {size.width, 1}};
304 [scroller_ scrollRectToVisible:rect animated:[animated boolValue]];
308 - (void) _setViewportWidth {
309 [[[self webView] _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
312 - (void) setViewportWidth:(float)width {
313 width_ = width != 0 ? width : [[self class] defaultWidth];
314 [self _setViewportWidth];
317 - (void) _setViewportWidthOnMainThread:(NSNumber *)width {
318 [self setViewportWidth:[width floatValue]];
321 - (void) setViewportWidthOnMainThread:(float)width {
322 [self performSelectorOnMainThread:@selector(_setViewportWidthOnMainThread:) withObject:[NSNumber numberWithFloat:width] waitUntilDone:NO];
325 - (void) webViewUpdateViewSettings:(UIWebView *)view {
326 [self _setViewportWidth];
329 - (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
330 [self dismissModalViewControllerAnimated:YES];
333 - (void) _setupMail:(MFMailComposeViewController *)controller {
336 - (void) _openMailToURL:(NSURL *)url {
337 if ($MFMailComposeViewController != nil && [$MFMailComposeViewController canSendMail]) {
338 MFMailComposeViewController *controller([[[$MFMailComposeViewController alloc] init] autorelease]);
339 [controller setMailComposeDelegate:self];
341 [controller setMailToURL:url];
343 [self _setupMail:controller];
345 [self presentModalViewController:controller animated:YES];
349 UIApplication *app([UIApplication sharedApplication]);
350 if ([app respondsToSelector:@selector(openURL:asPanel:)])
351 [app openURL:url asPanel:YES];
356 - (bool) _allowJavaScriptPanel {
360 - (bool) allowsNavigationAction {
361 return allowsNavigationAction_;
364 - (void) setAllowsNavigationAction:(bool)value {
365 allowsNavigationAction_ = value;
368 - (void) setAllowsNavigationActionByNumber:(NSNumber *)value {
369 [self setAllowsNavigationAction:[value boolValue]];
372 - (void) popViewControllerWithNumber:(NSNumber *)value {
373 UINavigationController *navigation([self navigationController]);
374 if ([navigation topViewController] == self)
375 [navigation popViewControllerAnimated:[value boolValue]];
378 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
379 NSValue *object([NSValue valueWithNonretainedObject:frame]);
380 if (![loading_ containsObject:object])
382 [loading_ removeObject:object];
384 [self _didFinishLoading];
386 if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == NSURLErrorCancelled)
389 if ([[error domain] isEqualToString:WebKitErrorDomain] && [error code] == WebKitErrorFrameLoadInterruptedByPolicyChange) {
394 if ([frame parentFrame] == nil) {
395 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
396 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
397 [[error localizedDescription] stringByAddingPercentEscapes]
404 - (void) pushRequest:(NSURLRequest *)request forAction:(NSDictionary *)action asPop:(bool)pop {
405 WebFrame *frame(nil);
406 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
407 frame = [WebActionElement objectForKey:@"WebElementFrame"];
409 frame = [[[[self webView] _documentView] webView] mainFrame];
411 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
412 NSString *referrer([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString]);
414 NSURL *url([request URL]);
416 // XXX: filter to internal usage?
417 CyteViewController *page([delegate_ pageForURL:url forExternal:NO withReferrer:referrer]);
420 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
421 [browser setRequest:request];
425 [page setDelegate:delegate_];
426 [page setPageColor:color_];
429 [[self navigationItem] setTitle:title_];
431 [[self navigationController] pushViewController:page animated:YES];
433 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
435 [navigation setDelegate:delegate_];
437 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
438 initWithTitle:UCLocalize("CLOSE")
439 style:UIBarButtonItemStylePlain
441 action:@selector(close)
444 [[self navigationController] presentModalViewController:navigation animated:YES];
448 // CyteWebViewDelegate {{{
449 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
451 static Pcre irritating("^(?"
452 ":" "The page at .* displayed insecure content from .*\\."
453 "|" "Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\."
456 if (NSString *data = [message objectForKey:@"message"])
457 if (irritating(data))
460 NSLog(@"addMessageToConsole:%@", message);
464 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
466 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ %@ frame:%@", action, request, [request allHTTPHeaderFields], frame);
469 if ([frame parentFrame] == nil) {
471 NSURL *url(request == nil ? nil : [request URL]);
473 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
475 [self pushRequest:request forAction:action asPop:NO];
482 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
484 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
487 if ([frame parentFrame] == nil) {
489 case CYWebPolicyDecisionIgnore:
490 if ([[request_ URL] isEqual:[request URL]])
494 case CYWebPolicyDecisionUse:
505 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
507 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
510 NSURL *url([request URL]);
514 if ([name isEqualToString:@"_open"])
515 [delegate_ openURL:url];
517 NSString *scheme([[url scheme] lowercaseString]);
518 if ([scheme isEqualToString:@"mailto"])
519 [self _openMailToURL:url];
521 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
527 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
529 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
533 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
535 NSLog(@"didCommitLoadForFrame:%@", frame);
538 if ([frame parentFrame] == nil) {
543 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
545 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
548 [self _didFailWithError:error forFrame:frame];
551 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
553 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
556 [self _didFailWithError:error forFrame:frame];
559 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
560 NSValue *object([NSValue valueWithNonretainedObject:frame]);
561 if (![loading_ containsObject:object])
563 [loading_ removeObject:object];
565 if ([frame parentFrame] == nil) {
566 if (DOMDocument *document = [frame DOMDocument])
567 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
568 for (DOMHTMLBodyElement *body in (id) bodies) {
569 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
573 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
574 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
575 DOMRGBColor *rgb([color getRGBColorValue]);
577 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
578 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
579 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
580 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
584 colorWithRed:(red / 255)
592 [super setPageColor:uic];
593 [scroller_ setBackgroundColor:color_];
598 [self _didFinishLoading];
601 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
602 if ([frame parentFrame] != nil)
607 [[self navigationItem] setTitle:title_];
610 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
612 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
615 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
617 if ([frame parentFrame] == nil) {
623 [registered_ removeAllObjects];
626 allowsNavigationAction_ = true;
628 [self setHidesNavigationBar:NO];
629 [self setScrollAlwaysBounceVertical:true];
630 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
632 // XXX: do we still need to do this?
633 [[self navigationItem] setTitle:nil];
636 [self _didStartLoading];
639 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
640 challenge_ = [challenge retain];
642 NSURLProtectionSpace *space([challenge protectionSpace]);
643 NSString *realm([space realm]);
647 UIAlertView *alert = [[[UIAlertView alloc]
651 cancelButtonTitle:UCLocalize("CANCEL")
652 otherButtonTitles:UCLocalize("LOGIN"), nil
655 [alert setContext:@"challenge"];
656 [alert setNumberOfRows:1];
658 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
659 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
661 UITextField *username([alert textFieldAtIndex:0]); {
662 UITextInputTraits *traits([username textInputTraits]);
663 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
664 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
665 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
666 [traits setReturnKeyType:UIReturnKeyNext];
669 UITextField *password([alert textFieldAtIndex:1]); {
670 UITextInputTraits *traits([password textInputTraits]);
671 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
672 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
673 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
674 // XXX: UIReturnKeyDone
675 [traits setReturnKeyType:UIReturnKeyNext];
676 [traits setSecureTextEntry:YES];
682 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
684 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
690 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
691 return [self _allowJavaScriptPanel];
694 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
695 return [self _allowJavaScriptPanel];
698 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
699 return [self _allowJavaScriptPanel];
702 - (void) webViewClose:(WebView *)view {
708 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
711 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
712 NSString *context([alert context]);
714 if ([context isEqualToString:@"sensitive"]) {
717 sensitive_ = [NSNumber numberWithBool:YES];
721 sensitive_ = [NSNumber numberWithBool:NO];
725 [alert dismissWithClickedButtonIndex:-1 animated:YES];
726 } else if ([context isEqualToString:@"challenge"]) {
727 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
729 if (button == [alert cancelButtonIndex])
730 [sender cancelAuthenticationChallenge:challenge_];
731 else if (button == [alert firstOtherButtonIndex]) {
732 NSString *username([[alert textFieldAtIndex:0] text]);
733 NSString *password([[alert textFieldAtIndex:1] text]);
735 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
737 [sender useCredential:credential forAuthenticationChallenge:challenge_];
742 [alert dismissWithClickedButtonIndex:-1 animated:YES];
743 } else if ([context isEqualToString:@"submit"]) {
744 if (button == [alert cancelButtonIndex]) {
745 } else if (button == [alert firstOtherButtonIndex]) {
746 if (request_ != nil) {
747 WebThreadLocked lock;
748 [[self webView] loadRequest:request_];
752 [alert dismissWithClickedButtonIndex:-1 animated:YES];
756 - (UIBarButtonItemStyle) rightButtonStyle {
757 if (style_ == nil) normal:
758 return UIBarButtonItemStylePlain;
759 else if ([style_ isEqualToString:@"Normal"])
760 return UIBarButtonItemStylePlain;
761 else if ([style_ isEqualToString:@"Highlighted"])
762 return UIBarButtonItemStyleDone;
766 - (UIBarButtonItem *) customButton {
769 else if ((/*clang:*/id) custom_ == [NSNull null])
770 return (UIBarButtonItem *) [NSNull null];
772 return [[[UIBarButtonItem alloc]
773 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
774 style:[self rightButtonStyle]
776 action:@selector(customButtonClicked)
780 - (UIBarButtonItem *) leftButton {
781 UINavigationItem *item([self navigationItem]);
782 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
785 if (UINavigationController *navigation = [self navigationController])
786 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
787 return [[[UIBarButtonItem alloc]
788 initWithTitle:UCLocalize("CLOSE")
789 style:UIBarButtonItemStylePlain
791 action:@selector(close)
797 - (void) applyLeftButton {
798 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
801 - (UIBarButtonItem *) rightButton {
805 - (void) applyLoadingTitle {
806 [[self navigationItem] setTitle:UCLocalize("LOADING")];
809 - (void) layoutRightButton {
810 [[loadingitem_ view] addSubview:indicator_];
811 [[loadingitem_ view] bringSubviewToFront:indicator_];
814 - (void) applyRightButton {
815 if ([self isLoading]) {
816 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
817 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
819 [indicator_ startAnimating];
820 [self applyLoadingTitle];
822 [indicator_ stopAnimating];
824 UIBarButtonItem *button([self customButton]);
826 button = [self rightButton];
827 else if (button == (UIBarButtonItem *) [NSNull null])
830 [[self navigationItem] setRightBarButtonItem:button animated:YES];
834 - (void) didStartLoading {
835 // Overridden in subclasses.
838 - (void) _didStartLoading {
839 [self applyRightButton];
841 if ([loading_ count] != 1)
844 if ([self retainsNetworkActivityIndicator])
845 [delegate_ retainNetworkActivityIndicator];
847 [self didStartLoading];
850 - (void) didFinishLoading {
851 // Overridden in subclasses.
854 - (void) _didFinishLoading {
855 if ([loading_ count] != 0)
858 [self applyRightButton];
859 [[self navigationItem] setTitle:title_];
861 if ([self retainsNetworkActivityIndicator])
862 [delegate_ releaseNetworkActivityIndicator];
864 [self didFinishLoading];
868 return [loading_ count] != 0;
871 - (id) initWithWidth:(float)width ofClass:(Class)_class {
872 if ((self = [super init]) != nil) {
876 [super setPageColor:nil];
878 allowsNavigationAction_ = true;
880 loading_ = [NSMutableSet setWithCapacity:5];
881 registered_ = [NSMutableSet setWithCapacity:5];
882 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
884 reloaditem_ = [[[UIBarButtonItem alloc]
885 initWithTitle:UCLocalize("RELOAD")
886 style:[self rightButtonStyle]
888 action:@selector(reloadButtonClicked)
891 loadingitem_ = [[[UIBarButtonItem alloc]
892 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
893 style:UIBarButtonItemStylePlain
895 action:@selector(reloadButtonClicked)
898 UIActivityIndicatorViewStyle style;
900 if (kCFCoreFoundationVersionNumber >= 800) {
901 style = UIActivityIndicatorViewStyleGray;
904 style = UIActivityIndicatorViewStyleWhite;
908 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
909 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
910 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
912 [self applyLeftButton];
913 [self applyRightButton];
917 - (NSString *) applicationNameForUserAgent {
922 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
924 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
925 [webview_ setDelegate:self];
926 [self setView:webview_];
928 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
929 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
931 [webview_ setDetectsPhoneNumbers:NO];
933 [webview_ setScalesPageToFit:YES];
935 UIWebDocumentView *document([webview_ _documentView]);
937 // XXX: I think this improves scrolling; the hardcoded-ness sucks
938 [document setTileSize:CGSizeMake(320, 500)];
940 WebView *webview([document webView]);
941 WebPreferences *preferences([webview preferences]);
943 // XXX: I have no clue if I actually /want/ this modification
944 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
945 [webview _setLayoutInterval:0];
946 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
947 [preferences _setLayoutInterval:0];
949 [preferences setCacheModel:WebCacheModelDocumentBrowser];
950 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
952 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
953 [preferences setOfflineWebApplicationCacheEnabled:YES];
955 if (NSString *agent = [self applicationNameForUserAgent])
956 [webview setApplicationNameForUserAgent:agent];
958 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
959 [webview setShouldUpdateWhileOffscreen:NO];
962 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
963 [document setAllowsMessaging:YES];
964 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
965 [webview _setAllowsMessaging:YES];
968 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
969 scroller_ = [webview_ _scrollView];
971 [scroller_ setDirectionalLockEnabled:YES];
972 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
973 [scroller_ setDelaysContentTouches:NO];
975 [scroller_ setCanCancelContentTouches:YES];
976 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
977 UIScroller *scroller([webview_ _scroller]);
978 scroller_ = (UIScrollView *) scroller;
980 [scroller setDirectionalScrolling:YES];
981 // XXX: we might be better off /not/ setting this on older systems
982 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
983 [scroller setScrollHysteresis:0]; /* 8 */
985 [scroller setThumbDetectionEnabled:NO];
987 // use NO with UIApplicationUseLegacyEvents(YES)
988 [scroller setEventMode:YES];
990 // XXX: this is handled by setBounces, right?
991 //[scroller setAllowsRubberBanding:YES];
994 [webview_ setOpaque:NO];
995 [webview_ setBackgroundColor:nil];
997 [scroller_ setFixedBackgroundPattern:YES];
998 [scroller_ setBackgroundColor:color_];
999 [scroller_ setClipsSubviews:YES];
1001 [scroller_ setBounces:YES];
1002 [scroller_ setScrollingEnabled:YES];
1003 [scroller_ setShowBackgroundShadow:NO];
1005 [self setViewportWidth:width_];
1007 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1008 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1009 [table setScrollsToTop:NO];
1010 [webview_ insertSubview:table atIndex:0];
1011 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1014 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1019 - (void) releaseSubviews {
1023 [self releaseNetworkActivityIndicator];
1025 [super releaseSubviews];
1028 - (id) initWithWidth:(float)width {
1029 return [self initWithWidth:width ofClass:[self class]];
1033 return [self initWithWidth:0];
1036 - (id) initWithURL:(NSURL *)url {
1037 if ((self = [self init]) != nil) {
1042 - (id) initWithRequest:(NSURLRequest *)request {
1043 if ((self = [self init]) != nil) {
1044 [self setRequest:request];
1048 - (void) callFunction:(WebScriptObject *)function {
1049 WebThreadLocked lock;
1051 WebView *webview([[[self webView] _documentView] webView]);
1052 WebFrame *frame([webview mainFrame]);
1054 JSGlobalContextRef context([frame globalContext]);
1055 JSObjectRef object([function JSObject]);
1056 if ($JSObjectCallAsFunction != NULL)
1057 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1060 - (void) reloadButtonClicked {
1061 [self reloadURLWithCache:NO];
1064 - (void) _customButtonClicked {
1065 [self reloadButtonClicked];
1068 - (void) customButtonClicked {
1070 if (function_ != nil)
1071 [self callFunction:function_];
1074 [self _customButtonClicked];
1077 + (float) defaultWidth {
1081 - (void) setNavigationBarStyle:(NSString *)name {
1083 if ([name isEqualToString:@"Black"])
1084 style = UIBarStyleBlack;
1086 style = UIBarStyleDefault;
1088 [[[self navigationController] navigationBar] setBarStyle:style];
1091 - (void) setNavigationBarTintColor:(UIColor *)color {
1092 [[[self navigationController] navigationBar] setTintColor:color];
1095 - (void) setBadgeValue:(id)value {
1096 [[[self navigationController] tabBarItem] setBadgeValue:value];
1099 - (void) setHidesBackButton:(bool)value {
1100 [[self navigationItem] setHidesBackButton:value];
1101 [self applyLeftButton];
1104 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1105 [self setHidesBackButton:[value boolValue]];
1108 - (void) dispatchEvent:(NSString *)event {
1109 [[self webView] dispatchEvent:event];
1112 - (bool) hidesNavigationBar {
1113 return hidesNavigationBar_;
1116 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1118 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1121 - (void) setHidesNavigationBar:(bool)value {
1122 if (hidesNavigationBar_ != value) {
1123 hidesNavigationBar_ = value;
1124 [self _setHidesNavigationBar:YES animated:YES];
1128 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1129 [self setHidesNavigationBar:[value boolValue]];
1132 - (void) setScrollAlwaysBounceVertical:(bool)value {
1133 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1134 UIScrollView *scroller([webview_ _scrollView]);
1135 [scroller setAlwaysBounceVertical:value];
1136 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1137 //UIScroller *scroller([webview_ _scroller]);
1138 // XXX: I am sad here.
1142 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1143 [self setScrollAlwaysBounceVertical:[value boolValue]];
1146 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1147 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1148 UIScrollView *scroller([webview_ _scrollView]);
1149 [scroller setIndicatorStyle:style];
1150 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1151 UIScroller *scroller([webview_ _scroller]);
1152 [scroller setScrollerIndicatorStyle:style];
1156 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1157 UIScrollViewIndicatorStyle value;
1160 else if ([style isEqualToString:@"default"])
1161 value = UIScrollViewIndicatorStyleDefault;
1162 else if ([style isEqualToString:@"black"])
1163 value = UIScrollViewIndicatorStyleBlack;
1164 else if ([style isEqualToString:@"white"])
1165 value = UIScrollViewIndicatorStyleWhite;
1168 [self setScrollIndicatorStyle:value];
1171 - (void) viewWillAppear:(BOOL)animated {
1174 if ([self hidesNavigationBar])
1175 [self _setHidesNavigationBar:YES animated:animated];
1177 // XXX: why isn't this evern called automatically?
1178 [[self webView] setNeedsLayout];
1180 [self dispatchEvent:@"CydiaViewWillAppear"];
1181 [super viewWillAppear:animated];
1184 - (void) viewDidAppear:(BOOL)animated {
1185 [super viewDidAppear:animated];
1186 [self dispatchEvent:@"CydiaViewDidAppear"];
1189 - (void) viewWillDisappear:(BOOL)animated {
1190 [self dispatchEvent:@"CydiaViewWillDisappear"];
1191 [super viewWillDisappear:animated];
1193 if ([self hidesNavigationBar])
1194 [self _setHidesNavigationBar:NO animated:animated];
1199 - (void) viewDidDisappear:(BOOL)animated {
1200 [super viewDidDisappear:animated];
1201 [self dispatchEvent:@"CydiaViewDidDisappear"];
1204 - (void) updateHeights:(NSTimer *)timer {
1205 for (WebFrame *frame in (id) registered_)
1206 [frame cydia$updateHeight];
1209 - (void) registerFrame:(WebFrame *)frame {
1210 [registered_ addObject:frame];
1213 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];