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) {
556 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
558 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
561 [self _didFailWithError:error forFrame:frame];
564 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
566 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
569 [self _didFailWithError:error forFrame:frame];
572 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
573 NSValue *object([NSValue valueWithNonretainedObject:frame]);
574 if (![loading_ containsObject:object])
576 [loading_ removeObject:object];
578 if ([frame parentFrame] == nil) {
579 if (DOMDocument *document = [frame DOMDocument])
580 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
581 for (DOMHTMLBodyElement *body in (id) bodies) {
582 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
586 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
587 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
588 DOMRGBColor *rgb([color getRGBColorValue]);
590 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
591 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
592 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
593 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
597 colorWithRed:(red / 255)
605 [super setPageColor:uic];
606 [scroller_ setBackgroundColor:color_];
611 [self _didFinishLoading];
614 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
615 if ([frame parentFrame] != nil)
620 [[self navigationItem] setTitle:title_];
623 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
625 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
628 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
630 if ([frame parentFrame] == nil) {
636 [registered_ removeAllObjects];
639 allowsNavigationAction_ = true;
641 [self setHidesNavigationBar:NO];
642 [self setScrollAlwaysBounceVertical:true];
643 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
645 // XXX: do we still need to do this?
646 [[self navigationItem] setTitle:nil];
649 [self _didStartLoading];
652 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
653 challenge_ = [challenge retain];
655 NSURLProtectionSpace *space([challenge protectionSpace]);
656 NSString *realm([space realm]);
660 UIAlertView *alert = [[[UIAlertView alloc]
664 cancelButtonTitle:UCLocalize("CANCEL")
665 otherButtonTitles:UCLocalize("LOGIN"), nil
668 [alert setContext:@"challenge"];
669 [alert setNumberOfRows:1];
671 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
672 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
674 UITextField *username([alert textFieldAtIndex:0]); {
675 NSObject<UITextInputTraits> *traits([username textInputTraits]);
676 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
677 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
678 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
679 [traits setReturnKeyType:UIReturnKeyNext];
682 UITextField *password([alert textFieldAtIndex:1]); {
683 NSObject<UITextInputTraits> *traits([password textInputTraits]);
684 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
685 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
686 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
687 // XXX: UIReturnKeyDone
688 [traits setReturnKeyType:UIReturnKeyNext];
689 [traits setSecureTextEntry:YES];
695 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
697 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
703 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
705 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
711 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
712 return [self _allowJavaScriptPanel];
715 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
716 return [self _allowJavaScriptPanel];
719 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
720 return [self _allowJavaScriptPanel];
723 - (void) webViewClose:(WebView *)view {
729 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
732 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
733 NSString *context([alert context]);
735 if ([context isEqualToString:@"sensitive"]) {
738 sensitive_ = [NSNumber numberWithBool:YES];
742 sensitive_ = [NSNumber numberWithBool:NO];
746 [alert dismissWithClickedButtonIndex:-1 animated:YES];
747 } else if ([context isEqualToString:@"challenge"]) {
748 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
750 if (button == [alert cancelButtonIndex])
751 [sender cancelAuthenticationChallenge:challenge_];
752 else if (button == [alert firstOtherButtonIndex]) {
753 NSString *username([[alert textFieldAtIndex:0] text]);
754 NSString *password([[alert textFieldAtIndex:1] text]);
756 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
758 [sender useCredential:credential forAuthenticationChallenge:challenge_];
763 [alert dismissWithClickedButtonIndex:-1 animated:YES];
764 } else if ([context isEqualToString:@"itmsappss"]) {
765 if (button == [alert cancelButtonIndex]) {
766 } else if (button == [alert firstOtherButtonIndex]) {
767 [delegate_ openURL:appstore_];
770 [alert dismissWithClickedButtonIndex:-1 animated:YES];
771 } else if ([context isEqualToString:@"submit"]) {
772 if (button == [alert cancelButtonIndex]) {
773 } else if (button == [alert firstOtherButtonIndex]) {
774 if (request_ != nil) {
775 WebThreadLocked lock;
776 [[self webView] loadRequest:request_];
780 [alert dismissWithClickedButtonIndex:-1 animated:YES];
784 - (UIBarButtonItemStyle) rightButtonStyle {
785 if (style_ == nil) normal:
786 return UIBarButtonItemStylePlain;
787 else if ([style_ isEqualToString:@"Normal"])
788 return UIBarButtonItemStylePlain;
789 else if ([style_ isEqualToString:@"Highlighted"])
790 return UIBarButtonItemStyleDone;
794 - (UIBarButtonItem *) customButton {
797 else if ((/*clang:*/id) custom_ == [NSNull null])
798 return (UIBarButtonItem *) [NSNull null];
800 return [[[UIBarButtonItem alloc]
801 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
802 style:[self rightButtonStyle]
804 action:@selector(customButtonClicked)
808 - (UIBarButtonItem *) leftButton {
809 UINavigationItem *item([self navigationItem]);
810 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
813 if (UINavigationController *navigation = [self navigationController])
814 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
815 return [[[UIBarButtonItem alloc]
816 initWithTitle:UCLocalize("CLOSE")
817 style:UIBarButtonItemStylePlain
819 action:@selector(close)
825 - (void) applyLeftButton {
826 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
829 - (UIBarButtonItem *) rightButton {
833 - (void) applyLoadingTitle {
834 [[self navigationItem] setTitle:UCLocalize("LOADING")];
837 - (void) layoutRightButton {
838 [[loadingitem_ view] addSubview:indicator_];
839 [[loadingitem_ view] bringSubviewToFront:indicator_];
842 - (void) applyRightButton {
843 if ([self isLoading]) {
844 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
845 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
847 [indicator_ startAnimating];
848 [self applyLoadingTitle];
850 [indicator_ stopAnimating];
852 UIBarButtonItem *button([self customButton]);
854 button = [self rightButton];
855 else if (button == (UIBarButtonItem *) [NSNull null])
858 [[self navigationItem] setRightBarButtonItem:button animated:YES];
862 - (void) didStartLoading {
863 // Overridden in subclasses.
866 - (void) _didStartLoading {
867 [self applyRightButton];
869 if ([loading_ count] != 1)
872 if ([self retainsNetworkActivityIndicator])
873 [delegate_ retainNetworkActivityIndicator];
875 [self didStartLoading];
878 - (void) didFinishLoading {
879 // Overridden in subclasses.
882 - (void) _didFinishLoading {
883 if ([loading_ count] != 0)
886 [self applyRightButton];
887 [[self navigationItem] setTitle:title_];
889 if ([self retainsNetworkActivityIndicator])
890 [delegate_ releaseNetworkActivityIndicator];
892 [self didFinishLoading];
896 return [loading_ count] != 0;
899 - (id) initWithWidth:(float)width ofClass:(Class)_class {
900 if ((self = [super init]) != nil) {
904 [super setPageColor:nil];
906 allowsNavigationAction_ = true;
908 loading_ = [NSMutableSet setWithCapacity:5];
909 registered_ = [NSMutableSet setWithCapacity:5];
910 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
912 reloaditem_ = [[[UIBarButtonItem alloc]
913 initWithTitle:UCLocalize("RELOAD")
914 style:[self rightButtonStyle]
916 action:@selector(reloadButtonClicked)
919 loadingitem_ = [[[UIBarButtonItem alloc]
920 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
921 style:UIBarButtonItemStylePlain
923 action:@selector(reloadButtonClicked)
926 UIActivityIndicatorViewStyle style;
928 if (kCFCoreFoundationVersionNumber >= 800) {
929 style = UIActivityIndicatorViewStyleGray;
932 style = UIActivityIndicatorViewStyleWhite;
936 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
937 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
938 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
940 [self applyLeftButton];
941 [self applyRightButton];
945 - (NSString *) applicationNameForUserAgent {
950 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
952 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
953 [webview_ setDelegate:self];
954 [self setView:webview_];
956 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
957 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
959 [webview_ setDetectsPhoneNumbers:NO];
961 [webview_ setScalesPageToFit:YES];
963 UIWebDocumentView *document([webview_ _documentView]);
965 // XXX: I think this improves scrolling; the hardcoded-ness sucks
966 [document setTileSize:CGSizeMake(320, 500)];
968 WebView *webview([document webView]);
969 WebPreferences *preferences([webview preferences]);
971 // XXX: I have no clue if I actually /want/ this modification
972 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
973 [webview _setLayoutInterval:0];
974 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
975 [preferences _setLayoutInterval:0];
977 [preferences setCacheModel:WebCacheModelDocumentBrowser];
978 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
980 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
981 [preferences setOfflineWebApplicationCacheEnabled:YES];
983 if (NSString *agent = [self applicationNameForUserAgent])
984 [webview setApplicationNameForUserAgent:agent];
986 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
987 [webview setShouldUpdateWhileOffscreen:NO];
990 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
991 [document setAllowsMessaging:YES];
992 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
993 [webview _setAllowsMessaging:YES];
996 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
997 scroller_ = [webview_ _scrollView];
999 [scroller_ setDirectionalLockEnabled:YES];
1000 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
1001 [scroller_ setDelaysContentTouches:NO];
1003 [scroller_ setCanCancelContentTouches:YES];
1004 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1005 UIScroller *scroller([webview_ _scroller]);
1006 scroller_ = (UIScrollView *) scroller;
1008 [scroller setDirectionalScrolling:YES];
1009 // XXX: we might be better off /not/ setting this on older systems
1010 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
1011 [scroller setScrollHysteresis:0]; /* 8 */
1013 [scroller setThumbDetectionEnabled:NO];
1015 // use NO with UIApplicationUseLegacyEvents(YES)
1016 [scroller setEventMode:YES];
1018 // XXX: this is handled by setBounces, right?
1019 //[scroller setAllowsRubberBanding:YES];
1022 [webview_ setOpaque:NO];
1023 [webview_ setBackgroundColor:nil];
1025 [scroller_ setFixedBackgroundPattern:YES];
1026 [scroller_ setBackgroundColor:color_];
1027 [scroller_ setClipsSubviews:YES];
1029 [scroller_ setBounces:YES];
1030 [scroller_ setScrollingEnabled:YES];
1031 [scroller_ setShowBackgroundShadow:NO];
1033 [self setViewportWidth:width_];
1035 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1036 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1037 [table setScrollsToTop:NO];
1038 [webview_ insertSubview:table atIndex:0];
1039 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1042 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1047 - (void) releaseSubviews {
1051 [self releaseNetworkActivityIndicator];
1053 [super releaseSubviews];
1056 - (id) initWithWidth:(float)width {
1057 return [self initWithWidth:width ofClass:[self class]];
1061 return [self initWithWidth:0];
1064 - (id) initWithURL:(NSURL *)url {
1065 if ((self = [self init]) != nil) {
1070 - (id) initWithRequest:(NSURLRequest *)request {
1071 if ((self = [self init]) != nil) {
1072 [self setRequest:request];
1076 + (void) _lockJavaScript:(WebPreferences *)preferences {
1077 WebThreadLocked lock;
1078 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1081 - (void) callFunction:(WebScriptObject *)function {
1082 WebThreadLocked lock;
1084 WebView *webview([[[self webView] _documentView] webView]);
1085 WebPreferences *preferences([webview preferences]);
1087 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
1088 if ([webview respondsToSelector:@selector(_preferencesChanged:)])
1089 [webview _preferencesChanged:preferences];
1091 [webview _preferencesChangedNotification:[NSNotification notificationWithName:@"" object:preferences]];
1093 WebFrame *frame([webview mainFrame]);
1094 JSGlobalContextRef context([frame globalContext]);
1096 JSObjectRef object([function JSObject]);
1097 if ($JSObjectCallAsFunction != NULL)
1098 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1100 // XXX: the JavaScript code submits a form, which seems to happen asynchronously
1101 NSObject *target([CyteWebViewController class]);
1102 [NSObject cancelPreviousPerformRequestsWithTarget:target selector:@selector(_lockJavaScript:) object:preferences];
1103 [target performSelector:@selector(_lockJavaScript:) withObject:preferences afterDelay:1];
1106 - (void) reloadButtonClicked {
1107 [self reloadURLWithCache:NO];
1110 - (void) _customButtonClicked {
1111 [self reloadButtonClicked];
1114 - (void) customButtonClicked {
1116 if (function_ != nil)
1117 [self callFunction:function_];
1120 [self _customButtonClicked];
1123 + (float) defaultWidth {
1127 - (void) setNavigationBarStyle:(NSString *)name {
1129 if ([name isEqualToString:@"Black"])
1130 style = UIBarStyleBlack;
1132 style = UIBarStyleDefault;
1134 [[[self navigationController] navigationBar] setBarStyle:style];
1137 - (void) setNavigationBarTintColor:(UIColor *)color {
1138 [[[self navigationController] navigationBar] setTintColor:color];
1141 - (void) setBadgeValue:(id)value {
1142 [[[self navigationController] tabBarItem] setBadgeValue:value];
1145 - (void) setHidesBackButton:(bool)value {
1146 [[self navigationItem] setHidesBackButton:value];
1147 [self applyLeftButton];
1150 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1151 [self setHidesBackButton:[value boolValue]];
1154 - (void) dispatchEvent:(NSString *)event {
1155 [[self webView] dispatchEvent:event];
1158 - (bool) hidesNavigationBar {
1159 return hidesNavigationBar_;
1162 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1164 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1167 - (void) setHidesNavigationBar:(bool)value {
1168 if (hidesNavigationBar_ != value) {
1169 hidesNavigationBar_ = value;
1170 [self _setHidesNavigationBar:YES animated:YES];
1174 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1175 [self setHidesNavigationBar:[value boolValue]];
1178 - (void) setScrollAlwaysBounceVertical:(bool)value {
1179 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1180 UIScrollView *scroller([webview_ _scrollView]);
1181 [scroller setAlwaysBounceVertical:value];
1182 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1183 //UIScroller *scroller([webview_ _scroller]);
1184 // XXX: I am sad here.
1188 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1189 [self setScrollAlwaysBounceVertical:[value boolValue]];
1192 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1193 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1194 UIScrollView *scroller([webview_ _scrollView]);
1195 [scroller setIndicatorStyle:style];
1196 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1197 UIScroller *scroller([webview_ _scroller]);
1198 [scroller setScrollerIndicatorStyle:style];
1202 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1203 UIScrollViewIndicatorStyle value;
1206 else if ([style isEqualToString:@"default"])
1207 value = UIScrollViewIndicatorStyleDefault;
1208 else if ([style isEqualToString:@"black"])
1209 value = UIScrollViewIndicatorStyleBlack;
1210 else if ([style isEqualToString:@"white"])
1211 value = UIScrollViewIndicatorStyleWhite;
1214 [self setScrollIndicatorStyle:value];
1217 - (void) viewWillAppear:(BOOL)animated {
1220 if ([self hidesNavigationBar])
1221 [self _setHidesNavigationBar:YES animated:animated];
1223 // XXX: why isn't this evern called automatically?
1224 [[self webView] setNeedsLayout];
1226 [self dispatchEvent:@"CydiaViewWillAppear"];
1227 [super viewWillAppear:animated];
1230 - (void) viewDidAppear:(BOOL)animated {
1231 [super viewDidAppear:animated];
1232 [self dispatchEvent:@"CydiaViewDidAppear"];
1235 - (void) viewWillDisappear:(BOOL)animated {
1236 [self dispatchEvent:@"CydiaViewWillDisappear"];
1237 [super viewWillDisappear:animated];
1239 if ([self hidesNavigationBar])
1240 [self _setHidesNavigationBar:NO animated:animated];
1245 - (void) viewDidDisappear:(BOOL)animated {
1246 [super viewDidDisappear:animated];
1247 [self dispatchEvent:@"CydiaViewDidDisappear"];
1250 - (void) updateHeights:(NSTimer *)timer {
1251 for (WebFrame *frame in (id) registered_)
1252 [frame cydia$updateHeight];
1255 - (void) registerFrame:(WebFrame *)frame {
1256 [registered_ addObject:frame];
1259 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];