1 #include "CyteKit/UCPlatform.h"
2 #include "CyteKit/WebViewController.h"
4 #include "CyteKit/MFMailComposeViewController-MailToURL.h"
6 #include "iPhonePrivate.h"
8 #include "CyteKit/IndirectDelegate.h"
9 #include "CyteKit/Localize.h"
10 #include "CyteKit/WebViewController.h"
11 #include "CyteKit/PerlCompatibleRegEx.hpp"
12 #include "CyteKit/WebThreadLocked.hpp"
14 //#include <QuartzCore/CALayer.h>
15 // XXX: fix the minimum requirement
16 extern NSString * const kCAFilterNearest;
18 #include <WebCore/WebCoreThread.h>
20 #import <WebKit/WebKitErrors.h>
21 #import <WebKit/WebPreferences.h>
23 #include <WebKit/DOMCSSPrimitiveValue.h>
24 #include <WebKit/DOMCSSStyleDeclaration.h>
25 #include <WebKit/DOMDocument.h>
26 #include <WebKit/DOMHTMLBodyElement.h>
27 #include <WebKit/DOMRGBColor.h>
30 #include <objc/runtime.h>
33 #define DefaultTimeout_ 120.0
35 #define ShowInternals 0
39 #define lprintf(args...) fprintf(stderr, args)
41 JSValueRef (*$JSObjectCallAsFunction)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *);
43 // XXX: centralize these special class things to some file or mechanism?
44 static Class $MFMailComposeViewController;
46 float CYScrollViewDecelerationRateNormal;
48 @interface WebFrame (Cydia)
49 - (void) cydia$updateHeight;
52 @implementation WebFrame (Cydia)
54 - (NSString *) description {
55 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[[([self provisionalDataSource] ?: [self dataSource]) request] URL] absoluteString]];
58 - (void) cydia$updateHeight {
59 [[[self frameElement] style]
61 value:[NSString stringWithFormat:@"%dpx",
62 [[[self DOMDocument] body] scrollHeight]]
68 /* Indirect Delegate {{{ */
69 @implementation IndirectDelegate
75 - (void) setDelegate:(id)delegate {
79 - (id) initWithDelegate:(id)delegate {
84 - (IMP) methodForSelector:(SEL)sel {
85 if (IMP method = [super methodForSelector:sel])
87 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
91 - (BOOL) respondsToSelector:(SEL)sel {
92 if ([super respondsToSelector:sel])
95 // XXX: WebThreadCreateNSInvocation returns nil
98 fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
101 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
104 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
105 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
109 fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
112 if (delegate_ != nil)
113 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
116 // XXX: I fucking hate Apple so very very bad
117 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
120 - (void) forwardInvocation:(NSInvocation *)inv {
121 SEL sel = [inv selector];
122 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
123 [inv invokeWithTarget:delegate_];
129 @implementation CyteWebViewController
132 #include "CyteKit/UCInternal.h"
135 + (void) _initialize {
136 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
140 js = dlopen("/System/Library/Frameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
142 js = dlopen("/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
144 $JSObjectCallAsFunction = reinterpret_cast<JSValueRef (*)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(js, "JSObjectCallAsFunction"));
146 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
147 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
149 if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
150 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
151 else // XXX: this actually might be fast on some older systems: we should look into this
152 CYScrollViewDecelerationRateNormal = 0.998;
155 - (bool) retainsNetworkActivityIndicator {
159 - (void) releaseNetworkActivityIndicator {
160 if ([loading_ count] != 0) {
161 [loading_ removeAllObjects];
163 if ([self retainsNetworkActivityIndicator])
164 [delegate_ releaseNetworkActivityIndicator];
170 NSLog(@"[CyteWebViewController dealloc]");
173 [self releaseNetworkActivityIndicator];
178 - (NSString *) description {
179 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[request_ URL] absoluteString]];
182 - (CyteWebView *) webView {
183 return (CyteWebView *) [self view];
186 - (NSURL *) URLWithURL:(NSURL *)url {
190 - (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy referrer:(NSString *)referrer {
191 NSMutableURLRequest *request([NSMutableURLRequest
192 requestWithURL:[self URLWithURL:url]
194 timeoutInterval:DefaultTimeout_
197 [request setValue:referrer forHTTPHeaderField:@"Referer"];
202 - (void) setRequest:(NSURLRequest *)request {
203 _assert(request_ == nil);
207 - (void) setURL:(NSURL *)url {
208 [self setURL:url withReferrer:nil];
211 - (void) setURL:(NSURL *)url withReferrer:(NSString *)referrer {
212 [self setRequest:[self requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy referrer:referrer]];
215 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
216 [self loadRequest:[self requestWithURL:url cachePolicy:policy referrer:nil]];
219 - (void) loadURL:(NSURL *)url {
220 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
223 - (void) loadRequest:(NSURLRequest *)request {
225 NSLog(@"loadRequest:%@", request);
231 WebThreadLocked lock;
232 [[self webView] loadRequest:request];
235 - (void) reloadURLWithCache:(BOOL)cache {
239 NSMutableURLRequest *request([request_ mutableCopy]);
240 [request setCachePolicy:(cache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData)];
244 if (cache || [request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
245 [self loadRequest:request_];
247 UIAlertView *alert = [[[UIAlertView alloc]
248 initWithTitle:UCLocalize("RESUBMIT_FORM")
251 cancelButtonTitle:UCLocalize("CANCEL")
253 UCLocalize("SUBMIT"),
257 [alert setContext:@"submit"];
262 - (void) reloadData {
266 [self dispatchEvent:@"CydiaReloadData"];
268 [self reloadURLWithCache:YES];
271 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
274 function_ = function;
276 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
279 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
282 function_ = function;
284 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
287 - (void) removeButton {
288 custom_ = [NSNull null];
289 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
292 - (void) scrollToBottomAnimated:(NSNumber *)animated {
293 CGSize size([scroller_ contentSize]);
294 CGPoint offset([scroller_ contentOffset]);
295 CGRect frame([scroller_ frame]);
297 if (size.height - offset.y < frame.size.height + 20.f) {
298 CGRect rect = {{0, size.height-1}, {size.width, 1}};
299 [scroller_ scrollRectToVisible:rect animated:[animated boolValue]];
303 - (void) _setViewportWidth {
304 [[[self webView] _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
307 - (void) setViewportWidth:(float)width {
308 width_ = width != 0 ? width : [[self class] defaultWidth];
309 [self _setViewportWidth];
312 - (void) _setViewportWidthOnMainThread:(NSNumber *)width {
313 [self setViewportWidth:[width floatValue]];
316 - (void) setViewportWidthOnMainThread:(float)width {
317 [self performSelectorOnMainThread:@selector(_setViewportWidthOnMainThread:) withObject:[NSNumber numberWithFloat:width] waitUntilDone:NO];
320 - (void) webViewUpdateViewSettings:(UIWebView *)view {
321 [self _setViewportWidth];
324 - (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
325 [self dismissModalViewControllerAnimated:YES];
328 - (void) _setupMail:(MFMailComposeViewController *)controller {
331 - (void) _openMailToURL:(NSURL *)url {
332 if ($MFMailComposeViewController != nil && [$MFMailComposeViewController canSendMail]) {
333 MFMailComposeViewController *controller([[[$MFMailComposeViewController alloc] init] autorelease]);
334 [controller setMailComposeDelegate:self];
336 [controller setMailToURL:url];
338 [self _setupMail:controller];
340 [self presentModalViewController:controller animated:YES];
344 UIApplication *app([UIApplication sharedApplication]);
345 if ([app respondsToSelector:@selector(openURL:asPanel:)])
346 [app openURL:url asPanel:YES];
351 - (bool) _allowJavaScriptPanel {
355 - (bool) allowsNavigationAction {
356 return allowsNavigationAction_;
359 - (void) setAllowsNavigationAction:(bool)value {
360 allowsNavigationAction_ = value;
363 - (void) setAllowsNavigationActionByNumber:(NSNumber *)value {
364 [self setAllowsNavigationAction:[value boolValue]];
367 - (void) popViewControllerWithNumber:(NSNumber *)value {
368 UINavigationController *navigation([self navigationController]);
369 if ([navigation topViewController] == self)
370 [navigation popViewControllerAnimated:[value boolValue]];
373 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
374 NSValue *object([NSValue valueWithNonretainedObject:frame]);
375 if (![loading_ containsObject:object])
377 [loading_ removeObject:object];
379 [self _didFinishLoading];
381 if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == NSURLErrorCancelled)
384 if ([[error domain] isEqualToString:WebKitErrorDomain] && [error code] == WebKitErrorFrameLoadInterruptedByPolicyChange) {
389 if ([frame parentFrame] == nil) {
390 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
391 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
392 [[error localizedDescription] stringByAddingPercentEscapes]
399 - (void) pushRequest:(NSURLRequest *)request forAction:(NSDictionary *)action asPop:(bool)pop {
400 WebFrame *frame(nil);
401 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
402 frame = [WebActionElement objectForKey:@"WebElementFrame"];
404 frame = [[[[self webView] _documentView] webView] mainFrame];
406 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
407 NSString *referrer([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString]);
409 NSURL *url([request URL]);
411 // XXX: filter to internal usage?
412 CyteViewController *page([delegate_ pageForURL:url forExternal:NO withReferrer:referrer]);
415 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
416 [browser setRequest:request];
420 [page setDelegate:delegate_];
421 [page setPageColor:color_];
424 [[self navigationItem] setTitle:title_];
426 [[self navigationController] pushViewController:page animated:YES];
428 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
430 [navigation setDelegate:delegate_];
432 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
433 initWithTitle:UCLocalize("CLOSE")
434 style:UIBarButtonItemStylePlain
436 action:@selector(close)
439 [[self navigationController] presentModalViewController:navigation animated:YES];
443 // CyteWebViewDelegate {{{
444 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
446 static Pcre irritating("^(?"
447 ":" "The page at .* displayed insecure content from .*\\."
448 "|" "Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\."
451 if (NSString *data = [message objectForKey:@"message"])
452 if (irritating(data))
455 NSLog(@"addMessageToConsole:%@", message);
459 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
461 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ %@ frame:%@", action, request, [request allHTTPHeaderFields], frame);
464 if ([frame parentFrame] == nil) {
466 NSURL *url(request == nil ? nil : [request URL]);
468 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
470 [self pushRequest:request forAction:action asPop:NO];
477 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
479 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
482 if ([frame parentFrame] == nil) {
484 case CYWebPolicyDecisionIgnore:
485 if ([[request_ URL] isEqual:[request URL]])
489 case CYWebPolicyDecisionUse:
500 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
502 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
505 NSURL *url([request URL]);
509 if ([name isEqualToString:@"_open"])
510 [delegate_ openURL:url];
512 NSString *scheme([[url scheme] lowercaseString]);
513 if ([scheme isEqualToString:@"mailto"])
514 [self _openMailToURL:url];
516 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
522 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
524 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
528 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
530 NSLog(@"didCommitLoadForFrame:%@", frame);
533 if ([frame parentFrame] == nil) {
538 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
540 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
543 [self _didFailWithError:error forFrame:frame];
546 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
548 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
551 [self _didFailWithError:error forFrame:frame];
554 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
555 NSValue *object([NSValue valueWithNonretainedObject:frame]);
556 if (![loading_ containsObject:object])
558 [loading_ removeObject:object];
560 if ([frame parentFrame] == nil) {
561 if (DOMDocument *document = [frame DOMDocument])
562 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
563 for (DOMHTMLBodyElement *body in (id) bodies) {
564 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
568 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
569 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
570 DOMRGBColor *rgb([color getRGBColorValue]);
572 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
573 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
574 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
575 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
579 colorWithRed:(red / 255)
587 [super setPageColor:uic];
588 [scroller_ setBackgroundColor:color_];
593 [self _didFinishLoading];
596 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
597 if ([frame parentFrame] != nil)
602 [[self navigationItem] setTitle:title_];
605 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
607 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
610 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
612 if ([frame parentFrame] == nil) {
618 [registered_ removeAllObjects];
621 allowsNavigationAction_ = true;
623 [self setHidesNavigationBar:NO];
624 [self setScrollAlwaysBounceVertical:true];
625 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
627 // XXX: do we still need to do this?
628 [[self navigationItem] setTitle:nil];
631 [self _didStartLoading];
634 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
635 challenge_ = [challenge retain];
637 NSURLProtectionSpace *space([challenge protectionSpace]);
638 NSString *realm([space realm]);
642 UIAlertView *alert = [[[UIAlertView alloc]
646 cancelButtonTitle:UCLocalize("CANCEL")
647 otherButtonTitles:UCLocalize("LOGIN"), nil
650 [alert setContext:@"challenge"];
651 [alert setNumberOfRows:1];
653 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
654 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
656 UITextField *username([alert textFieldAtIndex:0]); {
657 UITextInputTraits *traits([username textInputTraits]);
658 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
659 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
660 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
661 [traits setReturnKeyType:UIReturnKeyNext];
664 UITextField *password([alert textFieldAtIndex:1]); {
665 UITextInputTraits *traits([password textInputTraits]);
666 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
667 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
668 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
669 // XXX: UIReturnKeyDone
670 [traits setReturnKeyType:UIReturnKeyNext];
671 [traits setSecureTextEntry:YES];
677 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
679 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
685 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
686 return [self _allowJavaScriptPanel];
689 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
690 return [self _allowJavaScriptPanel];
693 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
694 return [self _allowJavaScriptPanel];
697 - (void) webViewClose:(WebView *)view {
703 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
706 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
707 NSString *context([alert context]);
709 if ([context isEqualToString:@"sensitive"]) {
712 sensitive_ = [NSNumber numberWithBool:YES];
716 sensitive_ = [NSNumber numberWithBool:NO];
720 [alert dismissWithClickedButtonIndex:-1 animated:YES];
721 } else if ([context isEqualToString:@"challenge"]) {
722 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
724 if (button == [alert cancelButtonIndex])
725 [sender cancelAuthenticationChallenge:challenge_];
726 else if (button == [alert firstOtherButtonIndex]) {
727 NSString *username([[alert textFieldAtIndex:0] text]);
728 NSString *password([[alert textFieldAtIndex:1] text]);
730 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
732 [sender useCredential:credential forAuthenticationChallenge:challenge_];
737 [alert dismissWithClickedButtonIndex:-1 animated:YES];
738 } else if ([context isEqualToString:@"submit"]) {
739 if (button == [alert cancelButtonIndex]) {
740 } else if (button == [alert firstOtherButtonIndex]) {
741 if (request_ != nil) {
742 WebThreadLocked lock;
743 [[self webView] loadRequest:request_];
747 [alert dismissWithClickedButtonIndex:-1 animated:YES];
751 - (UIBarButtonItemStyle) rightButtonStyle {
752 if (style_ == nil) normal:
753 return UIBarButtonItemStylePlain;
754 else if ([style_ isEqualToString:@"Normal"])
755 return UIBarButtonItemStylePlain;
756 else if ([style_ isEqualToString:@"Highlighted"])
757 return UIBarButtonItemStyleDone;
761 - (UIBarButtonItem *) customButton {
764 else if ((/*clang:*/id) custom_ == [NSNull null])
765 return (UIBarButtonItem *) [NSNull null];
767 return [[[UIBarButtonItem alloc]
768 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
769 style:[self rightButtonStyle]
771 action:@selector(customButtonClicked)
775 - (UIBarButtonItem *) leftButton {
776 UINavigationItem *item([self navigationItem]);
777 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
780 if (UINavigationController *navigation = [self navigationController])
781 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
782 return [[[UIBarButtonItem alloc]
783 initWithTitle:UCLocalize("CLOSE")
784 style:UIBarButtonItemStylePlain
786 action:@selector(close)
792 - (void) applyLeftButton {
793 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
796 - (UIBarButtonItem *) rightButton {
800 - (void) applyLoadingTitle {
801 [[self navigationItem] setTitle:UCLocalize("LOADING")];
804 - (void) layoutRightButton {
805 [[loadingitem_ view] addSubview:indicator_];
806 [[loadingitem_ view] bringSubviewToFront:indicator_];
809 - (void) applyRightButton {
810 if ([self isLoading]) {
811 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
812 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
814 [indicator_ startAnimating];
815 [self applyLoadingTitle];
817 [indicator_ stopAnimating];
819 UIBarButtonItem *button([self customButton]);
821 button = [self rightButton];
822 else if (button == (UIBarButtonItem *) [NSNull null])
825 [[self navigationItem] setRightBarButtonItem:button animated:YES];
829 - (void) didStartLoading {
830 // Overridden in subclasses.
833 - (void) _didStartLoading {
834 [self applyRightButton];
836 if ([loading_ count] != 1)
839 if ([self retainsNetworkActivityIndicator])
840 [delegate_ retainNetworkActivityIndicator];
842 [self didStartLoading];
845 - (void) didFinishLoading {
846 // Overridden in subclasses.
849 - (void) _didFinishLoading {
850 if ([loading_ count] != 0)
853 [self applyRightButton];
854 [[self navigationItem] setTitle:title_];
856 if ([self retainsNetworkActivityIndicator])
857 [delegate_ releaseNetworkActivityIndicator];
859 [self didFinishLoading];
863 return [loading_ count] != 0;
866 - (id) initWithWidth:(float)width ofClass:(Class)_class {
867 if ((self = [super init]) != nil) {
871 [super setPageColor:nil];
873 allowsNavigationAction_ = true;
875 loading_ = [NSMutableSet setWithCapacity:5];
876 registered_ = [NSMutableSet setWithCapacity:5];
877 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
879 reloaditem_ = [[[UIBarButtonItem alloc]
880 initWithTitle:UCLocalize("RELOAD")
881 style:[self rightButtonStyle]
883 action:@selector(reloadButtonClicked)
886 loadingitem_ = [[[UIBarButtonItem alloc]
887 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
888 style:UIBarButtonItemStylePlain
890 action:@selector(reloadButtonClicked)
893 UIActivityIndicatorViewStyle style;
895 if (kCFCoreFoundationVersionNumber >= 800) {
896 style = UIActivityIndicatorViewStyleGray;
899 style = UIActivityIndicatorViewStyleWhite;
903 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
904 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
905 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
907 [self applyLeftButton];
908 [self applyRightButton];
912 - (NSString *) applicationNameForUserAgent {
917 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
919 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
920 [webview_ setDelegate:self];
921 [self setView:webview_];
923 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
924 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
926 [webview_ setDetectsPhoneNumbers:NO];
928 [webview_ setScalesPageToFit:YES];
930 UIWebDocumentView *document([webview_ _documentView]);
932 // XXX: I think this improves scrolling; the hardcoded-ness sucks
933 [document setTileSize:CGSizeMake(320, 500)];
935 WebView *webview([document webView]);
936 WebPreferences *preferences([webview preferences]);
938 // XXX: I have no clue if I actually /want/ this modification
939 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
940 [webview _setLayoutInterval:0];
941 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
942 [preferences _setLayoutInterval:0];
944 [preferences setCacheModel:WebCacheModelDocumentBrowser];
945 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
947 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
948 [preferences setOfflineWebApplicationCacheEnabled:YES];
950 if (NSString *agent = [self applicationNameForUserAgent])
951 [webview setApplicationNameForUserAgent:agent];
953 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
954 [webview setShouldUpdateWhileOffscreen:NO];
957 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
958 [document setAllowsMessaging:YES];
959 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
960 [webview _setAllowsMessaging:YES];
963 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
964 scroller_ = [webview_ _scrollView];
966 [scroller_ setDirectionalLockEnabled:YES];
967 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
968 [scroller_ setDelaysContentTouches:NO];
970 [scroller_ setCanCancelContentTouches:YES];
971 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
972 UIScroller *scroller([webview_ _scroller]);
973 scroller_ = (UIScrollView *) scroller;
975 [scroller setDirectionalScrolling:YES];
976 // XXX: we might be better off /not/ setting this on older systems
977 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
978 [scroller setScrollHysteresis:0]; /* 8 */
980 [scroller setThumbDetectionEnabled:NO];
982 // use NO with UIApplicationUseLegacyEvents(YES)
983 [scroller setEventMode:YES];
985 // XXX: this is handled by setBounces, right?
986 //[scroller setAllowsRubberBanding:YES];
989 [webview_ setOpaque:NO];
990 [webview_ setBackgroundColor:nil];
992 [scroller_ setFixedBackgroundPattern:YES];
993 [scroller_ setBackgroundColor:color_];
994 [scroller_ setClipsSubviews:YES];
996 [scroller_ setBounces:YES];
997 [scroller_ setScrollingEnabled:YES];
998 [scroller_ setShowBackgroundShadow:NO];
1000 [self setViewportWidth:width_];
1002 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1003 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1004 [table setScrollsToTop:NO];
1005 [webview_ insertSubview:table atIndex:0];
1006 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1009 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1014 - (void) releaseSubviews {
1018 [self releaseNetworkActivityIndicator];
1020 [super releaseSubviews];
1023 - (id) initWithWidth:(float)width {
1024 return [self initWithWidth:width ofClass:[self class]];
1028 return [self initWithWidth:0];
1031 - (id) initWithURL:(NSURL *)url {
1032 if ((self = [self init]) != nil) {
1037 - (id) initWithRequest:(NSURLRequest *)request {
1038 if ((self = [self init]) != nil) {
1039 [self setRequest:request];
1043 - (void) callFunction:(WebScriptObject *)function {
1044 WebThreadLocked lock;
1046 WebView *webview([[[self webView] _documentView] webView]);
1047 WebFrame *frame([webview mainFrame]);
1049 JSGlobalContextRef context([frame globalContext]);
1050 JSObjectRef object([function JSObject]);
1051 if ($JSObjectCallAsFunction != NULL)
1052 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1055 - (void) reloadButtonClicked {
1056 [self reloadURLWithCache:NO];
1059 - (void) _customButtonClicked {
1060 [self reloadButtonClicked];
1063 - (void) customButtonClicked {
1065 if (function_ != nil)
1066 [self callFunction:function_];
1069 [self _customButtonClicked];
1072 + (float) defaultWidth {
1076 - (void) setNavigationBarStyle:(NSString *)name {
1078 if ([name isEqualToString:@"Black"])
1079 style = UIBarStyleBlack;
1081 style = UIBarStyleDefault;
1083 [[[self navigationController] navigationBar] setBarStyle:style];
1086 - (void) setNavigationBarTintColor:(UIColor *)color {
1087 [[[self navigationController] navigationBar] setTintColor:color];
1090 - (void) setBadgeValue:(id)value {
1091 [[[self navigationController] tabBarItem] setBadgeValue:value];
1094 - (void) setHidesBackButton:(bool)value {
1095 [[self navigationItem] setHidesBackButton:value];
1096 [self applyLeftButton];
1099 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1100 [self setHidesBackButton:[value boolValue]];
1103 - (void) dispatchEvent:(NSString *)event {
1104 [[self webView] dispatchEvent:event];
1107 - (bool) hidesNavigationBar {
1108 return hidesNavigationBar_;
1111 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1113 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1116 - (void) setHidesNavigationBar:(bool)value {
1117 if (hidesNavigationBar_ != value) {
1118 hidesNavigationBar_ = value;
1119 [self _setHidesNavigationBar:YES animated:YES];
1123 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1124 [self setHidesNavigationBar:[value boolValue]];
1127 - (void) setScrollAlwaysBounceVertical:(bool)value {
1128 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1129 UIScrollView *scroller([webview_ _scrollView]);
1130 [scroller setAlwaysBounceVertical:value];
1131 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1132 //UIScroller *scroller([webview_ _scroller]);
1133 // XXX: I am sad here.
1137 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1138 [self setScrollAlwaysBounceVertical:[value boolValue]];
1141 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1142 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1143 UIScrollView *scroller([webview_ _scrollView]);
1144 [scroller setIndicatorStyle:style];
1145 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1146 UIScroller *scroller([webview_ _scroller]);
1147 [scroller setScrollerIndicatorStyle:style];
1151 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1152 UIScrollViewIndicatorStyle value;
1155 else if ([style isEqualToString:@"default"])
1156 value = UIScrollViewIndicatorStyleDefault;
1157 else if ([style isEqualToString:@"black"])
1158 value = UIScrollViewIndicatorStyleBlack;
1159 else if ([style isEqualToString:@"white"])
1160 value = UIScrollViewIndicatorStyleWhite;
1163 [self setScrollIndicatorStyle:value];
1166 - (void) viewWillAppear:(BOOL)animated {
1169 if ([self hidesNavigationBar])
1170 [self _setHidesNavigationBar:YES animated:animated];
1172 // XXX: why isn't this evern called automatically?
1173 [[self webView] setNeedsLayout];
1175 [self dispatchEvent:@"CydiaViewWillAppear"];
1176 [super viewWillAppear:animated];
1179 - (void) viewDidAppear:(BOOL)animated {
1180 [super viewDidAppear:animated];
1181 [self dispatchEvent:@"CydiaViewDidAppear"];
1184 - (void) viewWillDisappear:(BOOL)animated {
1185 [self dispatchEvent:@"CydiaViewWillDisappear"];
1186 [super viewWillDisappear:animated];
1188 if ([self hidesNavigationBar])
1189 [self _setHidesNavigationBar:NO animated:animated];
1194 - (void) viewDidDisappear:(BOOL)animated {
1195 [super viewDidDisappear:animated];
1196 [self dispatchEvent:@"CydiaViewDidDisappear"];
1199 - (void) updateHeights:(NSTimer *)timer {
1200 for (WebFrame *frame in (id) registered_)
1201 [frame cydia$updateHeight];
1204 - (void) registerFrame:(WebFrame *)frame {
1205 [registered_ addObject:frame];
1208 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];