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]]
61 static _H<NSMutableSet> Diversions_;
63 @implementation Diversion {
69 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
70 if ((self = [super init]) != nil) {
71 pattern_ = [from UTF8String];
77 - (NSString *) divert:(NSString *)url {
78 return !pattern_(url) ? nil : pattern_->*format_;
81 + (NSURL *) divertURL:(NSURL *)url {
83 NSString *href([url absoluteString]);
85 for (Diversion *diversion in (id) Diversions_)
86 if (NSString *diverted = [diversion divert:href]) {
88 NSLog(@"div: %@", diverted);
90 url = [NSURL URLWithString:diverted];
101 - (NSUInteger) hash {
105 - (BOOL) isEqual:(Diversion *)object {
106 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
111 /* Indirect Delegate {{{ */
112 @implementation IndirectDelegate
118 - (void) setDelegate:(id)delegate {
119 delegate_ = delegate;
122 - (id) initWithDelegate:(id)delegate {
123 delegate_ = delegate;
127 - (IMP) methodForSelector:(SEL)sel {
128 if (IMP method = [super methodForSelector:sel])
130 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
134 - (BOOL) respondsToSelector:(SEL)sel {
135 if ([super respondsToSelector:sel])
138 // XXX: WebThreadCreateNSInvocation returns nil
141 fprintf(stderr, "[%s]R?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
144 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
147 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
148 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
152 fprintf(stderr, "[%s]S?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
155 if (delegate_ != nil)
156 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
159 // XXX: I fucking hate Apple so very very bad
160 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
163 - (void) forwardInvocation:(NSInvocation *)inv {
164 SEL sel = [inv selector];
165 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
166 [inv invokeWithTarget:delegate_];
172 @implementation CyteWebViewController {
173 _H<CyteWebView, 1> webview_;
174 _transient UIScrollView *scroller_;
176 _H<UIActivityIndicatorView> indicator_;
177 _H<IndirectDelegate, 1> indirect_;
178 _H<NSURLAuthenticationChallenge> challenge_;
181 _H<NSURLRequest> request_;
184 _transient NSNumber *sensitive_;
188 _H<NSMutableSet> loading_;
190 _H<NSMutableSet> registered_;
193 // XXX: NSString * or UIImage *
194 _H<NSObject> custom_;
197 _H<WebScriptObject> function_;
202 _H<UIBarButtonItem> reloaditem_;
203 _H<UIBarButtonItem> loadingitem_;
206 bool hidesNavigationBar_;
207 bool allowsNavigationAction_;
211 #include "CyteKit/UCInternal.h"
214 + (void) _initialize {
215 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
219 js = dlopen("/System/Library/Frameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
221 js = dlopen("/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
223 $JSObjectCallAsFunction = reinterpret_cast<JSValueRef (*)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(js, "JSObjectCallAsFunction"));
225 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
226 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
228 if (CGFloat *_UIScrollViewDecelerationRateNormal = reinterpret_cast<CGFloat *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
229 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
230 else // XXX: this actually might be fast on some older systems: we should look into this
231 CYScrollViewDecelerationRateNormal = 0.998;
233 Diversions_ = [NSMutableSet setWithCapacity:0];
236 - (bool) retainsNetworkActivityIndicator {
240 - (void) releaseNetworkActivityIndicator {
241 if ([loading_ count] != 0) {
242 [loading_ removeAllObjects];
244 if ([self retainsNetworkActivityIndicator])
245 [self.delegate releaseNetworkActivityIndicator];
251 NSLog(@"[CyteWebViewController dealloc]");
254 [self releaseNetworkActivityIndicator];
259 - (NSString *) description {
260 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[request_ URL] absoluteString]];
263 - (CyteWebView *) webView {
264 return (CyteWebView *) [self view];
267 - (CyteWebViewController *) indirect {
268 return (CyteWebViewController *) (IndirectDelegate *) indirect_;
271 + (void) addDiversion:(Diversion *)diversion {
272 [Diversions_ addObject:diversion];
275 - (NSURL *) URLWithURL:(NSURL *)url {
276 return [Diversion divertURL:url];
279 - (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy referrer:(NSString *)referrer {
280 NSMutableURLRequest *request([NSMutableURLRequest
281 requestWithURL:[self URLWithURL:url]
283 timeoutInterval:DefaultTimeout_
286 [request setValue:referrer forHTTPHeaderField:@"Referer"];
291 - (void) setRequest:(NSURLRequest *)request {
292 _assert(request_ == nil);
296 - (NSURLRequest *) request {
300 - (void) setURL:(NSURL *)url {
301 [self setURL:url withReferrer:nil];
304 - (void) setURL:(NSURL *)url withReferrer:(NSString *)referrer {
305 [self setRequest:[self requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy referrer:referrer]];
308 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
309 [self loadRequest:[self requestWithURL:url cachePolicy:policy referrer:nil]];
312 - (void) loadURL:(NSURL *)url {
313 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
316 - (void) loadRequest:(NSURLRequest *)request {
318 NSLog(@"loadRequest:%@", request);
324 WebThreadLocked lock;
325 [[self webView] loadRequest:request];
328 - (void) reloadURLWithCache:(BOOL)cache {
332 NSMutableURLRequest *request([request_ mutableCopy]);
333 [request setCachePolicy:(cache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData)];
337 if (cache || [request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
338 [self loadRequest:request_];
340 UIAlertView *alert = [[[UIAlertView alloc]
341 initWithTitle:UCLocalize("RESUBMIT_FORM")
344 cancelButtonTitle:UCLocalize("CANCEL")
346 UCLocalize("SUBMIT"),
350 [alert setContext:@"submit"];
355 - (void) reloadData {
359 [self dispatchEvent:@"CydiaReloadData"];
361 [self reloadURLWithCache:YES];
364 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
367 function_ = function;
369 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
372 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
375 function_ = function;
377 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
380 - (void) removeButton {
381 custom_ = [NSNull null];
382 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
385 - (void) scrollToBottomAnimated:(NSNumber *)animated {
386 CGSize size([scroller_ contentSize]);
387 CGPoint offset([scroller_ contentOffset]);
388 CGRect frame([scroller_ frame]);
390 if (size.height - offset.y < frame.size.height + 20.f) {
391 CGRect rect = {{0, size.height-1}, {size.width, 1}};
392 [scroller_ scrollRectToVisible:rect animated:[animated boolValue]];
396 - (void) _setViewportWidth {
397 [[[self webView] _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
400 - (void) setViewportWidth:(float)width {
401 width_ = width != 0 ? width : [[self class] defaultWidth];
402 [self _setViewportWidth];
405 - (void) _setViewportWidthOnMainThread:(NSNumber *)width {
406 [self setViewportWidth:[width floatValue]];
409 - (void) setViewportWidthOnMainThread:(float)width {
410 [self performSelectorOnMainThread:@selector(_setViewportWidthOnMainThread:) withObject:[NSNumber numberWithFloat:width] waitUntilDone:NO];
413 - (void) webViewUpdateViewSettings:(UIWebView *)view {
414 [self _setViewportWidth];
417 - (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
418 [self dismissModalViewControllerAnimated:YES];
421 - (void) _setupMail:(MFMailComposeViewController *)controller {
424 - (void) _openMailToURL:(NSURL *)url {
425 if ($MFMailComposeViewController != nil && [$MFMailComposeViewController canSendMail]) {
426 MFMailComposeViewController *controller([[[$MFMailComposeViewController alloc] init] autorelease]);
427 [controller setMailComposeDelegate:self];
429 [controller setMailToURL:url];
431 [self _setupMail:controller];
433 [self presentModalViewController:controller animated:YES];
437 UIApplication *app([UIApplication sharedApplication]);
438 if ([app respondsToSelector:@selector(openURL:asPanel:)])
439 [app openURL:url asPanel:YES];
444 - (bool) _allowJavaScriptPanel {
448 - (bool) allowsNavigationAction {
449 return allowsNavigationAction_;
452 - (void) setAllowsNavigationAction:(bool)value {
453 allowsNavigationAction_ = value;
456 - (void) setAllowsNavigationActionByNumber:(NSNumber *)value {
457 [self setAllowsNavigationAction:[value boolValue]];
460 - (void) popViewControllerWithNumber:(NSNumber *)value {
461 UINavigationController *navigation([self navigationController]);
462 if ([navigation topViewController] == self)
463 [navigation popViewControllerAnimated:[value boolValue]];
466 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
467 NSValue *object([NSValue valueWithNonretainedObject:frame]);
468 if (![loading_ containsObject:object])
470 [loading_ removeObject:object];
472 [self _didFinishLoading];
474 if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == NSURLErrorCancelled)
477 if ([[error domain] isEqualToString:WebKitErrorDomain] && [error code] == WebKitErrorFrameLoadInterruptedByPolicyChange) {
482 if ([frame parentFrame] == nil) {
483 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
484 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
485 [[error localizedDescription] stringByAddingPercentEscapes]
492 - (void) pushRequest:(NSURLRequest *)request forAction:(NSDictionary *)action asPop:(bool)pop {
493 WebFrame *frame(nil);
494 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
495 frame = [WebActionElement objectForKey:@"WebElementFrame"];
497 frame = [[[[self webView] _documentView] webView] mainFrame];
499 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
500 NSString *referrer([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString]);
502 NSURL *url([request URL]);
504 // XXX: filter to internal usage?
505 CyteViewController *page([self.delegate pageForURL:url forExternal:NO withReferrer:referrer]);
508 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
509 [browser setRequest:request];
513 [page setDelegate:self.delegate];
514 [page setPageColor:self.pageColor];
517 [[self navigationItem] setTitle:title_];
519 [[self navigationController] pushViewController:page animated:YES];
521 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
523 [navigation setDelegate:self.delegate];
525 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
526 initWithTitle:UCLocalize("CLOSE")
527 style:UIBarButtonItemStylePlain
529 action:@selector(close)
532 [[self navigationController] presentModalViewController:navigation animated:YES];
536 // CyteWebViewDelegate {{{
537 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
539 static RegEx irritating("(?"
540 ":" "The page at .* displayed insecure content from .*\\."
541 "|" "Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\."
544 if (NSString *data = [message objectForKey:@"message"])
545 if (irritating(data))
548 NSLog(@"addMessageToConsole:%@", message);
552 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
554 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ %@ frame:%@", action, request, [request allHTTPHeaderFields], frame);
557 NSURL *url(request == nil ? nil : [request URL]);
558 NSString *scheme([[url scheme] lowercaseString]);
559 NSString *absolute([[url absoluteString] lowercaseString]);
562 [scheme isEqualToString:@"itms"] ||
563 [scheme isEqualToString:@"itmss"] ||
564 [scheme isEqualToString:@"itms-apps"] ||
565 [scheme isEqualToString:@"itms-appss"] ||
566 [absolute hasPrefix:@"http://itunes.apple.com/"] ||
567 [absolute hasPrefix:@"https://itunes.apple.com/"] ||
571 UIAlertView *alert = [[[UIAlertView alloc]
572 initWithTitle:UCLocalize("APP_STORE_REDIRECT")
575 cancelButtonTitle:UCLocalize("CANCEL")
581 [alert setContext:@"itmsappss"];
588 if ([frame parentFrame] == nil) {
590 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
592 [self pushRequest:request forAction:action asPop:NO];
599 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
601 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ %@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
604 if ([frame parentFrame] == nil) {
606 case CYWebPolicyDecisionIgnore:
607 if ([[request_ URL] isEqual:[request URL]])
611 case CYWebPolicyDecisionUse:
622 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
624 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
627 NSURL *url([request URL]);
631 if ([name isEqualToString:@"_open"])
632 [self.delegate openURL:url];
634 NSString *scheme([[url scheme] lowercaseString]);
635 if ([scheme isEqualToString:@"mailto"])
636 [self _openMailToURL:url];
638 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
644 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
646 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
650 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
652 NSLog(@"didCommitLoadForFrame:%@", frame);
655 if ([frame parentFrame] == nil) {
659 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
661 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
664 [self _didFailWithError:error forFrame:frame];
667 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
669 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
672 [self _didFailWithError:error forFrame:frame];
675 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
676 NSValue *object([NSValue valueWithNonretainedObject:frame]);
677 if (![loading_ containsObject:object])
679 [loading_ removeObject:object];
681 if ([frame parentFrame] == nil) {
682 if (DOMDocument *document = [frame DOMDocument])
683 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
684 for (DOMHTMLBodyElement *body in (id) bodies) {
685 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
689 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
690 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
691 DOMRGBColor *rgb([color getRGBColorValue]);
693 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
694 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
695 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
696 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
700 colorWithRed:(red / 255)
708 [super setPageColor:uic];
709 [scroller_ setBackgroundColor:self.pageColor];
714 [self _didFinishLoading];
717 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
718 if ([frame parentFrame] != nil)
723 [[self navigationItem] setTitle:title_];
726 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
728 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
731 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
733 if ([frame parentFrame] == nil) {
739 [registered_ removeAllObjects];
742 allowsNavigationAction_ = true;
744 [self setHidesNavigationBar:NO];
745 [self setScrollAlwaysBounceVertical:true];
746 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
748 // XXX: do we still need to do this?
749 [[self navigationItem] setTitle:nil];
752 [self _didStartLoading];
755 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
756 challenge_ = [challenge retain];
758 NSURLProtectionSpace *space([challenge protectionSpace]);
759 NSString *realm([space realm]);
763 UIAlertView *alert = [[[UIAlertView alloc]
767 cancelButtonTitle:UCLocalize("CANCEL")
768 otherButtonTitles:UCLocalize("LOGIN"), nil
771 [alert setContext:@"challenge"];
772 [alert setNumberOfRows:1];
774 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
775 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
777 UITextField *username([alert textFieldAtIndex:0]); {
778 NSObject<UITextInputTraits> *traits([username textInputTraits]);
779 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
780 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
781 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
782 [traits setReturnKeyType:UIReturnKeyNext];
785 UITextField *password([alert textFieldAtIndex:1]); {
786 NSObject<UITextInputTraits> *traits([password textInputTraits]);
787 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
788 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
789 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
790 // XXX: UIReturnKeyDone
791 [traits setReturnKeyType:UIReturnKeyNext];
792 [traits setSecureTextEntry:YES];
798 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
800 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
806 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
808 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
814 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
815 return [self _allowJavaScriptPanel];
818 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
819 return [self _allowJavaScriptPanel];
822 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
823 return [self _allowJavaScriptPanel];
826 - (void) webViewClose:(WebView *)view {
832 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
835 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
836 NSString *context([alert context]);
838 if ([context isEqualToString:@"sensitive"]) {
841 sensitive_ = [NSNumber numberWithBool:YES];
845 sensitive_ = [NSNumber numberWithBool:NO];
849 [alert dismissWithClickedButtonIndex:-1 animated:YES];
850 } else if ([context isEqualToString:@"challenge"]) {
851 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
853 if (button == [alert cancelButtonIndex])
854 [sender cancelAuthenticationChallenge:challenge_];
855 else if (button == [alert firstOtherButtonIndex]) {
856 NSString *username([[alert textFieldAtIndex:0] text]);
857 NSString *password([[alert textFieldAtIndex:1] text]);
859 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
861 [sender useCredential:credential forAuthenticationChallenge:challenge_];
866 [alert dismissWithClickedButtonIndex:-1 animated:YES];
867 } else if ([context isEqualToString:@"itmsappss"]) {
868 if (button == [alert cancelButtonIndex]) {
869 } else if (button == [alert firstOtherButtonIndex]) {
870 [self.delegate openURL:appstore_];
873 [alert dismissWithClickedButtonIndex:-1 animated:YES];
874 } else if ([context isEqualToString:@"submit"]) {
875 if (button == [alert cancelButtonIndex]) {
876 } else if (button == [alert firstOtherButtonIndex]) {
877 if (request_ != nil) {
878 WebThreadLocked lock;
879 [[self webView] loadRequest:request_];
883 [alert dismissWithClickedButtonIndex:-1 animated:YES];
887 - (UIBarButtonItemStyle) rightButtonStyle {
888 if (style_ == nil) normal:
889 return UIBarButtonItemStylePlain;
890 else if ([style_ isEqualToString:@"Normal"])
891 return UIBarButtonItemStylePlain;
892 else if ([style_ isEqualToString:@"Highlighted"])
893 return UIBarButtonItemStyleDone;
897 - (UIBarButtonItem *) customButton {
899 return [self rightButton];
900 else if ((/*clang:*/id) custom_ == [NSNull null])
903 return [[[UIBarButtonItem alloc]
904 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
905 style:[self rightButtonStyle]
907 action:@selector(customButtonClicked)
911 - (UIBarButtonItem *) leftButton {
912 UINavigationItem *item([self navigationItem]);
913 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
916 if (UINavigationController *navigation = [self navigationController])
917 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
918 return [[[UIBarButtonItem alloc]
919 initWithTitle:UCLocalize("CLOSE")
920 style:UIBarButtonItemStylePlain
922 action:@selector(close)
928 - (void) applyLeftButton {
929 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
932 - (UIBarButtonItem *) rightButton {
936 - (void) applyLoadingTitle {
937 [[self navigationItem] setTitle:UCLocalize("LOADING")];
940 - (void) layoutRightButton {
941 [[loadingitem_ view] addSubview:indicator_];
942 [[loadingitem_ view] bringSubviewToFront:indicator_];
945 - (void) applyRightButton {
946 if ([self isLoading]) {
947 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
948 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
950 [indicator_ startAnimating];
951 [self applyLoadingTitle];
953 [indicator_ stopAnimating];
954 [[self navigationItem] setRightBarButtonItem:[self customButton] animated:YES];
958 - (void) didStartLoading {
959 // Overridden in subclasses.
962 - (void) _didStartLoading {
963 [self applyRightButton];
965 if ([loading_ count] != 1)
968 if ([self retainsNetworkActivityIndicator])
969 [self.delegate retainNetworkActivityIndicator];
971 [self didStartLoading];
974 - (void) didFinishLoading {
975 // Overridden in subclasses.
978 - (void) _didFinishLoading {
979 if ([loading_ count] != 0)
982 [self applyRightButton];
983 [[self navigationItem] setTitle:title_];
985 if ([self retainsNetworkActivityIndicator])
986 [self.delegate releaseNetworkActivityIndicator];
988 [self didFinishLoading];
992 return [loading_ count] != 0;
995 - (id) initWithWidth:(float)width ofClass:(Class)_class {
996 if ((self = [super init]) != nil) {
1000 [super setPageColor:nil];
1002 allowsNavigationAction_ = true;
1004 loading_ = [NSMutableSet setWithCapacity:5];
1005 registered_ = [NSMutableSet setWithCapacity:5];
1006 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
1008 reloaditem_ = [[[UIBarButtonItem alloc]
1009 initWithTitle:UCLocalize("RELOAD")
1010 style:[self rightButtonStyle]
1012 action:@selector(reloadButtonClicked)
1015 loadingitem_ = [[[UIBarButtonItem alloc]
1016 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
1017 style:UIBarButtonItemStylePlain
1019 action:@selector(customButtonClicked)
1022 UIActivityIndicatorViewStyle style;
1024 if (kCFCoreFoundationVersionNumber >= 800) {
1025 style = UIActivityIndicatorViewStyleGray;
1028 style = UIActivityIndicatorViewStyleWhite;
1032 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
1033 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
1034 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
1036 [self applyLeftButton];
1037 [self applyRightButton];
1041 static _H<NSString> UserAgent_;
1042 + (void) setApplicationNameForUserAgent:(NSString *)userAgent {
1043 UserAgent_ = userAgent;
1046 - (NSString *) applicationNameForUserAgent {
1051 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
1053 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
1054 [webview_ setDelegate:self];
1055 [self setView:webview_];
1057 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
1058 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
1060 [webview_ setDetectsPhoneNumbers:NO];
1062 [webview_ setScalesPageToFit:YES];
1064 UIWebDocumentView *document([webview_ _documentView]);
1066 // XXX: I think this improves scrolling; the hardcoded-ness sucks
1067 [document setTileSize:CGSizeMake(320, 500)];
1069 WebView *webview([document webView]);
1070 WebPreferences *preferences([webview preferences]);
1072 // XXX: I have no clue if I actually /want/ this modification
1073 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
1074 [webview _setLayoutInterval:0];
1075 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
1076 [preferences _setLayoutInterval:0];
1078 [preferences setCacheModel:WebCacheModelDocumentBrowser];
1079 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1081 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
1082 [preferences setOfflineWebApplicationCacheEnabled:YES];
1084 if (NSString *agent = [self applicationNameForUserAgent])
1085 [webview setApplicationNameForUserAgent:agent];
1087 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
1088 [webview setShouldUpdateWhileOffscreen:NO];
1091 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
1092 [document setAllowsMessaging:YES];
1093 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
1094 [webview _setAllowsMessaging:YES];
1097 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1098 scroller_ = [webview_ _scrollView];
1100 [scroller_ setDirectionalLockEnabled:YES];
1101 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
1102 [scroller_ setDelaysContentTouches:NO];
1104 [scroller_ setCanCancelContentTouches:YES];
1105 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1106 UIScroller *scroller([webview_ _scroller]);
1107 scroller_ = (UIScrollView *) scroller;
1109 [scroller setDirectionalScrolling:YES];
1110 // XXX: we might be better off /not/ setting this on older systems
1111 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
1112 [scroller setScrollHysteresis:0]; /* 8 */
1114 [scroller setThumbDetectionEnabled:NO];
1116 // use NO with UIApplicationUseLegacyEvents(YES)
1117 [scroller setEventMode:YES];
1119 // XXX: this is handled by setBounces, right?
1120 //[scroller setAllowsRubberBanding:YES];
1123 [webview_ setOpaque:NO];
1124 [webview_ setBackgroundColor:nil];
1126 [scroller_ setFixedBackgroundPattern:YES];
1127 [scroller_ setBackgroundColor:self.pageColor];
1128 [scroller_ setClipsSubviews:YES];
1130 [scroller_ setBounces:YES];
1131 [scroller_ setScrollingEnabled:YES];
1132 [scroller_ setShowBackgroundShadow:NO];
1134 [self setViewportWidth:width_];
1136 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1137 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1138 [table setScrollsToTop:NO];
1139 [webview_ insertSubview:table atIndex:0];
1140 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1143 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1148 - (void) releaseSubviews {
1152 [self releaseNetworkActivityIndicator];
1154 [super releaseSubviews];
1157 - (id) initWithWidth:(float)width {
1158 return [self initWithWidth:width ofClass:[self class]];
1162 return [self initWithWidth:0];
1165 - (id) initWithURL:(NSURL *)url {
1166 if ((self = [self init]) != nil) {
1171 - (id) initWithRequest:(NSURLRequest *)request {
1172 if ((self = [self init]) != nil) {
1173 [self setRequest:request];
1177 + (void) _lockJavaScript:(WebPreferences *)preferences {
1178 WebThreadLocked lock;
1179 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1182 - (void) callFunction:(WebScriptObject *)function {
1183 WebThreadLocked lock;
1185 WebView *webview([[[self webView] _documentView] webView]);
1186 WebPreferences *preferences([webview preferences]);
1188 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
1189 if ([webview respondsToSelector:@selector(_preferencesChanged:)])
1190 [webview _preferencesChanged:preferences];
1192 [webview _preferencesChangedNotification:[NSNotification notificationWithName:@"" object:preferences]];
1194 WebFrame *frame([webview mainFrame]);
1195 JSGlobalContextRef context([frame globalContext]);
1197 JSObjectRef object([function JSObject]);
1198 if ($JSObjectCallAsFunction != NULL)
1199 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1201 // XXX: the JavaScript code submits a form, which seems to happen asynchronously
1202 NSObject *target([CyteWebViewController class]);
1203 [NSObject cancelPreviousPerformRequestsWithTarget:target selector:@selector(_lockJavaScript:) object:preferences];
1204 [target performSelector:@selector(_lockJavaScript:) withObject:preferences afterDelay:1];
1207 - (void) reloadButtonClicked {
1208 [self reloadURLWithCache:NO];
1211 - (void) _customButtonClicked {
1212 [self reloadButtonClicked];
1215 - (void) customButtonClicked {
1217 if (function_ != nil)
1218 [self callFunction:function_];
1221 [self _customButtonClicked];
1224 + (float) defaultWidth {
1228 - (void) setNavigationBarStyle:(NSString *)name {
1230 if ([name isEqualToString:@"Black"])
1231 style = UIBarStyleBlack;
1233 style = UIBarStyleDefault;
1235 [[[self navigationController] navigationBar] setBarStyle:style];
1238 - (void) setNavigationBarTintColor:(UIColor *)color {
1239 [[[self navigationController] navigationBar] setTintColor:color];
1242 - (void) setBadgeValue:(id)value {
1243 [[[self navigationController] tabBarItem] setBadgeValue:value];
1246 - (void) setHidesBackButton:(bool)value {
1247 [[self navigationItem] setHidesBackButton:value];
1248 [self applyLeftButton];
1251 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1252 [self setHidesBackButton:[value boolValue]];
1255 - (void) dispatchEvent:(NSString *)event {
1256 [[self webView] dispatchEvent:event];
1259 - (bool) hidesNavigationBar {
1260 return hidesNavigationBar_;
1263 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1265 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1268 - (void) setHidesNavigationBar:(bool)value {
1269 if (hidesNavigationBar_ != value) {
1270 hidesNavigationBar_ = value;
1271 [self _setHidesNavigationBar:YES animated:YES];
1275 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1276 [self setHidesNavigationBar:[value boolValue]];
1279 - (void) setScrollAlwaysBounceVertical:(bool)value {
1280 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1281 UIScrollView *scroller([webview_ _scrollView]);
1282 [scroller setAlwaysBounceVertical:value];
1283 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1284 //UIScroller *scroller([webview_ _scroller]);
1285 // XXX: I am sad here.
1289 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1290 [self setScrollAlwaysBounceVertical:[value boolValue]];
1293 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1294 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1295 UIScrollView *scroller([webview_ _scrollView]);
1296 [scroller setIndicatorStyle:style];
1297 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1298 UIScroller *scroller([webview_ _scroller]);
1299 [scroller setScrollerIndicatorStyle:style];
1303 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1304 UIScrollViewIndicatorStyle value;
1307 else if ([style isEqualToString:@"default"])
1308 value = UIScrollViewIndicatorStyleDefault;
1309 else if ([style isEqualToString:@"black"])
1310 value = UIScrollViewIndicatorStyleBlack;
1311 else if ([style isEqualToString:@"white"])
1312 value = UIScrollViewIndicatorStyleWhite;
1315 [self setScrollIndicatorStyle:value];
1318 - (void) viewWillAppear:(BOOL)animated {
1321 if ([self hidesNavigationBar])
1322 [self _setHidesNavigationBar:YES animated:animated];
1324 // XXX: why isn't this evern called automatically?
1325 [[self webView] setNeedsLayout];
1327 [self dispatchEvent:@"CydiaViewWillAppear"];
1328 [super viewWillAppear:animated];
1331 - (void) viewDidAppear:(BOOL)animated {
1332 [super viewDidAppear:animated];
1333 [self dispatchEvent:@"CydiaViewDidAppear"];
1336 - (void) viewWillDisappear:(BOOL)animated {
1337 [self dispatchEvent:@"CydiaViewWillDisappear"];
1338 [super viewWillDisappear:animated];
1340 if ([self hidesNavigationBar])
1341 [self _setHidesNavigationBar:NO animated:animated];
1346 - (void) viewDidDisappear:(BOOL)animated {
1347 [super viewDidDisappear:animated];
1348 [self dispatchEvent:@"CydiaViewDidDisappear"];
1351 - (void) updateHeights:(NSTimer *)timer {
1352 for (WebFrame *frame in (id) registered_)
1353 [frame cydia$updateHeight];
1356 - (void) registerFrame:(WebFrame *)frame {
1357 [registered_ addObject:frame];
1360 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];
1365 MSClassHook(WAKWindow)
1367 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
1368 CGSize size([[UIScreen mainScreen] bounds].size);
1369 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
1370 if ([$WAKWindow hasLandscapeOrientation])
1371 std::swap(size.width, size.height);*/
1375 static struct WAKWindow$screenSize { WAKWindow$screenSize() {
1376 if ($WAKWindow != NULL)
1377 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
1378 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
1379 } } WAKWindow$screenSize;;
1381 MSClassHook(NSUserDefaults)
1383 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
1384 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
1385 return [NSString stringWithFormat:@"%@/%@/%@", NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject, NSBundle.mainBundle.bundleIdentifier, @"LocalStorage"];
1386 return _NSUserDefaults$objectForKey$(self, _cmd, key);
1389 CYHook(NSUserDefaults, objectForKey$, objectForKey:)