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 {
796 return [self rightButton];
797 else if ((/*clang:*/id) custom_ == [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];
851 [[self navigationItem] setRightBarButtonItem:[self customButton] animated:YES];
855 - (void) didStartLoading {
856 // Overridden in subclasses.
859 - (void) _didStartLoading {
860 [self applyRightButton];
862 if ([loading_ count] != 1)
865 if ([self retainsNetworkActivityIndicator])
866 [delegate_ retainNetworkActivityIndicator];
868 [self didStartLoading];
871 - (void) didFinishLoading {
872 // Overridden in subclasses.
875 - (void) _didFinishLoading {
876 if ([loading_ count] != 0)
879 [self applyRightButton];
880 [[self navigationItem] setTitle:title_];
882 if ([self retainsNetworkActivityIndicator])
883 [delegate_ releaseNetworkActivityIndicator];
885 [self didFinishLoading];
889 return [loading_ count] != 0;
892 - (id) initWithWidth:(float)width ofClass:(Class)_class {
893 if ((self = [super init]) != nil) {
897 [super setPageColor:nil];
899 allowsNavigationAction_ = true;
901 loading_ = [NSMutableSet setWithCapacity:5];
902 registered_ = [NSMutableSet setWithCapacity:5];
903 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
905 reloaditem_ = [[[UIBarButtonItem alloc]
906 initWithTitle:UCLocalize("RELOAD")
907 style:[self rightButtonStyle]
909 action:@selector(reloadButtonClicked)
912 loadingitem_ = [[[UIBarButtonItem alloc]
913 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
914 style:UIBarButtonItemStylePlain
916 action:@selector(customButtonClicked)
919 UIActivityIndicatorViewStyle style;
921 if (kCFCoreFoundationVersionNumber >= 800) {
922 style = UIActivityIndicatorViewStyleGray;
925 style = UIActivityIndicatorViewStyleWhite;
929 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
930 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
931 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
933 [self applyLeftButton];
934 [self applyRightButton];
938 - (NSString *) applicationNameForUserAgent {
943 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
945 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
946 [webview_ setDelegate:self];
947 [self setView:webview_];
949 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
950 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
952 [webview_ setDetectsPhoneNumbers:NO];
954 [webview_ setScalesPageToFit:YES];
956 UIWebDocumentView *document([webview_ _documentView]);
958 // XXX: I think this improves scrolling; the hardcoded-ness sucks
959 [document setTileSize:CGSizeMake(320, 500)];
961 WebView *webview([document webView]);
962 WebPreferences *preferences([webview preferences]);
964 // XXX: I have no clue if I actually /want/ this modification
965 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
966 [webview _setLayoutInterval:0];
967 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
968 [preferences _setLayoutInterval:0];
970 [preferences setCacheModel:WebCacheModelDocumentBrowser];
971 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
973 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
974 [preferences setOfflineWebApplicationCacheEnabled:YES];
976 if (NSString *agent = [self applicationNameForUserAgent])
977 [webview setApplicationNameForUserAgent:agent];
979 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
980 [webview setShouldUpdateWhileOffscreen:NO];
983 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
984 [document setAllowsMessaging:YES];
985 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
986 [webview _setAllowsMessaging:YES];
989 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
990 scroller_ = [webview_ _scrollView];
992 [scroller_ setDirectionalLockEnabled:YES];
993 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
994 [scroller_ setDelaysContentTouches:NO];
996 [scroller_ setCanCancelContentTouches:YES];
997 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
998 UIScroller *scroller([webview_ _scroller]);
999 scroller_ = (UIScrollView *) scroller;
1001 [scroller setDirectionalScrolling:YES];
1002 // XXX: we might be better off /not/ setting this on older systems
1003 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
1004 [scroller setScrollHysteresis:0]; /* 8 */
1006 [scroller setThumbDetectionEnabled:NO];
1008 // use NO with UIApplicationUseLegacyEvents(YES)
1009 [scroller setEventMode:YES];
1011 // XXX: this is handled by setBounces, right?
1012 //[scroller setAllowsRubberBanding:YES];
1015 [webview_ setOpaque:NO];
1016 [webview_ setBackgroundColor:nil];
1018 [scroller_ setFixedBackgroundPattern:YES];
1019 [scroller_ setBackgroundColor:color_];
1020 [scroller_ setClipsSubviews:YES];
1022 [scroller_ setBounces:YES];
1023 [scroller_ setScrollingEnabled:YES];
1024 [scroller_ setShowBackgroundShadow:NO];
1026 [self setViewportWidth:width_];
1028 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1029 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1030 [table setScrollsToTop:NO];
1031 [webview_ insertSubview:table atIndex:0];
1032 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1035 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1040 - (void) releaseSubviews {
1044 [self releaseNetworkActivityIndicator];
1046 [super releaseSubviews];
1049 - (id) initWithWidth:(float)width {
1050 return [self initWithWidth:width ofClass:[self class]];
1054 return [self initWithWidth:0];
1057 - (id) initWithURL:(NSURL *)url {
1058 if ((self = [self init]) != nil) {
1063 - (id) initWithRequest:(NSURLRequest *)request {
1064 if ((self = [self init]) != nil) {
1065 [self setRequest:request];
1069 + (void) _lockJavaScript:(WebPreferences *)preferences {
1070 WebThreadLocked lock;
1071 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1074 - (void) callFunction:(WebScriptObject *)function {
1075 WebThreadLocked lock;
1077 WebView *webview([[[self webView] _documentView] webView]);
1078 WebPreferences *preferences([webview preferences]);
1080 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
1081 if ([webview respondsToSelector:@selector(_preferencesChanged:)])
1082 [webview _preferencesChanged:preferences];
1084 [webview _preferencesChangedNotification:[NSNotification notificationWithName:@"" object:preferences]];
1086 WebFrame *frame([webview mainFrame]);
1087 JSGlobalContextRef context([frame globalContext]);
1089 JSObjectRef object([function JSObject]);
1090 if ($JSObjectCallAsFunction != NULL)
1091 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1093 // XXX: the JavaScript code submits a form, which seems to happen asynchronously
1094 NSObject *target([CyteWebViewController class]);
1095 [NSObject cancelPreviousPerformRequestsWithTarget:target selector:@selector(_lockJavaScript:) object:preferences];
1096 [target performSelector:@selector(_lockJavaScript:) withObject:preferences afterDelay:1];
1099 - (void) reloadButtonClicked {
1100 [self reloadURLWithCache:NO];
1103 - (void) _customButtonClicked {
1104 [self reloadButtonClicked];
1107 - (void) customButtonClicked {
1109 if (function_ != nil)
1110 [self callFunction:function_];
1113 [self _customButtonClicked];
1116 + (float) defaultWidth {
1120 - (void) setNavigationBarStyle:(NSString *)name {
1122 if ([name isEqualToString:@"Black"])
1123 style = UIBarStyleBlack;
1125 style = UIBarStyleDefault;
1127 [[[self navigationController] navigationBar] setBarStyle:style];
1130 - (void) setNavigationBarTintColor:(UIColor *)color {
1131 [[[self navigationController] navigationBar] setTintColor:color];
1134 - (void) setBadgeValue:(id)value {
1135 [[[self navigationController] tabBarItem] setBadgeValue:value];
1138 - (void) setHidesBackButton:(bool)value {
1139 [[self navigationItem] setHidesBackButton:value];
1140 [self applyLeftButton];
1143 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1144 [self setHidesBackButton:[value boolValue]];
1147 - (void) dispatchEvent:(NSString *)event {
1148 [[self webView] dispatchEvent:event];
1151 - (bool) hidesNavigationBar {
1152 return hidesNavigationBar_;
1155 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1157 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1160 - (void) setHidesNavigationBar:(bool)value {
1161 if (hidesNavigationBar_ != value) {
1162 hidesNavigationBar_ = value;
1163 [self _setHidesNavigationBar:YES animated:YES];
1167 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1168 [self setHidesNavigationBar:[value boolValue]];
1171 - (void) setScrollAlwaysBounceVertical:(bool)value {
1172 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1173 UIScrollView *scroller([webview_ _scrollView]);
1174 [scroller setAlwaysBounceVertical:value];
1175 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1176 //UIScroller *scroller([webview_ _scroller]);
1177 // XXX: I am sad here.
1181 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1182 [self setScrollAlwaysBounceVertical:[value boolValue]];
1185 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1186 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1187 UIScrollView *scroller([webview_ _scrollView]);
1188 [scroller setIndicatorStyle:style];
1189 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1190 UIScroller *scroller([webview_ _scroller]);
1191 [scroller setScrollerIndicatorStyle:style];
1195 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1196 UIScrollViewIndicatorStyle value;
1199 else if ([style isEqualToString:@"default"])
1200 value = UIScrollViewIndicatorStyleDefault;
1201 else if ([style isEqualToString:@"black"])
1202 value = UIScrollViewIndicatorStyleBlack;
1203 else if ([style isEqualToString:@"white"])
1204 value = UIScrollViewIndicatorStyleWhite;
1207 [self setScrollIndicatorStyle:value];
1210 - (void) viewWillAppear:(BOOL)animated {
1213 if ([self hidesNavigationBar])
1214 [self _setHidesNavigationBar:YES animated:animated];
1216 // XXX: why isn't this evern called automatically?
1217 [[self webView] setNeedsLayout];
1219 [self dispatchEvent:@"CydiaViewWillAppear"];
1220 [super viewWillAppear:animated];
1223 - (void) viewDidAppear:(BOOL)animated {
1224 [super viewDidAppear:animated];
1225 [self dispatchEvent:@"CydiaViewDidAppear"];
1228 - (void) viewWillDisappear:(BOOL)animated {
1229 [self dispatchEvent:@"CydiaViewWillDisappear"];
1230 [super viewWillDisappear:animated];
1232 if ([self hidesNavigationBar])
1233 [self _setHidesNavigationBar:NO animated:animated];
1238 - (void) viewDidDisappear:(BOOL)animated {
1239 [super viewDidDisappear:animated];
1240 [self dispatchEvent:@"CydiaViewDidDisappear"];
1243 - (void) updateHeights:(NSTimer *)timer {
1244 for (WebFrame *frame in (id) registered_)
1245 [frame cydia$updateHeight];
1248 - (void) registerFrame:(WebFrame *)frame {
1249 [registered_ addObject:frame];
1252 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];