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 /* XXX: this should probably not use du */
244 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
249 _assert(close(fds[1]) != -1);
251 if (FILE *du = fdopen(fds[0], "r")) {
253 while (fgets(line, sizeof(line), du) != NULL) {
254 size_t length(strlen(line));
255 while (length != 0 && line[length - 1] == '\n')
256 line[--length] = '\0';
257 if (char *tab = strchr(line, '\t')) {
259 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
264 } else _assert(close(fds[0]));
268 if (waitpid(pid, &status, 0) == -1)
280 - (void) setAutoPopup:(BOOL)popup {
281 [indirect_ setAutoPopup:popup];
284 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
285 [indirect_ setButtonImage:button withStyle:style toFunction:function];
288 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
289 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
292 - (void) setSpecial:(id)function {
293 [indirect_ setSpecial:function];
296 - (void) setFinishHook:(id)function {
297 [indirect_ setFinishHook:function];
300 - (void) setPopupHook:(id)function {
301 [indirect_ setPopupHook:function];
304 - (void) setViewportWidth:(float)width {
305 [indirect_ setViewportWidth:width];
308 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
309 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
310 unsigned count([arguments count]);
312 for (unsigned i(0); i != count; ++i)
313 values[i] = [arguments objectAtIndex:i];
314 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
317 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
318 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
320 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
326 @implementation BrowserView
329 #include "Internals.h"
334 NSLog(@"[BrowserView dealloc]");
337 if (challenge_ != nil)
338 [challenge_ release];
342 WebView *webview = [webview_ webView];
343 [webview setFrameLoadDelegate:nil];
344 [webview setResourceLoadDelegate:nil];
345 [webview setUIDelegate:nil];
346 [webview setScriptDebugDelegate:nil];
347 [webview setPolicyDelegate:nil];
349 [webview setDownloadDelegate:nil];
351 /* XXX: these are set by UIWebDocumentView
352 [webview _setFormDelegate:nil];
353 [webview _setUIKitDelegate:nil];
354 [webview setEditingDelegate:nil];*/
356 /* XXX: no one sets this, ever
357 [webview setWebMailDelegate:nil];*/
359 [webview_ setDelegate:nil];
360 [webview_ setGestureDelegate:nil];
361 [webview_ setFormEditingDelegate:nil];
362 [webview_ setInteractionDelegate:nil];
364 [indirect_ setDelegate:nil];
366 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
371 [webview_ removeFromSuperview];
372 [Documents_ addObject:[webview_ autorelease]];
383 [scroller_ setDelegate:nil];
389 if (function_ != nil)
399 [indicator_ release];
407 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
408 [self loadRequest:[NSURLRequest
415 - (void) loadURL:(NSURL *)url {
416 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
419 - (NSMutableURLRequest *) _addHeadersToRequest:(NSURLRequest *)request {
420 NSMutableURLRequest *copy = [request mutableCopy];
422 if (Machine_ != NULL)
423 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
424 if (UniqueID_ != nil)
425 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
428 [copy setValue:Role_ forHTTPHeaderField:@"X-Role"];
433 - (void) loadRequest:(NSURLRequest *)request {
438 [webview_ loadRequest:request];
446 if ([request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
447 [self loadRequest:request_];
449 UIActionSheet *sheet = [[[UIActionSheet alloc]
450 initWithTitle:CYLocalize("RESUBMIT_FORM")
451 buttons:[NSArray arrayWithObjects:CYLocalize("CANCEL"), CYLocalize("SUBMIT"), nil]
457 [sheet setNumberOfRows:1];
458 [sheet popupAlertAnimated:YES];
462 - (WebView *) webView {
463 return [webview_ webView];
466 - (UIWebDocumentView *) documentView {
470 /* XXX: WebThreadLock? */
471 - (void) _fixScroller:(CGRect)bounds {
476 UIFormAssistant *assistant([UIFormAssistant sharedFormAssistant]);
477 CGRect peripheral([assistant peripheralFrame]);
479 NSLog(@"per:%f", peripheral.size.height);
481 extra = peripheral.size.height;
484 CGRect subrect([scroller_ frame]);
485 subrect.size.height -= extra;
486 [scroller_ setScrollerIndicatorSubrect:subrect];
488 NSSize visible(NSMakeSize(subrect.size.width, subrect.size.height));
489 [webview_ setValue:[NSValue valueWithSize:visible] forGestureAttribute:UIGestureAttributeVisibleSize];
492 size.height += extra;
493 [scroller_ setContentSize:size];
495 [scroller_ releaseRubberBandIfNecessary];
498 - (void) fixScroller {
499 CGRect bounds([webview_ documentBounds]);
501 NSLog(@"_fs:(%f,%f+%f,%f)", bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
503 [self _fixScroller:bounds];
506 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
509 NSLog(@"dsf:(%f,%f+%f,%f)", frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
511 [self _fixScroller:frame];
514 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
515 [self view:sender didSetFrame:frame];
518 - (void) pushPage:(RVPage *)page {
519 [page setDelegate:delegate_];
520 [self setBackButtonTitle:title_];
521 [book_ pushPage:page];
527 // WTR: [self autorelease];
529 [book_ pushPage:self];
532 - (void) swapPage:(RVPage *)page {
533 [page setDelegate:delegate_];
535 [book_ swapPage:page];
537 [book_ pushPage:page];
540 - (BOOL) getSpecial:(NSURL *)url swap:(BOOL)swap {
542 NSLog(@"getSpecial:%@", url);
545 NSString *href([url absoluteString]);
546 NSString *scheme([[url scheme] lowercaseString]);
550 if ([href hasPrefix:@"apptapp://package/"])
551 page = [delegate_ pageForPackage:[href substringFromIndex:18]];
552 else if ([scheme isEqualToString:@"cydia"]) {
553 page = [delegate_ pageForURL:url hasTag:NULL];
556 } else if (![scheme isEqualToString:@"apptapp"])
561 [self swapPage:page];
563 [self pushPage:page];
567 - (void) webViewShow:(WebView *)sender {
568 /* XXX: this is where I cry myself to sleep */
571 - (bool) _allowJavaScriptPanel {
575 - (void) webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
576 if (![self _allowJavaScriptPanel])
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])
597 UIActionSheet *sheet = [[[UIActionSheet alloc]
599 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), CYLocalize("Cancel"), nil]
605 [sheet setNumberOfRows:1];
606 [sheet setBodyText:message];
607 [sheet popupAlertAnimated:YES];
609 NSRunLoop *loop([NSRunLoop currentRunLoop]);
610 NSDate *future([NSDate distantFuture]);
612 while (confirm_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
614 NSNumber *confirm([confirm_ autorelease]);
618 return [confirm boolValue];
621 - (void) setAutoPopup:(BOOL)popup {
625 - (void) setSpecial:(id)function {
627 [special_ autorelease];
628 special_ = function == nil ? nil : [function retain];
631 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
633 [button_ autorelease];
634 button_ = button == nil ? nil : [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:button]]] retain];
637 [style_ autorelease];
638 style_ = style == nil ? nil : [style retain];
640 if (function_ != nil)
641 [function_ autorelease];
642 function_ = function == nil ? nil : [function retain];
644 [self reloadButtons];
647 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
649 [button_ autorelease];
650 button_ = button == nil ? nil : [button retain];
653 [style_ autorelease];
654 style_ = style == nil ? nil : [style retain];
656 if (function_ != nil)
657 [function_ autorelease];
658 function_ = function == nil ? nil : [function retain];
660 [self reloadButtons];
663 - (void) setFinishHook:(id)function {
665 [finish_ autorelease];
666 finish_ = function == nil ? nil : [function retain];
669 - (void) setPopupHook:(id)function {
671 [closer_ autorelease];
672 closer_ = function == nil ? nil : [function retain];
675 - (void) webView:(WebView *)sender willBeginEditingFormElement:(id)element {
679 - (void) webView:(WebView *)sender didBeginEditingFormElement:(id)element {
683 - (void) webViewDidEndEditingFormElements:(WebView *)sender {
688 - (void) webViewClose:(WebView *)sender {
696 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
697 [window setValue:cydia_ forKey:@"cydia"];
700 - (void) webView:(WebView *)sender unableToImplementPolicyWithError:(NSError *)error frame:(WebFrame *)frame {
701 NSLog(@"err:%@", error);
704 - (void) webView:(WebView *)sender decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
706 NSLog(@"nwa:%@", name);
709 if (NSURL *url = [request URL]) {
710 if (name == nil) unknown: {
711 if (![self getSpecial:url swap:NO]) {
712 NSString *scheme([[url scheme] lowercaseString]);
713 if ([scheme isEqualToString:@"mailto"])
714 [delegate_ openMailToURL:url];
717 } else if ([name isEqualToString:@"_open"])
718 [delegate_ openURL:url];
719 else if ([name isEqualToString:@"_popup"]) {
720 NSString *scheme([[url scheme] lowercaseString]);
721 if ([scheme isEqualToString:@"mailto"])
722 [delegate_ openMailToURL:url];
724 RVBook *book([[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
725 [book setHook:indirect_];
727 RVPage *page([delegate_ pageForURL:url hasTag:NULL]);
729 /* XXX: call createWebViewWithRequest instead? */
731 [self setBackButtonTitle:title_];
733 BrowserView *browser([[[BrowserView alloc] initWithBook:book] autorelease]);
734 [browser loadURL:url];
738 [book setDelegate:delegate_];
739 [page setDelegate:delegate_];
742 [book_ pushBook:book];
751 - (void) webView:(WebView *)sender decidePolicyForMIMEType:(NSString *)type request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
752 if ([WebView canShowMIMEType:type])
755 // XXX: handle more mime types!
758 WebView *webview([webview_ webView]);
759 if (frame == [webview mainFrame])
760 [UIApp openURL:[request URL]];
764 - (void) webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
765 if (request == nil) ignore: {
770 NSURL *url([request URL]);
772 if (url == nil) use: {
773 if (!error_ && [frame parentFrame] == nil) {
775 [request_ autorelease];
776 request_ = [request retain];
778 NSLog(@"dpn:%@", request_);
784 WebView *webview([webview_ webView]);
785 if (frame == [webview mainFrame])
790 else NSLog(@"nav:%@:%@", url, [action description]);
793 const NSArray *capability;
795 #if 0 // XXX:3:GSSystemCopyCapability
796 capability = reinterpret_cast<const NSArray *>(GSSystemGetCapability(kGSDisplayIdentifiersCapability));
801 if (capability != nil && (
802 [capability containsObject:@"com.apple.Maps"] && [url mapsURL] ||
803 [capability containsObject:@"com.apple.youtube"] && [url youTubeURL]
810 int store(_not(int));
811 if (NSURL *itms = [url itmsURL:&store]) {
813 NSLog(@"itms#%@#%u#%@", url, store, itms);
816 if (capability != nil && (
817 store == 1 && [capability containsObject:@"com.apple.MobileStore"] ||
818 store == 2 && [capability containsObject:@"com.apple.AppStore"]
825 NSString *scheme([[url scheme] lowercaseString]);
827 if ([scheme isEqualToString:@"tel"]) {
832 if ([scheme isEqualToString:@"mailto"]) {
833 [delegate_ openMailToURL:url];
837 if ([self getSpecial:url swap:YES])
839 else if ([WebView _canHandleRequest:request])
841 else if ([url isSpringboardHandledURL])
847 - (void) webView:(WebView *)sender setStatusText:(NSString *)text {
848 //lprintf("Status:%s\n", [text UTF8String]);
851 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
852 NSString *context([sheet context]);
854 if ([context isEqualToString:@"alert"]) {
857 } else if ([context isEqualToString:@"confirm"]) {
860 confirm_ = [NSNumber numberWithBool:YES];
864 confirm_ = [NSNumber numberWithBool:NO];
869 } else if ([context isEqualToString:@"challenge"]) {
870 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
874 NSString *username([[sheet textFieldAtIndex:0] text]);
875 NSString *password([[sheet textFieldAtIndex:1] text]);
877 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
879 [sender useCredential:credential forAuthenticationChallenge:challenge_];
883 [sender cancelAuthenticationChallenge:challenge_];
890 [challenge_ release];
894 } else if ([context isEqualToString:@"submit"]) {
900 if (request_ != nil) {
902 [webview_ loadRequest:request_];
915 - (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
916 challenge_ = [challenge retain];
918 NSURLProtectionSpace *space([challenge protectionSpace]);
919 NSString *realm([space realm]);
923 UIActionSheet *sheet = [[[UIActionSheet alloc]
925 buttons:[NSArray arrayWithObjects:CYLocalize("LOGIN"), CYLocalize("CANCEL"), nil]
931 [sheet setNumberOfRows:1];
933 [sheet addTextFieldWithValue:@"" label:CYLocalize("USERNAME")];
934 [sheet addTextFieldWithValue:@"" label:CYLocalize("PASSWORD")];
936 UITextField *username([sheet textFieldAtIndex:0]); {
937 UITextInputTraits *traits([username textInputTraits]);
938 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
939 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
940 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
941 [traits setReturnKeyType:UIReturnKeyNext];
944 UITextField *password([sheet textFieldAtIndex:1]); {
945 UITextInputTraits *traits([password textInputTraits]);
946 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
947 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
948 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
949 // XXX: UIReturnKeyDone
950 [traits setReturnKeyType:UIReturnKeyNext];
951 [traits setSecureTextEntry:YES];
954 [sheet popupAlertAnimated:YES];
957 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
958 return [self _addHeadersToRequest:request];
961 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request windowFeatures:(NSDictionary *)features {
962 //- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request userGesture:(BOOL)gesture {
964 NSLog(@"cwv:%@ (%@): %@", request, title_, features == nil ? @"{}" : [features description]);
965 //NSLog(@"cwv:%@ (%@): %@", request, title_, gesture ? @"Yes" : @"No");
968 NSNumber *value([features objectForKey:@"width"]);
969 float width(value == nil ? 0 : [value floatValue]);
971 RVBook *book(!popup_ ? book_ : [[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
973 /* XXX: deal with cydia:// pages */
974 BrowserView *browser([[[BrowserView alloc] initWithBook:book forWidth:width] autorelease]);
976 if (features != nil && popup_) {
977 [book setDelegate:delegate_];
978 [book setHook:indirect_];
979 [browser setDelegate:delegate_];
981 [browser loadRequest:request];
983 [book setPage:browser];
984 [book_ pushBook:book];
985 } else if (request == nil) {
986 [self setBackButtonTitle:title_];
987 [browser setDelegate:delegate_];
990 [self pushPage:browser];
991 [browser loadRequest:request];
994 return [browser webView];
997 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
998 return [self webView:sender createWebViewWithRequest:request windowFeatures:nil];
999 //return [self webView:sender createWebViewWithRequest:request userGesture:YES];
1002 - (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
1003 if ([frame parentFrame] != nil)
1006 title_ = [title retain];
1007 [book_ reloadTitleForPage:self];
1010 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
1011 if ([loading_ count] == 0)
1013 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
1015 if ([frame parentFrame] == nil) {
1016 [webview_ resignFirstResponder];
1020 if (title_ != nil) {
1025 if (button_ != nil) {
1030 if (style_ != nil) {
1035 if (function_ != nil) {
1036 [function_ release];
1040 if (finish_ != nil) {
1045 if (closer_ != nil) {
1050 if (special_ != nil) {
1055 [book_ reloadTitleForPage:self];
1057 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
1059 if ([scroller_ respondsToSelector:@selector(setZoomScale:duration:)])
1060 [scroller_ setZoomScale:1 duration:0];
1062 [scroller_ setZoomScale:1 animated:NO];
1064 CGRect webrect = [scroller_ bounds];
1065 webrect.size.height = 0;
1066 [webview_ setFrame:webrect];
1069 [self reloadButtons];
1072 - (void) _finishLoading {
1073 size_t count([loading_ count]);
1076 if (reloading_ || count != 0)
1079 [self callFunction:finish_];
1080 [self reloadButtons];
1083 - (bool) isLoading {
1084 return [loading_ count] != 0;
1087 - (void) reloadButtons {
1088 if ([self isLoading])
1089 [indicator_ startAnimation];
1091 [indicator_ stopAnimation];
1092 [super reloadButtons];
1095 - (BOOL) webView:(WebView *)sender shouldScrollToPoint:(struct CGPoint)point forFrame:(WebFrame *)frame {
1096 return [webview_ webView:sender shouldScrollToPoint:point forFrame:frame];
1099 - (void) webView:(WebView *)sender didReceiveViewportArguments:(id)arguments forFrame:(WebFrame *)frame {
1100 return [webview_ webView:sender didReceiveViewportArguments:arguments forFrame:frame];
1103 - (void) webView:(WebView *)sender needsScrollNotifications:(id)notifications forFrame:(WebFrame *)frame {
1104 return [webview_ webView:sender needsScrollNotifications:notifications forFrame:frame];
1107 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
1109 return [webview_ webView:sender didCommitLoadForFrame:frame];
1112 - (void) webView:(WebView *)sender didReceiveDocTypeForFrame:(WebFrame *)frame {
1113 return [webview_ webView:sender didReceiveDocTypeForFrame:frame];
1116 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
1117 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
1118 [self _finishLoading];
1120 if ([frame parentFrame] == nil) {
1121 if (DOMDocument *document = [frame DOMDocument])
1122 if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
1123 for (DOMHTMLBodyElement *body in bodies) {
1124 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
1126 bool colored(false);
1128 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
1129 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
1130 DOMRGBColor *rgb([color getRGBColorValue]);
1132 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
1133 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
1134 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
1135 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
1139 if (red == 0xc7 && green == 0xce && blue == 0xd5)
1140 uic = [UIColor pinStripeColor];
1141 else if (alpha != 0)
1143 colorWithRed:(red / 255)
1151 [scroller_ setBackgroundColor:uic];
1157 [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
1162 return [webview_ webView:sender didFinishLoadForFrame:frame];
1165 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
1166 if ([frame parentFrame] == nil)
1169 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
1170 [self _finishLoading];
1175 if ([frame parentFrame] == nil) {
1176 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
1177 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
1178 [[error localizedDescription] stringByAddingPercentEscapes]
1185 - (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
1186 [self _didFailWithError:error forFrame:frame];
1189 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
1190 [self _didFailWithError:error forFrame:frame];
1193 - (void) webView:(WebView *)sender addMessageToConsole:(NSDictionary *)dictionary {
1194 #if LogBrowser || ForSaurik
1195 lprintf("Console:%s\n", [[dictionary description] UTF8String]);
1199 /* XXX: fix this stupid include file
1200 - (void) webView:(WebView *)sender frame:(WebFrame *)frame exceededDatabaseQuotaForSecurityOrigin:(WebSecurityOrigin *)origin database:(NSString *)database {
1201 [origin setQuota:0x500000];
1204 - (void) _setTileDrawingEnabled:(BOOL)enabled {
1205 //[webview_ setTileDrawingEnabled:enabled];
1208 - (void) setViewportWidth:(float)width {
1209 width_ = width ? width != 0 : [[self class] defaultWidth];
1210 [webview_ setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
1213 - (void) willStartGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
1214 [self _setTileDrawingEnabled:NO];
1217 - (void) didFinishGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
1218 [self _setTileDrawingEnabled:YES];
1219 [webview_ redrawScaledDocument];
1222 - (void) scrollerWillStartDragging:(UIScroller *)scroller {
1223 [self _setTileDrawingEnabled:NO];
1226 - (void) scrollerDidEndDragging:(UIScroller *)scroller willSmoothScroll:(BOOL)smooth {
1227 [self _setTileDrawingEnabled:YES];
1230 - (void) scrollerDidEndDragging:(UIScroller *)scroller {
1231 [self _setTileDrawingEnabled:YES];
1234 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
1235 if ((self = [super initWithBook:book]) != nil) {
1236 loading_ = [[NSMutableSet alloc] initWithCapacity:3];
1239 struct CGRect bounds = [self bounds];
1241 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
1242 [self addSubview:scroller_];
1244 [scroller_ setFixedBackgroundPattern:YES];
1245 [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
1247 [scroller_ setScrollingEnabled:YES];
1248 [scroller_ setClipsSubviews:YES];
1249 [scroller_ setAllowsRubberBanding:YES];
1251 [scroller_ setDelegate:self];
1252 [scroller_ setBounces:YES];
1253 [scroller_ setScrollHysteresis:8];
1254 [scroller_ setThumbDetectionEnabled:NO];
1255 [scroller_ setDirectionalScrolling:YES];
1256 [scroller_ setScrollDecelerationFactor:0.99]; /* 0.989324 */
1257 [scroller_ setEventMode:YES];
1258 [scroller_ setShowBackgroundShadow:NO]; /* YES */
1259 [scroller_ setAllowsRubberBanding:YES]; /* Vertical */
1260 [scroller_ setAdjustForContentSizeChange:YES]; /* NO */
1262 CGRect webrect = [scroller_ bounds];
1263 webrect.size.height = 0;
1270 webview_ = [Documents_ lastObject];
1271 if (webview_ != nil) {
1272 webview_ = [webview_ retain];
1273 webview = [webview_ webView];
1274 [Documents_ removeLastObject];
1275 [webview_ setFrame:webrect];
1280 webview_ = [[UIWebDocumentView alloc] initWithFrame:webrect];
1281 webview = [webview_ webView];
1283 // XXX: this is terribly (too?) expensive
1284 //[webview_ setDrawsBackground:NO];
1285 [webview setPreferencesIdentifier:@"Cydia"];
1287 [webview_ setTileSize:CGSizeMake(webrect.size.width, 500)];
1289 [webview_ setAllowsMessaging:YES];
1291 [webview_ setTilingEnabled:YES];
1292 [webview_ setDrawsGrid:NO];
1293 [webview_ setLogsTilingChanges:NO];
1294 [webview_ setTileMinificationFilter:kCAFilterNearest];
1295 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
1296 /* XXX: abstractify */
1297 [webview_ setDataDetectorTypes:0x80000000];
1299 [webview_ setDetectsPhoneNumbers:NO];
1300 [webview_ setAutoresizes:YES];
1302 [webview_ setMinimumScale:0.25f forDocumentTypes:0x10];
1303 [webview_ setMaximumScale:5.00f forDocumentTypes:0x10];
1304 [webview_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x10];
1305 //[webview_ setViewportSize:CGSizeMake(980, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
1307 [webview_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x2];
1309 [webview_ setMinimumScale:1.00f forDocumentTypes:0x8];
1310 [webview_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x8];
1311 [webview_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x8];
1313 [webview_ _setDocumentType:0x4];
1315 if ([webview_ respondsToSelector:@selector(UIWebDocumentView:)])
1316 [webview_ setZoomsFocusedFormControl:YES];
1317 [webview_ setContentsPosition:7];
1318 [webview_ setEnabledGestures:0xa];
1319 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeIsZoomRubberBandEnabled];
1320 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeUpdatesScroller];
1322 [webview_ setSmoothsFonts:YES];
1323 [webview_ setAllowsImageSheet:YES];
1324 [webview _setUsesLoaderCache:YES];
1326 [webview setGroupName:@"CydiaGroup"];
1327 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
1328 [webview _setLayoutInterval:0];
1331 [self setViewportWidth:width];
1333 [webview_ setDelegate:self];
1334 [webview_ setGestureDelegate:self];
1335 [webview_ setFormEditingDelegate:self];
1336 [webview_ setInteractionDelegate:self];
1338 [scroller_ addSubview:webview_];
1340 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
1342 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
1343 NSString *application = package == nil ? @"Cydia" : [NSString
1344 stringWithFormat:@"Cydia/%@",
1348 if (Product_ != nil)
1349 application = [NSString stringWithFormat:@"%@ Version/%@", application, Product_];
1351 application = [NSString stringWithFormat:@"%@ Mobile/%@", application, Build_];
1353 application = [NSString stringWithFormat:@"%@ Safari/%@", application, Safari_];
1355 [webview setApplicationNameForUserAgent:application];
1357 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
1358 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
1360 [webview setFrameLoadDelegate:indirect_];
1361 [webview setResourceLoadDelegate:indirect_];
1362 [webview setUIDelegate:indirect_];
1363 [webview setScriptDebugDelegate:indirect_];
1364 [webview setPolicyDelegate:indirect_];
1368 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite];
1369 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 12, indsize.width, indsize.height)];
1370 [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
1372 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
1373 [scroller_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
1375 /*UIWebView *test([[[UIWebView alloc] initWithFrame:[self bounds]] autorelease]);
1376 [test loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.saurik.com/"]]];
1377 [self addSubview:test];*/
1381 - (id) initWithBook:(RVBook *)book {
1382 return [self initWithBook:book forWidth:0];
1385 - (NSString *) stringByEvaluatingJavaScriptFromString:(NSString *)script {
1387 WebView *webview([webview_ webView]);
1388 NSString *string([webview stringByEvaluatingJavaScriptFromString:script]);
1393 - (void) callFunction:(WebScriptObject *)function {
1396 WebView *webview([webview_ webView]);
1397 WebFrame *frame([webview mainFrame]);
1399 id _private(MSHookIvar<id>(webview, "_private"));
1400 WebCore::Page *page(_private == nil ? NULL : MSHookIvar<WebCore::Page *>(_private, "page"));
1401 WebCore::Settings *settings(page == NULL ? NULL : page->settings());
1404 if (settings == NULL)
1407 no = settings->JavaScriptCanOpenWindowsAutomatically();
1408 settings->setJavaScriptCanOpenWindowsAutomatically(true);
1411 [delegate_ clearFirstResponder];
1412 JSObjectRef object([function JSObject]);
1413 JSGlobalContextRef context([frame globalContext]);
1414 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
1416 if (settings != NULL)
1417 settings->setJavaScriptCanOpenWindowsAutomatically(no);
1422 - (void) didCloseBook:(RVBook *)book {
1424 [self callFunction:closer_];
1427 - (void) __rightButtonClicked {
1432 - (void) _rightButtonClicked {
1434 if (function_ != nil)
1435 [self callFunction:function_];
1438 [self __rightButtonClicked];
1441 - (id) _rightButtonTitle {
1442 return CYLocalize("RELOAD");
1445 - (id) rightButtonTitle {
1446 return [self isLoading] ? @"" : button_ != nil ? button_ : [self _rightButtonTitle];
1449 - (UINavigationButtonStyle) rightButtonStyle {
1450 if (style_ == nil) normal:
1451 return UINavigationButtonStyleNormal;
1452 else if ([style_ isEqualToString:@"Normal"])
1453 return UINavigationButtonStyleNormal;
1454 else if ([style_ isEqualToString:@"Back"])
1455 return UINavigationButtonStyleBack;
1456 else if ([style_ isEqualToString:@"Highlighted"])
1457 return UINavigationButtonStyleHighlighted;
1458 else if ([style_ isEqualToString:@"Destructive"])
1459 return UINavigationButtonStyleDestructive;
1463 - (NSString *) title {
1464 return title_ == nil ? CYLocalize("LOADING") : title_;
1467 - (NSString *) backButtonTitle {
1468 return CYLocalize("BROWSER");
1471 - (void) setPageActive:(BOOL)active {
1473 [indicator_ removeFromSuperview];
1475 [[book_ navigationBar] addSubview:indicator_];
1478 - (void) resetViewAnimated:(BOOL)animated {
1481 - (void) setPushed:(bool)pushed {
1485 + (float) defaultWidth {