1 #include "CyteKit/UCPlatform.h"
2 #include "CyteKit/WebViewController.h"
4 #include "CyteKit/MFMailComposeViewController-MailToURL.h"
6 #include "iPhonePrivate.h"
8 #include "CyteKit/IndirectDelegate.h"
9 #include "CyteKit/Localize.h"
10 #include "CyteKit/WebViewController.h"
11 #include "CyteKit/PerlCompatibleRegEx.hpp"
12 #include "CyteKit/WebThreadLocked.hpp"
14 //#include <QuartzCore/CALayer.h>
15 // XXX: fix the minimum requirement
16 extern NSString * const kCAFilterNearest;
18 #include <WebCore/WebCoreThread.h>
20 #import <WebKit/WebKitErrors.h>
21 #import <WebKit/WebPreferences.h>
23 #include <WebKit/DOMCSSPrimitiveValue.h>
24 #include <WebKit/DOMCSSStyleDeclaration.h>
25 #include <WebKit/DOMDocument.h>
26 #include <WebKit/DOMHTMLBodyElement.h>
27 #include <WebKit/DOMRGBColor.h>
30 #include <objc/runtime.h>
33 #define DefaultTimeout_ 120.0
35 #define ShowInternals 0
39 #define lprintf(args...) fprintf(stderr, args)
41 JSValueRef (*$JSObjectCallAsFunction)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *);
43 // XXX: centralize these special class things to some file or mechanism?
44 static Class $MFMailComposeViewController;
46 float CYScrollViewDecelerationRateNormal;
48 @interface WebFrame (Cydia)
49 - (void) cydia$updateHeight;
52 @implementation WebFrame (Cydia)
54 - (NSString *) description {
55 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[[([self provisionalDataSource] ?: [self dataSource]) request] URL] absoluteString]];
58 - (void) cydia$updateHeight {
59 [[[self frameElement] style]
61 value:[NSString stringWithFormat:@"%dpx",
62 [[[self DOMDocument] body] scrollHeight]]
68 /* Indirect Delegate {{{ */
69 @implementation IndirectDelegate
75 - (void) setDelegate:(id)delegate {
79 - (id) initWithDelegate:(id)delegate {
84 - (IMP) methodForSelector:(SEL)sel {
85 if (IMP method = [super methodForSelector:sel])
87 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
91 - (BOOL) respondsToSelector:(SEL)sel {
92 if ([super respondsToSelector:sel])
95 // XXX: WebThreadCreateNSInvocation returns nil
98 fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
101 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
104 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
105 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
109 fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
112 if (delegate_ != nil)
113 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
116 // XXX: I fucking hate Apple so very very bad
117 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
120 - (void) forwardInvocation:(NSInvocation *)inv {
121 SEL sel = [inv selector];
122 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
123 [inv invokeWithTarget:delegate_];
129 @implementation CyteWebViewController
132 #include "CyteKit/UCInternal.h"
135 + (void) _initialize {
136 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
140 js = dlopen("/System/Library/Frameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
142 js = dlopen("/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
144 $JSObjectCallAsFunction = reinterpret_cast<JSValueRef (*)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(js, "JSObjectCallAsFunction"));
146 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
147 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
149 if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
150 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
151 else // XXX: this actually might be fast on some older systems: we should look into this
152 CYScrollViewDecelerationRateNormal = 0.998;
155 - (bool) retainsNetworkActivityIndicator {
159 - (void) releaseNetworkActivityIndicator {
160 if ([loading_ count] != 0) {
161 [loading_ removeAllObjects];
163 if ([self retainsNetworkActivityIndicator])
164 [delegate_ releaseNetworkActivityIndicator];
170 NSLog(@"[CyteWebViewController dealloc]");
173 [self releaseNetworkActivityIndicator];
178 - (NSString *) description {
179 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[request_ URL] absoluteString]];
182 - (CyteWebView *) webView {
183 return (CyteWebView *) [self view];
186 - (NSURL *) URLWithURL:(NSURL *)url {
190 - (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy referrer:(NSString *)referrer {
191 NSMutableURLRequest *request([NSMutableURLRequest
192 requestWithURL:[self URLWithURL:url]
194 timeoutInterval:DefaultTimeout_
197 [request setValue:referrer forHTTPHeaderField:@"Referer"];
202 - (void) setRequest:(NSURLRequest *)request {
203 _assert(request_ == nil);
207 - (void) setURL:(NSURL *)url {
208 [self setURL:url withReferrer:nil];
211 - (void) setURL:(NSURL *)url withReferrer:(NSString *)referrer {
212 [self setRequest:[self requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy referrer:referrer]];
215 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
216 [self loadRequest:[self requestWithURL:url cachePolicy:policy referrer:nil]];
219 - (void) loadURL:(NSURL *)url {
220 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
223 - (void) loadRequest:(NSURLRequest *)request {
225 NSLog(@"loadRequest:%@", request);
231 WebThreadLocked lock;
232 [[self webView] loadRequest:request];
235 - (void) reloadURLWithCache:(BOOL)cache {
239 NSMutableURLRequest *request([request_ mutableCopy]);
240 [request setCachePolicy:(cache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData)];
244 if (cache || [request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
245 [self loadRequest:request_];
247 UIAlertView *alert = [[[UIAlertView alloc]
248 initWithTitle:UCLocalize("RESUBMIT_FORM")
251 cancelButtonTitle:UCLocalize("CANCEL")
253 UCLocalize("SUBMIT"),
257 [alert setContext:@"submit"];
262 - (void) reloadData {
266 [self dispatchEvent:@"CydiaReloadData"];
268 [self reloadURLWithCache:YES];
271 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
274 function_ = function;
276 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
279 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
282 function_ = function;
284 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
287 - (void) removeButton {
288 custom_ = [NSNull null];
289 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
292 - (void) scrollToBottomAnimated:(NSNumber *)animated {
293 CGSize size([scroller_ contentSize]);
294 CGPoint offset([scroller_ contentOffset]);
295 CGRect frame([scroller_ frame]);
297 if (size.height - offset.y < frame.size.height + 20.f) {
298 CGRect rect = {{0, size.height-1}, {size.width, 1}};
299 [scroller_ scrollRectToVisible:rect animated:[animated boolValue]];
303 - (void) _setViewportWidth {
304 [[[self webView] _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
307 - (void) setViewportWidth:(float)width {
308 width_ = width != 0 ? width : [[self class] defaultWidth];
309 [self _setViewportWidth];
312 - (void) _setViewportWidthOnMainThread:(NSNumber *)width {
313 [self setViewportWidth:[width floatValue]];
316 - (void) setViewportWidthOnMainThread:(float)width {
317 [self performSelectorOnMainThread:@selector(_setViewportWidthOnMainThread:) withObject:[NSNumber numberWithFloat:width] waitUntilDone:NO];
320 - (void) webViewUpdateViewSettings:(UIWebView *)view {
321 [self _setViewportWidth];
324 - (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
325 [self dismissModalViewControllerAnimated:YES];
328 - (void) _setupMail:(MFMailComposeViewController *)controller {
331 - (void) _openMailToURL:(NSURL *)url {
332 if ($MFMailComposeViewController != nil && [$MFMailComposeViewController canSendMail]) {
333 MFMailComposeViewController *controller([[[$MFMailComposeViewController alloc] init] autorelease]);
334 [controller setMailComposeDelegate:self];
336 [controller setMailToURL:url];
338 [self _setupMail:controller];
340 [self presentModalViewController:controller animated:YES];
344 UIApplication *app([UIApplication sharedApplication]);
345 if ([app respondsToSelector:@selector(openURL:asPanel:)])
346 [app openURL:url asPanel:YES];
351 - (bool) _allowJavaScriptPanel {
355 - (bool) allowsNavigationAction {
356 return allowsNavigationAction_;
359 - (void) setAllowsNavigationAction:(bool)value {
360 allowsNavigationAction_ = value;
363 - (void) setAllowsNavigationActionByNumber:(NSNumber *)value {
364 [self setAllowsNavigationAction:[value boolValue]];
367 - (void) popViewControllerWithNumber:(NSNumber *)value {
368 UINavigationController *navigation([self navigationController]);
369 if ([navigation topViewController] == self)
370 [navigation popViewControllerAnimated:[value boolValue]];
373 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
374 NSValue *object([NSValue valueWithNonretainedObject:frame]);
375 if (![loading_ containsObject:object])
377 [loading_ removeObject:object];
379 [self _didFinishLoading];
381 if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == NSURLErrorCancelled)
384 if ([[error domain] isEqualToString:WebKitErrorDomain] && [error code] == WebKitErrorFrameLoadInterruptedByPolicyChange) {
389 if ([frame parentFrame] == nil) {
390 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
391 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
392 [[error localizedDescription] stringByAddingPercentEscapes]
399 - (void) pushRequest:(NSURLRequest *)request forAction:(NSDictionary *)action asPop:(bool)pop {
400 WebFrame *frame(nil);
401 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
402 frame = [WebActionElement objectForKey:@"WebElementFrame"];
404 frame = [[[[self webView] _documentView] webView] mainFrame];
406 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
407 NSString *referrer([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString]);
409 NSURL *url([request URL]);
411 // XXX: filter to internal usage?
412 CyteViewController *page([delegate_ pageForURL:url forExternal:NO withReferrer:referrer]);
415 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
416 [browser setRequest:request];
420 [page setDelegate:delegate_];
421 [page setPageColor:color_];
424 [[self navigationItem] setTitle:title_];
426 [[self navigationController] pushViewController:page animated:YES];
428 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
430 [navigation setDelegate:delegate_];
432 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
433 initWithTitle:UCLocalize("CLOSE")
434 style:UIBarButtonItemStylePlain
436 action:@selector(close)
439 [[self navigationController] presentModalViewController:navigation animated:YES];
443 // CyteWebViewDelegate {{{
444 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
446 static Pcre irritating("^(?"
447 ":" "The page at .* displayed insecure content from .*\\."
448 "|" "Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\."
451 if (NSString *data = [message objectForKey:@"message"])
452 if (irritating(data))
455 NSLog(@"addMessageToConsole:%@", message);
459 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
461 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ %@ frame:%@", action, request, [request allHTTPHeaderFields], frame);
464 NSURL *url(request == nil ? nil : [request URL]);
465 if ([[url scheme] isEqualToString:@"itms-appss"] || [[url absoluteString] hasPrefix:@"https://itunes.apple.com/app/"]) {
468 UIAlertView *alert = [[[UIAlertView alloc]
469 initWithTitle:UCLocalize("APP_STORE_REDIRECT")
472 cancelButtonTitle:UCLocalize("CANCEL")
478 [alert setContext:@"itmsappss"];
485 if ([frame parentFrame] == nil) {
487 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
489 [self pushRequest:request forAction:action asPop:NO];
496 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
498 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
501 if ([frame parentFrame] == nil) {
503 case CYWebPolicyDecisionIgnore:
504 if ([[request_ URL] isEqual:[request URL]])
508 case CYWebPolicyDecisionUse:
519 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
521 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
524 NSURL *url([request URL]);
528 if ([name isEqualToString:@"_open"])
529 [delegate_ openURL:url];
531 NSString *scheme([[url scheme] lowercaseString]);
532 if ([scheme isEqualToString:@"mailto"])
533 [self _openMailToURL:url];
535 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
541 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
543 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
547 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
549 NSLog(@"didCommitLoadForFrame:%@", frame);
552 if ([frame parentFrame] == nil) {
557 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
559 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
562 [self _didFailWithError:error forFrame:frame];
565 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
567 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
570 [self _didFailWithError:error forFrame:frame];
573 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
574 NSValue *object([NSValue valueWithNonretainedObject:frame]);
575 if (![loading_ containsObject:object])
577 [loading_ removeObject:object];
579 if ([frame parentFrame] == nil) {
580 if (DOMDocument *document = [frame DOMDocument])
581 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
582 for (DOMHTMLBodyElement *body in (id) bodies) {
583 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
587 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
588 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
589 DOMRGBColor *rgb([color getRGBColorValue]);
591 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
592 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
593 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
594 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
598 colorWithRed:(red / 255)
606 [super setPageColor:uic];
607 [scroller_ setBackgroundColor:color_];
612 [self _didFinishLoading];
615 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
616 if ([frame parentFrame] != nil)
621 [[self navigationItem] setTitle:title_];
624 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
626 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
629 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
631 if ([frame parentFrame] == nil) {
637 [registered_ removeAllObjects];
640 allowsNavigationAction_ = true;
642 [self setHidesNavigationBar:NO];
643 [self setScrollAlwaysBounceVertical:true];
644 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
646 // XXX: do we still need to do this?
647 [[self navigationItem] setTitle:nil];
650 [self _didStartLoading];
653 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
654 challenge_ = [challenge retain];
656 NSURLProtectionSpace *space([challenge protectionSpace]);
657 NSString *realm([space realm]);
661 UIAlertView *alert = [[[UIAlertView alloc]
665 cancelButtonTitle:UCLocalize("CANCEL")
666 otherButtonTitles:UCLocalize("LOGIN"), nil
669 [alert setContext:@"challenge"];
670 [alert setNumberOfRows:1];
672 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
673 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
675 UITextField *username([alert textFieldAtIndex:0]); {
676 UITextInputTraits *traits([username textInputTraits]);
677 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
678 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
679 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
680 [traits setReturnKeyType:UIReturnKeyNext];
683 UITextField *password([alert textFieldAtIndex:1]); {
684 UITextInputTraits *traits([password textInputTraits]);
685 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
686 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
687 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
688 // XXX: UIReturnKeyDone
689 [traits setReturnKeyType:UIReturnKeyNext];
690 [traits setSecureTextEntry:YES];
696 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
698 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
704 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
705 return [self _allowJavaScriptPanel];
708 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
709 return [self _allowJavaScriptPanel];
712 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
713 return [self _allowJavaScriptPanel];
716 - (void) webViewClose:(WebView *)view {
722 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
725 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
726 NSString *context([alert context]);
728 if ([context isEqualToString:@"sensitive"]) {
731 sensitive_ = [NSNumber numberWithBool:YES];
735 sensitive_ = [NSNumber numberWithBool:NO];
739 [alert dismissWithClickedButtonIndex:-1 animated:YES];
740 } else if ([context isEqualToString:@"challenge"]) {
741 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
743 if (button == [alert cancelButtonIndex])
744 [sender cancelAuthenticationChallenge:challenge_];
745 else if (button == [alert firstOtherButtonIndex]) {
746 NSString *username([[alert textFieldAtIndex:0] text]);
747 NSString *password([[alert textFieldAtIndex:1] text]);
749 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
751 [sender useCredential:credential forAuthenticationChallenge:challenge_];
756 [alert dismissWithClickedButtonIndex:-1 animated:YES];
757 } else if ([context isEqualToString:@"itmsappss"]) {
758 if (button == [alert cancelButtonIndex]) {
759 } else if (button == [alert firstOtherButtonIndex]) {
760 [delegate_ openURL:appstore_];
763 [alert dismissWithClickedButtonIndex:-1 animated:YES];
764 } else if ([context isEqualToString:@"submit"]) {
765 if (button == [alert cancelButtonIndex]) {
766 } else if (button == [alert firstOtherButtonIndex]) {
767 if (request_ != nil) {
768 WebThreadLocked lock;
769 [[self webView] loadRequest:request_];
773 [alert dismissWithClickedButtonIndex:-1 animated:YES];
777 - (UIBarButtonItemStyle) rightButtonStyle {
778 if (style_ == nil) normal:
779 return UIBarButtonItemStylePlain;
780 else if ([style_ isEqualToString:@"Normal"])
781 return UIBarButtonItemStylePlain;
782 else if ([style_ isEqualToString:@"Highlighted"])
783 return UIBarButtonItemStyleDone;
787 - (UIBarButtonItem *) customButton {
790 else if ((/*clang:*/id) custom_ == [NSNull null])
791 return (UIBarButtonItem *) [NSNull null];
793 return [[[UIBarButtonItem alloc]
794 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
795 style:[self rightButtonStyle]
797 action:@selector(customButtonClicked)
801 - (UIBarButtonItem *) leftButton {
802 UINavigationItem *item([self navigationItem]);
803 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
806 if (UINavigationController *navigation = [self navigationController])
807 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
808 return [[[UIBarButtonItem alloc]
809 initWithTitle:UCLocalize("CLOSE")
810 style:UIBarButtonItemStylePlain
812 action:@selector(close)
818 - (void) applyLeftButton {
819 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
822 - (UIBarButtonItem *) rightButton {
826 - (void) applyLoadingTitle {
827 [[self navigationItem] setTitle:UCLocalize("LOADING")];
830 - (void) layoutRightButton {
831 [[loadingitem_ view] addSubview:indicator_];
832 [[loadingitem_ view] bringSubviewToFront:indicator_];
835 - (void) applyRightButton {
836 if ([self isLoading]) {
837 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
838 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
840 [indicator_ startAnimating];
841 [self applyLoadingTitle];
843 [indicator_ stopAnimating];
845 UIBarButtonItem *button([self customButton]);
847 button = [self rightButton];
848 else if (button == (UIBarButtonItem *) [NSNull null])
851 [[self navigationItem] setRightBarButtonItem:button 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(reloadButtonClicked)
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];