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 {
519 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
521 NSLog(@"didCommitLoadForFrame:%@", frame);
524 if ([frame parentFrame] == nil) {
529 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
531 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
534 [self _didFailWithError:error forFrame:frame];
537 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
539 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
542 [self _didFailWithError:error forFrame:frame];
545 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
546 NSValue *object([NSValue valueWithNonretainedObject:frame]);
547 if (![loading_ containsObject:object])
549 [loading_ removeObject:object];
551 if ([frame parentFrame] == nil) {
552 if (DOMDocument *document = [frame DOMDocument])
553 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
554 for (DOMHTMLBodyElement *body in (id) bodies) {
555 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
559 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
560 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
561 DOMRGBColor *rgb([color getRGBColorValue]);
563 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
564 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
565 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
566 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
568 if (red == 0xc7 && green == 0xce && blue == 0xd5)
569 uic = [UIColor pinStripeColor];
572 colorWithRed:(red / 255)
580 [scroller_ setBackgroundColor:(uic ?: [UIColor clearColor])];
585 [self _didFinishLoading];
588 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
589 if ([frame parentFrame] != nil)
594 [[self navigationItem] setTitle:title_];
597 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
599 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
602 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
604 if ([frame parentFrame] == nil) {
610 [registered_ removeAllObjects];
613 allowsNavigationAction_ = true;
615 [self setHidesNavigationBar:NO];
616 [self setScrollAlwaysBounceVertical:true];
617 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
619 // XXX: do we still need to do this?
620 [[self navigationItem] setTitle:nil];
623 [self _didStartLoading];
626 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
628 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
634 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
635 return [self _allowJavaScriptPanel];
638 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
639 return [self _allowJavaScriptPanel];
642 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
643 return [self _allowJavaScriptPanel];
646 - (void) webViewClose:(WebView *)view {
652 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
655 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
656 NSString *context([alert context]);
658 if ([context isEqualToString:@"sensitive"]) {
661 sensitive_ = [NSNumber numberWithBool:YES];
665 sensitive_ = [NSNumber numberWithBool:NO];
669 [alert dismissWithClickedButtonIndex:-1 animated:YES];
670 } else if ([context isEqualToString:@"challenge"]) {
671 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
675 NSString *username([[alert textFieldAtIndex:0] text]);
676 NSString *password([[alert textFieldAtIndex:1] text]);
678 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
680 [sender useCredential:credential forAuthenticationChallenge:challenge_];
684 [sender cancelAuthenticationChallenge:challenge_];
692 [alert dismissWithClickedButtonIndex:-1 animated:YES];
693 } else if ([context isEqualToString:@"submit"]) {
694 if (button == [alert cancelButtonIndex]) {
695 } else if (button == [alert firstOtherButtonIndex]) {
696 if (request_ != nil) {
697 WebThreadLocked lock;
698 [[self webView] loadRequest:request_];
702 [alert dismissWithClickedButtonIndex:-1 animated:YES];
706 - (UIBarButtonItemStyle) rightButtonStyle {
707 if (style_ == nil) normal:
708 return UIBarButtonItemStylePlain;
709 else if ([style_ isEqualToString:@"Normal"])
710 return UIBarButtonItemStylePlain;
711 else if ([style_ isEqualToString:@"Highlighted"])
712 return UIBarButtonItemStyleDone;
716 - (UIBarButtonItem *) customButton {
719 else if ((/*clang:*/id) custom_ == [NSNull null])
720 return (UIBarButtonItem *) [NSNull null];
722 return [[[UIBarButtonItem alloc]
723 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
724 style:[self rightButtonStyle]
726 action:@selector(customButtonClicked)
730 - (UIBarButtonItem *) leftButton {
731 UINavigationItem *item([self navigationItem]);
732 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
735 if (UINavigationController *navigation = [self navigationController])
736 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
737 return [[[UIBarButtonItem alloc]
738 initWithTitle:UCLocalize("CLOSE")
739 style:UIBarButtonItemStylePlain
741 action:@selector(close)
747 - (void) applyLeftButton {
748 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
751 - (UIBarButtonItem *) rightButton {
755 - (void) applyLoadingTitle {
756 [[self navigationItem] setTitle:UCLocalize("LOADING")];
759 - (void) layoutRightButton {
760 [[loadingitem_ view] addSubview:indicator_];
761 [[loadingitem_ view] bringSubviewToFront:indicator_];
764 - (void) applyRightButton {
765 if ([self isLoading]) {
766 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
767 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
769 [indicator_ startAnimating];
770 [self applyLoadingTitle];
772 [indicator_ stopAnimating];
774 UIBarButtonItem *button([self customButton]);
776 button = [self rightButton];
777 else if (button == (UIBarButtonItem *) [NSNull null])
780 [[self navigationItem] setRightBarButtonItem:button animated:YES];
784 - (void) didStartLoading {
785 // Overridden in subclasses.
788 - (void) _didStartLoading {
789 [self applyRightButton];
791 if ([loading_ count] != 1)
794 if ([self retainsNetworkActivityIndicator])
795 [delegate_ retainNetworkActivityIndicator];
797 [self didStartLoading];
800 - (void) didFinishLoading {
801 // Overridden in subclasses.
804 - (void) _didFinishLoading {
805 if ([loading_ count] != 0)
808 [self applyRightButton];
809 [[self navigationItem] setTitle:title_];
811 if ([self retainsNetworkActivityIndicator])
812 [delegate_ releaseNetworkActivityIndicator];
814 [self didFinishLoading];
818 return [loading_ count] != 0;
821 - (id) initWithWidth:(float)width ofClass:(Class)_class {
822 if ((self = [super init]) != nil) {
826 allowsNavigationAction_ = true;
828 loading_ = [NSMutableSet setWithCapacity:5];
829 registered_ = [NSMutableSet setWithCapacity:5];
830 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
832 reloaditem_ = [[[UIBarButtonItem alloc]
833 initWithTitle:UCLocalize("RELOAD")
834 style:[self rightButtonStyle]
836 action:@selector(reloadButtonClicked)
839 loadingitem_ = [[[UIBarButtonItem alloc]
841 style:UIBarButtonItemStylePlain
843 action:@selector(reloadButtonClicked)
846 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
847 [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
848 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
850 [self applyLeftButton];
851 [self applyRightButton];
855 - (NSString *) applicationNameForUserAgent {
860 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
862 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
863 [webview_ setDelegate:self];
864 [self setView:webview_];
866 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
867 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
869 [webview_ setDetectsPhoneNumbers:NO];
871 [webview_ setScalesPageToFit:YES];
873 UIWebDocumentView *document([webview_ _documentView]);
875 // XXX: I think this improves scrolling; the hardcoded-ness sucks
876 [document setTileSize:CGSizeMake(320, 500)];
878 [document setBackgroundColor:[UIColor clearColor]];
880 // XXX: this is terribly (too?) expensive
881 [document setDrawsBackground:NO];
883 WebView *webview([document webView]);
884 WebPreferences *preferences([webview preferences]);
886 // XXX: I have no clue if I actually /want/ this modification
887 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
888 [webview _setLayoutInterval:0];
889 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
890 [preferences _setLayoutInterval:0];
892 [preferences setCacheModel:WebCacheModelDocumentBrowser];
893 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
895 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
896 [preferences setOfflineWebApplicationCacheEnabled:YES];
898 if (NSString *agent = [self applicationNameForUserAgent])
899 [webview setApplicationNameForUserAgent:agent];
901 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
902 [webview setShouldUpdateWhileOffscreen:NO];
905 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
906 [document setAllowsMessaging:YES];
907 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
908 [webview _setAllowsMessaging:YES];
911 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
912 scroller_ = [webview_ _scrollView];
914 [scroller_ setDirectionalLockEnabled:YES];
915 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
916 [scroller_ setDelaysContentTouches:NO];
918 [scroller_ setCanCancelContentTouches:YES];
919 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
920 UIScroller *scroller([webview_ _scroller]);
921 scroller_ = (UIScrollView *) scroller;
923 [scroller setDirectionalScrolling:YES];
924 // XXX: we might be better off /not/ setting this on older systems
925 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
926 [scroller setScrollHysteresis:0]; /* 8 */
928 [scroller setThumbDetectionEnabled:NO];
930 // use NO with UIApplicationUseLegacyEvents(YES)
931 [scroller setEventMode:YES];
933 // XXX: this is handled by setBounces, right?
934 //[scroller setAllowsRubberBanding:YES];
937 [scroller_ setFixedBackgroundPattern:YES];
938 [scroller_ setBackgroundColor:[UIColor clearColor]];
939 [scroller_ setClipsSubviews:YES];
941 [scroller_ setBounces:YES];
942 [scroller_ setScrollingEnabled:YES];
943 [scroller_ setShowBackgroundShadow:NO];
945 [self setViewportWidth:width_];
947 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
948 [table setScrollsToTop:NO];
949 [webview_ insertSubview:table atIndex:0];
951 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
952 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
957 - (void) releaseSubviews {
961 [self releaseNetworkActivityIndicator];
963 [super releaseSubviews];
966 - (id) initWithWidth:(float)width {
967 return [self initWithWidth:width ofClass:[self class]];
971 return [self initWithWidth:0];
974 - (id) initWithURL:(NSURL *)url {
975 if ((self = [self init]) != nil) {
980 - (id) initWithRequest:(NSURLRequest *)request {
981 if ((self = [self init]) != nil) {
982 [self setRequest:request];
986 - (void) callFunction:(WebScriptObject *)function {
987 WebThreadLocked lock;
989 WebView *webview([[[self webView] _documentView] webView]);
990 WebFrame *frame([webview mainFrame]);
992 JSGlobalContextRef context([frame globalContext]);
993 JSObjectRef object([function JSObject]);
994 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
997 - (void) reloadButtonClicked {
998 [self reloadURLWithCache:NO];
1001 - (void) _customButtonClicked {
1002 [self reloadButtonClicked];
1005 - (void) customButtonClicked {
1007 if (function_ != nil)
1008 [self callFunction:function_];
1011 [self _customButtonClicked];
1014 + (float) defaultWidth {
1018 - (void) setNavigationBarStyle:(NSString *)name {
1020 if ([name isEqualToString:@"Black"])
1021 style = UIBarStyleBlack;
1023 style = UIBarStyleDefault;
1025 [[[self navigationController] navigationBar] setBarStyle:style];
1028 - (void) setNavigationBarTintColor:(UIColor *)color {
1029 [[[self navigationController] navigationBar] setTintColor:color];
1032 - (void) setBadgeValue:(id)value {
1033 [[[self navigationController] tabBarItem] setBadgeValue:value];
1036 - (void) setHidesBackButton:(bool)value {
1037 [[self navigationItem] setHidesBackButton:value];
1038 [self applyLeftButton];
1041 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1042 [self setHidesBackButton:[value boolValue]];
1045 - (void) dispatchEvent:(NSString *)event {
1046 [[self webView] dispatchEvent:event];
1049 - (bool) hidesNavigationBar {
1050 return hidesNavigationBar_;
1053 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1055 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1058 - (void) setHidesNavigationBar:(bool)value {
1059 if (hidesNavigationBar_ != value) {
1060 hidesNavigationBar_ = value;
1061 [self _setHidesNavigationBar:YES animated:YES];
1065 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1066 [self setHidesNavigationBar:[value boolValue]];
1069 - (void) setScrollAlwaysBounceVertical:(bool)value {
1070 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1071 UIScrollView *scroller([webview_ _scrollView]);
1072 [scroller setAlwaysBounceVertical:value];
1073 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1074 //UIScroller *scroller([webview_ _scroller]);
1075 // XXX: I am sad here.
1079 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1080 [self setScrollAlwaysBounceVertical:[value boolValue]];
1083 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1084 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1085 UIScrollView *scroller([webview_ _scrollView]);
1086 [scroller setIndicatorStyle:style];
1087 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1088 UIScroller *scroller([webview_ _scroller]);
1089 [scroller setScrollerIndicatorStyle:style];
1093 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1094 UIScrollViewIndicatorStyle value;
1097 else if ([style isEqualToString:@"default"])
1098 value = UIScrollViewIndicatorStyleDefault;
1099 else if ([style isEqualToString:@"black"])
1100 value = UIScrollViewIndicatorStyleBlack;
1101 else if ([style isEqualToString:@"white"])
1102 value = UIScrollViewIndicatorStyleWhite;
1105 [self setScrollIndicatorStyle:value];
1108 - (void) viewWillAppear:(BOOL)animated {
1111 if ([self hidesNavigationBar])
1112 [self _setHidesNavigationBar:YES animated:animated];
1114 // XXX: why isn't this evern called automatically?
1115 [[self webView] setNeedsLayout];
1117 [self dispatchEvent:@"CydiaViewWillAppear"];
1118 [super viewWillAppear:animated];
1121 - (void) viewDidAppear:(BOOL)animated {
1122 [super viewDidAppear:animated];
1123 [self dispatchEvent:@"CydiaViewDidAppear"];
1126 - (void) viewWillDisappear:(BOOL)animated {
1127 [self dispatchEvent:@"CydiaViewWillDisappear"];
1128 [super viewWillDisappear:animated];
1130 if ([self hidesNavigationBar])
1131 [self _setHidesNavigationBar:NO animated:animated];
1136 - (void) viewDidDisappear:(BOOL)animated {
1137 [super viewDidDisappear:animated];
1138 [self dispatchEvent:@"CydiaViewDidDisappear"];
1141 - (void) updateHeights:(NSTimer *)timer {
1142 for (WebFrame *frame in (id) registered_)
1143 [frame cydia$updateHeight];
1146 - (void) registerFrame:(WebFrame *)frame {
1147 [registered_ addObject:frame];
1150 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];