1 #include "CyteKit/UCPlatform.h"
3 #include "CyteKit/IndirectDelegate.h"
4 #include "CyteKit/Localize.h"
5 #include "CyteKit/MFMailComposeViewController-MailToURL.h"
6 #include "CyteKit/RegEx.hpp"
7 #include "CyteKit/WebThreadLocked.hpp"
8 #include "CyteKit/WebViewController.h"
10 #include "iPhonePrivate.h"
12 //#include <QuartzCore/CALayer.h>
13 // XXX: fix the minimum requirement
14 extern NSString * const kCAFilterNearest;
16 #include <WebCore/WebCoreThread.h>
19 #include <objc/runtime.h>
22 #define DefaultTimeout_ 120.0
24 #define ShowInternals 0
28 #define lprintf(args...) fprintf(stderr, args)
30 JSValueRef (*$JSObjectCallAsFunction)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *);
32 // XXX: centralize these special class things to some file or mechanism?
33 static Class $MFMailComposeViewController;
35 float CYScrollViewDecelerationRateNormal;
37 @interface WebFrame (Cydia)
38 - (void) cydia$updateHeight;
41 @implementation WebFrame (Cydia)
43 - (NSString *) description {
44 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[[([self provisionalDataSource] ?: [self dataSource]) request] URL] absoluteString]];
47 - (void) cydia$updateHeight {
48 [[[self frameElement] style]
50 value:[NSString stringWithFormat:@"%dpx",
51 [[[self DOMDocument] body] scrollHeight]]
57 /* Indirect Delegate {{{ */
58 @implementation IndirectDelegate
64 - (void) setDelegate:(id)delegate {
68 - (id) initWithDelegate:(id)delegate {
73 - (IMP) methodForSelector:(SEL)sel {
74 if (IMP method = [super methodForSelector:sel])
76 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
80 - (BOOL) respondsToSelector:(SEL)sel {
81 if ([super respondsToSelector:sel])
84 // XXX: WebThreadCreateNSInvocation returns nil
87 fprintf(stderr, "[%s]R?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
90 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
93 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
94 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
98 fprintf(stderr, "[%s]S?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
101 if (delegate_ != nil)
102 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
105 // XXX: I fucking hate Apple so very very bad
106 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
109 - (void) forwardInvocation:(NSInvocation *)inv {
110 SEL sel = [inv selector];
111 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
112 [inv invokeWithTarget:delegate_];
118 @implementation CyteWebViewController
121 #include "CyteKit/UCInternal.h"
124 + (void) _initialize {
125 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
129 js = dlopen("/System/Library/Frameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
131 js = dlopen("/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
133 $JSObjectCallAsFunction = reinterpret_cast<JSValueRef (*)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(js, "JSObjectCallAsFunction"));
135 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
136 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
138 if (CGFloat *_UIScrollViewDecelerationRateNormal = reinterpret_cast<CGFloat *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
139 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
140 else // XXX: this actually might be fast on some older systems: we should look into this
141 CYScrollViewDecelerationRateNormal = 0.998;
144 - (bool) retainsNetworkActivityIndicator {
148 - (void) releaseNetworkActivityIndicator {
149 if ([loading_ count] != 0) {
150 [loading_ removeAllObjects];
152 if ([self retainsNetworkActivityIndicator])
153 [delegate_ releaseNetworkActivityIndicator];
159 NSLog(@"[CyteWebViewController dealloc]");
162 [self releaseNetworkActivityIndicator];
167 - (NSString *) description {
168 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[request_ URL] absoluteString]];
171 - (CyteWebView *) webView {
172 return (CyteWebView *) [self view];
175 - (NSURL *) URLWithURL:(NSURL *)url {
179 - (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy referrer:(NSString *)referrer {
180 NSMutableURLRequest *request([NSMutableURLRequest
181 requestWithURL:[self URLWithURL:url]
183 timeoutInterval:DefaultTimeout_
186 [request setValue:referrer forHTTPHeaderField:@"Referer"];
191 - (void) setRequest:(NSURLRequest *)request {
192 _assert(request_ == nil);
196 - (void) setURL:(NSURL *)url {
197 [self setURL:url withReferrer:nil];
200 - (void) setURL:(NSURL *)url withReferrer:(NSString *)referrer {
201 [self setRequest:[self requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy referrer:referrer]];
204 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
205 [self loadRequest:[self requestWithURL:url cachePolicy:policy referrer:nil]];
208 - (void) loadURL:(NSURL *)url {
209 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
212 - (void) loadRequest:(NSURLRequest *)request {
214 NSLog(@"loadRequest:%@", request);
220 WebThreadLocked lock;
221 [[self webView] loadRequest:request];
224 - (void) reloadURLWithCache:(BOOL)cache {
228 NSMutableURLRequest *request([request_ mutableCopy]);
229 [request setCachePolicy:(cache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData)];
233 if (cache || [request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
234 [self loadRequest:request_];
236 UIAlertView *alert = [[[UIAlertView alloc]
237 initWithTitle:UCLocalize("RESUBMIT_FORM")
240 cancelButtonTitle:UCLocalize("CANCEL")
242 UCLocalize("SUBMIT"),
246 [alert setContext:@"submit"];
251 - (void) reloadData {
255 [self dispatchEvent:@"CydiaReloadData"];
257 [self reloadURLWithCache:YES];
260 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
263 function_ = function;
265 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
268 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
271 function_ = function;
273 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
276 - (void) removeButton {
277 custom_ = [NSNull null];
278 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
281 - (void) scrollToBottomAnimated:(NSNumber *)animated {
282 CGSize size([scroller_ contentSize]);
283 CGPoint offset([scroller_ contentOffset]);
284 CGRect frame([scroller_ frame]);
286 if (size.height - offset.y < frame.size.height + 20.f) {
287 CGRect rect = {{0, size.height-1}, {size.width, 1}};
288 [scroller_ scrollRectToVisible:rect animated:[animated boolValue]];
292 - (void) _setViewportWidth {
293 [[[self webView] _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
296 - (void) setViewportWidth:(float)width {
297 width_ = width != 0 ? width : [[self class] defaultWidth];
298 [self _setViewportWidth];
301 - (void) _setViewportWidthOnMainThread:(NSNumber *)width {
302 [self setViewportWidth:[width floatValue]];
305 - (void) setViewportWidthOnMainThread:(float)width {
306 [self performSelectorOnMainThread:@selector(_setViewportWidthOnMainThread:) withObject:[NSNumber numberWithFloat:width] waitUntilDone:NO];
309 - (void) webViewUpdateViewSettings:(UIWebView *)view {
310 [self _setViewportWidth];
313 - (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
314 [self dismissModalViewControllerAnimated:YES];
317 - (void) _setupMail:(MFMailComposeViewController *)controller {
320 - (void) _openMailToURL:(NSURL *)url {
321 if ($MFMailComposeViewController != nil && [$MFMailComposeViewController canSendMail]) {
322 MFMailComposeViewController *controller([[[$MFMailComposeViewController alloc] init] autorelease]);
323 [controller setMailComposeDelegate:self];
325 [controller setMailToURL:url];
327 [self _setupMail:controller];
329 [self presentModalViewController:controller animated:YES];
333 UIApplication *app([UIApplication sharedApplication]);
334 if ([app respondsToSelector:@selector(openURL:asPanel:)])
335 [app openURL:url asPanel:YES];
340 - (bool) _allowJavaScriptPanel {
344 - (bool) allowsNavigationAction {
345 return allowsNavigationAction_;
348 - (void) setAllowsNavigationAction:(bool)value {
349 allowsNavigationAction_ = value;
352 - (void) setAllowsNavigationActionByNumber:(NSNumber *)value {
353 [self setAllowsNavigationAction:[value boolValue]];
356 - (void) popViewControllerWithNumber:(NSNumber *)value {
357 UINavigationController *navigation([self navigationController]);
358 if ([navigation topViewController] == self)
359 [navigation popViewControllerAnimated:[value boolValue]];
362 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
363 NSValue *object([NSValue valueWithNonretainedObject:frame]);
364 if (![loading_ containsObject:object])
366 [loading_ removeObject:object];
368 [self _didFinishLoading];
370 if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == NSURLErrorCancelled)
373 if ([[error domain] isEqualToString:WebKitErrorDomain] && [error code] == WebKitErrorFrameLoadInterruptedByPolicyChange) {
378 if ([frame parentFrame] == nil) {
379 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
380 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
381 [[error localizedDescription] stringByAddingPercentEscapes]
388 - (void) pushRequest:(NSURLRequest *)request forAction:(NSDictionary *)action asPop:(bool)pop {
389 WebFrame *frame(nil);
390 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
391 frame = [WebActionElement objectForKey:@"WebElementFrame"];
393 frame = [[[[self webView] _documentView] webView] mainFrame];
395 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
396 NSString *referrer([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString]);
398 NSURL *url([request URL]);
400 // XXX: filter to internal usage?
401 CyteViewController *page([delegate_ pageForURL:url forExternal:NO withReferrer:referrer]);
404 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
405 [browser setRequest:request];
409 [page setDelegate:delegate_];
410 [page setPageColor:color_];
413 [[self navigationItem] setTitle:title_];
415 [[self navigationController] pushViewController:page animated:YES];
417 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
419 [navigation setDelegate:delegate_];
421 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
422 initWithTitle:UCLocalize("CLOSE")
423 style:UIBarButtonItemStylePlain
425 action:@selector(close)
428 [[self navigationController] presentModalViewController:navigation animated:YES];
432 // CyteWebViewDelegate {{{
433 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
435 static RegEx irritating("(?"
436 ":" "The page at .* displayed insecure content from .*\\."
437 "|" "Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\."
440 if (NSString *data = [message objectForKey:@"message"])
441 if (irritating(data))
444 NSLog(@"addMessageToConsole:%@", message);
448 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
450 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ %@ frame:%@", action, request, [request allHTTPHeaderFields], frame);
453 NSURL *url(request == nil ? nil : [request URL]);
454 NSString *scheme([[url scheme] lowercaseString]);
455 NSString *absolute([[url absoluteString] lowercaseString]);
458 [scheme isEqualToString:@"itms"] ||
459 [scheme isEqualToString:@"itmss"] ||
460 [scheme isEqualToString:@"itms-apps"] ||
461 [scheme isEqualToString:@"itms-appss"] ||
462 [absolute hasPrefix:@"http://itunes.apple.com/"] ||
463 [absolute hasPrefix:@"https://itunes.apple.com/"] ||
467 UIAlertView *alert = [[[UIAlertView alloc]
468 initWithTitle:UCLocalize("APP_STORE_REDIRECT")
471 cancelButtonTitle:UCLocalize("CANCEL")
477 [alert setContext:@"itmsappss"];
484 if ([frame parentFrame] == nil) {
486 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
488 [self pushRequest:request forAction:action asPop:NO];
495 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
497 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ %@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
500 if ([frame parentFrame] == nil) {
502 case CYWebPolicyDecisionIgnore:
503 if ([[request_ URL] isEqual:[request URL]])
507 case CYWebPolicyDecisionUse:
518 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
520 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
523 NSURL *url([request URL]);
527 if ([name isEqualToString:@"_open"])
528 [delegate_ openURL:url];
530 NSString *scheme([[url scheme] lowercaseString]);
531 if ([scheme isEqualToString:@"mailto"])
532 [self _openMailToURL:url];
534 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
540 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
542 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
546 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
548 NSLog(@"didCommitLoadForFrame:%@", frame);
551 if ([frame parentFrame] == nil) {
555 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
557 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
560 [self _didFailWithError:error forFrame:frame];
563 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
565 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
568 [self _didFailWithError:error forFrame:frame];
571 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
572 NSValue *object([NSValue valueWithNonretainedObject:frame]);
573 if (![loading_ containsObject:object])
575 [loading_ removeObject:object];
577 if ([frame parentFrame] == nil) {
578 if (DOMDocument *document = [frame DOMDocument])
579 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
580 for (DOMHTMLBodyElement *body in (id) bodies) {
581 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
585 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
586 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
587 DOMRGBColor *rgb([color getRGBColorValue]);
589 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
590 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
591 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
592 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
596 colorWithRed:(red / 255)
604 [super setPageColor:uic];
605 [scroller_ setBackgroundColor:color_];
610 [self _didFinishLoading];
613 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
614 if ([frame parentFrame] != nil)
619 [[self navigationItem] setTitle:title_];
622 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
624 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
627 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
629 if ([frame parentFrame] == nil) {
635 [registered_ removeAllObjects];
638 allowsNavigationAction_ = true;
640 [self setHidesNavigationBar:NO];
641 [self setScrollAlwaysBounceVertical:true];
642 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
644 // XXX: do we still need to do this?
645 [[self navigationItem] setTitle:nil];
648 [self _didStartLoading];
651 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
652 challenge_ = [challenge retain];
654 NSURLProtectionSpace *space([challenge protectionSpace]);
655 NSString *realm([space realm]);
659 UIAlertView *alert = [[[UIAlertView alloc]
663 cancelButtonTitle:UCLocalize("CANCEL")
664 otherButtonTitles:UCLocalize("LOGIN"), nil
667 [alert setContext:@"challenge"];
668 [alert setNumberOfRows:1];
670 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
671 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
673 UITextField *username([alert textFieldAtIndex:0]); {
674 NSObject<UITextInputTraits> *traits([username textInputTraits]);
675 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
676 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
677 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
678 [traits setReturnKeyType:UIReturnKeyNext];
681 UITextField *password([alert textFieldAtIndex:1]); {
682 NSObject<UITextInputTraits> *traits([password textInputTraits]);
683 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
684 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
685 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
686 // XXX: UIReturnKeyDone
687 [traits setReturnKeyType:UIReturnKeyNext];
688 [traits setSecureTextEntry:YES];
694 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
696 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
702 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
704 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
710 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
711 return [self _allowJavaScriptPanel];
714 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
715 return [self _allowJavaScriptPanel];
718 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
719 return [self _allowJavaScriptPanel];
722 - (void) webViewClose:(WebView *)view {
728 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
731 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
732 NSString *context([alert context]);
734 if ([context isEqualToString:@"sensitive"]) {
737 sensitive_ = [NSNumber numberWithBool:YES];
741 sensitive_ = [NSNumber numberWithBool:NO];
745 [alert dismissWithClickedButtonIndex:-1 animated:YES];
746 } else if ([context isEqualToString:@"challenge"]) {
747 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
749 if (button == [alert cancelButtonIndex])
750 [sender cancelAuthenticationChallenge:challenge_];
751 else if (button == [alert firstOtherButtonIndex]) {
752 NSString *username([[alert textFieldAtIndex:0] text]);
753 NSString *password([[alert textFieldAtIndex:1] text]);
755 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
757 [sender useCredential:credential forAuthenticationChallenge:challenge_];
762 [alert dismissWithClickedButtonIndex:-1 animated:YES];
763 } else if ([context isEqualToString:@"itmsappss"]) {
764 if (button == [alert cancelButtonIndex]) {
765 } else if (button == [alert firstOtherButtonIndex]) {
766 [delegate_ openURL:appstore_];
769 [alert dismissWithClickedButtonIndex:-1 animated:YES];
770 } else if ([context isEqualToString:@"submit"]) {
771 if (button == [alert cancelButtonIndex]) {
772 } else if (button == [alert firstOtherButtonIndex]) {
773 if (request_ != nil) {
774 WebThreadLocked lock;
775 [[self webView] loadRequest:request_];
779 [alert dismissWithClickedButtonIndex:-1 animated:YES];
783 - (UIBarButtonItemStyle) rightButtonStyle {
784 if (style_ == nil) normal:
785 return UIBarButtonItemStylePlain;
786 else if ([style_ isEqualToString:@"Normal"])
787 return UIBarButtonItemStylePlain;
788 else if ([style_ isEqualToString:@"Highlighted"])
789 return UIBarButtonItemStyleDone;
793 - (UIBarButtonItem *) customButton {
795 return [self rightButton];
796 else if ((/*clang:*/id) custom_ == [NSNull null])
799 return [[[UIBarButtonItem alloc]
800 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
801 style:[self rightButtonStyle]
803 action:@selector(customButtonClicked)
807 - (UIBarButtonItem *) leftButton {
808 UINavigationItem *item([self navigationItem]);
809 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
812 if (UINavigationController *navigation = [self navigationController])
813 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
814 return [[[UIBarButtonItem alloc]
815 initWithTitle:UCLocalize("CLOSE")
816 style:UIBarButtonItemStylePlain
818 action:@selector(close)
824 - (void) applyLeftButton {
825 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
828 - (UIBarButtonItem *) rightButton {
832 - (void) applyLoadingTitle {
833 [[self navigationItem] setTitle:UCLocalize("LOADING")];
836 - (void) layoutRightButton {
837 [[loadingitem_ view] addSubview:indicator_];
838 [[loadingitem_ view] bringSubviewToFront:indicator_];
841 - (void) applyRightButton {
842 if ([self isLoading]) {
843 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
844 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
846 [indicator_ startAnimating];
847 [self applyLoadingTitle];
849 [indicator_ stopAnimating];
850 [[self navigationItem] setRightBarButtonItem:[self customButton] animated:YES];
854 - (void) didStartLoading {
855 // Overridden in subclasses.
858 - (void) _didStartLoading {
859 [self applyRightButton];
861 if ([loading_ count] != 1)
864 if ([self retainsNetworkActivityIndicator])
865 [delegate_ retainNetworkActivityIndicator];
867 [self didStartLoading];
870 - (void) didFinishLoading {
871 // Overridden in subclasses.
874 - (void) _didFinishLoading {
875 if ([loading_ count] != 0)
878 [self applyRightButton];
879 [[self navigationItem] setTitle:title_];
881 if ([self retainsNetworkActivityIndicator])
882 [delegate_ releaseNetworkActivityIndicator];
884 [self didFinishLoading];
888 return [loading_ count] != 0;
891 - (id) initWithWidth:(float)width ofClass:(Class)_class {
892 if ((self = [super init]) != nil) {
896 [super setPageColor:nil];
898 allowsNavigationAction_ = true;
900 loading_ = [NSMutableSet setWithCapacity:5];
901 registered_ = [NSMutableSet setWithCapacity:5];
902 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
904 reloaditem_ = [[[UIBarButtonItem alloc]
905 initWithTitle:UCLocalize("RELOAD")
906 style:[self rightButtonStyle]
908 action:@selector(reloadButtonClicked)
911 loadingitem_ = [[[UIBarButtonItem alloc]
912 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
913 style:UIBarButtonItemStylePlain
915 action:@selector(customButtonClicked)
918 UIActivityIndicatorViewStyle style;
920 if (kCFCoreFoundationVersionNumber >= 800) {
921 style = UIActivityIndicatorViewStyleGray;
924 style = UIActivityIndicatorViewStyleWhite;
928 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
929 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
930 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
932 [self applyLeftButton];
933 [self applyRightButton];
937 - (NSString *) applicationNameForUserAgent {
942 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
944 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
945 [webview_ setDelegate:self];
946 [self setView:webview_];
948 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
949 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
951 [webview_ setDetectsPhoneNumbers:NO];
953 [webview_ setScalesPageToFit:YES];
955 UIWebDocumentView *document([webview_ _documentView]);
957 // XXX: I think this improves scrolling; the hardcoded-ness sucks
958 [document setTileSize:CGSizeMake(320, 500)];
960 WebView *webview([document webView]);
961 WebPreferences *preferences([webview preferences]);
963 // XXX: I have no clue if I actually /want/ this modification
964 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
965 [webview _setLayoutInterval:0];
966 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
967 [preferences _setLayoutInterval:0];
969 [preferences setCacheModel:WebCacheModelDocumentBrowser];
970 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
972 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
973 [preferences setOfflineWebApplicationCacheEnabled:YES];
975 if (NSString *agent = [self applicationNameForUserAgent])
976 [webview setApplicationNameForUserAgent:agent];
978 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
979 [webview setShouldUpdateWhileOffscreen:NO];
982 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
983 [document setAllowsMessaging:YES];
984 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
985 [webview _setAllowsMessaging:YES];
988 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
989 scroller_ = [webview_ _scrollView];
991 [scroller_ setDirectionalLockEnabled:YES];
992 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
993 [scroller_ setDelaysContentTouches:NO];
995 [scroller_ setCanCancelContentTouches:YES];
996 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
997 UIScroller *scroller([webview_ _scroller]);
998 scroller_ = (UIScrollView *) scroller;
1000 [scroller setDirectionalScrolling:YES];
1001 // XXX: we might be better off /not/ setting this on older systems
1002 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
1003 [scroller setScrollHysteresis:0]; /* 8 */
1005 [scroller setThumbDetectionEnabled:NO];
1007 // use NO with UIApplicationUseLegacyEvents(YES)
1008 [scroller setEventMode:YES];
1010 // XXX: this is handled by setBounces, right?
1011 //[scroller setAllowsRubberBanding:YES];
1014 [webview_ setOpaque:NO];
1015 [webview_ setBackgroundColor:nil];
1017 [scroller_ setFixedBackgroundPattern:YES];
1018 [scroller_ setBackgroundColor:color_];
1019 [scroller_ setClipsSubviews:YES];
1021 [scroller_ setBounces:YES];
1022 [scroller_ setScrollingEnabled:YES];
1023 [scroller_ setShowBackgroundShadow:NO];
1025 [self setViewportWidth:width_];
1027 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1028 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1029 [table setScrollsToTop:NO];
1030 [webview_ insertSubview:table atIndex:0];
1031 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1034 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1039 - (void) releaseSubviews {
1043 [self releaseNetworkActivityIndicator];
1045 [super releaseSubviews];
1048 - (id) initWithWidth:(float)width {
1049 return [self initWithWidth:width ofClass:[self class]];
1053 return [self initWithWidth:0];
1056 - (id) initWithURL:(NSURL *)url {
1057 if ((self = [self init]) != nil) {
1062 - (id) initWithRequest:(NSURLRequest *)request {
1063 if ((self = [self init]) != nil) {
1064 [self setRequest:request];
1068 + (void) _lockJavaScript:(WebPreferences *)preferences {
1069 WebThreadLocked lock;
1070 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1073 - (void) callFunction:(WebScriptObject *)function {
1074 WebThreadLocked lock;
1076 WebView *webview([[[self webView] _documentView] webView]);
1077 WebPreferences *preferences([webview preferences]);
1079 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
1080 if ([webview respondsToSelector:@selector(_preferencesChanged:)])
1081 [webview _preferencesChanged:preferences];
1083 [webview _preferencesChangedNotification:[NSNotification notificationWithName:@"" object:preferences]];
1085 WebFrame *frame([webview mainFrame]);
1086 JSGlobalContextRef context([frame globalContext]);
1088 JSObjectRef object([function JSObject]);
1089 if ($JSObjectCallAsFunction != NULL)
1090 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1092 // XXX: the JavaScript code submits a form, which seems to happen asynchronously
1093 NSObject *target([CyteWebViewController class]);
1094 [NSObject cancelPreviousPerformRequestsWithTarget:target selector:@selector(_lockJavaScript:) object:preferences];
1095 [target performSelector:@selector(_lockJavaScript:) withObject:preferences afterDelay:1];
1098 - (void) reloadButtonClicked {
1099 [self reloadURLWithCache:NO];
1102 - (void) _customButtonClicked {
1103 [self reloadButtonClicked];
1106 - (void) customButtonClicked {
1108 if (function_ != nil)
1109 [self callFunction:function_];
1112 [self _customButtonClicked];
1115 + (float) defaultWidth {
1119 - (void) setNavigationBarStyle:(NSString *)name {
1121 if ([name isEqualToString:@"Black"])
1122 style = UIBarStyleBlack;
1124 style = UIBarStyleDefault;
1126 [[[self navigationController] navigationBar] setBarStyle:style];
1129 - (void) setNavigationBarTintColor:(UIColor *)color {
1130 [[[self navigationController] navigationBar] setTintColor:color];
1133 - (void) setBadgeValue:(id)value {
1134 [[[self navigationController] tabBarItem] setBadgeValue:value];
1137 - (void) setHidesBackButton:(bool)value {
1138 [[self navigationItem] setHidesBackButton:value];
1139 [self applyLeftButton];
1142 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1143 [self setHidesBackButton:[value boolValue]];
1146 - (void) dispatchEvent:(NSString *)event {
1147 [[self webView] dispatchEvent:event];
1150 - (bool) hidesNavigationBar {
1151 return hidesNavigationBar_;
1154 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1156 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1159 - (void) setHidesNavigationBar:(bool)value {
1160 if (hidesNavigationBar_ != value) {
1161 hidesNavigationBar_ = value;
1162 [self _setHidesNavigationBar:YES animated:YES];
1166 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1167 [self setHidesNavigationBar:[value boolValue]];
1170 - (void) setScrollAlwaysBounceVertical:(bool)value {
1171 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1172 UIScrollView *scroller([webview_ _scrollView]);
1173 [scroller setAlwaysBounceVertical:value];
1174 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1175 //UIScroller *scroller([webview_ _scroller]);
1176 // XXX: I am sad here.
1180 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1181 [self setScrollAlwaysBounceVertical:[value boolValue]];
1184 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1185 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1186 UIScrollView *scroller([webview_ _scrollView]);
1187 [scroller setIndicatorStyle:style];
1188 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1189 UIScroller *scroller([webview_ _scroller]);
1190 [scroller setScrollerIndicatorStyle:style];
1194 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1195 UIScrollViewIndicatorStyle value;
1198 else if ([style isEqualToString:@"default"])
1199 value = UIScrollViewIndicatorStyleDefault;
1200 else if ([style isEqualToString:@"black"])
1201 value = UIScrollViewIndicatorStyleBlack;
1202 else if ([style isEqualToString:@"white"])
1203 value = UIScrollViewIndicatorStyleWhite;
1206 [self setScrollIndicatorStyle:value];
1209 - (void) viewWillAppear:(BOOL)animated {
1212 if ([self hidesNavigationBar])
1213 [self _setHidesNavigationBar:YES animated:animated];
1215 // XXX: why isn't this evern called automatically?
1216 [[self webView] setNeedsLayout];
1218 [self dispatchEvent:@"CydiaViewWillAppear"];
1219 [super viewWillAppear:animated];
1222 - (void) viewDidAppear:(BOOL)animated {
1223 [super viewDidAppear:animated];
1224 [self dispatchEvent:@"CydiaViewDidAppear"];
1227 - (void) viewWillDisappear:(BOOL)animated {
1228 [self dispatchEvent:@"CydiaViewWillDisappear"];
1229 [super viewWillDisappear:animated];
1231 if ([self hidesNavigationBar])
1232 [self _setHidesNavigationBar:NO animated:animated];
1237 - (void) viewDidDisappear:(BOOL)animated {
1238 [super viewDidDisappear:animated];
1239 [self dispatchEvent:@"CydiaViewDidDisappear"];
1242 - (void) updateHeights:(NSTimer *)timer {
1243 for (WebFrame *frame in (id) registered_)
1244 [frame cydia$updateHeight];
1247 - (void) registerFrame:(WebFrame *)frame {
1248 [registered_ addObject:frame];
1251 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];