1 #include <UICaboodle/BrowserView.h>
2 #include <UICaboodle/UCLocalize.h>
4 #import <QuartzCore/CALayer.h>
5 // XXX: fix the minimum requirement
6 extern NSString * const kCAFilterNearest;
8 #include <WebCore/WebCoreThread.h>
9 #include <WebKit/WebPreferences-WebPrivate.h>
11 #include "substrate.h"
15 static CFArrayRef (*$GSSystemCopyCapability)(CFStringRef);
16 static CFArrayRef (*$GSSystemGetCapability)(CFStringRef);
18 @interface NSString (UIKit)
19 - (NSString *) stringByAddingPercentEscapes;
22 /* Indirect Delegate {{{ */
23 @interface IndirectDelegate : NSObject {
24 _transient volatile id delegate_;
27 - (void) setDelegate:(id)delegate;
28 - (id) initWithDelegate:(id)delegate;
31 @implementation IndirectDelegate
33 - (void) setDelegate:(id)delegate {
37 - (id) initWithDelegate:(id)delegate {
42 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
44 return [delegate_ webView:sender didClearWindowObject:window forFrame:frame];
47 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
49 return [delegate_ webView:sender didCommitLoadForFrame:frame];
52 - (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
54 return [delegate_ webView:sender didFailLoadWithError:error forFrame:frame];
57 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
59 return [delegate_ webView:sender didFailProvisionalLoadWithError:error forFrame:frame];
62 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
64 return [delegate_ webView:sender didFinishLoadForFrame:frame];
67 - (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
69 return [delegate_ webView:sender didReceiveTitle:title forFrame:frame];
72 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
74 return [delegate_ webView:sender didStartProvisionalLoadForFrame:frame];
77 - (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
79 return [delegate_ webView:sender resource:identifier didReceiveAuthenticationChallenge:challenge fromDataSource:source];
82 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
84 return [delegate_ webView:sender resource:identifier willSendRequest:request redirectResponse:redirectResponse fromDataSource:source];
88 - (IMP) methodForSelector:(SEL)sel {
89 if (IMP method = [super methodForSelector:sel])
91 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
95 - (BOOL) respondsToSelector:(SEL)sel {
96 if ([super respondsToSelector:sel])
98 // XXX: WebThreadCreateNSInvocation returns nil
99 //fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
100 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
103 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
104 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
106 //fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
107 if (delegate_ != nil)
108 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
110 // XXX: I fucking hate Apple so very very bad
111 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
114 - (void) forwardInvocation:(NSInvocation *)inv {
115 SEL sel = [inv selector];
116 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
117 [inv invokeWithTarget:delegate_];
123 @interface WebView (UICaboodle)
124 - (void) setScriptDebugDelegate:(id)delegate;
125 - (void) _setFormDelegate:(id)delegate;
126 - (void) _setUIKitDelegate:(id)delegate;
127 - (void) setWebMailDelegate:(id)delegate;
128 - (void) _setLayoutInterval:(float)interval;
131 @implementation WebScriptObject (UICaboodle)
134 id length([self valueForKey:@"length"]);
135 if ([length respondsToSelector:@selector(intValue)])
136 return [length intValue];
141 - (id) objectAtIndex:(unsigned)index {
142 return [self webScriptValueAtIndex:index];
148 /* Mail Composition {{{ */
149 @interface MailToView : PopUpView {
150 MailComposeController *controller_;
153 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
157 @implementation MailToView
160 [controller_ release];
164 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
168 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
169 NSLog(@"did:%@", delivery);
170 // [UIApp setStatusBarShowsProgress:NO];
171 if ([controller error]){
172 NSArray *buttons = [NSArray arrayWithObjects:UCLocalize("OK"), nil];
173 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:UCLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
174 [mailAlertSheet setBodyText:[controller error]];
175 [mailAlertSheet popupAlertAnimated:YES];
180 NSLog(@"%@", [controller_ error]);
181 NSArray *buttons = [NSArray arrayWithObjects:UCLocalize("OK"), nil];
182 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:UCLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
183 [mailAlertSheet setBodyText:[controller_ error]];
184 [mailAlertSheet popupAlertAnimated:YES];
187 - (void) deliverMessage { _pooled
191 if (![controller_ deliverMessage])
192 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
195 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
196 if ([controller_ needsDelivery])
197 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
202 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
203 if ((self = [super initWithView:view delegate:delegate]) != nil) {
204 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
205 [controller_ setDelegate:self];
206 [controller_ initializeUI];
207 [controller_ setupForURL:url];
209 UIView *view([controller_ view]);
210 [overlay_ addSubview:view];
218 #define ShowInternals 0
221 #define lprintf(args...) fprintf(stderr, args)
223 @implementation BrowserView
226 #include "UICaboodle/UCInternal.h"
229 + (void) _initialize {
230 [WebView enableWebThread];
232 WebPreferences *preferences([WebPreferences standardPreferences]);
233 [preferences setCacheModel:WebCacheModelDocumentBrowser];
234 [preferences setOfflineWebApplicationCacheEnabled:YES];
236 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
238 $GSSystemCopyCapability = reinterpret_cast<CFArrayRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
239 $GSSystemGetCapability = reinterpret_cast<CFArrayRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
244 NSLog(@"[BrowserView dealloc]");
247 if (challenge_ != nil)
248 [challenge_ release];
252 WebView *webview = [webview_ webView];
253 [webview setFrameLoadDelegate:nil];
254 [webview setResourceLoadDelegate:nil];
255 [webview setUIDelegate:nil];
256 [webview setScriptDebugDelegate:nil];
257 [webview setPolicyDelegate:nil];
259 /* XXX: these are set by UIWebDocumentView
260 [webview setDownloadDelegate:nil];
261 [webview _setFormDelegate:nil];
262 [webview _setUIKitDelegate:nil];
263 [webview setEditingDelegate:nil];*/
265 /* XXX: no one sets this, ever
266 [webview setWebMailDelegate:nil];*/
268 [webview_ setDelegate:nil];
269 [webview_ setGestureDelegate:nil];
270 [webview_ setFormEditingDelegate:nil];
271 [webview_ setInteractionDelegate:nil];
273 [indirect_ setDelegate:nil];
275 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
280 [webview_ removeFromSuperview];
281 [Documents_ addObject:[webview_ autorelease]];
290 [scroller_ setDelegate:nil];
296 if (function_ != nil)
306 [indicator_ release];
309 if (sensitive_ != nil)
310 [sensitive_ release];
316 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
317 [self loadRequest:[NSURLRequest
324 - (void) loadURL:(NSURL *)url {
325 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
328 - (void) loadRequest:(NSURLRequest *)request {
333 [webview_ loadRequest:request];
341 if ([request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
342 [self loadRequest:request_];
344 UIActionSheet *sheet = [[[UIActionSheet alloc]
345 initWithTitle:UCLocalize("RESUBMIT_FORM")
346 buttons:[NSArray arrayWithObjects:UCLocalize("CANCEL"), UCLocalize("SUBMIT"), nil]
352 [sheet setNumberOfRows:1];
353 [sheet popupAlertAnimated:YES];
357 - (WebView *) webView {
358 return [webview_ webView];
361 - (UIWebDocumentView *) documentView {
365 /* XXX: WebThreadLock? */
366 - (void) _fixScroller:(CGRect)bounds {
371 UIFormAssistant *assistant([UIFormAssistant sharedFormAssistant]);
372 CGRect peripheral([assistant peripheralFrame]);
374 NSLog(@"per:%f", peripheral.size.height);
376 extra = peripheral.size.height;
379 CGRect subrect([scroller_ frame]);
380 subrect.size.height -= extra;
381 [scroller_ setScrollerIndicatorSubrect:subrect];
383 NSSize visible(NSMakeSize(subrect.size.width, subrect.size.height));
384 [webview_ setValue:[NSValue valueWithSize:visible] forGestureAttribute:UIGestureAttributeVisibleSize];
387 size.height += extra;
388 [scroller_ setContentSize:size];
390 [scroller_ releaseRubberBandIfNecessary];
393 - (void) fixScroller {
394 CGRect bounds([webview_ documentBounds]);
396 NSLog(@"_fs:(%f,%f+%f,%f)", bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
398 [self _fixScroller:bounds];
401 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
404 NSLog(@"dsf:(%f,%f+%f,%f)", frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
406 [self _fixScroller:frame];
409 - (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
410 [self view:sender didSetFrame:frame];
413 - (void) pushPage:(RVPage *)page {
414 [page setDelegate:delegate_];
415 [self setBackButtonTitle:title_];
416 [book_ pushPage:page];
422 // WTR: [self autorelease];
424 [book_ pushPage:self];
427 - (void) swapPage:(RVPage *)page {
428 [page setDelegate:delegate_];
430 [book_ swapPage:page];
432 [book_ pushPage:page];
435 - (BOOL) getSpecial:(NSURL *)url swap:(BOOL)swap {
437 NSLog(@"getSpecial:%@", url);
440 if (RVPage *page = [delegate_ pageForURL:url hasTag:NULL]) {
442 [self swapPage:page];
444 [self pushPage:page];
451 - (void) formAssistant:(id)sender didBeginEditingFormNode:(id)node {
454 - (void) formAssistant:(id)sender didEndEditingFormNode:(id)node {
458 - (void) webViewShow:(WebView *)sender {
459 /* XXX: this is where I cry myself to sleep */
462 - (bool) _allowJavaScriptPanel {
466 - (bool) allowSensitiveRequests {
467 return [self _allowJavaScriptPanel];
470 - (void) _promptForSensitive:(NSMutableArray *)array {
471 NSString *name([array objectAtIndex:0]);
473 UIActionSheet *sheet = [[[UIActionSheet alloc]
475 buttons:[NSArray arrayWithObjects:UCLocalize("YES"), UCLocalize("NO"), nil]
481 NSString *host(@"XXX");
483 [sheet setNumberOfRows:1];
484 [sheet setBodyText:[NSString stringWithFormat:@"The website at %@ is requesting your phone's %@. This is almost certainly for product licensing purposes. Will you allow this?", host, name]];
485 [sheet popupAlertAnimated:YES];
487 NSRunLoop *loop([NSRunLoop currentRunLoop]);
488 NSDate *future([NSDate distantFuture]);
490 while (sensitive_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
492 NSNumber *sensitive([sensitive_ autorelease]);
496 [array replaceObjectAtIndex:0 withObject:sensitive];
499 - (bool) promptForSensitive:(NSString *)name {
500 if (![self allowSensitiveRequests])
503 NSMutableArray *array([NSMutableArray arrayWithCapacity:1]);
504 [array addObject:name];
506 [self performSelectorOnMainThread:@selector(_promptForSensitive:) withObject:array waitUntilDone:YES];
507 return [[array lastObject] boolValue];
510 - (void) webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
511 if (![self _allowJavaScriptPanel])
515 UIActionSheet *sheet = [[[UIActionSheet alloc]
517 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
523 [sheet setBodyText:message];
524 [sheet popupAlertAnimated:YES];
527 - (BOOL) webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
528 if (![self _allowJavaScriptPanel])
532 UIActionSheet *sheet = [[[UIActionSheet alloc]
534 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), UCLocalize("CANCEL"), nil]
540 [sheet setNumberOfRows:1];
541 [sheet setBodyText:message];
542 [sheet popupAlertAnimated:YES];
544 NSRunLoop *loop([NSRunLoop currentRunLoop]);
545 NSDate *future([NSDate distantFuture]);
547 while (confirm_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
549 NSNumber *confirm([confirm_ autorelease]);
553 return [confirm boolValue];
556 - (void) setAutoPopup:(BOOL)popup {
560 - (void) setSpecial:(id)function {
562 [special_ autorelease];
563 special_ = function == nil ? nil : [function retain];
566 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
568 [button_ autorelease];
569 button_ = button == nil ? nil : [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:button]]] retain];
572 [style_ autorelease];
573 style_ = style == nil ? nil : [style retain];
575 if (function_ != nil)
576 [function_ autorelease];
577 function_ = function == nil ? nil : [function retain];
579 [self reloadButtons];
582 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
584 [button_ autorelease];
585 button_ = button == nil ? nil : [button retain];
588 [style_ autorelease];
589 style_ = style == nil ? nil : [style retain];
591 if (function_ != nil)
592 [function_ autorelease];
593 function_ = function == nil ? nil : [function retain];
595 [self reloadButtons];
598 - (void) setFinishHook:(id)function {
600 [finish_ autorelease];
601 finish_ = function == nil ? nil : [function retain];
604 - (void) setPopupHook:(id)function {
606 [closer_ autorelease];
607 closer_ = function == nil ? nil : [function retain];
610 - (void) _openMailToURL:(NSURL *)url {
611 // XXX: this makes me sad
613 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
615 [UIApp openURL:url];// asPanel:YES];
619 - (void) webView:(WebView *)sender willBeginEditingFormElement:(id)element {
623 - (void) webView:(WebView *)sender didBeginEditingFormElement:(id)element {
627 - (void) webViewDidEndEditingFormElements:(WebView *)sender {
632 - (void) webViewClose:(WebView *)sender {
640 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
643 - (void) webView:(WebView *)sender unableToImplementPolicyWithError:(NSError *)error frame:(WebFrame *)frame {
644 NSLog(@"err:%@", error);
647 - (void) webView:(WebView *)sender decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
649 NSLog(@"nwa:%@", name);
652 if (NSURL *url = [request URL]) {
653 if (name == nil) unknown: {
654 if (![self getSpecial:url swap:NO]) {
655 NSString *scheme([[url scheme] lowercaseString]);
656 if ([scheme isEqualToString:@"mailto"])
657 [self _openMailToURL:url];
660 } else if ([name isEqualToString:@"_open"])
661 [delegate_ openURL:url];
662 else if ([name isEqualToString:@"_popup"]) {
663 NSString *scheme([[url scheme] lowercaseString]);
664 if ([scheme isEqualToString:@"mailto"])
665 [self _openMailToURL:url];
667 RVBook *book([[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
668 [book setHook:indirect_];
670 RVPage *page([delegate_ pageForURL:url hasTag:NULL]);
672 /* XXX: call createWebViewWithRequest instead? */
674 [self setBackButtonTitle:title_];
676 BrowserView *browser([[[class_ alloc] initWithBook:book] autorelease]);
677 [browser loadURL:url];
681 [book setDelegate:delegate_];
682 [page setDelegate:delegate_];
685 [book_ pushBook:book];
694 - (void) webView:(WebView *)sender decidePolicyForMIMEType:(NSString *)type request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
695 if ([WebView canShowMIMEType:type])
698 // XXX: handle more mime types!
701 WebView *webview([webview_ webView]);
702 if (frame == [webview mainFrame])
703 [UIApp openURL:[request URL]];
707 - (void) webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
708 if (request == nil) ignore: {
713 NSURL *url([request URL]);
714 NSString *host([url host]);
716 if (url == nil) use: {
717 if (!error_ && [frame parentFrame] == nil) {
719 [request_ autorelease];
720 request_ = [request retain];
722 NSLog(@"dpn:%@", request_);
728 WebView *webview([webview_ webView]);
729 if (frame == [webview mainFrame])
734 else NSLog(@"nav:%@:%@", url, [action description]);
737 const NSArray *capability;
739 if ($GSSystemCopyCapability != NULL) {
740 capability = reinterpret_cast<const NSArray *>((*$GSSystemCopyCapability)(kGSDisplayIdentifiersCapability));
741 capability = [capability autorelease];
742 } else if ($GSSystemGetCapability != NULL) {
743 capability = reinterpret_cast<const NSArray *>((*$GSSystemGetCapability)(kGSDisplayIdentifiersCapability));
749 if (capability != nil && (
750 [url isGoogleMapsURL] && [capability containsObject:@"com.apple.Maps"] && (open = [url mapsURL]) != nil||
751 [host hasSuffix:@"youtube.com"] && [capability containsObject:@"com.apple.youtube"] && (open = [url youTubeURL]) != nil ||
752 [url respondsToSelector:@selector(phobosURL)] && (open = [url phobosURL]) != nil
760 int store(_not(int));
761 if (NSURL *itms = [url itmsURL:&store]) {
763 NSLog(@"itms#%@#%u#%@", url, store, itms);
766 if (capability != nil && (
767 store == 1 && [capability containsObject:@"com.apple.MobileStore"] ||
768 store == 2 && [capability containsObject:@"com.apple.AppStore"]
775 NSString *scheme([[url scheme] lowercaseString]);
777 if ([scheme isEqualToString:@"tel"]) {
782 if ([scheme isEqualToString:@"mailto"]) {
783 [self _openMailToURL:url];
787 if ([self getSpecial:url swap:YES])
789 else if ([WebView _canHandleRequest:request])
791 else if ([url isSpringboardHandledURL])
797 - (void) webView:(WebView *)sender setStatusText:(NSString *)text {
798 //lprintf("Status:%s\n", [text UTF8String]);
801 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
802 NSString *context([sheet context]);
804 if ([context isEqualToString:@"alert"]) {
807 } else if ([context isEqualToString:@"confirm"]) {
810 confirm_ = [NSNumber numberWithBool:YES];
814 confirm_ = [NSNumber numberWithBool:NO];
819 } else if ([context isEqualToString:@"sensitive"]) {
822 sensitive_ = [NSNumber numberWithBool:YES];
826 sensitive_ = [NSNumber numberWithBool:NO];
831 } else if ([context isEqualToString:@"challenge"]) {
832 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
836 NSString *username([[sheet textFieldAtIndex:0] text]);
837 NSString *password([[sheet textFieldAtIndex:1] text]);
839 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
841 [sender useCredential:credential forAuthenticationChallenge:challenge_];
845 [sender cancelAuthenticationChallenge:challenge_];
852 [challenge_ release];
856 } else if ([context isEqualToString:@"submit"]) {
862 if (request_ != nil) {
864 [webview_ loadRequest:request_];
877 - (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
878 challenge_ = [challenge retain];
880 NSURLProtectionSpace *space([challenge protectionSpace]);
881 NSString *realm([space realm]);
885 UIActionSheet *sheet = [[[UIActionSheet alloc]
887 buttons:[NSArray arrayWithObjects:UCLocalize("LOGIN"), UCLocalize("CANCEL"), nil]
893 [sheet setNumberOfRows:1];
895 [sheet addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
896 [sheet addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
898 UITextField *username([sheet textFieldAtIndex:0]); {
899 UITextInputTraits *traits([username textInputTraits]);
900 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
901 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
902 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
903 [traits setReturnKeyType:UIReturnKeyNext];
906 UITextField *password([sheet textFieldAtIndex:1]); {
907 UITextInputTraits *traits([password textInputTraits]);
908 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
909 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
910 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
911 // XXX: UIReturnKeyDone
912 [traits setReturnKeyType:UIReturnKeyNext];
913 [traits setSecureTextEntry:YES];
916 [sheet popupAlertAnimated:YES];
919 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
923 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request windowFeatures:(NSDictionary *)features {
924 //- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request userGesture:(BOOL)gesture {
926 NSLog(@"cwv:%@ (%@): %@", request, title_, features == nil ? @"{}" : [features description]);
927 //NSLog(@"cwv:%@ (%@): %@", request, title_, gesture ? @"Yes" : @"No");
930 NSNumber *value([features objectForKey:@"width"]);
931 float width(value == nil ? 0 : [value floatValue]);
933 RVBook *book(!popup_ ? book_ : [[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
935 /* XXX: deal with cydia:// pages */
936 BrowserView *browser([[[class_ alloc] initWithBook:book forWidth:width] autorelease]);
938 if (features != nil && popup_) {
939 [book setDelegate:delegate_];
940 [book setHook:indirect_];
941 [browser setDelegate:delegate_];
943 [browser loadRequest:request];
945 [book setPage:browser];
946 [book_ pushBook:book];
947 } else if (request == nil) {
948 [self setBackButtonTitle:title_];
949 [browser setDelegate:delegate_];
952 [self pushPage:browser];
953 [browser loadRequest:request];
956 return [browser webView];
959 - (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
960 return [self webView:sender createWebViewWithRequest:request windowFeatures:nil];
961 //return [self webView:sender createWebViewWithRequest:request userGesture:YES];
964 - (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
965 if ([frame parentFrame] != nil)
968 title_ = [title retain];
969 [book_ reloadTitleForPage:self];
972 - (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
973 /*if ([loading_ count] == 0)
975 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
977 if ([frame parentFrame] == nil) {
978 [webview_ resignFirstResponder];
987 if (button_ != nil) {
997 if (function_ != nil) {
1002 if (finish_ != nil) {
1007 if (closer_ != nil) {
1012 if (special_ != nil) {
1017 [book_ reloadTitleForPage:self];
1019 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
1021 if ([scroller_ respondsToSelector:@selector(setZoomScale:duration:)])
1022 [scroller_ setZoomScale:1 duration:0];
1023 else if ([scroller_ respondsToSelector:@selector(_setZoomScale:duration:)])
1024 [scroller_ _setZoomScale:1 duration:0];
1025 /*else if ([scroller_ respondsToSelector:@selector(setZoomScale:animated:)])
1026 [scroller_ setZoomScale:1 animated:NO];*/
1028 CGRect webrect = [scroller_ bounds];
1029 webrect.size.height = 0;
1030 [webview_ setFrame:webrect];
1033 [self reloadButtons];
1036 - (void) _finishLoading {
1037 size_t count([loading_ count]);
1039 [self autorelease];*/
1040 if (reloading_ || count != 0)
1043 [self callFunction:finish_];
1044 [self reloadButtons];
1047 - (bool) isLoading {
1048 return [loading_ count] != 0;
1051 - (void) reloadButtons {
1052 if ([self isLoading])
1053 [indicator_ startAnimation];
1055 [indicator_ stopAnimation];
1056 [super reloadButtons];
1059 - (BOOL) webView:(WebView *)sender shouldScrollToPoint:(struct CGPoint)point forFrame:(WebFrame *)frame {
1060 return [webview_ webView:sender shouldScrollToPoint:point forFrame:frame];
1063 - (void) webView:(WebView *)sender didReceiveViewportArguments:(id)arguments forFrame:(WebFrame *)frame {
1064 return [webview_ webView:sender didReceiveViewportArguments:arguments forFrame:frame];
1067 - (void) webView:(WebView *)sender needsScrollNotifications:(id)notifications forFrame:(WebFrame *)frame {
1068 return [webview_ webView:sender needsScrollNotifications:notifications forFrame:frame];
1071 - (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
1073 return [webview_ webView:sender didCommitLoadForFrame:frame];
1076 - (void) webView:(WebView *)sender didReceiveDocTypeForFrame:(WebFrame *)frame {
1077 return [webview_ webView:sender didReceiveDocTypeForFrame:frame];
1080 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
1081 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
1082 [self _finishLoading];
1084 if ([frame parentFrame] == nil) {
1085 if (DOMDocument *document = [frame DOMDocument])
1086 if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
1087 for (DOMHTMLBodyElement *body in bodies) {
1088 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
1090 bool colored(false);
1092 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
1093 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
1094 DOMRGBColor *rgb([color getRGBColorValue]);
1096 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
1097 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
1098 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
1099 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
1103 if (red == 0xc7 && green == 0xce && blue == 0xd5)
1104 uic = [UIColor pinStripeColor];
1105 else if (alpha != 0)
1107 colorWithRed:(red / 255)
1115 [scroller_ setBackgroundColor:uic];
1121 [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
1126 return [webview_ webView:sender didFinishLoadForFrame:frame];
1129 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
1131 /*if ([frame parentFrame] == nil)
1132 [self autorelease];*/
1134 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
1135 [self _finishLoading];
1140 if ([frame parentFrame] == nil) {
1141 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
1142 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
1143 [[error localizedDescription] stringByAddingPercentEscapes]
1150 - (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
1151 [self _didFailWithError:error forFrame:frame];
1154 - (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
1155 [self _didFailWithError:error forFrame:frame];
1158 - (void) webView:(WebView *)sender addMessageToConsole:(NSDictionary *)dictionary {
1159 #if LogBrowser || ForSaurik
1160 lprintf("Console:%s\n", [[dictionary description] UTF8String]);
1164 /* XXX: fix this stupid include file
1165 - (void) webView:(WebView *)sender frame:(WebFrame *)frame exceededDatabaseQuotaForSecurityOrigin:(WebSecurityOrigin *)origin database:(NSString *)database {
1166 [origin setQuota:0x500000];
1169 - (void) _setTileDrawingEnabled:(BOOL)enabled {
1170 //[webview_ setTileDrawingEnabled:enabled];
1173 - (void) setViewportWidth:(float)width {
1174 width_ = width != 0 ? width : [[self class] defaultWidth];
1175 [webview_ setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
1178 - (void) willStartGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
1179 [self _setTileDrawingEnabled:NO];
1182 - (void) didFinishGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
1183 [self _setTileDrawingEnabled:YES];
1184 [webview_ redrawScaledDocument];
1187 - (void) scrollerWillStartDragging:(UIScroller *)scroller {
1188 [self _setTileDrawingEnabled:NO];
1191 - (void) scrollerDidEndDragging:(UIScroller *)scroller willSmoothScroll:(BOOL)smooth {
1192 [self _setTileDrawingEnabled:YES];
1195 - (void) scrollerDidEndDragging:(UIScroller *)scroller {
1196 [self _setTileDrawingEnabled:YES];
1199 - (id) initWithBook:(RVBook *)book forWidth:(float)width ofClass:(Class)_class {
1200 if ((self = [super initWithBook:book]) != nil) {
1202 loading_ = [[NSMutableSet alloc] initWithCapacity:3];
1205 struct CGRect bounds = [self bounds];
1207 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
1208 [self addSubview:scroller_];
1210 [scroller_ setFixedBackgroundPattern:YES];
1211 [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
1213 [scroller_ setScrollingEnabled:YES];
1214 [scroller_ setClipsSubviews:YES];
1215 [scroller_ setAllowsRubberBanding:YES];
1217 [scroller_ setDelegate:self];
1218 [scroller_ setBounces:YES];
1219 [scroller_ setScrollHysteresis:8];
1220 [scroller_ setThumbDetectionEnabled:NO];
1221 [scroller_ setDirectionalScrolling:YES];
1222 [scroller_ setScrollDecelerationFactor:0.99]; /* 0.989324 */
1223 [scroller_ setEventMode:YES];
1224 [scroller_ setShowBackgroundShadow:NO]; /* YES */
1225 [scroller_ setAllowsRubberBanding:YES]; /* Vertical */
1226 [scroller_ setAdjustForContentSizeChange:YES]; /* NO */
1228 CGRect webrect = [scroller_ bounds];
1229 webrect.size.height = 0;
1236 webview_ = [Documents_ lastObject];
1237 if (webview_ != nil) {
1238 webview_ = [webview_ retain];
1239 webview = [webview_ webView];
1240 [Documents_ removeLastObject];
1241 [webview_ setFrame:webrect];
1246 webview_ = [[UIWebDocumentView alloc] initWithFrame:webrect];
1247 webview = [webview_ webView];
1249 // XXX: this is terribly (too?) expensive
1250 //[webview_ setDrawsBackground:NO];
1251 [webview setPreferencesIdentifier:@"Cydia"];
1253 [webview_ setTileSize:CGSizeMake(webrect.size.width, 500)];
1255 if ([webview_ respondsToSelector:@selector(enableReachability)])
1256 [webview_ enableReachability];
1258 [webview_ setAllowsMessaging:YES];
1260 if ([webview_ respondsToSelector:@selector(useSelectionAssistantWithMode:)])
1261 [webview_ useSelectionAssistantWithMode:0];
1263 [webview_ setTilingEnabled:YES];
1264 [webview_ setDrawsGrid:NO];
1265 [webview_ setLogsTilingChanges:NO];
1266 [webview_ setTileMinificationFilter:kCAFilterNearest];
1268 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
1269 /* XXX: abstractify */
1270 [webview_ setDataDetectorTypes:0x80000000];
1272 [webview_ setDetectsPhoneNumbers:NO];
1274 [webview_ setAutoresizes:YES];
1276 [webview_ setMinimumScale:0.25f forDocumentTypes:0x10];
1277 [webview_ setMaximumScale:5.00f forDocumentTypes:0x10];
1278 [webview_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x10];
1279 //[webview_ setViewportSize:CGSizeMake(980, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
1281 [webview_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x2];
1283 [webview_ setMinimumScale:1.00f forDocumentTypes:0x8];
1284 [webview_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x8];
1285 [webview_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x8];
1287 [webview_ _setDocumentType:0x4];
1289 if ([webview_ respondsToSelector:@selector(UIWebDocumentView:)])
1290 [webview_ setZoomsFocusedFormControl:YES];
1291 [webview_ setContentsPosition:7];
1292 [webview_ setEnabledGestures:0xa];
1293 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeIsZoomRubberBandEnabled];
1294 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeUpdatesScroller];
1296 [webview_ setSmoothsFonts:YES];
1297 [webview_ setAllowsImageSheet:YES];
1298 [webview _setUsesLoaderCache:YES];
1300 [webview setGroupName:@"CydiaGroup"];
1302 WebPreferences *preferences([webview preferences]);
1304 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
1305 [webview _setLayoutInterval:0];
1307 [preferences _setLayoutInterval:0];
1310 [self setViewportWidth:width];
1312 [webview_ setDelegate:self];
1313 [webview_ setGestureDelegate:self];
1314 [webview_ setFormEditingDelegate:self];
1315 [webview_ setInteractionDelegate:self];
1317 [scroller_ addSubview:webview_];
1319 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
1321 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
1323 [webview setFrameLoadDelegate:indirect_];
1324 [webview setPolicyDelegate:indirect_];
1325 [webview setResourceLoadDelegate:indirect_];
1326 [webview setUIDelegate:indirect_];
1328 /* XXX: do not turn this on under penalty of extreme pain */
1329 [webview setScriptDebugDelegate:nil];
1333 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite];
1334 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 12, indsize.width, indsize.height)];
1335 [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
1337 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
1338 [scroller_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
1340 /*UIWebView *test([[[UIWebView alloc] initWithFrame:[self bounds]] autorelease]);
1341 [test loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.saurik.com/"]]];
1342 [self addSubview:test];*/
1346 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
1347 return [self initWithBook:book forWidth:width ofClass:[self class]];
1350 - (id) initWithBook:(RVBook *)book {
1351 return [self initWithBook:book forWidth:0];
1354 - (NSString *) stringByEvaluatingJavaScriptFromString:(NSString *)script {
1356 WebView *webview([webview_ webView]);
1357 NSString *string([webview stringByEvaluatingJavaScriptFromString:script]);
1362 - (void) callFunction:(WebScriptObject *)function {
1365 WebView *webview([webview_ webView]);
1366 WebFrame *frame([webview mainFrame]);
1368 id _private(MSHookIvar<id>(webview, "_private"));
1369 WebCore::Page *page(_private == nil ? NULL : MSHookIvar<WebCore::Page *>(_private, "page"));
1370 WebCore::Settings *settings(page == NULL ? NULL : page->settings());
1373 if (settings == NULL)
1376 no = settings->JavaScriptCanOpenWindowsAutomatically();
1377 settings->setJavaScriptCanOpenWindowsAutomatically(true);
1380 if (UIWindow *window = [self window])
1381 if (UIResponder *responder = [window firstResponder])
1382 [responder resignFirstResponder];
1384 JSObjectRef object([function JSObject]);
1385 JSGlobalContextRef context([frame globalContext]);
1386 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
1388 if (settings != NULL)
1389 settings->setJavaScriptCanOpenWindowsAutomatically(no);
1394 - (void) didCloseBook:(RVBook *)book {
1396 [self callFunction:closer_];
1399 - (void) __rightButtonClicked {
1404 - (void) _rightButtonClicked {
1406 if (function_ != nil)
1407 [self callFunction:function_];
1410 [self __rightButtonClicked];
1413 - (id) _rightButtonTitle {
1414 return UCLocalize("RELOAD");
1417 - (id) rightButtonTitle {
1418 return [self isLoading] ? @"" : button_ != nil ? button_ : [self _rightButtonTitle];
1421 - (UINavigationButtonStyle) rightButtonStyle {
1422 if (style_ == nil) normal:
1423 return UINavigationButtonStyleNormal;
1424 else if ([style_ isEqualToString:@"Normal"])
1425 return UINavigationButtonStyleNormal;
1426 else if ([style_ isEqualToString:@"Back"])
1427 return UINavigationButtonStyleBack;
1428 else if ([style_ isEqualToString:@"Highlighted"])
1429 return UINavigationButtonStyleHighlighted;
1430 else if ([style_ isEqualToString:@"Destructive"])
1431 return UINavigationButtonStyleDestructive;
1435 - (NSString *) title {
1436 return title_ == nil ? UCLocalize("LOADING") : title_;
1439 - (NSString *) backButtonTitle {
1440 return UCLocalize("BROWSER");
1443 - (void) setPageActive:(BOOL)active {
1445 [indicator_ removeFromSuperview];
1447 [[book_ navigationBar] addSubview:indicator_];
1450 - (void) resetViewAnimated:(BOOL)animated {
1453 - (void) setPushed:(bool)pushed {
1457 + (float) defaultWidth {