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"
11 #include <Menes/ObjectHandle.h>
13 //#include <QuartzCore/CALayer.h>
14 // XXX: fix the minimum requirement
15 extern NSString * const kCAFilterNearest;
17 #include <WebCore/WebCoreThread.h>
20 #include <objc/runtime.h>
22 #include "Substrate.hpp"
25 #define DefaultTimeout_ 120.0
27 #define ShowInternals 0
31 #define lprintf(args...) fprintf(stderr, args)
33 JSValueRef (*$JSObjectCallAsFunction)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *);
35 // XXX: centralize these special class things to some file or mechanism?
36 static Class $MFMailComposeViewController;
38 float CYScrollViewDecelerationRateNormal;
40 @interface WebFrame (Cydia)
41 - (void) cydia$updateHeight;
44 @implementation WebFrame (Cydia)
46 - (NSString *) description {
47 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[[([self provisionalDataSource] ?: [self dataSource]) request] URL] absoluteString]];
50 - (void) cydia$updateHeight {
51 [[[self frameElement] style]
53 value:[NSString stringWithFormat:@"%dpx",
54 [[[self DOMDocument] body] scrollHeight]]
60 /* Indirect Delegate {{{ */
61 @implementation IndirectDelegate
67 - (void) setDelegate:(id)delegate {
71 - (id) initWithDelegate:(id)delegate {
76 - (IMP) methodForSelector:(SEL)sel {
77 if (IMP method = [super methodForSelector:sel])
79 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
83 - (BOOL) respondsToSelector:(SEL)sel {
84 if ([super respondsToSelector:sel])
87 // XXX: WebThreadCreateNSInvocation returns nil
90 fprintf(stderr, "[%s]R?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
93 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
96 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
97 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
101 fprintf(stderr, "[%s]S?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
104 if (delegate_ != nil)
105 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
108 // XXX: I fucking hate Apple so very very bad
109 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
112 - (void) forwardInvocation:(NSInvocation *)inv {
113 SEL sel = [inv selector];
114 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
115 [inv invokeWithTarget:delegate_];
121 @implementation CyteWebViewController {
122 _H<CyteWebView, 1> webview_;
123 _transient UIScrollView *scroller_;
125 _H<UIActivityIndicatorView> indicator_;
126 _H<IndirectDelegate, 1> indirect_;
127 _H<NSURLAuthenticationChallenge> challenge_;
130 _H<NSURLRequest> request_;
133 _transient NSNumber *sensitive_;
137 _H<NSMutableSet> loading_;
139 _H<NSMutableSet> registered_;
142 // XXX: NSString * or UIImage *
143 _H<NSObject> custom_;
146 _H<WebScriptObject> function_;
151 _H<UIBarButtonItem> reloaditem_;
152 _H<UIBarButtonItem> loadingitem_;
155 bool hidesNavigationBar_;
156 bool allowsNavigationAction_;
160 #include "CyteKit/UCInternal.h"
163 + (void) _initialize {
164 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
168 js = dlopen("/System/Library/Frameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
170 js = dlopen("/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
172 $JSObjectCallAsFunction = reinterpret_cast<JSValueRef (*)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(js, "JSObjectCallAsFunction"));
174 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
175 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
177 if (CGFloat *_UIScrollViewDecelerationRateNormal = reinterpret_cast<CGFloat *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
178 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
179 else // XXX: this actually might be fast on some older systems: we should look into this
180 CYScrollViewDecelerationRateNormal = 0.998;
183 - (bool) retainsNetworkActivityIndicator {
187 - (void) releaseNetworkActivityIndicator {
188 if ([loading_ count] != 0) {
189 [loading_ removeAllObjects];
191 if ([self retainsNetworkActivityIndicator])
192 [self.delegate releaseNetworkActivityIndicator];
198 NSLog(@"[CyteWebViewController dealloc]");
201 [self releaseNetworkActivityIndicator];
206 - (NSString *) description {
207 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[request_ URL] absoluteString]];
210 - (CyteWebView *) webView {
211 return (CyteWebView *) [self view];
214 - (CyteWebViewController *) indirect {
215 return (CyteWebViewController *) (IndirectDelegate *) indirect_;
218 - (NSURL *) URLWithURL:(NSURL *)url {
222 - (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy referrer:(NSString *)referrer {
223 NSMutableURLRequest *request([NSMutableURLRequest
224 requestWithURL:[self URLWithURL:url]
226 timeoutInterval:DefaultTimeout_
229 [request setValue:referrer forHTTPHeaderField:@"Referer"];
234 - (void) setRequest:(NSURLRequest *)request {
235 _assert(request_ == nil);
239 - (NSURLRequest *) request {
243 - (void) setURL:(NSURL *)url {
244 [self setURL:url withReferrer:nil];
247 - (void) setURL:(NSURL *)url withReferrer:(NSString *)referrer {
248 [self setRequest:[self requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy referrer:referrer]];
251 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
252 [self loadRequest:[self requestWithURL:url cachePolicy:policy referrer:nil]];
255 - (void) loadURL:(NSURL *)url {
256 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
259 - (void) loadRequest:(NSURLRequest *)request {
261 NSLog(@"loadRequest:%@", request);
267 WebThreadLocked lock;
268 [[self webView] loadRequest:request];
271 - (void) reloadURLWithCache:(BOOL)cache {
275 NSMutableURLRequest *request([request_ mutableCopy]);
276 [request setCachePolicy:(cache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData)];
280 if (cache || [request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
281 [self loadRequest:request_];
283 UIAlertView *alert = [[[UIAlertView alloc]
284 initWithTitle:UCLocalize("RESUBMIT_FORM")
287 cancelButtonTitle:UCLocalize("CANCEL")
289 UCLocalize("SUBMIT"),
293 [alert setContext:@"submit"];
298 - (void) reloadData {
302 [self dispatchEvent:@"CydiaReloadData"];
304 [self reloadURLWithCache:YES];
307 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
310 function_ = function;
312 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
315 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
318 function_ = function;
320 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
323 - (void) removeButton {
324 custom_ = [NSNull null];
325 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
328 - (void) scrollToBottomAnimated:(NSNumber *)animated {
329 CGSize size([scroller_ contentSize]);
330 CGPoint offset([scroller_ contentOffset]);
331 CGRect frame([scroller_ frame]);
333 if (size.height - offset.y < frame.size.height + 20.f) {
334 CGRect rect = {{0, size.height-1}, {size.width, 1}};
335 [scroller_ scrollRectToVisible:rect animated:[animated boolValue]];
339 - (void) _setViewportWidth {
340 [[[self webView] _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
343 - (void) setViewportWidth:(float)width {
344 width_ = width != 0 ? width : [[self class] defaultWidth];
345 [self _setViewportWidth];
348 - (void) _setViewportWidthOnMainThread:(NSNumber *)width {
349 [self setViewportWidth:[width floatValue]];
352 - (void) setViewportWidthOnMainThread:(float)width {
353 [self performSelectorOnMainThread:@selector(_setViewportWidthOnMainThread:) withObject:[NSNumber numberWithFloat:width] waitUntilDone:NO];
356 - (void) webViewUpdateViewSettings:(UIWebView *)view {
357 [self _setViewportWidth];
360 - (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
361 [self dismissModalViewControllerAnimated:YES];
364 - (void) _setupMail:(MFMailComposeViewController *)controller {
367 - (void) _openMailToURL:(NSURL *)url {
368 if ($MFMailComposeViewController != nil && [$MFMailComposeViewController canSendMail]) {
369 MFMailComposeViewController *controller([[[$MFMailComposeViewController alloc] init] autorelease]);
370 [controller setMailComposeDelegate:self];
372 [controller setMailToURL:url];
374 [self _setupMail:controller];
376 [self presentModalViewController:controller animated:YES];
380 UIApplication *app([UIApplication sharedApplication]);
381 if ([app respondsToSelector:@selector(openURL:asPanel:)])
382 [app openURL:url asPanel:YES];
387 - (bool) _allowJavaScriptPanel {
391 - (bool) allowsNavigationAction {
392 return allowsNavigationAction_;
395 - (void) setAllowsNavigationAction:(bool)value {
396 allowsNavigationAction_ = value;
399 - (void) setAllowsNavigationActionByNumber:(NSNumber *)value {
400 [self setAllowsNavigationAction:[value boolValue]];
403 - (void) popViewControllerWithNumber:(NSNumber *)value {
404 UINavigationController *navigation([self navigationController]);
405 if ([navigation topViewController] == self)
406 [navigation popViewControllerAnimated:[value boolValue]];
409 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
410 NSValue *object([NSValue valueWithNonretainedObject:frame]);
411 if (![loading_ containsObject:object])
413 [loading_ removeObject:object];
415 [self _didFinishLoading];
417 if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == NSURLErrorCancelled)
420 if ([[error domain] isEqualToString:WebKitErrorDomain] && [error code] == WebKitErrorFrameLoadInterruptedByPolicyChange) {
425 if ([frame parentFrame] == nil) {
426 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
427 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
428 [[error localizedDescription] stringByAddingPercentEscapes]
435 - (void) pushRequest:(NSURLRequest *)request forAction:(NSDictionary *)action asPop:(bool)pop {
436 WebFrame *frame(nil);
437 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
438 frame = [WebActionElement objectForKey:@"WebElementFrame"];
440 frame = [[[[self webView] _documentView] webView] mainFrame];
442 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
443 NSString *referrer([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString]);
445 NSURL *url([request URL]);
447 // XXX: filter to internal usage?
448 CyteViewController *page([self.delegate pageForURL:url forExternal:NO withReferrer:referrer]);
451 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
452 [browser setRequest:request];
456 [page setDelegate:self.delegate];
457 [page setPageColor:self.pageColor];
460 [[self navigationItem] setTitle:title_];
462 [[self navigationController] pushViewController:page animated:YES];
464 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
466 [navigation setDelegate:self.delegate];
468 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
469 initWithTitle:UCLocalize("CLOSE")
470 style:UIBarButtonItemStylePlain
472 action:@selector(close)
475 [[self navigationController] presentModalViewController:navigation animated:YES];
479 // CyteWebViewDelegate {{{
480 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
482 static RegEx irritating("(?"
483 ":" "The page at .* displayed insecure content from .*\\."
484 "|" "Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\."
487 if (NSString *data = [message objectForKey:@"message"])
488 if (irritating(data))
491 NSLog(@"addMessageToConsole:%@", message);
495 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
497 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ %@ frame:%@", action, request, [request allHTTPHeaderFields], frame);
500 NSURL *url(request == nil ? nil : [request URL]);
501 NSString *scheme([[url scheme] lowercaseString]);
502 NSString *absolute([[url absoluteString] lowercaseString]);
505 [scheme isEqualToString:@"itms"] ||
506 [scheme isEqualToString:@"itmss"] ||
507 [scheme isEqualToString:@"itms-apps"] ||
508 [scheme isEqualToString:@"itms-appss"] ||
509 [absolute hasPrefix:@"http://itunes.apple.com/"] ||
510 [absolute hasPrefix:@"https://itunes.apple.com/"] ||
514 UIAlertView *alert = [[[UIAlertView alloc]
515 initWithTitle:UCLocalize("APP_STORE_REDIRECT")
518 cancelButtonTitle:UCLocalize("CANCEL")
524 [alert setContext:@"itmsappss"];
531 if ([frame parentFrame] == nil) {
533 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
535 [self pushRequest:request forAction:action asPop:NO];
542 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
544 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ %@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
547 if ([frame parentFrame] == nil) {
549 case CYWebPolicyDecisionIgnore:
550 if ([[request_ URL] isEqual:[request URL]])
554 case CYWebPolicyDecisionUse:
565 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
567 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
570 NSURL *url([request URL]);
574 if ([name isEqualToString:@"_open"])
575 [self.delegate openURL:url];
577 NSString *scheme([[url scheme] lowercaseString]);
578 if ([scheme isEqualToString:@"mailto"])
579 [self _openMailToURL:url];
581 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
587 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
589 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
593 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
595 NSLog(@"didCommitLoadForFrame:%@", frame);
598 if ([frame parentFrame] == nil) {
602 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
604 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
607 [self _didFailWithError:error forFrame:frame];
610 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
612 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
615 [self _didFailWithError:error forFrame:frame];
618 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
619 NSValue *object([NSValue valueWithNonretainedObject:frame]);
620 if (![loading_ containsObject:object])
622 [loading_ removeObject:object];
624 if ([frame parentFrame] == nil) {
625 if (DOMDocument *document = [frame DOMDocument])
626 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
627 for (DOMHTMLBodyElement *body in (id) bodies) {
628 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
632 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
633 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
634 DOMRGBColor *rgb([color getRGBColorValue]);
636 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
637 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
638 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
639 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
643 colorWithRed:(red / 255)
651 [super setPageColor:uic];
652 [scroller_ setBackgroundColor:self.pageColor];
657 [self _didFinishLoading];
660 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
661 if ([frame parentFrame] != nil)
666 [[self navigationItem] setTitle:title_];
669 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
671 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
674 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
676 if ([frame parentFrame] == nil) {
682 [registered_ removeAllObjects];
685 allowsNavigationAction_ = true;
687 [self setHidesNavigationBar:NO];
688 [self setScrollAlwaysBounceVertical:true];
689 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
691 // XXX: do we still need to do this?
692 [[self navigationItem] setTitle:nil];
695 [self _didStartLoading];
698 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
699 challenge_ = [challenge retain];
701 NSURLProtectionSpace *space([challenge protectionSpace]);
702 NSString *realm([space realm]);
706 UIAlertView *alert = [[[UIAlertView alloc]
710 cancelButtonTitle:UCLocalize("CANCEL")
711 otherButtonTitles:UCLocalize("LOGIN"), nil
714 [alert setContext:@"challenge"];
715 [alert setNumberOfRows:1];
717 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
718 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
720 UITextField *username([alert textFieldAtIndex:0]); {
721 NSObject<UITextInputTraits> *traits([username textInputTraits]);
722 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
723 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
724 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
725 [traits setReturnKeyType:UIReturnKeyNext];
728 UITextField *password([alert textFieldAtIndex:1]); {
729 NSObject<UITextInputTraits> *traits([password textInputTraits]);
730 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
731 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
732 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
733 // XXX: UIReturnKeyDone
734 [traits setReturnKeyType:UIReturnKeyNext];
735 [traits setSecureTextEntry:YES];
741 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
743 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
749 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
751 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
757 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
758 return [self _allowJavaScriptPanel];
761 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
762 return [self _allowJavaScriptPanel];
765 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
766 return [self _allowJavaScriptPanel];
769 - (void) webViewClose:(WebView *)view {
775 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
778 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
779 NSString *context([alert context]);
781 if ([context isEqualToString:@"sensitive"]) {
784 sensitive_ = [NSNumber numberWithBool:YES];
788 sensitive_ = [NSNumber numberWithBool:NO];
792 [alert dismissWithClickedButtonIndex:-1 animated:YES];
793 } else if ([context isEqualToString:@"challenge"]) {
794 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
796 if (button == [alert cancelButtonIndex])
797 [sender cancelAuthenticationChallenge:challenge_];
798 else if (button == [alert firstOtherButtonIndex]) {
799 NSString *username([[alert textFieldAtIndex:0] text]);
800 NSString *password([[alert textFieldAtIndex:1] text]);
802 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
804 [sender useCredential:credential forAuthenticationChallenge:challenge_];
809 [alert dismissWithClickedButtonIndex:-1 animated:YES];
810 } else if ([context isEqualToString:@"itmsappss"]) {
811 if (button == [alert cancelButtonIndex]) {
812 } else if (button == [alert firstOtherButtonIndex]) {
813 [self.delegate openURL:appstore_];
816 [alert dismissWithClickedButtonIndex:-1 animated:YES];
817 } else if ([context isEqualToString:@"submit"]) {
818 if (button == [alert cancelButtonIndex]) {
819 } else if (button == [alert firstOtherButtonIndex]) {
820 if (request_ != nil) {
821 WebThreadLocked lock;
822 [[self webView] loadRequest:request_];
826 [alert dismissWithClickedButtonIndex:-1 animated:YES];
830 - (UIBarButtonItemStyle) rightButtonStyle {
831 if (style_ == nil) normal:
832 return UIBarButtonItemStylePlain;
833 else if ([style_ isEqualToString:@"Normal"])
834 return UIBarButtonItemStylePlain;
835 else if ([style_ isEqualToString:@"Highlighted"])
836 return UIBarButtonItemStyleDone;
840 - (UIBarButtonItem *) customButton {
842 return [self rightButton];
843 else if ((/*clang:*/id) custom_ == [NSNull null])
846 return [[[UIBarButtonItem alloc]
847 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
848 style:[self rightButtonStyle]
850 action:@selector(customButtonClicked)
854 - (UIBarButtonItem *) leftButton {
855 UINavigationItem *item([self navigationItem]);
856 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
859 if (UINavigationController *navigation = [self navigationController])
860 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
861 return [[[UIBarButtonItem alloc]
862 initWithTitle:UCLocalize("CLOSE")
863 style:UIBarButtonItemStylePlain
865 action:@selector(close)
871 - (void) applyLeftButton {
872 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
875 - (UIBarButtonItem *) rightButton {
879 - (void) applyLoadingTitle {
880 [[self navigationItem] setTitle:UCLocalize("LOADING")];
883 - (void) layoutRightButton {
884 [[loadingitem_ view] addSubview:indicator_];
885 [[loadingitem_ view] bringSubviewToFront:indicator_];
888 - (void) applyRightButton {
889 if ([self isLoading]) {
890 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
891 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
893 [indicator_ startAnimating];
894 [self applyLoadingTitle];
896 [indicator_ stopAnimating];
897 [[self navigationItem] setRightBarButtonItem:[self customButton] animated:YES];
901 - (void) didStartLoading {
902 // Overridden in subclasses.
905 - (void) _didStartLoading {
906 [self applyRightButton];
908 if ([loading_ count] != 1)
911 if ([self retainsNetworkActivityIndicator])
912 [self.delegate retainNetworkActivityIndicator];
914 [self didStartLoading];
917 - (void) didFinishLoading {
918 // Overridden in subclasses.
921 - (void) _didFinishLoading {
922 if ([loading_ count] != 0)
925 [self applyRightButton];
926 [[self navigationItem] setTitle:title_];
928 if ([self retainsNetworkActivityIndicator])
929 [self.delegate releaseNetworkActivityIndicator];
931 [self didFinishLoading];
935 return [loading_ count] != 0;
938 - (id) initWithWidth:(float)width ofClass:(Class)_class {
939 if ((self = [super init]) != nil) {
943 [super setPageColor:nil];
945 allowsNavigationAction_ = true;
947 loading_ = [NSMutableSet setWithCapacity:5];
948 registered_ = [NSMutableSet setWithCapacity:5];
949 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
951 reloaditem_ = [[[UIBarButtonItem alloc]
952 initWithTitle:UCLocalize("RELOAD")
953 style:[self rightButtonStyle]
955 action:@selector(reloadButtonClicked)
958 loadingitem_ = [[[UIBarButtonItem alloc]
959 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
960 style:UIBarButtonItemStylePlain
962 action:@selector(customButtonClicked)
965 UIActivityIndicatorViewStyle style;
967 if (kCFCoreFoundationVersionNumber >= 800) {
968 style = UIActivityIndicatorViewStyleGray;
971 style = UIActivityIndicatorViewStyleWhite;
975 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
976 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
977 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
979 [self applyLeftButton];
980 [self applyRightButton];
984 - (NSString *) applicationNameForUserAgent {
989 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
991 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
992 [webview_ setDelegate:self];
993 [self setView:webview_];
995 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
996 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
998 [webview_ setDetectsPhoneNumbers:NO];
1000 [webview_ setScalesPageToFit:YES];
1002 UIWebDocumentView *document([webview_ _documentView]);
1004 // XXX: I think this improves scrolling; the hardcoded-ness sucks
1005 [document setTileSize:CGSizeMake(320, 500)];
1007 WebView *webview([document webView]);
1008 WebPreferences *preferences([webview preferences]);
1010 // XXX: I have no clue if I actually /want/ this modification
1011 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
1012 [webview _setLayoutInterval:0];
1013 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
1014 [preferences _setLayoutInterval:0];
1016 [preferences setCacheModel:WebCacheModelDocumentBrowser];
1017 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1019 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
1020 [preferences setOfflineWebApplicationCacheEnabled:YES];
1022 if (NSString *agent = [self applicationNameForUserAgent])
1023 [webview setApplicationNameForUserAgent:agent];
1025 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
1026 [webview setShouldUpdateWhileOffscreen:NO];
1029 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
1030 [document setAllowsMessaging:YES];
1031 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
1032 [webview _setAllowsMessaging:YES];
1035 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1036 scroller_ = [webview_ _scrollView];
1038 [scroller_ setDirectionalLockEnabled:YES];
1039 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
1040 [scroller_ setDelaysContentTouches:NO];
1042 [scroller_ setCanCancelContentTouches:YES];
1043 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1044 UIScroller *scroller([webview_ _scroller]);
1045 scroller_ = (UIScrollView *) scroller;
1047 [scroller setDirectionalScrolling:YES];
1048 // XXX: we might be better off /not/ setting this on older systems
1049 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
1050 [scroller setScrollHysteresis:0]; /* 8 */
1052 [scroller setThumbDetectionEnabled:NO];
1054 // use NO with UIApplicationUseLegacyEvents(YES)
1055 [scroller setEventMode:YES];
1057 // XXX: this is handled by setBounces, right?
1058 //[scroller setAllowsRubberBanding:YES];
1061 [webview_ setOpaque:NO];
1062 [webview_ setBackgroundColor:nil];
1064 [scroller_ setFixedBackgroundPattern:YES];
1065 [scroller_ setBackgroundColor:self.pageColor];
1066 [scroller_ setClipsSubviews:YES];
1068 [scroller_ setBounces:YES];
1069 [scroller_ setScrollingEnabled:YES];
1070 [scroller_ setShowBackgroundShadow:NO];
1072 [self setViewportWidth:width_];
1074 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1075 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1076 [table setScrollsToTop:NO];
1077 [webview_ insertSubview:table atIndex:0];
1078 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1081 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1086 - (void) releaseSubviews {
1090 [self releaseNetworkActivityIndicator];
1092 [super releaseSubviews];
1095 - (id) initWithWidth:(float)width {
1096 return [self initWithWidth:width ofClass:[self class]];
1100 return [self initWithWidth:0];
1103 - (id) initWithURL:(NSURL *)url {
1104 if ((self = [self init]) != nil) {
1109 - (id) initWithRequest:(NSURLRequest *)request {
1110 if ((self = [self init]) != nil) {
1111 [self setRequest:request];
1115 + (void) _lockJavaScript:(WebPreferences *)preferences {
1116 WebThreadLocked lock;
1117 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1120 - (void) callFunction:(WebScriptObject *)function {
1121 WebThreadLocked lock;
1123 WebView *webview([[[self webView] _documentView] webView]);
1124 WebPreferences *preferences([webview preferences]);
1126 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
1127 if ([webview respondsToSelector:@selector(_preferencesChanged:)])
1128 [webview _preferencesChanged:preferences];
1130 [webview _preferencesChangedNotification:[NSNotification notificationWithName:@"" object:preferences]];
1132 WebFrame *frame([webview mainFrame]);
1133 JSGlobalContextRef context([frame globalContext]);
1135 JSObjectRef object([function JSObject]);
1136 if ($JSObjectCallAsFunction != NULL)
1137 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1139 // XXX: the JavaScript code submits a form, which seems to happen asynchronously
1140 NSObject *target([CyteWebViewController class]);
1141 [NSObject cancelPreviousPerformRequestsWithTarget:target selector:@selector(_lockJavaScript:) object:preferences];
1142 [target performSelector:@selector(_lockJavaScript:) withObject:preferences afterDelay:1];
1145 - (void) reloadButtonClicked {
1146 [self reloadURLWithCache:NO];
1149 - (void) _customButtonClicked {
1150 [self reloadButtonClicked];
1153 - (void) customButtonClicked {
1155 if (function_ != nil)
1156 [self callFunction:function_];
1159 [self _customButtonClicked];
1162 + (float) defaultWidth {
1166 - (void) setNavigationBarStyle:(NSString *)name {
1168 if ([name isEqualToString:@"Black"])
1169 style = UIBarStyleBlack;
1171 style = UIBarStyleDefault;
1173 [[[self navigationController] navigationBar] setBarStyle:style];
1176 - (void) setNavigationBarTintColor:(UIColor *)color {
1177 [[[self navigationController] navigationBar] setTintColor:color];
1180 - (void) setBadgeValue:(id)value {
1181 [[[self navigationController] tabBarItem] setBadgeValue:value];
1184 - (void) setHidesBackButton:(bool)value {
1185 [[self navigationItem] setHidesBackButton:value];
1186 [self applyLeftButton];
1189 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1190 [self setHidesBackButton:[value boolValue]];
1193 - (void) dispatchEvent:(NSString *)event {
1194 [[self webView] dispatchEvent:event];
1197 - (bool) hidesNavigationBar {
1198 return hidesNavigationBar_;
1201 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1203 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1206 - (void) setHidesNavigationBar:(bool)value {
1207 if (hidesNavigationBar_ != value) {
1208 hidesNavigationBar_ = value;
1209 [self _setHidesNavigationBar:YES animated:YES];
1213 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1214 [self setHidesNavigationBar:[value boolValue]];
1217 - (void) setScrollAlwaysBounceVertical:(bool)value {
1218 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1219 UIScrollView *scroller([webview_ _scrollView]);
1220 [scroller setAlwaysBounceVertical:value];
1221 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1222 //UIScroller *scroller([webview_ _scroller]);
1223 // XXX: I am sad here.
1227 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1228 [self setScrollAlwaysBounceVertical:[value boolValue]];
1231 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1232 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1233 UIScrollView *scroller([webview_ _scrollView]);
1234 [scroller setIndicatorStyle:style];
1235 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1236 UIScroller *scroller([webview_ _scroller]);
1237 [scroller setScrollerIndicatorStyle:style];
1241 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1242 UIScrollViewIndicatorStyle value;
1245 else if ([style isEqualToString:@"default"])
1246 value = UIScrollViewIndicatorStyleDefault;
1247 else if ([style isEqualToString:@"black"])
1248 value = UIScrollViewIndicatorStyleBlack;
1249 else if ([style isEqualToString:@"white"])
1250 value = UIScrollViewIndicatorStyleWhite;
1253 [self setScrollIndicatorStyle:value];
1256 - (void) viewWillAppear:(BOOL)animated {
1259 if ([self hidesNavigationBar])
1260 [self _setHidesNavigationBar:YES animated:animated];
1262 // XXX: why isn't this evern called automatically?
1263 [[self webView] setNeedsLayout];
1265 [self dispatchEvent:@"CydiaViewWillAppear"];
1266 [super viewWillAppear:animated];
1269 - (void) viewDidAppear:(BOOL)animated {
1270 [super viewDidAppear:animated];
1271 [self dispatchEvent:@"CydiaViewDidAppear"];
1274 - (void) viewWillDisappear:(BOOL)animated {
1275 [self dispatchEvent:@"CydiaViewWillDisappear"];
1276 [super viewWillDisappear:animated];
1278 if ([self hidesNavigationBar])
1279 [self _setHidesNavigationBar:NO animated:animated];
1284 - (void) viewDidDisappear:(BOOL)animated {
1285 [super viewDidDisappear:animated];
1286 [self dispatchEvent:@"CydiaViewDidDisappear"];
1289 - (void) updateHeights:(NSTimer *)timer {
1290 for (WebFrame *frame in (id) registered_)
1291 [frame cydia$updateHeight];
1294 - (void) registerFrame:(WebFrame *)frame {
1295 [registered_ addObject:frame];
1298 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];
1303 MSClassHook(WAKWindow)
1305 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
1306 CGSize size([[UIScreen mainScreen] bounds].size);
1307 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
1308 if ([$WAKWindow hasLandscapeOrientation])
1309 std::swap(size.width, size.height);*/
1313 static struct WAKWindow$screenSize { WAKWindow$screenSize() {
1314 if ($WAKWindow != NULL)
1315 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
1316 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
1317 } } WAKWindow$screenSize;;
1319 MSClassHook(NSUserDefaults)
1321 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
1322 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
1323 return [NSString stringWithFormat:@"%@/%@/%@", NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject, NSBundle.mainBundle.bundleIdentifier, @"LocalStorage"];
1324 return _NSUserDefaults$objectForKey$(self, _cmd, key);
1327 CYHook(NSUserDefaults, objectForKey$, objectForKey:)