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 // XXX: centralize these special class things to some file or mechanism?
42 static Class $MFMailComposeViewController;
44 float CYScrollViewDecelerationRateNormal;
46 @interface WebView (Apple)
47 - (void) _setLayoutInterval:(float)interval;
48 - (void) _setAllowsMessaging:(BOOL)allows;
51 @interface WebFrame (Cydia)
52 - (void) cydia$updateHeight;
55 @implementation WebFrame (Cydia)
57 - (NSString *) description {
58 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[[([self provisionalDataSource] ?: [self dataSource]) request] URL] absoluteString]];
61 - (void) cydia$updateHeight {
62 [[[self frameElement] style]
64 value:[NSString stringWithFormat:@"%dpx",
65 [[[self DOMDocument] body] scrollHeight]]
71 /* Indirect Delegate {{{ */
72 @implementation IndirectDelegate
78 - (void) setDelegate:(id)delegate {
82 - (id) initWithDelegate:(id)delegate {
87 - (IMP) methodForSelector:(SEL)sel {
88 if (IMP method = [super methodForSelector:sel])
90 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
94 - (BOOL) respondsToSelector:(SEL)sel {
95 if ([super respondsToSelector:sel])
98 // XXX: WebThreadCreateNSInvocation returns nil
101 fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
104 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
107 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
108 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
112 fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
115 if (delegate_ != nil)
116 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
119 // XXX: I fucking hate Apple so very very bad
120 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
123 - (void) forwardInvocation:(NSInvocation *)inv {
124 SEL sel = [inv selector];
125 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
126 [inv invokeWithTarget:delegate_];
132 @implementation CyteWebViewController
135 #include "CyteKit/UCInternal.h"
138 + (void) _initialize {
139 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
141 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
142 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
144 if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
145 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
146 else // XXX: this actually might be fast on some older systems: we should look into this
147 CYScrollViewDecelerationRateNormal = 0.998;
150 - (bool) retainsNetworkActivityIndicator {
154 - (void) releaseNetworkActivityIndicator {
155 if ([loading_ count] != 0) {
156 [loading_ removeAllObjects];
158 if ([self retainsNetworkActivityIndicator])
159 [delegate_ releaseNetworkActivityIndicator];
165 NSLog(@"[CyteWebViewController dealloc]");
168 [self releaseNetworkActivityIndicator];
173 - (NSString *) description {
174 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[request_ URL] absoluteString]];
177 - (CyteWebView *) webView {
178 return (CyteWebView *) [self view];
181 - (NSURL *) URLWithURL:(NSURL *)url {
185 - (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy referrer:(NSString *)referrer {
186 NSMutableURLRequest *request([NSMutableURLRequest
187 requestWithURL:[self URLWithURL:url]
189 timeoutInterval:DefaultTimeout_
192 [request setValue:referrer forHTTPHeaderField:@"Referer"];
197 - (void) setRequest:(NSURLRequest *)request {
198 _assert(request_ == nil);
202 - (void) setURL:(NSURL *)url {
203 [self setURL:url withReferrer:nil];
206 - (void) setURL:(NSURL *)url withReferrer:(NSString *)referrer {
207 [self setRequest:[self requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy referrer:referrer]];
210 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
211 [self loadRequest:[self requestWithURL:url cachePolicy:policy referrer:nil]];
214 - (void) loadURL:(NSURL *)url {
215 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
218 - (void) loadRequest:(NSURLRequest *)request {
220 NSLog(@"loadRequest:%@", request);
226 WebThreadLocked lock;
227 [[self webView] loadRequest:request];
230 - (void) reloadURLWithCache:(BOOL)cache {
234 NSMutableURLRequest *request([request_ mutableCopy]);
235 [request setCachePolicy:(cache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData)];
239 if (cache || [request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
240 [self loadRequest:request_];
242 UIAlertView *alert = [[[UIAlertView alloc]
243 initWithTitle:UCLocalize("RESUBMIT_FORM")
246 cancelButtonTitle:UCLocalize("CANCEL")
248 UCLocalize("SUBMIT"),
252 [alert setContext:@"submit"];
257 - (void) reloadData {
261 [self dispatchEvent:@"CydiaReloadData"];
263 [self reloadURLWithCache:YES];
266 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
269 function_ = function;
271 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
274 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
277 function_ = function;
279 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
282 - (void) removeButton {
283 custom_ = [NSNull null];
284 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
287 - (void) scrollToBottomAnimated:(NSNumber *)animated {
288 CGSize size([scroller_ contentSize]);
289 CGPoint offset([scroller_ contentOffset]);
290 CGRect frame([scroller_ frame]);
292 if (size.height - offset.y < frame.size.height + 20.f) {
293 CGRect rect = {{0, size.height-1}, {size.width, 1}};
294 [scroller_ scrollRectToVisible:rect animated:[animated boolValue]];
298 - (void) _setViewportWidth {
299 [[[self webView] _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
302 - (void) setViewportWidth:(float)width {
303 width_ = width != 0 ? width : [[self class] defaultWidth];
304 [self _setViewportWidth];
307 - (void) _setViewportWidthOnMainThread:(NSNumber *)width {
308 [self setViewportWidth:[width floatValue]];
311 - (void) setViewportWidthOnMainThread:(float)width {
312 [self performSelectorOnMainThread:@selector(_setViewportWidthOnMainThread:) withObject:[NSNumber numberWithFloat:width] waitUntilDone:NO];
315 - (void) webViewUpdateViewSettings:(UIWebView *)view {
316 [self _setViewportWidth];
319 - (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
320 [self dismissModalViewControllerAnimated:YES];
323 - (void) _setupMail:(MFMailComposeViewController *)controller {
326 - (void) _openMailToURL:(NSURL *)url {
327 if ($MFMailComposeViewController != nil && [$MFMailComposeViewController canSendMail]) {
328 MFMailComposeViewController *controller([[[$MFMailComposeViewController alloc] init] autorelease]);
329 [controller setMailComposeDelegate:self];
331 [controller setMailToURL:url];
333 [self _setupMail:controller];
335 [self presentModalViewController:controller animated:YES];
339 UIApplication *app([UIApplication sharedApplication]);
340 if ([app respondsToSelector:@selector(openURL:asPanel:)])
341 [app openURL:url asPanel:YES];
346 - (bool) _allowJavaScriptPanel {
350 - (bool) allowsNavigationAction {
351 return allowsNavigationAction_;
354 - (void) setAllowsNavigationAction:(bool)value {
355 allowsNavigationAction_ = value;
358 - (void) setAllowsNavigationActionByNumber:(NSNumber *)value {
359 [self setAllowsNavigationAction:[value boolValue]];
362 - (void) popViewControllerWithNumber:(NSNumber *)value {
363 UINavigationController *navigation([self navigationController]);
364 if ([navigation topViewController] == self)
365 [navigation popViewControllerAnimated:[value boolValue]];
368 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
369 NSValue *object([NSValue valueWithNonretainedObject:frame]);
370 if (![loading_ containsObject:object])
372 [loading_ removeObject:object];
374 [self _didFinishLoading];
376 if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == NSURLErrorCancelled)
379 if ([[error domain] isEqualToString:WebKitErrorDomain] && [error code] == WebKitErrorFrameLoadInterruptedByPolicyChange) {
384 if ([frame parentFrame] == nil) {
385 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
386 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
387 [[error localizedDescription] stringByAddingPercentEscapes]
394 - (void) pushRequest:(NSURLRequest *)request forAction:(NSDictionary *)action asPop:(bool)pop {
395 WebFrame *frame(nil);
396 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
397 frame = [WebActionElement objectForKey:@"WebElementFrame"];
399 frame = [[[[self webView] _documentView] webView] mainFrame];
401 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
402 NSString *referrer([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString]);
404 NSURL *url([request URL]);
406 // XXX: filter to internal usage?
407 CyteViewController *page([delegate_ pageForURL:url forExternal:NO withReferrer:referrer]);
410 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
411 [browser setRequest:request];
415 [page setDelegate:delegate_];
418 [[self navigationItem] setTitle:title_];
420 [[self navigationController] pushViewController:page animated:YES];
422 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
424 [navigation setDelegate:delegate_];
426 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
427 initWithTitle:UCLocalize("CLOSE")
428 style:UIBarButtonItemStylePlain
430 action:@selector(close)
433 [[self navigationController] presentModalViewController:navigation animated:YES];
437 // CyteWebViewDelegate {{{
438 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
440 static Pcre irritating("^(?"
441 ":" "The page at .* displayed insecure content from .*\\."
442 "|" "Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\."
445 if (NSString *data = [message objectForKey:@"message"])
446 if (irritating(data))
449 NSLog(@"addMessageToConsole:%@", message);
453 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
455 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ %@ frame:%@", action, request, [request allHTTPHeaderFields], frame);
458 if ([frame parentFrame] == nil) {
460 NSURL *url(request == nil ? nil : [request URL]);
462 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
464 [self pushRequest:request forAction:action asPop:NO];
471 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
473 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
476 if ([frame parentFrame] == nil) {
478 case CYWebPolicyDecisionIgnore:
479 if ([[request_ URL] isEqual:[request URL]])
483 case CYWebPolicyDecisionUse:
494 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
496 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
499 NSURL *url([request URL]);
503 if ([name isEqualToString:@"_open"])
504 [delegate_ openURL:url];
506 NSString *scheme([[url scheme] lowercaseString]);
507 if ([scheme isEqualToString:@"mailto"])
508 [self _openMailToURL:url];
510 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
516 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
518 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
522 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
524 NSLog(@"didCommitLoadForFrame:%@", frame);
527 if ([frame parentFrame] == nil) {
532 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
534 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
537 [self _didFailWithError:error forFrame:frame];
540 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
542 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
545 [self _didFailWithError:error forFrame:frame];
548 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
549 NSValue *object([NSValue valueWithNonretainedObject:frame]);
550 if (![loading_ containsObject:object])
552 [loading_ removeObject:object];
554 if ([frame parentFrame] == nil) {
555 if (DOMDocument *document = [frame DOMDocument])
556 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
557 for (DOMHTMLBodyElement *body in (id) bodies) {
558 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
562 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
563 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
564 DOMRGBColor *rgb([color getRGBColorValue]);
566 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
567 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
568 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
569 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
571 if (red == 0xc7 && green == 0xce && blue == 0xd5)
572 uic = [UIColor pinStripeColor];
575 colorWithRed:(red / 255)
583 [scroller_ setBackgroundColor:(uic ?: [UIColor clearColor])];
588 [self _didFinishLoading];
591 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
592 if ([frame parentFrame] != nil)
597 [[self navigationItem] setTitle:title_];
600 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
602 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
605 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
607 if ([frame parentFrame] == nil) {
613 [registered_ removeAllObjects];
616 allowsNavigationAction_ = true;
618 [self setHidesNavigationBar:NO];
619 [self setScrollAlwaysBounceVertical:true];
620 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
622 // XXX: do we still need to do this?
623 [[self navigationItem] setTitle:nil];
626 [self _didStartLoading];
629 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
631 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
637 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
638 return [self _allowJavaScriptPanel];
641 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
642 return [self _allowJavaScriptPanel];
645 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
646 return [self _allowJavaScriptPanel];
649 - (void) webViewClose:(WebView *)view {
655 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
658 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
659 NSString *context([alert context]);
661 if ([context isEqualToString:@"sensitive"]) {
664 sensitive_ = [NSNumber numberWithBool:YES];
668 sensitive_ = [NSNumber numberWithBool:NO];
672 [alert dismissWithClickedButtonIndex:-1 animated:YES];
673 } else if ([context isEqualToString:@"challenge"]) {
674 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
678 NSString *username([[alert textFieldAtIndex:0] text]);
679 NSString *password([[alert textFieldAtIndex:1] text]);
681 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
683 [sender useCredential:credential forAuthenticationChallenge:challenge_];
687 [sender cancelAuthenticationChallenge:challenge_];
695 [alert dismissWithClickedButtonIndex:-1 animated:YES];
696 } else if ([context isEqualToString:@"submit"]) {
697 if (button == [alert cancelButtonIndex]) {
698 } else if (button == [alert firstOtherButtonIndex]) {
699 if (request_ != nil) {
700 WebThreadLocked lock;
701 [[self webView] loadRequest:request_];
705 [alert dismissWithClickedButtonIndex:-1 animated:YES];
709 - (UIBarButtonItemStyle) rightButtonStyle {
710 if (style_ == nil) normal:
711 return UIBarButtonItemStylePlain;
712 else if ([style_ isEqualToString:@"Normal"])
713 return UIBarButtonItemStylePlain;
714 else if ([style_ isEqualToString:@"Highlighted"])
715 return UIBarButtonItemStyleDone;
719 - (UIBarButtonItem *) customButton {
722 else if ((/*clang:*/id) custom_ == [NSNull null])
723 return (UIBarButtonItem *) [NSNull null];
725 return [[[UIBarButtonItem alloc]
726 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
727 style:[self rightButtonStyle]
729 action:@selector(customButtonClicked)
733 - (UIBarButtonItem *) leftButton {
734 UINavigationItem *item([self navigationItem]);
735 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
738 if (UINavigationController *navigation = [self navigationController])
739 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
740 return [[[UIBarButtonItem alloc]
741 initWithTitle:UCLocalize("CLOSE")
742 style:UIBarButtonItemStylePlain
744 action:@selector(close)
750 - (void) applyLeftButton {
751 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
754 - (UIBarButtonItem *) rightButton {
758 - (void) applyLoadingTitle {
759 [[self navigationItem] setTitle:UCLocalize("LOADING")];
762 - (void) layoutRightButton {
763 [[loadingitem_ view] addSubview:indicator_];
764 [[loadingitem_ view] bringSubviewToFront:indicator_];
767 - (void) applyRightButton {
768 if ([self isLoading]) {
769 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
770 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
772 [indicator_ startAnimating];
773 [self applyLoadingTitle];
775 [indicator_ stopAnimating];
777 UIBarButtonItem *button([self customButton]);
779 button = [self rightButton];
780 else if (button == (UIBarButtonItem *) [NSNull null])
783 [[self navigationItem] setRightBarButtonItem:button animated:YES];
787 - (void) didStartLoading {
788 // Overridden in subclasses.
791 - (void) _didStartLoading {
792 [self applyRightButton];
794 if ([loading_ count] != 1)
797 if ([self retainsNetworkActivityIndicator])
798 [delegate_ retainNetworkActivityIndicator];
800 [self didStartLoading];
803 - (void) didFinishLoading {
804 // Overridden in subclasses.
807 - (void) _didFinishLoading {
808 if ([loading_ count] != 0)
811 [self applyRightButton];
812 [[self navigationItem] setTitle:title_];
814 if ([self retainsNetworkActivityIndicator])
815 [delegate_ releaseNetworkActivityIndicator];
817 [self didFinishLoading];
821 return [loading_ count] != 0;
824 - (id) initWithWidth:(float)width ofClass:(Class)_class {
825 if ((self = [super init]) != nil) {
829 allowsNavigationAction_ = true;
831 loading_ = [NSMutableSet setWithCapacity:5];
832 registered_ = [NSMutableSet setWithCapacity:5];
833 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
835 reloaditem_ = [[[UIBarButtonItem alloc]
836 initWithTitle:UCLocalize("RELOAD")
837 style:[self rightButtonStyle]
839 action:@selector(reloadButtonClicked)
842 loadingitem_ = [[[UIBarButtonItem alloc]
844 style:UIBarButtonItemStylePlain
846 action:@selector(reloadButtonClicked)
849 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
850 [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
851 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
853 [self applyLeftButton];
854 [self applyRightButton];
858 - (NSString *) applicationNameForUserAgent {
863 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
865 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
866 [webview_ setDelegate:self];
867 [self setView:webview_];
869 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
870 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
872 [webview_ setDetectsPhoneNumbers:NO];
874 [webview_ setScalesPageToFit:YES];
876 UIWebDocumentView *document([webview_ _documentView]);
878 // XXX: I think this improves scrolling; the hardcoded-ness sucks
879 [document setTileSize:CGSizeMake(320, 500)];
881 [document setBackgroundColor:[UIColor clearColor]];
883 // XXX: this is terribly (too?) expensive
884 [document setDrawsBackground:NO];
886 WebView *webview([document webView]);
887 WebPreferences *preferences([webview preferences]);
889 // XXX: I have no clue if I actually /want/ this modification
890 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
891 [webview _setLayoutInterval:0];
892 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
893 [preferences _setLayoutInterval:0];
895 [preferences setCacheModel:WebCacheModelDocumentBrowser];
896 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
898 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
899 [preferences setOfflineWebApplicationCacheEnabled:YES];
901 if (NSString *agent = [self applicationNameForUserAgent])
902 [webview setApplicationNameForUserAgent:agent];
904 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
905 [webview setShouldUpdateWhileOffscreen:NO];
908 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
909 [document setAllowsMessaging:YES];
910 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
911 [webview _setAllowsMessaging:YES];
914 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
915 scroller_ = [webview_ _scrollView];
917 [scroller_ setDirectionalLockEnabled:YES];
918 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
919 [scroller_ setDelaysContentTouches:NO];
921 [scroller_ setCanCancelContentTouches:YES];
922 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
923 UIScroller *scroller([webview_ _scroller]);
924 scroller_ = (UIScrollView *) scroller;
926 [scroller setDirectionalScrolling:YES];
927 // XXX: we might be better off /not/ setting this on older systems
928 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
929 [scroller setScrollHysteresis:0]; /* 8 */
931 [scroller setThumbDetectionEnabled:NO];
933 // use NO with UIApplicationUseLegacyEvents(YES)
934 [scroller setEventMode:YES];
936 // XXX: this is handled by setBounces, right?
937 //[scroller setAllowsRubberBanding:YES];
940 [scroller_ setFixedBackgroundPattern:YES];
941 [scroller_ setBackgroundColor:[UIColor clearColor]];
942 [scroller_ setClipsSubviews:YES];
944 [scroller_ setBounces:YES];
945 [scroller_ setScrollingEnabled:YES];
946 [scroller_ setShowBackgroundShadow:NO];
948 [self setViewportWidth:width_];
950 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
951 [table setScrollsToTop:NO];
952 [webview_ insertSubview:table atIndex:0];
954 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
955 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
960 - (void) releaseSubviews {
964 [self releaseNetworkActivityIndicator];
966 [super releaseSubviews];
969 - (id) initWithWidth:(float)width {
970 return [self initWithWidth:width ofClass:[self class]];
974 return [self initWithWidth:0];
977 - (id) initWithURL:(NSURL *)url {
978 if ((self = [self init]) != nil) {
983 - (id) initWithRequest:(NSURLRequest *)request {
984 if ((self = [self init]) != nil) {
985 [self setRequest:request];
989 - (void) callFunction:(WebScriptObject *)function {
990 WebThreadLocked lock;
992 WebView *webview([[[self webView] _documentView] webView]);
993 WebFrame *frame([webview mainFrame]);
995 JSGlobalContextRef context([frame globalContext]);
996 JSObjectRef object([function JSObject]);
997 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
1000 - (void) reloadButtonClicked {
1001 [self reloadURLWithCache:NO];
1004 - (void) _customButtonClicked {
1005 [self reloadButtonClicked];
1008 - (void) customButtonClicked {
1010 if (function_ != nil)
1011 [self callFunction:function_];
1014 [self _customButtonClicked];
1017 + (float) defaultWidth {
1021 - (void) setNavigationBarStyle:(NSString *)name {
1023 if ([name isEqualToString:@"Black"])
1024 style = UIBarStyleBlack;
1026 style = UIBarStyleDefault;
1028 [[[self navigationController] navigationBar] setBarStyle:style];
1031 - (void) setNavigationBarTintColor:(UIColor *)color {
1032 [[[self navigationController] navigationBar] setTintColor:color];
1035 - (void) setBadgeValue:(id)value {
1036 [[[self navigationController] tabBarItem] setBadgeValue:value];
1039 - (void) setHidesBackButton:(bool)value {
1040 [[self navigationItem] setHidesBackButton:value];
1041 [self applyLeftButton];
1044 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1045 [self setHidesBackButton:[value boolValue]];
1048 - (void) dispatchEvent:(NSString *)event {
1049 [[self webView] dispatchEvent:event];
1052 - (bool) hidesNavigationBar {
1053 return hidesNavigationBar_;
1056 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1058 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1061 - (void) setHidesNavigationBar:(bool)value {
1062 if (hidesNavigationBar_ != value) {
1063 hidesNavigationBar_ = value;
1064 [self _setHidesNavigationBar:YES animated:YES];
1068 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1069 [self setHidesNavigationBar:[value boolValue]];
1072 - (void) setScrollAlwaysBounceVertical:(bool)value {
1073 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1074 UIScrollView *scroller([webview_ _scrollView]);
1075 [scroller setAlwaysBounceVertical:value];
1076 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1077 //UIScroller *scroller([webview_ _scroller]);
1078 // XXX: I am sad here.
1082 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1083 [self setScrollAlwaysBounceVertical:[value boolValue]];
1086 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1087 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1088 UIScrollView *scroller([webview_ _scrollView]);
1089 [scroller setIndicatorStyle:style];
1090 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1091 UIScroller *scroller([webview_ _scroller]);
1092 [scroller setScrollerIndicatorStyle:style];
1096 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1097 UIScrollViewIndicatorStyle value;
1100 else if ([style isEqualToString:@"default"])
1101 value = UIScrollViewIndicatorStyleDefault;
1102 else if ([style isEqualToString:@"black"])
1103 value = UIScrollViewIndicatorStyleBlack;
1104 else if ([style isEqualToString:@"white"])
1105 value = UIScrollViewIndicatorStyleWhite;
1108 [self setScrollIndicatorStyle:value];
1111 - (void) viewWillAppear:(BOOL)animated {
1114 if ([self hidesNavigationBar])
1115 [self _setHidesNavigationBar:YES animated:animated];
1117 // XXX: why isn't this evern called automatically?
1118 [[self webView] setNeedsLayout];
1120 [self dispatchEvent:@"CydiaViewWillAppear"];
1121 [super viewWillAppear:animated];
1124 - (void) viewDidAppear:(BOOL)animated {
1125 [super viewDidAppear:animated];
1126 [self dispatchEvent:@"CydiaViewDidAppear"];
1129 - (void) viewWillDisappear:(BOOL)animated {
1130 [self dispatchEvent:@"CydiaViewWillDisappear"];
1131 [super viewWillDisappear:animated];
1133 if ([self hidesNavigationBar])
1134 [self _setHidesNavigationBar:NO animated:animated];
1139 - (void) viewDidDisappear:(BOOL)animated {
1140 [super viewDidDisappear:animated];
1141 [self dispatchEvent:@"CydiaViewDidDisappear"];
1144 - (void) updateHeights:(NSTimer *)timer {
1145 for (WebFrame *frame in (id) registered_)
1146 [frame cydia$updateHeight];
1149 - (void) registerFrame:(WebFrame *)frame {
1150 [registered_ addObject:frame];
1153 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];