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 description]);
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])
579 UIActionSheet *sheet = [[[UIActionSheet alloc]
581 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
587 [sheet setBodyText:message];
588 [sheet popupAlertAnimated:YES];
591 - (BOOL) webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
592 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]);
617 return [confirm boolValue];
620 - (void) setAutoPopup:(BOOL)popup {
624 - (void) setSpecial:(id)function {
626 [special_ autorelease];
627 special_ = function == nil ? nil : [function retain];
630 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
632 [button_ autorelease];
633 button_ = button == nil ? nil : [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:button]]] retain];
636 [style_ autorelease];
637 style_ = style == nil ? nil : [style retain];
639 if (function_ != nil)
640 [function_ autorelease];
641 function_ = function == nil ? nil : [function retain];
643 [self reloadButtons];
646 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
648 [button_ autorelease];
649 button_ = button == nil ? nil : [button retain];
652 [style_ autorelease];
653 style_ = style == nil ? nil : [style retain];
655 if (function_ != nil)
656 [function_ autorelease];
657 function_ = function == nil ? nil : [function retain];
659 [self reloadButtons];
662 - (void) setFinishHook:(id)function {
664 [finish_ autorelease];
665 finish_ = function == nil ? nil : [function retain];
668 - (void) setPopupHook:(id)function {
670 [closer_ autorelease];
671 closer_ = function == nil ? nil : [function retain];
674 - (void) webView:(WebView *)sender willBeginEditingFormElement:(id)element {
678 - (void) webView:(WebView *)sender didBeginEditingFormElement:(id)element {
682 - (void) webViewDidEndEditingFormElements:(WebView *)sender {
687 - (void) webViewClose:(WebView *)sender {
695 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
696 [window setValue:cydia_ forKey:@"cydia"];
699 - (void) webView:(WebView *)sender unableToImplementPolicyWithError:(NSError *)error frame:(WebFrame *)frame {
700 NSLog(@"err:%@", error);
703 - (void) webView:(WebView *)sender decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
705 NSLog(@"nwa:%@", name);
708 if (NSURL *url = [request URL]) {
709 if (name == nil) unknown: {
710 if (![self getSpecial:url swap:NO]) {
711 NSString *scheme([[url scheme] lowercaseString]);
712 if ([scheme isEqualToString:@"mailto"])
713 [delegate_ openMailToURL:url];
716 } else if ([name isEqualToString:@"_open"])
717 [delegate_ openURL:url];
718 else if ([name isEqualToString:@"_popup"]) {
719 NSString *scheme([[url scheme] lowercaseString]);
720 if ([scheme isEqualToString:@"mailto"])
721 [delegate_ openMailToURL:url];
723 RVBook *book([[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
724 [book setHook:indirect_];
726 RVPage *page([delegate_ pageForURL:url hasTag:NULL]);
728 /* XXX: call createWebViewWithRequest instead? */
730 [self setBackButtonTitle:title_];
732 BrowserView *browser([[[BrowserView alloc] initWithBook:book] autorelease]);
733 [browser loadURL:url];
737 [book setDelegate:delegate_];
738 [page setDelegate:delegate_];
741 [book_ pushBook:book];
750 - (void) webView:(WebView *)sender decidePolicyForMIMEType:(NSString *)type request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
751 if ([WebView canShowMIMEType:type])
754 // XXX: handle more mime types!
757 WebView *webview([webview_ webView]);
758 if (frame == [webview mainFrame])
759 [UIApp openURL:[request URL]];
763 - (void) webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
764 if (request == nil) ignore: {
769 NSURL *url([request URL]);
771 if (url == nil) use: {
772 if (!error_ && [frame parentFrame] == nil) {
774 [request_ autorelease];
775 request_ = [request retain];
777 NSLog(@"dpn:%@", request_);
783 WebView *webview([webview_ webView]);
784 if (frame == [webview mainFrame])
789 else NSLog(@"nav:%@:%@", url, [action description]);
792 const NSArray *capability;
794 #if 0 // XXX:3:GSSystemCopyCapability
795 capability = reinterpret_cast<const NSArray *>(GSSystemGetCapability(kGSDisplayIdentifiersCapability));
800 if (capability != nil && (
801 [capability containsObject:@"com.apple.Maps"] && [url mapsURL] ||
802 [capability containsObject:@"com.apple.youtube"] && [url youTubeURL]
809 int store(_not(int));
810 if (NSURL *itms = [url itmsURL:&store]) {
812 NSLog(@"itms#%@#%u#%@", url, store, itms);
815 if (capability != nil && (
816 store == 1 && [capability containsObject:@"com.apple.MobileStore"] ||
817 store == 2 && [capability containsObject:@"com.apple.AppStore"]
824 NSString *scheme([[url scheme] lowercaseString]);
826 if ([scheme isEqualToString:@"tel"]) {
831 if ([scheme isEqualToString:@"mailto"]) {
832 [delegate_ openMailToURL:url];
836 if ([self getSpecial:url swap:YES])
838 else if ([WebView _canHandleRequest:request])
840 else if ([url isSpringboardHandledURL])
846 - (void) webView:(WebView *)sender setStatusText:(NSString *)text {
847 //lprintf("Status:%s\n", [text UTF8String]);
850 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
851 NSString *context([sheet context]);
853 if ([context isEqualToString:@"alert"]) {
856 } else if ([context isEqualToString:@"confirm"]) {
859 confirm_ = [NSNumber numberWithBool:YES];
863 confirm_ = [NSNumber numberWithBool:NO];
868 } else if ([context isEqualToString:@"challenge"]) {
869 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
873 NSString *username([[sheet textFieldAtIndex:0] text]);
874 NSString *password([[sheet textFieldAtIndex:1] text]);
876 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
878 [sender useCredential:credential forAuthenticationChallenge:challenge_];
882 [sender cancelAuthenticationChallenge:challenge_];
889 [challenge_ release];
893 } else if ([context isEqualToString:@"submit"]) {
899 if (request_ != nil) {
901 [webview_ loadRequest:request_];
914 - (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
915 challenge_ = [challenge retain];
917 NSURLProtectionSpace *space([challenge protectionSpace]);
918 NSString *realm([space realm]);
922 UIActionSheet *sheet = [[[UIActionSheet alloc]
924 buttons:[NSArray arrayWithObjects:CYLocalize("LOGIN"), CYLocalize("CANCEL"), nil]
930 [sheet setNumberOfRows:1];
932 [sheet addTextFieldWithValue:@"" label:CYLocalize("USERNAME")];
933 [sheet addTextFieldWithValue:@"" label:CYLocalize("PASSWORD")];
935 UITextField *username([sheet textFieldAtIndex:0]); {
936 UITextInputTraits *traits([username textInputTraits]);
937 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
938 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
939 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
940 [traits setReturnKeyType:UIReturnKeyNext];
943 UITextField *password([sheet textFieldAtIndex:1]); {
944 UITextInputTraits *traits([password textInputTraits]);
945 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
946 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
947 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
948 // XXX: UIReturnKeyDone
949 [traits setReturnKeyType:UIReturnKeyNext];
950 [traits setSecureTextEntry:YES];
953 [sheet popupAlertAnimated:YES];
956 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
957 return [self _addHeadersToRequest:request];
960 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request windowFeatures:(NSDictionary *)features {
961 //- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request userGesture:(BOOL)gesture {
963 NSLog(@"cwv:%@ (%@): %@", request, title_, features == nil ? @"{}" : [features description]);
964 //NSLog(@"cwv:%@ (%@): %@", request, title_, gesture ? @"Yes" : @"No");
967 NSNumber *value([features objectForKey:@"width"]);
968 float width(value == nil ? 0 : [value floatValue]);
970 RVBook *book(!popup_ ? book_ : [[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
972 /* XXX: deal with cydia:// pages */
973 BrowserView *browser([[[BrowserView alloc] initWithBook:book forWidth:width] autorelease]);
975 if (features != nil && popup_) {
976 [book setDelegate:delegate_];
977 [book setHook:indirect_];
978 [browser setDelegate:delegate_];
980 [browser loadRequest:request];
982 [book setPage:browser];
983 [book_ pushBook:book];
984 } else if (request == nil) {
985 [self setBackButtonTitle:title_];
986 [browser setDelegate:delegate_];
989 [self pushPage:browser];
990 [browser loadRequest:request];
993 return [browser webView];
996 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
997 return [self webView:sender createWebViewWithRequest:request windowFeatures:nil];
998 //return [self webView:sender createWebViewWithRequest:request userGesture:YES];
1001 - (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
1002 if ([frame parentFrame] != nil)
1005 title_ = [title retain];
1006 [book_ reloadTitleForPage:self];
1009 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
1010 if ([loading_ count] == 0)
1012 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
1014 if ([frame parentFrame] == nil) {
1015 [webview_ resignFirstResponder];
1019 if (title_ != nil) {
1024 if (button_ != nil) {
1029 if (style_ != nil) {
1034 if (function_ != nil) {
1035 [function_ release];
1039 if (finish_ != nil) {
1044 if (closer_ != nil) {
1049 if (special_ != nil) {
1054 [book_ reloadTitleForPage:self];
1056 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
1058 if ([scroller_ respondsToSelector:@selector(setZoomScale:duration:)])
1059 [scroller_ setZoomScale:1 duration:0];
1061 [scroller_ setZoomScale:1 animated:NO];
1063 CGRect webrect = [scroller_ bounds];
1064 webrect.size.height = 0;
1065 [webview_ setFrame:webrect];
1068 [self reloadButtons];
1071 - (void) _finishLoading {
1072 size_t count([loading_ count]);
1075 if (reloading_ || count != 0)
1078 [self callFunction:finish_];
1079 [self reloadButtons];
1082 - (bool) isLoading {
1083 return [loading_ count] != 0;
1086 - (void) reloadButtons {
1087 if ([self isLoading])
1088 [indicator_ startAnimation];
1090 [indicator_ stopAnimation];
1091 [super reloadButtons];
1094 - (BOOL) webView:(WebView *)sender shouldScrollToPoint:(struct CGPoint)point forFrame:(WebFrame *)frame {
1095 return [webview_ webView:sender shouldScrollToPoint:point forFrame:frame];
1098 - (void) webView:(WebView *)sender didReceiveViewportArguments:(id)arguments forFrame:(WebFrame *)frame {
1099 return [webview_ webView:sender didReceiveViewportArguments:arguments forFrame:frame];
1102 - (void) webView:(WebView *)sender needsScrollNotifications:(id)notifications forFrame:(WebFrame *)frame {
1103 return [webview_ webView:sender needsScrollNotifications:notifications forFrame:frame];
1106 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
1108 return [webview_ webView:sender didCommitLoadForFrame:frame];
1111 - (void) webView:(WebView *)sender didReceiveDocTypeForFrame:(WebFrame *)frame {
1112 return [webview_ webView:sender didReceiveDocTypeForFrame:frame];
1115 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
1116 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
1117 [self _finishLoading];
1119 if ([frame parentFrame] == nil) {
1120 if (DOMDocument *document = [frame DOMDocument])
1121 if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
1122 for (DOMHTMLBodyElement *body in bodies) {
1123 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
1125 bool colored(false);
1127 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
1128 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
1129 DOMRGBColor *rgb([color getRGBColorValue]);
1131 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
1132 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
1133 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
1134 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
1138 if (red == 0xc7 && green == 0xce && blue == 0xd5)
1139 uic = [UIColor pinStripeColor];
1140 else if (alpha != 0)
1142 colorWithRed:(red / 255)
1150 [scroller_ setBackgroundColor:uic];
1156 [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
1161 return [webview_ webView:sender didFinishLoadForFrame:frame];
1164 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
1165 if ([frame parentFrame] == nil)
1168 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
1169 [self _finishLoading];
1174 if ([frame parentFrame] == nil) {
1175 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
1176 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
1177 [[error localizedDescription] stringByAddingPercentEscapes]
1184 - (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
1185 [self _didFailWithError:error forFrame:frame];
1188 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
1189 [self _didFailWithError:error forFrame:frame];
1192 - (void) webView:(WebView *)sender addMessageToConsole:(NSDictionary *)dictionary {
1193 #if LogBrowser || ForSaurik
1194 lprintf("Console:%s\n", [[dictionary description] UTF8String]);
1198 /* XXX: fix this stupid include file
1199 - (void) webView:(WebView *)sender frame:(WebFrame *)frame exceededDatabaseQuotaForSecurityOrigin:(WebSecurityOrigin *)origin database:(NSString *)database {
1200 [origin setQuota:0x500000];
1203 - (void) _setTileDrawingEnabled:(BOOL)enabled {
1204 //[webview_ setTileDrawingEnabled:enabled];
1207 - (void) setViewportWidth:(float)width {
1208 width_ = width ? width != 0 : [[self class] defaultWidth];
1209 [webview_ setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
1212 - (void) willStartGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
1213 [self _setTileDrawingEnabled:NO];
1216 - (void) didFinishGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
1217 [self _setTileDrawingEnabled:YES];
1218 [webview_ redrawScaledDocument];
1221 - (void) scrollerWillStartDragging:(UIScroller *)scroller {
1222 [self _setTileDrawingEnabled:NO];
1225 - (void) scrollerDidEndDragging:(UIScroller *)scroller willSmoothScroll:(BOOL)smooth {
1226 [self _setTileDrawingEnabled:YES];
1229 - (void) scrollerDidEndDragging:(UIScroller *)scroller {
1230 [self _setTileDrawingEnabled:YES];
1233 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
1234 if ((self = [super initWithBook:book]) != nil) {
1235 loading_ = [[NSMutableSet alloc] initWithCapacity:3];
1238 struct CGRect bounds = [self bounds];
1240 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
1241 [self addSubview:scroller_];
1243 [scroller_ setFixedBackgroundPattern:YES];
1244 [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
1246 [scroller_ setScrollingEnabled:YES];
1247 [scroller_ setClipsSubviews:YES];
1248 [scroller_ setAllowsRubberBanding:YES];
1250 [scroller_ setDelegate:self];
1251 [scroller_ setBounces:YES];
1252 [scroller_ setScrollHysteresis:8];
1253 [scroller_ setThumbDetectionEnabled:NO];
1254 [scroller_ setDirectionalScrolling:YES];
1255 [scroller_ setScrollDecelerationFactor:0.99]; /* 0.989324 */
1256 [scroller_ setEventMode:YES];
1257 [scroller_ setShowBackgroundShadow:NO]; /* YES */
1258 [scroller_ setAllowsRubberBanding:YES]; /* Vertical */
1259 [scroller_ setAdjustForContentSizeChange:YES]; /* NO */
1261 CGRect webrect = [scroller_ bounds];
1262 webrect.size.height = 0;
1269 webview_ = [Documents_ lastObject];
1270 if (webview_ != nil) {
1271 webview_ = [webview_ retain];
1272 webview = [webview_ webView];
1273 [Documents_ removeLastObject];
1274 [webview_ setFrame:webrect];
1279 webview_ = [[UIWebDocumentView alloc] initWithFrame:webrect];
1280 webview = [webview_ webView];
1282 // XXX: this is terribly (too?) expensive
1283 //[webview_ setDrawsBackground:NO];
1284 [webview setPreferencesIdentifier:@"Cydia"];
1286 [webview_ setTileSize:CGSizeMake(webrect.size.width, 500)];
1288 [webview_ setAllowsMessaging:YES];
1290 [webview_ setTilingEnabled:YES];
1291 [webview_ setDrawsGrid:NO];
1292 [webview_ setLogsTilingChanges:NO];
1293 [webview_ setTileMinificationFilter:kCAFilterNearest];
1294 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
1295 /* XXX: abstractify */
1296 [webview_ setDataDetectorTypes:0x80000000];
1298 [webview_ setDetectsPhoneNumbers:NO];
1299 [webview_ setAutoresizes:YES];
1301 [webview_ setMinimumScale:0.25f forDocumentTypes:0x10];
1302 [webview_ setMaximumScale:5.00f forDocumentTypes:0x10];
1303 [webview_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x10];
1304 //[webview_ setViewportSize:CGSizeMake(980, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
1306 [webview_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x2];
1308 [webview_ setMinimumScale:1.00f forDocumentTypes:0x8];
1309 [webview_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x8];
1310 [webview_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x8];
1312 [webview_ _setDocumentType:0x4];
1314 if ([webview_ respondsToSelector:@selector(UIWebDocumentView:)])
1315 [webview_ setZoomsFocusedFormControl:YES];
1316 [webview_ setContentsPosition:7];
1317 [webview_ setEnabledGestures:0xa];
1318 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeIsZoomRubberBandEnabled];
1319 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeUpdatesScroller];
1321 [webview_ setSmoothsFonts:YES];
1322 [webview_ setAllowsImageSheet:YES];
1323 [webview _setUsesLoaderCache:YES];
1325 [webview setGroupName:@"CydiaGroup"];
1326 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
1327 [webview _setLayoutInterval:0];
1330 [self setViewportWidth:width];
1332 [webview_ setDelegate:self];
1333 [webview_ setGestureDelegate:self];
1334 [webview_ setFormEditingDelegate:self];
1335 [webview_ setInteractionDelegate:self];
1337 [scroller_ addSubview:webview_];
1339 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
1341 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
1342 NSString *application = package == nil ? @"Cydia" : [NSString
1343 stringWithFormat:@"Cydia/%@",
1347 if (Product_ != nil)
1348 application = [NSString stringWithFormat:@"%@ Version/%@", application, Product_];
1350 application = [NSString stringWithFormat:@"%@ Mobile/%@", application, Build_];
1352 application = [NSString stringWithFormat:@"%@ Safari/%@", application, Safari_];
1354 [webview setApplicationNameForUserAgent:application];
1356 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
1357 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
1359 [webview setFrameLoadDelegate:indirect_];
1360 [webview setResourceLoadDelegate:indirect_];
1361 [webview setUIDelegate:indirect_];
1362 [webview setScriptDebugDelegate:indirect_];
1363 [webview setPolicyDelegate:indirect_];
1367 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite];
1368 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 12, indsize.width, indsize.height)];
1369 [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
1371 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
1372 [scroller_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
1374 /*UIWebView *test([[[UIWebView alloc] initWithFrame:[self bounds]] autorelease]);
1375 [test loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.saurik.com/"]]];
1376 [self addSubview:test];*/
1380 - (id) initWithBook:(RVBook *)book {
1381 return [self initWithBook:book forWidth:0];
1384 - (NSString *) stringByEvaluatingJavaScriptFromString:(NSString *)script {
1386 WebView *webview([webview_ webView]);
1387 NSString *string([webview stringByEvaluatingJavaScriptFromString:script]);
1392 - (void) callFunction:(WebScriptObject *)function {
1395 WebView *webview([webview_ webView]);
1396 WebFrame *frame([webview mainFrame]);
1398 id _private(MSHookIvar<id>(webview, "_private"));
1399 WebCore::Page *page(_private == nil ? NULL : MSHookIvar<WebCore::Page *>(_private, "page"));
1400 WebCore::Settings *settings(page == NULL ? NULL : page->settings());
1403 if (settings == NULL)
1406 no = settings->JavaScriptCanOpenWindowsAutomatically();
1407 settings->setJavaScriptCanOpenWindowsAutomatically(true);
1410 [delegate_ clearFirstResponder];
1411 JSObjectRef object([function JSObject]);
1412 JSGlobalContextRef context([frame globalContext]);
1413 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
1415 if (settings != NULL)
1416 settings->setJavaScriptCanOpenWindowsAutomatically(no);
1421 - (void) didCloseBook:(RVBook *)book {
1423 [self callFunction:closer_];
1426 - (void) __rightButtonClicked {
1431 - (void) _rightButtonClicked {
1433 if (function_ != nil)
1434 [self callFunction:function_];
1437 [self __rightButtonClicked];
1440 - (id) _rightButtonTitle {
1441 return CYLocalize("RELOAD");
1444 - (id) rightButtonTitle {
1445 return [self isLoading] ? @"" : button_ != nil ? button_ : [self _rightButtonTitle];
1448 - (UINavigationButtonStyle) rightButtonStyle {
1449 if (style_ == nil) normal:
1450 return UINavigationButtonStyleNormal;
1451 else if ([style_ isEqualToString:@"Normal"])
1452 return UINavigationButtonStyleNormal;
1453 else if ([style_ isEqualToString:@"Back"])
1454 return UINavigationButtonStyleBack;
1455 else if ([style_ isEqualToString:@"Highlighted"])
1456 return UINavigationButtonStyleHighlighted;
1457 else if ([style_ isEqualToString:@"Destructive"])
1458 return UINavigationButtonStyleDestructive;
1462 - (NSString *) title {
1463 return title_ == nil ? CYLocalize("LOADING") : title_;
1466 - (NSString *) backButtonTitle {
1467 return CYLocalize("BROWSER");
1470 - (void) setPageActive:(BOOL)active {
1472 [indicator_ removeFromSuperview];
1474 [[book_ navigationBar] addSubview:indicator_];
1477 - (void) resetViewAnimated:(BOOL)animated {
1480 - (void) setPushed:(bool)pushed {
1484 + (float) defaultWidth {