1 #include <BrowserView.h>
3 #include <WebCore/WebCoreThread.h>
5 /* Indirect Delegate {{{ */
6 @interface IndirectDelegate : NSObject {
7 _transient volatile id delegate_;
10 - (void) setDelegate:(id)delegate;
11 - (id) initWithDelegate:(id)delegate;
14 @implementation IndirectDelegate
16 - (void) setDelegate:(id)delegate {
20 - (id) initWithDelegate:(id)delegate {
25 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
27 return [delegate_ webView:sender didClearWindowObject:window forFrame:frame];
30 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
32 return [delegate_ webView:sender didCommitLoadForFrame:frame];
35 - (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
37 return [delegate_ webView:sender didFailLoadWithError:error forFrame:frame];
40 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
42 return [delegate_ webView:sender didFailProvisionalLoadWithError:error forFrame:frame];
45 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
47 return [delegate_ webView:sender didFinishLoadForFrame:frame];
50 - (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
52 return [delegate_ webView:sender didReceiveTitle:title forFrame:frame];
55 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
57 return [delegate_ webView:sender didStartProvisionalLoadForFrame:frame];
60 - (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
62 return [delegate_ webView:sender resource:identifier didReceiveAuthenticationChallenge:challenge fromDataSource:source];
65 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
67 return [delegate_ webView:sender resource:identifier willSendRequest:request redirectResponse:redirectResponse fromDataSource:source];
71 - (IMP) methodForSelector:(SEL)sel {
72 if (IMP method = [super methodForSelector:sel])
74 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
78 - (BOOL) respondsToSelector:(SEL)sel {
79 if ([super respondsToSelector:sel])
81 // XXX: WebThreadCreateNSInvocation returns nil
82 //fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
83 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
86 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
87 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
89 //fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
91 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
93 // XXX: I fucking hate Apple so very very bad
94 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
97 - (void) forwardInvocation:(NSInvocation *)inv {
98 SEL sel = [inv selector];
99 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
100 [inv invokeWithTarget:delegate_];
106 @interface WebView (Cydia)
107 - (void) setScriptDebugDelegate:(id)delegate;
108 - (void) _setFormDelegate:(id)delegate;
109 - (void) _setUIKitDelegate:(id)delegate;
110 - (void) setWebMailDelegate:(id)delegate;
111 - (void) _setLayoutInterval:(float)interval;
114 @interface WebScriptObject (Cydia)
117 - (id) objectAtIndex:(unsigned)index;
121 @implementation WebScriptObject (Cydia)
124 id length([self valueForKey:@"length"]);
125 if ([length respondsToSelector:@selector(intValue)])
126 return [length intValue];
131 - (id) objectAtIndex:(unsigned)index {
132 return [self webScriptValueAtIndex:index];
137 /* Web Scripting {{{ */
138 @interface CydiaObject : NSObject {
142 - (id) initWithDelegate:(IndirectDelegate *)indirect;
145 @implementation CydiaObject
152 - (id) initWithDelegate:(IndirectDelegate *)indirect {
153 if ((self = [super init]) != nil) {
154 indirect_ = [indirect retain];
158 + (NSArray *) _attributeKeys {
159 return [NSArray arrayWithObjects:@"device", nil];
162 - (NSArray *) attributeKeys {
163 return [[self class] _attributeKeys];
166 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
167 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
170 - (NSString *) device {
171 return [[UIDevice currentDevice] uniqueIdentifier];
174 + (NSString *) webScriptNameForSelector:(SEL)selector {
175 if (selector == @selector(close))
177 else if (selector == @selector(getPackageById:))
178 return @"getPackageById";
179 else if (selector == @selector(setAutoPopup:))
180 return @"setAutoPopup";
181 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
182 return @"setButtonImage";
183 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
184 return @"setButtonTitle";
185 else if (selector == @selector(setFinishHook:))
186 return @"setFinishHook";
187 else if (selector == @selector(setPopupHook:))
188 return @"setPopupHook";
189 else if (selector == @selector(setSpecial:))
190 return @"setSpecial";
191 else if (selector == @selector(setViewportWidth:))
192 return @"setViewportWidth";
193 else if (selector == @selector(supports:))
195 else if (selector == @selector(stringWithFormat:arguments:))
197 else if (selector == @selector(localizedStringForKey:value:table:))
199 else if (selector == @selector(du:))
201 else if (selector == @selector(statfs:))
207 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
208 return [self webScriptNameForSelector:selector] == nil;
211 - (BOOL) supports:(NSString *)feature {
212 return [feature isEqualToString:@"window.open"];
215 - (Package *) getPackageById:(NSString *)id {
216 return [[Database sharedInstance] packageWithName:id];
219 - (NSArray *) statfs:(NSString *)path {
222 if (path == nil || statfs([path UTF8String], &stat) == -1)
225 return [NSArray arrayWithObjects:
226 [NSNumber numberWithUnsignedLong:stat.f_bsize],
227 [NSNumber numberWithUnsignedLong:stat.f_blocks],
228 [NSNumber numberWithUnsignedLong:stat.f_bfree],
232 - (NSNumber *) du:(NSString *)path {
233 NSNumber *value(nil);
236 _assert(pipe(fds) != -1);
238 pid_t pid(ExecFork());
240 _assert(dup2(fds[1], 1) != -1);
241 _assert(close(fds[0]) != -1);
242 _assert(close(fds[1]) != -1);
243 execlp("du", "du", "-s", [path UTF8String], NULL);
248 _assert(close(fds[1]) != -1);
250 if (FILE *du = fdopen(fds[0], "r")) {
252 while (fgets(line, sizeof(line), du) != NULL) {
253 size_t length(strlen(line));
254 while (length != 0 && line[length - 1] == '\n')
255 line[--length] = '\0';
256 if (char *tab = strchr(line, '\t')) {
258 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
263 } else _assert(close(fds[0]));
267 if (waitpid(pid, &status, 0) == -1)
279 - (void) setAutoPopup:(BOOL)popup {
280 [indirect_ setAutoPopup:popup];
283 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
284 [indirect_ setButtonImage:button withStyle:style toFunction:function];
287 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
288 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
291 - (void) setSpecial:(id)function {
292 [indirect_ setSpecial:function];
295 - (void) setFinishHook:(id)function {
296 [indirect_ setFinishHook:function];
299 - (void) setPopupHook:(id)function {
300 [indirect_ setPopupHook:function];
303 - (void) setViewportWidth:(float)width {
304 [indirect_ setViewportWidth:width];
307 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
308 NSLog(@"SWF:\"%@\" A:%@", format, arguments);
309 unsigned count([arguments count]);
311 for (unsigned i(0); i != count; ++i)
312 values[i] = [arguments objectAtIndex:i];
313 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
316 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
317 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
319 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
325 @implementation BrowserView
328 #include "Internals.h"
333 NSLog(@"[BrowserView dealloc]");
336 if (challenge_ != nil)
337 [challenge_ release];
341 WebView *webview = [webview_ webView];
342 [webview setFrameLoadDelegate:nil];
343 [webview setResourceLoadDelegate:nil];
344 [webview setUIDelegate:nil];
345 [webview setScriptDebugDelegate:nil];
346 [webview setPolicyDelegate:nil];
348 [webview setDownloadDelegate:nil];
350 /* XXX: these are set by UIWebDocumentView
351 [webview _setFormDelegate:nil];
352 [webview _setUIKitDelegate:nil];
353 [webview setEditingDelegate:nil];*/
355 /* XXX: no one sets this, ever
356 [webview setWebMailDelegate:nil];*/
358 [webview_ setDelegate:nil];
359 [webview_ setGestureDelegate:nil];
360 [webview_ setFormEditingDelegate:nil];
361 [webview_ setInteractionDelegate:nil];
363 [indirect_ setDelegate:nil];
365 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
370 [webview_ removeFromSuperview];
371 [Documents_ addObject:[webview_ autorelease]];
382 [scroller_ setDelegate:nil];
388 if (function_ != nil)
398 [indicator_ release];
406 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
407 [self loadRequest:[NSURLRequest
414 - (void) loadURL:(NSURL *)url {
415 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
418 - (NSMutableURLRequest *) _addHeadersToRequest:(NSURLRequest *)request {
419 NSMutableURLRequest *copy = [request mutableCopy];
421 if (Machine_ != NULL)
422 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
423 if (UniqueID_ != nil)
424 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
427 [copy setValue:Role_ forHTTPHeaderField:@"X-Role"];
432 - (void) loadRequest:(NSURLRequest *)request {
437 [webview_ loadRequest:request];
445 if ([request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
446 [self loadRequest:request_];
448 UIActionSheet *sheet = [[[UIActionSheet alloc]
449 initWithTitle:CYLocalize("RESUBMIT_FORM")
450 buttons:[NSArray arrayWithObjects:CYLocalize("CANCEL"), CYLocalize("SUBMIT"), nil]
456 [sheet setNumberOfRows:1];
457 [sheet popupAlertAnimated:YES];
461 - (WebView *) webView {
462 return [webview_ webView];
465 - (UIWebDocumentView *) documentView {
469 /* XXX: WebThreadLock? */
470 - (void) _fixScroller:(CGRect)bounds {
475 UIFormAssistant *assistant([UIFormAssistant sharedFormAssistant]);
476 CGRect peripheral([assistant peripheralFrame]);
478 NSLog(@"per:%f", peripheral.size.height);
480 extra = peripheral.size.height;
483 CGRect subrect([scroller_ frame]);
484 subrect.size.height -= extra;
485 [scroller_ setScrollerIndicatorSubrect:subrect];
487 NSSize visible(NSMakeSize(subrect.size.width, subrect.size.height));
488 [webview_ setValue:[NSValue valueWithSize:visible] forGestureAttribute:UIGestureAttributeVisibleSize];
491 size.height += extra;
492 [scroller_ setContentSize:size];
494 [scroller_ releaseRubberBandIfNecessary];
497 - (void) fixScroller {
498 CGRect bounds([webview_ documentBounds]);
500 NSLog(@"_fs:(%f,%f+%f,%f)", bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
502 [self _fixScroller:bounds];
505 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
508 NSLog(@"dsf:(%f,%f+%f,%f)", frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
510 [self _fixScroller:frame];
513 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
514 [self view:sender didSetFrame:frame];
517 - (void) pushPage:(RVPage *)page {
518 [page setDelegate:delegate_];
519 [self setBackButtonTitle:title_];
520 [book_ pushPage:page];
526 // WTR: [self autorelease];
528 [book_ pushPage:self];
531 - (void) swapPage:(RVPage *)page {
532 [page setDelegate:delegate_];
534 [book_ swapPage:page];
536 [book_ pushPage:page];
539 - (BOOL) getSpecial:(NSURL *)url swap:(BOOL)swap {
541 NSLog(@"getSpecial:%@", url);
544 NSString *href([url absoluteString]);
545 NSString *scheme([[url scheme] lowercaseString]);
549 if ([href hasPrefix:@"apptapp://package/"])
550 page = [delegate_ pageForPackage:[href substringFromIndex:18]];
551 else if ([scheme isEqualToString:@"cydia"]) {
552 page = [delegate_ pageForURL:url hasTag:NULL];
555 } else if (![scheme isEqualToString:@"apptapp"])
560 [self swapPage:page];
562 [self pushPage:page];
566 - (void) webViewShow:(WebView *)sender {
567 /* XXX: this is where I cry myself to sleep */
570 - (bool) _allowJavaScriptPanel {
574 - (void) webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
575 if (![self _allowJavaScriptPanel])
578 // WTR: [self retain];
580 UIActionSheet *sheet = [[[UIActionSheet alloc]
582 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
588 [sheet setBodyText:message];
589 [sheet popupAlertAnimated:YES];
592 - (BOOL) webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
593 if (![self _allowJavaScriptPanel])
596 UIActionSheet *sheet = [[[UIActionSheet alloc]
598 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), CYLocalize("Cancel"), nil]
604 [sheet setNumberOfRows:1];
605 [sheet setBodyText:message];
606 [sheet popupAlertAnimated:YES];
608 NSRunLoop *loop([NSRunLoop currentRunLoop]);
609 NSDate *future([NSDate distantFuture]);
611 while (confirm_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
613 NSNumber *confirm([confirm_ autorelease]);
615 return [confirm boolValue];
618 - (void) setAutoPopup:(BOOL)popup {
622 - (void) setSpecial:(id)function {
624 [special_ autorelease];
625 special_ = function == nil ? nil : [function retain];
628 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
630 [button_ autorelease];
631 button_ = button == nil ? nil : [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:button]]] retain];
634 [style_ autorelease];
635 style_ = style == nil ? nil : [style retain];
637 if (function_ != nil)
638 [function_ autorelease];
639 function_ = function == nil ? nil : [function retain];
641 [self reloadButtons];
644 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
646 [button_ autorelease];
647 button_ = button == nil ? nil : [button retain];
650 [style_ autorelease];
651 style_ = style == nil ? nil : [style retain];
653 if (function_ != nil)
654 [function_ autorelease];
655 function_ = function == nil ? nil : [function retain];
657 [self reloadButtons];
660 - (void) setFinishHook:(id)function {
662 [finish_ autorelease];
663 finish_ = function == nil ? nil : [function retain];
666 - (void) setPopupHook:(id)function {
668 [closer_ autorelease];
669 closer_ = function == nil ? nil : [function retain];
672 - (void) webView:(WebView *)sender willBeginEditingFormElement:(id)element {
676 - (void) webView:(WebView *)sender didBeginEditingFormElement:(id)element {
680 - (void) webViewDidEndEditingFormElements:(WebView *)sender {
685 - (void) webViewClose:(WebView *)sender {
693 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
694 [window setValue:cydia_ forKey:@"cydia"];
697 - (void) webView:(WebView *)sender unableToImplementPolicyWithError:(NSError *)error frame:(WebFrame *)frame {
698 NSLog(@"err:%@", error);
701 - (void) webView:(WebView *)sender decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
703 NSLog(@"nwa:%@", name);
706 if (NSURL *url = [request URL]) {
707 if (name == nil) unknown: {
708 if (![self getSpecial:url swap:NO]) {
709 NSString *scheme([[url scheme] lowercaseString]);
710 if ([scheme isEqualToString:@"mailto"])
711 [delegate_ openMailToURL:url];
714 } else if ([name isEqualToString:@"_open"])
715 [delegate_ openURL:url];
716 else if ([name isEqualToString:@"_popup"]) {
717 NSString *scheme([[url scheme] lowercaseString]);
718 if ([scheme isEqualToString:@"mailto"])
719 [delegate_ openMailToURL:url];
721 RVBook *book([[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
722 [book setHook:indirect_];
724 RVPage *page([delegate_ pageForURL:url hasTag:NULL]);
726 /* XXX: call createWebViewWithRequest instead? */
728 [self setBackButtonTitle:title_];
730 BrowserView *browser([[[BrowserView alloc] initWithBook:book] autorelease]);
731 [browser loadURL:url];
735 [book setDelegate:delegate_];
736 [page setDelegate:delegate_];
739 [book_ pushBook:book];
748 - (void) webView:(WebView *)sender decidePolicyForMIMEType:(NSString *)type request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
749 if ([WebView canShowMIMEType:type])
752 // XXX: handle more mime types!
755 WebView *webview([webview_ webView]);
756 if (frame == [webview mainFrame])
757 [UIApp openURL:[request URL]];
761 - (void) webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
762 if (request == nil) ignore: {
767 NSURL *url([request URL]);
769 if (url == nil) use: {
770 if (!error_ && [frame parentFrame] == nil) {
772 [request_ autorelease];
773 request_ = [request retain];
775 NSLog(@"dpn:%@", request_);
781 WebView *webview([webview_ webView]);
782 if (frame == [webview mainFrame])
787 else NSLog(@"nav:%@:%@", url, [action description]);
790 const NSArray *capability;
792 #if 0 // XXX:3:GSSystemCopyCapability
793 capability = reinterpret_cast<const NSArray *>(GSSystemGetCapability(kGSDisplayIdentifiersCapability));
798 if (capability != nil && (
799 [capability containsObject:@"com.apple.Maps"] && [url mapsURL] ||
800 [capability containsObject:@"com.apple.youtube"] && [url youTubeURL]
807 int store(_not(int));
808 if (NSURL *itms = [url itmsURL:&store]) {
810 NSLog(@"itms#%@#%u#%@", url, store, itms);
813 if (capability != nil && (
814 store == 1 && [capability containsObject:@"com.apple.MobileStore"] ||
815 store == 2 && [capability containsObject:@"com.apple.AppStore"]
822 NSString *scheme([[url scheme] lowercaseString]);
824 if ([scheme isEqualToString:@"tel"]) {
829 if ([scheme isEqualToString:@"mailto"]) {
830 [delegate_ openMailToURL:url];
834 if ([self getSpecial:url swap:YES])
836 else if ([WebView _canHandleRequest:request])
838 else if ([url isSpringboardHandledURL])
844 - (void) webView:(WebView *)sender setStatusText:(NSString *)text {
845 //lprintf("Status:%s\n", [text UTF8String]);
848 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
849 NSString *context([sheet context]);
851 if ([context isEqualToString:@"alert"]) {
854 } else if ([context isEqualToString:@"confirm"]) {
857 confirm_ = [NSNumber numberWithBool:YES];
861 confirm_ = [NSNumber numberWithBool:NO];
866 } else if ([context isEqualToString:@"challenge"]) {
867 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
871 NSString *username([[sheet textFieldAtIndex:0] text]);
872 NSString *password([[sheet textFieldAtIndex:1] text]);
874 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
876 [sender useCredential:credential forAuthenticationChallenge:challenge_];
880 [sender cancelAuthenticationChallenge:challenge_];
887 [challenge_ release];
891 } else if ([context isEqualToString:@"submit"]) {
897 if (request_ != nil) {
899 [webview_ loadRequest:request_];
912 - (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
913 challenge_ = [challenge retain];
915 NSURLProtectionSpace *space([challenge protectionSpace]);
916 NSString *realm([space realm]);
920 UIActionSheet *sheet = [[[UIActionSheet alloc]
922 buttons:[NSArray arrayWithObjects:CYLocalize("LOGIN"), CYLocalize("CANCEL"), nil]
928 [sheet setNumberOfRows:1];
930 [sheet addTextFieldWithValue:@"" label:CYLocalize("USERNAME")];
931 [sheet addTextFieldWithValue:@"" label:CYLocalize("PASSWORD")];
933 UITextField *username([sheet textFieldAtIndex:0]); {
934 UITextInputTraits *traits([username textInputTraits]);
935 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
936 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
937 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
938 [traits setReturnKeyType:UIReturnKeyNext];
941 UITextField *password([sheet textFieldAtIndex:1]); {
942 UITextInputTraits *traits([password textInputTraits]);
943 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
944 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
945 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
946 // XXX: UIReturnKeyDone
947 [traits setReturnKeyType:UIReturnKeyNext];
948 [traits setSecureTextEntry:YES];
951 [sheet popupAlertAnimated:YES];
954 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
955 return [self _addHeadersToRequest:request];
958 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request windowFeatures:(NSDictionary *)features {
959 //- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request userGesture:(BOOL)gesture {
961 NSLog(@"cwv:%@ (%@): %@", request, title_, features == nil ? @"{}" : [features description]);
962 //NSLog(@"cwv:%@ (%@): %@", request, title_, gesture ? @"Yes" : @"No");
965 NSNumber *value([features objectForKey:@"width"]);
966 float width(value == nil ? 0 : [value floatValue]);
968 RVBook *book(!popup_ ? book_ : [[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
970 /* XXX: deal with cydia:// pages */
971 BrowserView *browser([[[BrowserView alloc] initWithBook:book forWidth:width] autorelease]);
973 if (features != nil && popup_) {
974 [book setDelegate:delegate_];
975 [book setHook:indirect_];
976 [browser setDelegate:delegate_];
978 [browser loadRequest:request];
980 [book setPage:browser];
981 [book_ pushBook:book];
982 } else if (request == nil) {
983 [self setBackButtonTitle:title_];
984 [browser setDelegate:delegate_];
987 [self pushPage:browser];
988 [browser loadRequest:request];
991 return [browser webView];
994 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
995 return [self webView:sender createWebViewWithRequest:request windowFeatures:nil];
996 //return [self webView:sender createWebViewWithRequest:request userGesture:YES];
999 - (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
1000 if ([frame parentFrame] != nil)
1003 title_ = [title retain];
1004 [book_ reloadTitleForPage:self];
1007 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
1008 [loading_ addObject:frame];
1010 if ([frame parentFrame] == nil) {
1011 [webview_ resignFirstResponder];
1015 if (title_ != nil) {
1020 if (button_ != nil) {
1025 if (style_ != nil) {
1030 if (function_ != nil) {
1031 [function_ release];
1035 if (finish_ != nil) {
1040 if (closer_ != nil) {
1045 if (special_ != nil) {
1050 [book_ reloadTitleForPage:self];
1052 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
1054 if ([scroller_ respondsToSelector:@selector(setZoomScale:duration:)])
1055 [scroller_ setZoomScale:1 duration:0];
1057 [scroller_ setZoomScale:1 animated:NO];
1059 CGRect webrect = [scroller_ bounds];
1060 webrect.size.height = 0;
1061 [webview_ setFrame:webrect];
1064 [self reloadButtons];
1067 - (void) _finishLoading {
1068 if (reloading_ || [loading_ count] != 0)
1071 [self callFunction:finish_];
1072 [self reloadButtons];
1075 - (bool) isLoading {
1076 return [loading_ count] != 0;
1079 - (void) reloadButtons {
1080 if ([self isLoading])
1081 [indicator_ startAnimation];
1083 [indicator_ stopAnimation];
1084 [super reloadButtons];
1087 - (BOOL) webView:(WebView *)sender shouldScrollToPoint:(struct CGPoint)point forFrame:(WebFrame *)frame {
1088 return [webview_ webView:sender shouldScrollToPoint:point forFrame:frame];
1091 - (void) webView:(WebView *)sender didReceiveViewportArguments:(id)arguments forFrame:(WebFrame *)frame {
1092 return [webview_ webView:sender didReceiveViewportArguments:arguments forFrame:frame];
1095 - (void) webView:(WebView *)sender needsScrollNotifications:(id)notifications forFrame:(WebFrame *)frame {
1096 return [webview_ webView:sender needsScrollNotifications:notifications forFrame:frame];
1099 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
1101 return [webview_ webView:sender didCommitLoadForFrame:frame];
1104 - (void) webView:(WebView *)sender didReceiveDocTypeForFrame:(WebFrame *)frame {
1105 return [webview_ webView:sender didReceiveDocTypeForFrame:frame];
1108 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
1109 [loading_ removeObject:frame];
1111 [self _finishLoading];
1113 if ([frame parentFrame] == nil) {
1114 if (DOMDocument *document = [frame DOMDocument])
1115 if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
1116 for (DOMHTMLBodyElement *body in bodies) {
1117 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
1119 bool colored(false);
1121 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
1122 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
1123 DOMRGBColor *rgb([color getRGBColorValue]);
1125 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
1126 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
1127 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
1128 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
1132 if (red == 0xc7 && green == 0xce && blue == 0xd5)
1133 uic = [UIColor pinStripeColor];
1134 else if (alpha != 0)
1136 colorWithRed:(red / 255)
1144 [scroller_ setBackgroundColor:uic];
1150 [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
1155 return [webview_ webView:sender didFinishLoadForFrame:frame];
1158 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
1159 [loading_ removeObject:frame];
1163 [self _finishLoading];
1165 if ([frame parentFrame] == nil) {
1166 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
1167 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
1168 [[error localizedDescription] stringByAddingPercentEscapes]
1175 - (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
1176 [self _didFailWithError:error forFrame:frame];
1179 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
1180 [self _didFailWithError:error forFrame:frame];
1183 - (void) webView:(WebView *)sender addMessageToConsole:(NSDictionary *)dictionary {
1184 #if LogBrowser || ForSaurik
1185 lprintf("Console:%s\n", [[dictionary description] UTF8String]);
1189 /* XXX: fix this stupid include file
1190 - (void) webView:(WebView *)sender frame:(WebFrame *)frame exceededDatabaseQuotaForSecurityOrigin:(WebSecurityOrigin *)origin database:(NSString *)database {
1191 [origin setQuota:0x500000];
1194 - (void) _setTileDrawingEnabled:(BOOL)enabled {
1195 //[webview_ setTileDrawingEnabled:enabled];
1198 - (void) setViewportWidth:(float)width {
1199 width_ = width ? width != 0 : [[self class] defaultWidth];
1200 [webview_ setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
1203 - (void) willStartGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
1204 [self _setTileDrawingEnabled:NO];
1207 - (void) didFinishGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
1208 [self _setTileDrawingEnabled:YES];
1209 [webview_ redrawScaledDocument];
1212 - (void) scrollerWillStartDragging:(UIScroller *)scroller {
1213 [self _setTileDrawingEnabled:NO];
1216 - (void) scrollerDidEndDragging:(UIScroller *)scroller willSmoothScroll:(BOOL)smooth {
1217 [self _setTileDrawingEnabled:YES];
1220 - (void) scrollerDidEndDragging:(UIScroller *)scroller {
1221 [self _setTileDrawingEnabled:YES];
1224 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
1225 if ((self = [super initWithBook:book]) != nil) {
1226 loading_ = [[NSMutableSet alloc] initWithCapacity:3];
1229 struct CGRect bounds = [self bounds];
1231 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
1232 [self addSubview:scroller_];
1234 [scroller_ setFixedBackgroundPattern:YES];
1235 [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
1237 [scroller_ setScrollingEnabled:YES];
1238 [scroller_ setClipsSubviews:YES];
1239 [scroller_ setAllowsRubberBanding:YES];
1241 [scroller_ setDelegate:self];
1242 [scroller_ setBounces:YES];
1243 [scroller_ setScrollHysteresis:8];
1244 [scroller_ setThumbDetectionEnabled:NO];
1245 [scroller_ setDirectionalScrolling:YES];
1246 [scroller_ setScrollDecelerationFactor:0.99]; /* 0.989324 */
1247 [scroller_ setEventMode:YES];
1248 [scroller_ setShowBackgroundShadow:NO]; /* YES */
1249 [scroller_ setAllowsRubberBanding:YES]; /* Vertical */
1250 [scroller_ setAdjustForContentSizeChange:YES]; /* NO */
1252 CGRect webrect = [scroller_ bounds];
1253 webrect.size.height = 0;
1260 webview_ = [Documents_ lastObject];
1261 if (webview_ != nil) {
1262 webview_ = [webview_ retain];
1263 webview = [webview_ webView];
1264 [Documents_ removeLastObject];
1265 [webview_ setFrame:webrect];
1270 webview_ = [[UIWebDocumentView alloc] initWithFrame:webrect];
1271 webview = [webview_ webView];
1273 // XXX: this is terribly (too?) expensive
1274 //[webview_ setDrawsBackground:NO];
1275 [webview setPreferencesIdentifier:@"Cydia"];
1277 [webview_ setTileSize:CGSizeMake(webrect.size.width, 500)];
1279 [webview_ setAllowsMessaging:YES];
1281 [webview_ setTilingEnabled:YES];
1282 [webview_ setDrawsGrid:NO];
1283 [webview_ setLogsTilingChanges:NO];
1284 [webview_ setTileMinificationFilter:kCAFilterNearest];
1285 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
1286 /* XXX: abstractify */
1287 [webview_ setDataDetectorTypes:0x80000000];
1289 [webview_ setDetectsPhoneNumbers:NO];
1290 [webview_ setAutoresizes:YES];
1292 [webview_ setMinimumScale:0.25f forDocumentTypes:0x10];
1293 [webview_ setMaximumScale:5.00f forDocumentTypes:0x10];
1294 [webview_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x10];
1295 //[webview_ setViewportSize:CGSizeMake(980, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
1297 [webview_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x2];
1299 [webview_ setMinimumScale:1.00f forDocumentTypes:0x8];
1300 [webview_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x8];
1301 [webview_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x8];
1303 [webview_ _setDocumentType:0x4];
1305 if ([webview_ respondsToSelector:@selector(UIWebDocumentView:)])
1306 [webview_ setZoomsFocusedFormControl:YES];
1307 [webview_ setContentsPosition:7];
1308 [webview_ setEnabledGestures:0xa];
1309 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeIsZoomRubberBandEnabled];
1310 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeUpdatesScroller];
1312 [webview_ setSmoothsFonts:YES];
1313 [webview_ setAllowsImageSheet:YES];
1314 [webview _setUsesLoaderCache:YES];
1316 [webview setGroupName:@"CydiaGroup"];
1317 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
1318 [webview _setLayoutInterval:0];
1321 [self setViewportWidth:width];
1323 [webview_ setDelegate:self];
1324 [webview_ setGestureDelegate:self];
1325 [webview_ setFormEditingDelegate:self];
1326 [webview_ setInteractionDelegate:self];
1328 [scroller_ addSubview:webview_];
1330 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
1332 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
1333 NSString *application = package == nil ? @"Cydia" : [NSString
1334 stringWithFormat:@"Cydia/%@",
1338 if (Product_ != nil)
1339 application = [NSString stringWithFormat:@"%@ Version/%@", application, Product_];
1341 application = [NSString stringWithFormat:@"%@ Mobile/%@", application, Build_];
1343 application = [NSString stringWithFormat:@"%@ Safari/%@", application, Safari_];
1345 [webview setApplicationNameForUserAgent:application];
1347 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
1348 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
1350 [webview setFrameLoadDelegate:indirect_];
1351 [webview setResourceLoadDelegate:indirect_];
1352 [webview setUIDelegate:indirect_];
1353 [webview setScriptDebugDelegate:indirect_];
1354 [webview setPolicyDelegate:indirect_];
1358 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite];
1359 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 12, indsize.width, indsize.height)];
1360 [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
1362 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
1363 [scroller_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
1365 /*UIWebView *test([[[UIWebView alloc] initWithFrame:[self bounds]] autorelease]);
1366 [test loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.saurik.com/"]]];
1367 [self addSubview:test];*/
1371 - (id) initWithBook:(RVBook *)book {
1372 return [self initWithBook:book forWidth:0];
1375 - (NSString *) stringByEvaluatingJavaScriptFromString:(NSString *)script {
1377 WebView *webview([webview_ webView]);
1378 NSString *string([webview stringByEvaluatingJavaScriptFromString:script]);
1383 - (void) callFunction:(WebScriptObject *)function {
1386 WebView *webview([webview_ webView]);
1387 WebFrame *frame([webview mainFrame]);
1389 id _private(MSHookIvar<id>(webview, "_private"));
1390 WebCore::Page *page(_private == nil ? NULL : MSHookIvar<WebCore::Page *>(_private, "page"));
1391 WebCore::Settings *settings(page == NULL ? NULL : page->settings());
1394 if (settings == NULL)
1397 no = settings->JavaScriptCanOpenWindowsAutomatically();
1398 settings->setJavaScriptCanOpenWindowsAutomatically(true);
1401 [delegate_ clearFirstResponder];
1402 JSObjectRef object([function JSObject]);
1403 JSGlobalContextRef context([frame globalContext]);
1404 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
1406 if (settings != NULL)
1407 settings->setJavaScriptCanOpenWindowsAutomatically(no);
1412 - (void) didCloseBook:(RVBook *)book {
1414 [self callFunction:closer_];
1417 - (void) __rightButtonClicked {
1422 - (void) _rightButtonClicked {
1424 if (function_ != nil)
1425 [self callFunction:function_];
1428 [self __rightButtonClicked];
1431 - (id) _rightButtonTitle {
1432 return CYLocalize("RELOAD");
1435 - (id) rightButtonTitle {
1436 return [self isLoading] ? @"" : button_ != nil ? button_ : [self _rightButtonTitle];
1439 - (UINavigationButtonStyle) rightButtonStyle {
1440 if (style_ == nil) normal:
1441 return UINavigationButtonStyleNormal;
1442 else if ([style_ isEqualToString:@"Normal"])
1443 return UINavigationButtonStyleNormal;
1444 else if ([style_ isEqualToString:@"Back"])
1445 return UINavigationButtonStyleBack;
1446 else if ([style_ isEqualToString:@"Highlighted"])
1447 return UINavigationButtonStyleHighlighted;
1448 else if ([style_ isEqualToString:@"Destructive"])
1449 return UINavigationButtonStyleDestructive;
1453 - (NSString *) title {
1454 return title_ == nil ? CYLocalize("LOADING") : title_;
1457 - (NSString *) backButtonTitle {
1458 return CYLocalize("BROWSER");
1461 - (void) setPageActive:(BOOL)active {
1463 [indicator_ removeFromSuperview];
1465 [[book_ navigationBar] addSubview:indicator_];
1468 - (void) resetViewAnimated:(BOOL)animated {
1471 - (void) setPushed:(bool)pushed {
1475 + (float) defaultWidth {