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/RegEx.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 RegEx 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 NSString *scheme([[url scheme] lowercaseString]);
466 NSString *absolute([[url absoluteString] lowercaseString]);
469 [scheme isEqualToString:@"itms"] ||
470 [scheme isEqualToString:@"itmss"] ||
471 [scheme isEqualToString:@"itms-apps"] ||
472 [scheme isEqualToString:@"itms-appss"] ||
473 [absolute hasPrefix:@"http://itunes.apple.com/"] ||
474 [absolute hasPrefix:@"https://itunes.apple.com/"] ||
478 UIAlertView *alert = [[[UIAlertView alloc]
479 initWithTitle:UCLocalize("APP_STORE_REDIRECT")
482 cancelButtonTitle:UCLocalize("CANCEL")
488 [alert setContext:@"itmsappss"];
495 if ([frame parentFrame] == nil) {
497 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
499 [self pushRequest:request forAction:action asPop:NO];
506 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
508 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
511 if ([frame parentFrame] == nil) {
513 case CYWebPolicyDecisionIgnore:
514 if ([[request_ URL] isEqual:[request URL]])
518 case CYWebPolicyDecisionUse:
529 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
531 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
534 NSURL *url([request URL]);
538 if ([name isEqualToString:@"_open"])
539 [delegate_ openURL:url];
541 NSString *scheme([[url scheme] lowercaseString]);
542 if ([scheme isEqualToString:@"mailto"])
543 [self _openMailToURL:url];
545 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
551 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
553 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
557 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
559 NSLog(@"didCommitLoadForFrame:%@", frame);
562 if ([frame parentFrame] == nil) {
567 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
569 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
572 [self _didFailWithError:error forFrame:frame];
575 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
577 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
580 [self _didFailWithError:error forFrame:frame];
583 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
584 NSValue *object([NSValue valueWithNonretainedObject:frame]);
585 if (![loading_ containsObject:object])
587 [loading_ removeObject:object];
589 if ([frame parentFrame] == nil) {
590 if (DOMDocument *document = [frame DOMDocument])
591 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
592 for (DOMHTMLBodyElement *body in (id) bodies) {
593 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
597 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
598 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
599 DOMRGBColor *rgb([color getRGBColorValue]);
601 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
602 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
603 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
604 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
608 colorWithRed:(red / 255)
616 [super setPageColor:uic];
617 [scroller_ setBackgroundColor:color_];
622 [self _didFinishLoading];
625 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
626 if ([frame parentFrame] != nil)
631 [[self navigationItem] setTitle:title_];
634 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
636 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
639 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
641 if ([frame parentFrame] == nil) {
647 [registered_ removeAllObjects];
650 allowsNavigationAction_ = true;
652 [self setHidesNavigationBar:NO];
653 [self setScrollAlwaysBounceVertical:true];
654 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
656 // XXX: do we still need to do this?
657 [[self navigationItem] setTitle:nil];
660 [self _didStartLoading];
663 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
664 challenge_ = [challenge retain];
666 NSURLProtectionSpace *space([challenge protectionSpace]);
667 NSString *realm([space realm]);
671 UIAlertView *alert = [[[UIAlertView alloc]
675 cancelButtonTitle:UCLocalize("CANCEL")
676 otherButtonTitles:UCLocalize("LOGIN"), nil
679 [alert setContext:@"challenge"];
680 [alert setNumberOfRows:1];
682 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
683 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
685 UITextField *username([alert textFieldAtIndex:0]); {
686 UITextInputTraits *traits([username textInputTraits]);
687 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
688 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
689 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
690 [traits setReturnKeyType:UIReturnKeyNext];
693 UITextField *password([alert textFieldAtIndex:1]); {
694 UITextInputTraits *traits([password textInputTraits]);
695 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
696 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
697 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
698 // XXX: UIReturnKeyDone
699 [traits setReturnKeyType:UIReturnKeyNext];
700 [traits setSecureTextEntry:YES];
706 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
708 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
714 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
716 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
722 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
723 return [self _allowJavaScriptPanel];
726 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
727 return [self _allowJavaScriptPanel];
730 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
731 return [self _allowJavaScriptPanel];
734 - (void) webViewClose:(WebView *)view {
740 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
743 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
744 NSString *context([alert context]);
746 if ([context isEqualToString:@"sensitive"]) {
749 sensitive_ = [NSNumber numberWithBool:YES];
753 sensitive_ = [NSNumber numberWithBool:NO];
757 [alert dismissWithClickedButtonIndex:-1 animated:YES];
758 } else if ([context isEqualToString:@"challenge"]) {
759 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
761 if (button == [alert cancelButtonIndex])
762 [sender cancelAuthenticationChallenge:challenge_];
763 else if (button == [alert firstOtherButtonIndex]) {
764 NSString *username([[alert textFieldAtIndex:0] text]);
765 NSString *password([[alert textFieldAtIndex:1] text]);
767 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
769 [sender useCredential:credential forAuthenticationChallenge:challenge_];
774 [alert dismissWithClickedButtonIndex:-1 animated:YES];
775 } else if ([context isEqualToString:@"itmsappss"]) {
776 if (button == [alert cancelButtonIndex]) {
777 } else if (button == [alert firstOtherButtonIndex]) {
778 [delegate_ openURL:appstore_];
781 [alert dismissWithClickedButtonIndex:-1 animated:YES];
782 } else if ([context isEqualToString:@"submit"]) {
783 if (button == [alert cancelButtonIndex]) {
784 } else if (button == [alert firstOtherButtonIndex]) {
785 if (request_ != nil) {
786 WebThreadLocked lock;
787 [[self webView] loadRequest:request_];
791 [alert dismissWithClickedButtonIndex:-1 animated:YES];
795 - (UIBarButtonItemStyle) rightButtonStyle {
796 if (style_ == nil) normal:
797 return UIBarButtonItemStylePlain;
798 else if ([style_ isEqualToString:@"Normal"])
799 return UIBarButtonItemStylePlain;
800 else if ([style_ isEqualToString:@"Highlighted"])
801 return UIBarButtonItemStyleDone;
805 - (UIBarButtonItem *) customButton {
808 else if ((/*clang:*/id) custom_ == [NSNull null])
809 return (UIBarButtonItem *) [NSNull null];
811 return [[[UIBarButtonItem alloc]
812 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
813 style:[self rightButtonStyle]
815 action:@selector(customButtonClicked)
819 - (UIBarButtonItem *) leftButton {
820 UINavigationItem *item([self navigationItem]);
821 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
824 if (UINavigationController *navigation = [self navigationController])
825 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
826 return [[[UIBarButtonItem alloc]
827 initWithTitle:UCLocalize("CLOSE")
828 style:UIBarButtonItemStylePlain
830 action:@selector(close)
836 - (void) applyLeftButton {
837 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
840 - (UIBarButtonItem *) rightButton {
844 - (void) applyLoadingTitle {
845 [[self navigationItem] setTitle:UCLocalize("LOADING")];
848 - (void) layoutRightButton {
849 [[loadingitem_ view] addSubview:indicator_];
850 [[loadingitem_ view] bringSubviewToFront:indicator_];
853 - (void) applyRightButton {
854 if ([self isLoading]) {
855 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
856 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
858 [indicator_ startAnimating];
859 [self applyLoadingTitle];
861 [indicator_ stopAnimating];
863 UIBarButtonItem *button([self customButton]);
865 button = [self rightButton];
866 else if (button == (UIBarButtonItem *) [NSNull null])
869 [[self navigationItem] setRightBarButtonItem:button animated:YES];
873 - (void) didStartLoading {
874 // Overridden in subclasses.
877 - (void) _didStartLoading {
878 [self applyRightButton];
880 if ([loading_ count] != 1)
883 if ([self retainsNetworkActivityIndicator])
884 [delegate_ retainNetworkActivityIndicator];
886 [self didStartLoading];
889 - (void) didFinishLoading {
890 // Overridden in subclasses.
893 - (void) _didFinishLoading {
894 if ([loading_ count] != 0)
897 [self applyRightButton];
898 [[self navigationItem] setTitle:title_];
900 if ([self retainsNetworkActivityIndicator])
901 [delegate_ releaseNetworkActivityIndicator];
903 [self didFinishLoading];
907 return [loading_ count] != 0;
910 - (id) initWithWidth:(float)width ofClass:(Class)_class {
911 if ((self = [super init]) != nil) {
915 [super setPageColor:nil];
917 allowsNavigationAction_ = true;
919 loading_ = [NSMutableSet setWithCapacity:5];
920 registered_ = [NSMutableSet setWithCapacity:5];
921 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
923 reloaditem_ = [[[UIBarButtonItem alloc]
924 initWithTitle:UCLocalize("RELOAD")
925 style:[self rightButtonStyle]
927 action:@selector(reloadButtonClicked)
930 loadingitem_ = [[[UIBarButtonItem alloc]
931 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
932 style:UIBarButtonItemStylePlain
934 action:@selector(reloadButtonClicked)
937 UIActivityIndicatorViewStyle style;
939 if (kCFCoreFoundationVersionNumber >= 800) {
940 style = UIActivityIndicatorViewStyleGray;
943 style = UIActivityIndicatorViewStyleWhite;
947 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
948 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
949 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
951 [self applyLeftButton];
952 [self applyRightButton];
956 - (NSString *) applicationNameForUserAgent {
961 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
963 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
964 [webview_ setDelegate:self];
965 [self setView:webview_];
967 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
968 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
970 [webview_ setDetectsPhoneNumbers:NO];
972 [webview_ setScalesPageToFit:YES];
974 UIWebDocumentView *document([webview_ _documentView]);
976 // XXX: I think this improves scrolling; the hardcoded-ness sucks
977 [document setTileSize:CGSizeMake(320, 500)];
979 WebView *webview([document webView]);
980 WebPreferences *preferences([webview preferences]);
982 // XXX: I have no clue if I actually /want/ this modification
983 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
984 [webview _setLayoutInterval:0];
985 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
986 [preferences _setLayoutInterval:0];
988 [preferences setCacheModel:WebCacheModelDocumentBrowser];
989 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
991 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
992 [preferences setOfflineWebApplicationCacheEnabled:YES];
994 if (NSString *agent = [self applicationNameForUserAgent])
995 [webview setApplicationNameForUserAgent:agent];
997 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
998 [webview setShouldUpdateWhileOffscreen:NO];
1001 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
1002 [document setAllowsMessaging:YES];
1003 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
1004 [webview _setAllowsMessaging:YES];
1007 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1008 scroller_ = [webview_ _scrollView];
1010 [scroller_ setDirectionalLockEnabled:YES];
1011 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
1012 [scroller_ setDelaysContentTouches:NO];
1014 [scroller_ setCanCancelContentTouches:YES];
1015 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1016 UIScroller *scroller([webview_ _scroller]);
1017 scroller_ = (UIScrollView *) scroller;
1019 [scroller setDirectionalScrolling:YES];
1020 // XXX: we might be better off /not/ setting this on older systems
1021 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
1022 [scroller setScrollHysteresis:0]; /* 8 */
1024 [scroller setThumbDetectionEnabled:NO];
1026 // use NO with UIApplicationUseLegacyEvents(YES)
1027 [scroller setEventMode:YES];
1029 // XXX: this is handled by setBounces, right?
1030 //[scroller setAllowsRubberBanding:YES];
1033 [webview_ setOpaque:NO];
1034 [webview_ setBackgroundColor:nil];
1036 [scroller_ setFixedBackgroundPattern:YES];
1037 [scroller_ setBackgroundColor:color_];
1038 [scroller_ setClipsSubviews:YES];
1040 [scroller_ setBounces:YES];
1041 [scroller_ setScrollingEnabled:YES];
1042 [scroller_ setShowBackgroundShadow:NO];
1044 [self setViewportWidth:width_];
1046 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1047 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1048 [table setScrollsToTop:NO];
1049 [webview_ insertSubview:table atIndex:0];
1050 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1053 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1058 - (void) releaseSubviews {
1062 [self releaseNetworkActivityIndicator];
1064 [super releaseSubviews];
1067 - (id) initWithWidth:(float)width {
1068 return [self initWithWidth:width ofClass:[self class]];
1072 return [self initWithWidth:0];
1075 - (id) initWithURL:(NSURL *)url {
1076 if ((self = [self init]) != nil) {
1081 - (id) initWithRequest:(NSURLRequest *)request {
1082 if ((self = [self init]) != nil) {
1083 [self setRequest:request];
1087 + (void) _lockJavaScript:(WebPreferences *)preferences {
1088 WebThreadLocked lock;
1089 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1092 - (void) callFunction:(WebScriptObject *)function {
1093 WebThreadLocked lock;
1095 WebView *webview([[[self webView] _documentView] webView]);
1096 WebPreferences *preferences([webview preferences]);
1098 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
1099 if ([webview respondsToSelector:@selector(_preferencesChanged:)])
1100 [webview _preferencesChanged:preferences];
1102 [webview _preferencesChangedNotification:[NSNotification notificationWithName:@"" object:preferences]];
1104 WebFrame *frame([webview mainFrame]);
1105 JSGlobalContextRef context([frame globalContext]);
1107 JSObjectRef object([function JSObject]);
1108 if ($JSObjectCallAsFunction != NULL)
1109 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1111 // XXX: the JavaScript code submits a form, which seems to happen asynchronously
1112 NSObject *target([CyteWebViewController class]);
1113 [NSObject cancelPreviousPerformRequestsWithTarget:target selector:@selector(_lockJavaScript:) object:preferences];
1114 [target performSelector:@selector(_lockJavaScript:) withObject:preferences afterDelay:1];
1117 - (void) reloadButtonClicked {
1118 [self reloadURLWithCache:NO];
1121 - (void) _customButtonClicked {
1122 [self reloadButtonClicked];
1125 - (void) customButtonClicked {
1127 if (function_ != nil)
1128 [self callFunction:function_];
1131 [self _customButtonClicked];
1134 + (float) defaultWidth {
1138 - (void) setNavigationBarStyle:(NSString *)name {
1140 if ([name isEqualToString:@"Black"])
1141 style = UIBarStyleBlack;
1143 style = UIBarStyleDefault;
1145 [[[self navigationController] navigationBar] setBarStyle:style];
1148 - (void) setNavigationBarTintColor:(UIColor *)color {
1149 [[[self navigationController] navigationBar] setTintColor:color];
1152 - (void) setBadgeValue:(id)value {
1153 [[[self navigationController] tabBarItem] setBadgeValue:value];
1156 - (void) setHidesBackButton:(bool)value {
1157 [[self navigationItem] setHidesBackButton:value];
1158 [self applyLeftButton];
1161 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1162 [self setHidesBackButton:[value boolValue]];
1165 - (void) dispatchEvent:(NSString *)event {
1166 [[self webView] dispatchEvent:event];
1169 - (bool) hidesNavigationBar {
1170 return hidesNavigationBar_;
1173 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1175 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1178 - (void) setHidesNavigationBar:(bool)value {
1179 if (hidesNavigationBar_ != value) {
1180 hidesNavigationBar_ = value;
1181 [self _setHidesNavigationBar:YES animated:YES];
1185 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1186 [self setHidesNavigationBar:[value boolValue]];
1189 - (void) setScrollAlwaysBounceVertical:(bool)value {
1190 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1191 UIScrollView *scroller([webview_ _scrollView]);
1192 [scroller setAlwaysBounceVertical:value];
1193 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1194 //UIScroller *scroller([webview_ _scroller]);
1195 // XXX: I am sad here.
1199 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1200 [self setScrollAlwaysBounceVertical:[value boolValue]];
1203 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1204 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1205 UIScrollView *scroller([webview_ _scrollView]);
1206 [scroller setIndicatorStyle:style];
1207 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1208 UIScroller *scroller([webview_ _scroller]);
1209 [scroller setScrollerIndicatorStyle:style];
1213 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1214 UIScrollViewIndicatorStyle value;
1217 else if ([style isEqualToString:@"default"])
1218 value = UIScrollViewIndicatorStyleDefault;
1219 else if ([style isEqualToString:@"black"])
1220 value = UIScrollViewIndicatorStyleBlack;
1221 else if ([style isEqualToString:@"white"])
1222 value = UIScrollViewIndicatorStyleWhite;
1225 [self setScrollIndicatorStyle:value];
1228 - (void) viewWillAppear:(BOOL)animated {
1231 if ([self hidesNavigationBar])
1232 [self _setHidesNavigationBar:YES animated:animated];
1234 // XXX: why isn't this evern called automatically?
1235 [[self webView] setNeedsLayout];
1237 [self dispatchEvent:@"CydiaViewWillAppear"];
1238 [super viewWillAppear:animated];
1241 - (void) viewDidAppear:(BOOL)animated {
1242 [super viewDidAppear:animated];
1243 [self dispatchEvent:@"CydiaViewDidAppear"];
1246 - (void) viewWillDisappear:(BOOL)animated {
1247 [self dispatchEvent:@"CydiaViewWillDisappear"];
1248 [super viewWillDisappear:animated];
1250 if ([self hidesNavigationBar])
1251 [self _setHidesNavigationBar:NO animated:animated];
1256 - (void) viewDidDisappear:(BOOL)animated {
1257 [super viewDidDisappear:animated];
1258 [self dispatchEvent:@"CydiaViewDidDisappear"];
1261 - (void) updateHeights:(NSTimer *)timer {
1262 for (WebFrame *frame in (id) registered_)
1263 [frame cydia$updateHeight];
1266 - (void) registerFrame:(WebFrame *)frame {
1267 [registered_ addObject:frame];
1270 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];