]> git.saurik.com Git - cydia.git/blob - CyteKit/WebViewController.mm
Rewrite error handling in APT to make it saner :/.
[cydia.git] / CyteKit / WebViewController.mm
1 #include "CyteKit/UCPlatform.h"
2 #include "CyteKit/WebViewController.h"
3
4 #include "CyteKit/MFMailComposeViewController-MailToURL.h"
5
6 #include "iPhonePrivate.h"
7
8 #include "CyteKit/IndirectDelegate.h"
9 #include "CyteKit/Localize.h"
10 #include "CyteKit/WebViewController.h"
11 #include "CyteKit/RegEx.hpp"
12 #include "CyteKit/WebThreadLocked.hpp"
13
14 //#include <QuartzCore/CALayer.h>
15 // XXX: fix the minimum requirement
16 extern NSString * const kCAFilterNearest;
17
18 #include <WebCore/WebCoreThread.h>
19
20 #import <WebKit/WebKitErrors.h>
21 #import <WebKit/WebPreferences.h>
22
23 #include <WebKit/DOMCSSPrimitiveValue.h>
24 #include <WebKit/DOMCSSStyleDeclaration.h>
25 #include <WebKit/DOMDocument.h>
26 #include <WebKit/DOMHTMLBodyElement.h>
27 #include <WebKit/DOMRGBColor.h>
28
29 #include <dlfcn.h>
30 #include <objc/runtime.h>
31
32 #define ForSaurik 0
33 #define DefaultTimeout_ 120.0
34
35 #define ShowInternals 0
36 #define LogBrowser 0
37 #define LogMessages 0
38
39 #define lprintf(args...) fprintf(stderr, args)
40
41 JSValueRef (*$JSObjectCallAsFunction)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *);
42
43 // XXX: centralize these special class things to some file or mechanism?
44 static Class $MFMailComposeViewController;
45
46 float CYScrollViewDecelerationRateNormal;
47
48 @interface WebFrame (Cydia)
49 - (void) cydia$updateHeight;
50 @end
51
52 @implementation WebFrame (Cydia)
53
54 - (NSString *) description {
55 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[[([self provisionalDataSource] ?: [self dataSource]) request] URL] absoluteString]];
56 }
57
58 - (void) cydia$updateHeight {
59 [[[self frameElement] style]
60 setProperty:@"height"
61 value:[NSString stringWithFormat:@"%dpx",
62 [[[self DOMDocument] body] scrollHeight]]
63 priority:nil];
64 }
65
66 @end
67
68 /* Indirect Delegate {{{ */
69 @implementation IndirectDelegate
70
71 - (id) delegate {
72 return delegate_;
73 }
74
75 - (void) setDelegate:(id)delegate {
76 delegate_ = delegate;
77 }
78
79 - (id) initWithDelegate:(id)delegate {
80 delegate_ = delegate;
81 return self;
82 }
83
84 - (IMP) methodForSelector:(SEL)sel {
85 if (IMP method = [super methodForSelector:sel])
86 return method;
87 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
88 return NULL;
89 }
90
91 - (BOOL) respondsToSelector:(SEL)sel {
92 if ([super respondsToSelector:sel])
93 return YES;
94
95 // XXX: WebThreadCreateNSInvocation returns nil
96
97 #if ShowInternals
98 fprintf(stderr, "[%s]R?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
99 #endif
100
101 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
102 }
103
104 - (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
105 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
106 return method;
107
108 #if ShowInternals
109 fprintf(stderr, "[%s]S?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
110 #endif
111
112 if (delegate_ != nil)
113 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
114 return sig;
115
116 // XXX: I fucking hate Apple so very very bad
117 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
118 }
119
120 - (void) forwardInvocation:(NSInvocation *)inv {
121 SEL sel = [inv selector];
122 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
123 [inv invokeWithTarget:delegate_];
124 }
125
126 @end
127 /* }}} */
128
129 @implementation CyteWebViewController
130
131 #if ShowInternals
132 #include "CyteKit/UCInternal.h"
133 #endif
134
135 + (void) _initialize {
136 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
137
138 void *js(NULL);
139 if (js == NULL)
140 js = dlopen("/System/Library/Frameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
141 if (js == NULL)
142 js = dlopen("/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore", RTLD_GLOBAL | RTLD_LAZY);
143 if (js != NULL)
144 $JSObjectCallAsFunction = reinterpret_cast<JSValueRef (*)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(js, "JSObjectCallAsFunction"));
145
146 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
147 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
148
149 if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
150 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
151 else // XXX: this actually might be fast on some older systems: we should look into this
152 CYScrollViewDecelerationRateNormal = 0.998;
153 }
154
155 - (bool) retainsNetworkActivityIndicator {
156 return true;
157 }
158
159 - (void) releaseNetworkActivityIndicator {
160 if ([loading_ count] != 0) {
161 [loading_ removeAllObjects];
162
163 if ([self retainsNetworkActivityIndicator])
164 [delegate_ releaseNetworkActivityIndicator];
165 }
166 }
167
168 - (void) dealloc {
169 #if LogBrowser
170 NSLog(@"[CyteWebViewController dealloc]");
171 #endif
172
173 [self releaseNetworkActivityIndicator];
174
175 [super dealloc];
176 }
177
178 - (NSString *) description {
179 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[request_ URL] absoluteString]];
180 }
181
182 - (CyteWebView *) webView {
183 return (CyteWebView *) [self view];
184 }
185
186 - (NSURL *) URLWithURL:(NSURL *)url {
187 return url;
188 }
189
190 - (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy referrer:(NSString *)referrer {
191 NSMutableURLRequest *request([NSMutableURLRequest
192 requestWithURL:[self URLWithURL:url]
193 cachePolicy:policy
194 timeoutInterval:DefaultTimeout_
195 ]);
196
197 [request setValue:referrer forHTTPHeaderField:@"Referer"];
198
199 return request;
200 }
201
202 - (void) setRequest:(NSURLRequest *)request {
203 _assert(request_ == nil);
204 request_ = request;
205 }
206
207 - (void) setURL:(NSURL *)url {
208 [self setURL:url withReferrer:nil];
209 }
210
211 - (void) setURL:(NSURL *)url withReferrer:(NSString *)referrer {
212 [self setRequest:[self requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy referrer:referrer]];
213 }
214
215 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
216 [self loadRequest:[self requestWithURL:url cachePolicy:policy referrer:nil]];
217 }
218
219 - (void) loadURL:(NSURL *)url {
220 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
221 }
222
223 - (void) loadRequest:(NSURLRequest *)request {
224 #if LogBrowser
225 NSLog(@"loadRequest:%@", request);
226 #endif
227
228 error_ = false;
229 ready_ = true;
230
231 WebThreadLocked lock;
232 [[self webView] loadRequest:request];
233 }
234
235 - (void) reloadURLWithCache:(BOOL)cache {
236 if (request_ == nil)
237 return;
238
239 NSMutableURLRequest *request([request_ mutableCopy]);
240 [request setCachePolicy:(cache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData)];
241
242 request_ = request;
243
244 if (cache || [request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
245 [self loadRequest:request_];
246 else {
247 UIAlertView *alert = [[[UIAlertView alloc]
248 initWithTitle:UCLocalize("RESUBMIT_FORM")
249 message:nil
250 delegate:self
251 cancelButtonTitle:UCLocalize("CANCEL")
252 otherButtonTitles:
253 UCLocalize("SUBMIT"),
254 nil
255 ] autorelease];
256
257 [alert setContext:@"submit"];
258 [alert show];
259 }
260 }
261
262 - (void) reloadData {
263 [super reloadData];
264
265 if (ready_)
266 [self dispatchEvent:@"CydiaReloadData"];
267 else
268 [self reloadURLWithCache:YES];
269 }
270
271 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
272 custom_ = button;
273 style_ = style;
274 function_ = function;
275
276 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
277 }
278
279 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
280 custom_ = button;
281 style_ = style;
282 function_ = function;
283
284 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
285 }
286
287 - (void) removeButton {
288 custom_ = [NSNull null];
289 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
290 }
291
292 - (void) scrollToBottomAnimated:(NSNumber *)animated {
293 CGSize size([scroller_ contentSize]);
294 CGPoint offset([scroller_ contentOffset]);
295 CGRect frame([scroller_ frame]);
296
297 if (size.height - offset.y < frame.size.height + 20.f) {
298 CGRect rect = {{0, size.height-1}, {size.width, 1}};
299 [scroller_ scrollRectToVisible:rect animated:[animated boolValue]];
300 }
301 }
302
303 - (void) _setViewportWidth {
304 [[[self webView] _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
305 }
306
307 - (void) setViewportWidth:(float)width {
308 width_ = width != 0 ? width : [[self class] defaultWidth];
309 [self _setViewportWidth];
310 }
311
312 - (void) _setViewportWidthOnMainThread:(NSNumber *)width {
313 [self setViewportWidth:[width floatValue]];
314 }
315
316 - (void) setViewportWidthOnMainThread:(float)width {
317 [self performSelectorOnMainThread:@selector(_setViewportWidthOnMainThread:) withObject:[NSNumber numberWithFloat:width] waitUntilDone:NO];
318 }
319
320 - (void) webViewUpdateViewSettings:(UIWebView *)view {
321 [self _setViewportWidth];
322 }
323
324 - (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
325 [self dismissModalViewControllerAnimated:YES];
326 }
327
328 - (void) _setupMail:(MFMailComposeViewController *)controller {
329 }
330
331 - (void) _openMailToURL:(NSURL *)url {
332 if ($MFMailComposeViewController != nil && [$MFMailComposeViewController canSendMail]) {
333 MFMailComposeViewController *controller([[[$MFMailComposeViewController alloc] init] autorelease]);
334 [controller setMailComposeDelegate:self];
335
336 [controller setMailToURL:url];
337
338 [self _setupMail:controller];
339
340 [self presentModalViewController:controller animated:YES];
341 return;
342 }
343
344 UIApplication *app([UIApplication sharedApplication]);
345 if ([app respondsToSelector:@selector(openURL:asPanel:)])
346 [app openURL:url asPanel:YES];
347 else
348 [app openURL:url];
349 }
350
351 - (bool) _allowJavaScriptPanel {
352 return true;
353 }
354
355 - (bool) allowsNavigationAction {
356 return allowsNavigationAction_;
357 }
358
359 - (void) setAllowsNavigationAction:(bool)value {
360 allowsNavigationAction_ = value;
361 }
362
363 - (void) setAllowsNavigationActionByNumber:(NSNumber *)value {
364 [self setAllowsNavigationAction:[value boolValue]];
365 }
366
367 - (void) popViewControllerWithNumber:(NSNumber *)value {
368 UINavigationController *navigation([self navigationController]);
369 if ([navigation topViewController] == self)
370 [navigation popViewControllerAnimated:[value boolValue]];
371 }
372
373 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
374 NSValue *object([NSValue valueWithNonretainedObject:frame]);
375 if (![loading_ containsObject:object])
376 return;
377 [loading_ removeObject:object];
378
379 [self _didFinishLoading];
380
381 if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == NSURLErrorCancelled)
382 return;
383
384 if ([[error domain] isEqualToString:WebKitErrorDomain] && [error code] == WebKitErrorFrameLoadInterruptedByPolicyChange) {
385 request_ = nil;
386 return;
387 }
388
389 if ([frame parentFrame] == nil) {
390 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
391 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
392 [[error localizedDescription] stringByAddingPercentEscapes]
393 ]]];
394
395 error_ = true;
396 }
397 }
398
399 - (void) pushRequest:(NSURLRequest *)request forAction:(NSDictionary *)action asPop:(bool)pop {
400 WebFrame *frame(nil);
401 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
402 frame = [WebActionElement objectForKey:@"WebElementFrame"];
403 if (frame == nil)
404 frame = [[[[self webView] _documentView] webView] mainFrame];
405
406 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
407 NSString *referrer([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString]);
408
409 NSURL *url([request URL]);
410
411 // XXX: filter to internal usage?
412 CyteViewController *page([delegate_ pageForURL:url forExternal:NO withReferrer:referrer]);
413
414 if (page == nil) {
415 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
416 [browser setRequest:request];
417 page = browser;
418 }
419
420 [page setDelegate:delegate_];
421 [page setPageColor:color_];
422
423 if (!pop) {
424 [[self navigationItem] setTitle:title_];
425
426 [[self navigationController] pushViewController:page animated:YES];
427 } else {
428 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
429
430 [navigation setDelegate:delegate_];
431
432 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
433 initWithTitle:UCLocalize("CLOSE")
434 style:UIBarButtonItemStylePlain
435 target:page
436 action:@selector(close)
437 ] autorelease]];
438
439 [[self navigationController] presentModalViewController:navigation animated:YES];
440 }
441 }
442
443 // CyteWebViewDelegate {{{
444 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
445 #if LogMessages
446 static RegEx irritating("(?"
447 ":" "The page at .* displayed insecure content from .*\\."
448 "|" "Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\."
449 ")\\n");
450
451 if (NSString *data = [message objectForKey:@"message"])
452 if (irritating(data))
453 return;
454
455 NSLog(@"addMessageToConsole:%@", message);
456 #endif
457 }
458
459 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
460 #if LogBrowser
461 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ %@ frame:%@", action, request, [request allHTTPHeaderFields], frame);
462 #endif
463
464 NSURL *url(request == nil ? nil : [request URL]);
465 NSString *scheme([[url scheme] lowercaseString]);
466 NSString *absolute([[url absoluteString] lowercaseString]);
467
468 if (
469 [scheme isEqualToString:@"itms"] ||
470 [scheme isEqualToString:@"itmss"] ||
471 [scheme isEqualToString:@"itms-apps"] ||
472 [scheme isEqualToString:@"itms-appss"] ||
473 [absolute hasPrefix:@"http://itunes.apple.com/"] ||
474 [absolute hasPrefix:@"https://itunes.apple.com/"] ||
475 false) {
476 appstore_ = url;
477
478 UIAlertView *alert = [[[UIAlertView alloc]
479 initWithTitle:UCLocalize("APP_STORE_REDIRECT")
480 message:nil
481 delegate:self
482 cancelButtonTitle:UCLocalize("CANCEL")
483 otherButtonTitles:
484 UCLocalize("ALLOW"),
485 nil
486 ] autorelease];
487
488 [alert setContext:@"itmsappss"];
489 [alert show];
490
491 [listener ignore];
492 return;
493 }
494
495 if ([frame parentFrame] == nil) {
496 if (!error_) {
497 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
498 if (url != nil)
499 [self pushRequest:request forAction:action asPop:NO];
500 [listener ignore];
501 }
502 }
503 }
504 }
505
506 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
507 #if LogBrowser
508 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ %@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
509 #endif
510
511 if ([frame parentFrame] == nil) {
512 switch (decision) {
513 case CYWebPolicyDecisionIgnore:
514 if ([[request_ URL] isEqual:[request URL]])
515 request_ = nil;
516 break;
517
518 case CYWebPolicyDecisionUse:
519 if (!error_)
520 request_ = request;
521 break;
522
523 default:
524 break;
525 }
526 }
527 }
528
529 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
530 #if LogBrowser
531 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
532 #endif
533
534 NSURL *url([request URL]);
535 if (url == nil)
536 return;
537
538 if ([name isEqualToString:@"_open"])
539 [delegate_ openURL:url];
540 else {
541 NSString *scheme([[url scheme] lowercaseString]);
542 if ([scheme isEqualToString:@"mailto"])
543 [self _openMailToURL:url];
544 else
545 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
546 }
547
548 [listener ignore];
549 }
550
551 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
552 #if LogBrowser
553 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
554 #endif
555 }
556
557 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
558 #if LogBrowser
559 NSLog(@"didCommitLoadForFrame:%@", frame);
560 #endif
561
562 if ([frame parentFrame] == nil) {
563 loaded_ = true;
564 }
565 }
566
567 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
568 #if LogBrowser
569 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
570 #endif
571
572 [self _didFailWithError:error forFrame:frame];
573 }
574
575 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
576 #if LogBrowser
577 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
578 #endif
579
580 [self _didFailWithError:error forFrame:frame];
581 }
582
583 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
584 NSValue *object([NSValue valueWithNonretainedObject:frame]);
585 if (![loading_ containsObject:object])
586 return;
587 [loading_ removeObject:object];
588
589 if ([frame parentFrame] == nil) {
590 if (DOMDocument *document = [frame DOMDocument])
591 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
592 for (DOMHTMLBodyElement *body in (id) bodies) {
593 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
594
595 UIColor *uic(nil);
596
597 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
598 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
599 DOMRGBColor *rgb([color getRGBColorValue]);
600
601 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
602 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
603 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
604 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
605
606 if (alpha == 1)
607 uic = [UIColor
608 colorWithRed:(red / 255)
609 green:(green / 255)
610 blue:(blue / 255)
611 alpha:alpha
612 ];
613 }
614 }
615
616 [super setPageColor:uic];
617 [scroller_ setBackgroundColor:color_];
618 break;
619 }
620 }
621
622 [self _didFinishLoading];
623 }
624
625 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
626 if ([frame parentFrame] != nil)
627 return;
628
629 title_ = title;
630
631 [[self navigationItem] setTitle:title_];
632 }
633
634 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
635 #if LogBrowser
636 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
637 #endif
638
639 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
640
641 if ([frame parentFrame] == nil) {
642 title_ = nil;
643 custom_ = nil;
644 style_ = nil;
645 function_ = nil;
646
647 [registered_ removeAllObjects];
648 timer_ = nil;
649
650 allowsNavigationAction_ = true;
651
652 [self setHidesNavigationBar:NO];
653 [self setScrollAlwaysBounceVertical:true];
654 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
655
656 // XXX: do we still need to do this?
657 [[self navigationItem] setTitle:nil];
658 }
659
660 [self _didStartLoading];
661 }
662
663 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
664 challenge_ = [challenge retain];
665
666 NSURLProtectionSpace *space([challenge protectionSpace]);
667 NSString *realm([space realm]);
668 if (realm == nil)
669 realm = @"";
670
671 UIAlertView *alert = [[[UIAlertView alloc]
672 initWithTitle:realm
673 message:nil
674 delegate:self
675 cancelButtonTitle:UCLocalize("CANCEL")
676 otherButtonTitles:UCLocalize("LOGIN"), nil
677 ] autorelease];
678
679 [alert setContext:@"challenge"];
680 [alert setNumberOfRows:1];
681
682 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
683 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
684
685 UITextField *username([alert textFieldAtIndex:0]); {
686 UITextInputTraits *traits([username textInputTraits]);
687 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
688 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
689 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
690 [traits setReturnKeyType:UIReturnKeyNext];
691 }
692
693 UITextField *password([alert textFieldAtIndex:1]); {
694 UITextInputTraits *traits([password textInputTraits]);
695 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
696 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
697 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
698 // XXX: UIReturnKeyDone
699 [traits setReturnKeyType:UIReturnKeyNext];
700 [traits setSecureTextEntry:YES];
701 }
702
703 [alert show];
704 }
705
706 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
707 #if LogBrowser
708 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
709 #endif
710
711 return request;
712 }
713
714 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
715 #if LogBrowser
716 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
717 #endif
718
719 return request;
720 }
721
722 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
723 return [self _allowJavaScriptPanel];
724 }
725
726 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
727 return [self _allowJavaScriptPanel];
728 }
729
730 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
731 return [self _allowJavaScriptPanel];
732 }
733
734 - (void) webViewClose:(WebView *)view {
735 [self close];
736 }
737 // }}}
738
739 - (void) close {
740 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
741 }
742
743 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
744 NSString *context([alert context]);
745
746 if ([context isEqualToString:@"sensitive"]) {
747 switch (button) {
748 case 1:
749 sensitive_ = [NSNumber numberWithBool:YES];
750 break;
751
752 case 2:
753 sensitive_ = [NSNumber numberWithBool:NO];
754 break;
755 }
756
757 [alert dismissWithClickedButtonIndex:-1 animated:YES];
758 } else if ([context isEqualToString:@"challenge"]) {
759 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
760
761 if (button == [alert cancelButtonIndex])
762 [sender cancelAuthenticationChallenge:challenge_];
763 else if (button == [alert firstOtherButtonIndex]) {
764 NSString *username([[alert textFieldAtIndex:0] text]);
765 NSString *password([[alert textFieldAtIndex:1] text]);
766
767 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
768
769 [sender useCredential:credential forAuthenticationChallenge:challenge_];
770 }
771
772 challenge_ = nil;
773
774 [alert dismissWithClickedButtonIndex:-1 animated:YES];
775 } else if ([context isEqualToString:@"itmsappss"]) {
776 if (button == [alert cancelButtonIndex]) {
777 } else if (button == [alert firstOtherButtonIndex]) {
778 [delegate_ openURL:appstore_];
779 }
780
781 [alert dismissWithClickedButtonIndex:-1 animated:YES];
782 } else if ([context isEqualToString:@"submit"]) {
783 if (button == [alert cancelButtonIndex]) {
784 } else if (button == [alert firstOtherButtonIndex]) {
785 if (request_ != nil) {
786 WebThreadLocked lock;
787 [[self webView] loadRequest:request_];
788 }
789 }
790
791 [alert dismissWithClickedButtonIndex:-1 animated:YES];
792 }
793 }
794
795 - (UIBarButtonItemStyle) rightButtonStyle {
796 if (style_ == nil) normal:
797 return UIBarButtonItemStylePlain;
798 else if ([style_ isEqualToString:@"Normal"])
799 return UIBarButtonItemStylePlain;
800 else if ([style_ isEqualToString:@"Highlighted"])
801 return UIBarButtonItemStyleDone;
802 else goto normal;
803 }
804
805 - (UIBarButtonItem *) customButton {
806 if (custom_ == nil)
807 return nil;
808 else if ((/*clang:*/id) custom_ == [NSNull null])
809 return (UIBarButtonItem *) [NSNull null];
810
811 return [[[UIBarButtonItem alloc]
812 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
813 style:[self rightButtonStyle]
814 target:self
815 action:@selector(customButtonClicked)
816 ] autorelease];
817 }
818
819 - (UIBarButtonItem *) leftButton {
820 UINavigationItem *item([self navigationItem]);
821 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
822 return nil;
823
824 if (UINavigationController *navigation = [self navigationController])
825 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
826 return [[[UIBarButtonItem alloc]
827 initWithTitle:UCLocalize("CLOSE")
828 style:UIBarButtonItemStylePlain
829 target:self
830 action:@selector(close)
831 ] autorelease];
832
833 return nil;
834 }
835
836 - (void) applyLeftButton {
837 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
838 }
839
840 - (UIBarButtonItem *) rightButton {
841 return reloaditem_;
842 }
843
844 - (void) applyLoadingTitle {
845 [[self navigationItem] setTitle:UCLocalize("LOADING")];
846 }
847
848 - (void) layoutRightButton {
849 [[loadingitem_ view] addSubview:indicator_];
850 [[loadingitem_ view] bringSubviewToFront:indicator_];
851 }
852
853 - (void) applyRightButton {
854 if ([self isLoading]) {
855 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
856 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
857
858 [indicator_ startAnimating];
859 [self applyLoadingTitle];
860 } else {
861 [indicator_ stopAnimating];
862
863 UIBarButtonItem *button([self customButton]);
864 if (button == nil)
865 button = [self rightButton];
866 else if (button == (UIBarButtonItem *) [NSNull null])
867 button = nil;
868
869 [[self navigationItem] setRightBarButtonItem:button animated:YES];
870 }
871 }
872
873 - (void) didStartLoading {
874 // Overridden in subclasses.
875 }
876
877 - (void) _didStartLoading {
878 [self applyRightButton];
879
880 if ([loading_ count] != 1)
881 return;
882
883 if ([self retainsNetworkActivityIndicator])
884 [delegate_ retainNetworkActivityIndicator];
885
886 [self didStartLoading];
887 }
888
889 - (void) didFinishLoading {
890 // Overridden in subclasses.
891 }
892
893 - (void) _didFinishLoading {
894 if ([loading_ count] != 0)
895 return;
896
897 [self applyRightButton];
898 [[self navigationItem] setTitle:title_];
899
900 if ([self retainsNetworkActivityIndicator])
901 [delegate_ releaseNetworkActivityIndicator];
902
903 [self didFinishLoading];
904 }
905
906 - (bool) isLoading {
907 return [loading_ count] != 0;
908 }
909
910 - (id) initWithWidth:(float)width ofClass:(Class)_class {
911 if ((self = [super init]) != nil) {
912 width_ = width;
913 class_ = _class;
914
915 [super setPageColor:nil];
916
917 allowsNavigationAction_ = true;
918
919 loading_ = [NSMutableSet setWithCapacity:5];
920 registered_ = [NSMutableSet setWithCapacity:5];
921 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
922
923 reloaditem_ = [[[UIBarButtonItem alloc]
924 initWithTitle:UCLocalize("RELOAD")
925 style:[self rightButtonStyle]
926 target:self
927 action:@selector(reloadButtonClicked)
928 ] autorelease];
929
930 loadingitem_ = [[[UIBarButtonItem alloc]
931 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
932 style:UIBarButtonItemStylePlain
933 target:self
934 action:@selector(reloadButtonClicked)
935 ] autorelease];
936
937 UIActivityIndicatorViewStyle style;
938 float left;
939 if (kCFCoreFoundationVersionNumber >= 800) {
940 style = UIActivityIndicatorViewStyleGray;
941 left = 7;
942 } else {
943 style = UIActivityIndicatorViewStyleWhite;
944 left = 15;
945 }
946
947 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
948 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
949 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
950
951 [self applyLeftButton];
952 [self applyRightButton];
953 } return self;
954 }
955
956 - (NSString *) applicationNameForUserAgent {
957 return nil;
958 }
959
960 - (void) loadView {
961 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
962
963 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
964 [webview_ setDelegate:self];
965 [self setView:webview_];
966
967 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
968 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
969 else
970 [webview_ setDetectsPhoneNumbers:NO];
971
972 [webview_ setScalesPageToFit:YES];
973
974 UIWebDocumentView *document([webview_ _documentView]);
975
976 // XXX: I think this improves scrolling; the hardcoded-ness sucks
977 [document setTileSize:CGSizeMake(320, 500)];
978
979 WebView *webview([document webView]);
980 WebPreferences *preferences([webview preferences]);
981
982 // XXX: I have no clue if I actually /want/ this modification
983 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
984 [webview _setLayoutInterval:0];
985 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
986 [preferences _setLayoutInterval:0];
987
988 [preferences setCacheModel:WebCacheModelDocumentBrowser];
989 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
990
991 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
992 [preferences setOfflineWebApplicationCacheEnabled:YES];
993
994 if (NSString *agent = [self applicationNameForUserAgent])
995 [webview setApplicationNameForUserAgent:agent];
996
997 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
998 [webview setShouldUpdateWhileOffscreen:NO];
999
1000 #if LogMessages
1001 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
1002 [document setAllowsMessaging:YES];
1003 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
1004 [webview _setAllowsMessaging:YES];
1005 #endif
1006
1007 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1008 scroller_ = [webview_ _scrollView];
1009
1010 [scroller_ setDirectionalLockEnabled:YES];
1011 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
1012 [scroller_ setDelaysContentTouches:NO];
1013
1014 [scroller_ setCanCancelContentTouches:YES];
1015 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1016 UIScroller *scroller([webview_ _scroller]);
1017 scroller_ = (UIScrollView *) scroller;
1018
1019 [scroller setDirectionalScrolling:YES];
1020 // XXX: we might be better off /not/ setting this on older systems
1021 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
1022 [scroller setScrollHysteresis:0]; /* 8 */
1023
1024 [scroller setThumbDetectionEnabled:NO];
1025
1026 // use NO with UIApplicationUseLegacyEvents(YES)
1027 [scroller setEventMode:YES];
1028
1029 // XXX: this is handled by setBounces, right?
1030 //[scroller setAllowsRubberBanding:YES];
1031 }
1032
1033 [webview_ setOpaque:NO];
1034 [webview_ setBackgroundColor:nil];
1035
1036 [scroller_ setFixedBackgroundPattern:YES];
1037 [scroller_ setBackgroundColor:color_];
1038 [scroller_ setClipsSubviews:YES];
1039
1040 [scroller_ setBounces:YES];
1041 [scroller_ setScrollingEnabled:YES];
1042 [scroller_ setShowBackgroundShadow:NO];
1043
1044 [self setViewportWidth:width_];
1045
1046 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1047 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1048 [table setScrollsToTop:NO];
1049 [webview_ insertSubview:table atIndex:0];
1050 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1051 }
1052
1053 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1054
1055 ready_ = false;
1056 }
1057
1058 - (void) releaseSubviews {
1059 webview_ = nil;
1060 scroller_ = nil;
1061
1062 [self releaseNetworkActivityIndicator];
1063
1064 [super releaseSubviews];
1065 }
1066
1067 - (id) initWithWidth:(float)width {
1068 return [self initWithWidth:width ofClass:[self class]];
1069 }
1070
1071 - (id) init {
1072 return [self initWithWidth:0];
1073 }
1074
1075 - (id) initWithURL:(NSURL *)url {
1076 if ((self = [self init]) != nil) {
1077 [self setURL:url];
1078 } return self;
1079 }
1080
1081 - (id) initWithRequest:(NSURLRequest *)request {
1082 if ((self = [self init]) != nil) {
1083 [self setRequest:request];
1084 } return self;
1085 }
1086
1087 + (void) _lockJavaScript:(WebPreferences *)preferences {
1088 WebThreadLocked lock;
1089 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1090 }
1091
1092 - (void) callFunction:(WebScriptObject *)function {
1093 WebThreadLocked lock;
1094
1095 WebView *webview([[[self webView] _documentView] webView]);
1096 WebPreferences *preferences([webview preferences]);
1097
1098 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
1099 if ([webview respondsToSelector:@selector(_preferencesChanged:)])
1100 [webview _preferencesChanged:preferences];
1101 else
1102 [webview _preferencesChangedNotification:[NSNotification notificationWithName:@"" object:preferences]];
1103
1104 WebFrame *frame([webview mainFrame]);
1105 JSGlobalContextRef context([frame globalContext]);
1106
1107 JSObjectRef object([function JSObject]);
1108 if ($JSObjectCallAsFunction != NULL)
1109 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1110
1111 // XXX: the JavaScript code submits a form, which seems to happen asynchronously
1112 NSObject *target([CyteWebViewController class]);
1113 [NSObject cancelPreviousPerformRequestsWithTarget:target selector:@selector(_lockJavaScript:) object:preferences];
1114 [target performSelector:@selector(_lockJavaScript:) withObject:preferences afterDelay:1];
1115 }
1116
1117 - (void) reloadButtonClicked {
1118 [self reloadURLWithCache:NO];
1119 }
1120
1121 - (void) _customButtonClicked {
1122 [self reloadButtonClicked];
1123 }
1124
1125 - (void) customButtonClicked {
1126 #if !AlwaysReload
1127 if (function_ != nil)
1128 [self callFunction:function_];
1129 else
1130 #endif
1131 [self _customButtonClicked];
1132 }
1133
1134 + (float) defaultWidth {
1135 return 980;
1136 }
1137
1138 - (void) setNavigationBarStyle:(NSString *)name {
1139 UIBarStyle style;
1140 if ([name isEqualToString:@"Black"])
1141 style = UIBarStyleBlack;
1142 else
1143 style = UIBarStyleDefault;
1144
1145 [[[self navigationController] navigationBar] setBarStyle:style];
1146 }
1147
1148 - (void) setNavigationBarTintColor:(UIColor *)color {
1149 [[[self navigationController] navigationBar] setTintColor:color];
1150 }
1151
1152 - (void) setBadgeValue:(id)value {
1153 [[[self navigationController] tabBarItem] setBadgeValue:value];
1154 }
1155
1156 - (void) setHidesBackButton:(bool)value {
1157 [[self navigationItem] setHidesBackButton:value];
1158 [self applyLeftButton];
1159 }
1160
1161 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1162 [self setHidesBackButton:[value boolValue]];
1163 }
1164
1165 - (void) dispatchEvent:(NSString *)event {
1166 [[self webView] dispatchEvent:event];
1167 }
1168
1169 - (bool) hidesNavigationBar {
1170 return hidesNavigationBar_;
1171 }
1172
1173 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1174 if (visible_)
1175 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1176 }
1177
1178 - (void) setHidesNavigationBar:(bool)value {
1179 if (hidesNavigationBar_ != value) {
1180 hidesNavigationBar_ = value;
1181 [self _setHidesNavigationBar:YES animated:YES];
1182 }
1183 }
1184
1185 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1186 [self setHidesNavigationBar:[value boolValue]];
1187 }
1188
1189 - (void) setScrollAlwaysBounceVertical:(bool)value {
1190 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1191 UIScrollView *scroller([webview_ _scrollView]);
1192 [scroller setAlwaysBounceVertical:value];
1193 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1194 //UIScroller *scroller([webview_ _scroller]);
1195 // XXX: I am sad here.
1196 } else return;
1197 }
1198
1199 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1200 [self setScrollAlwaysBounceVertical:[value boolValue]];
1201 }
1202
1203 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1204 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1205 UIScrollView *scroller([webview_ _scrollView]);
1206 [scroller setIndicatorStyle:style];
1207 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1208 UIScroller *scroller([webview_ _scroller]);
1209 [scroller setScrollerIndicatorStyle:style];
1210 } else return;
1211 }
1212
1213 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1214 UIScrollViewIndicatorStyle value;
1215
1216 if (false);
1217 else if ([style isEqualToString:@"default"])
1218 value = UIScrollViewIndicatorStyleDefault;
1219 else if ([style isEqualToString:@"black"])
1220 value = UIScrollViewIndicatorStyleBlack;
1221 else if ([style isEqualToString:@"white"])
1222 value = UIScrollViewIndicatorStyleWhite;
1223 else return;
1224
1225 [self setScrollIndicatorStyle:value];
1226 }
1227
1228 - (void) viewWillAppear:(BOOL)animated {
1229 visible_ = true;
1230
1231 if ([self hidesNavigationBar])
1232 [self _setHidesNavigationBar:YES animated:animated];
1233
1234 // XXX: why isn't this evern called automatically?
1235 [[self webView] setNeedsLayout];
1236
1237 [self dispatchEvent:@"CydiaViewWillAppear"];
1238 [super viewWillAppear:animated];
1239 }
1240
1241 - (void) viewDidAppear:(BOOL)animated {
1242 [super viewDidAppear:animated];
1243 [self dispatchEvent:@"CydiaViewDidAppear"];
1244 }
1245
1246 - (void) viewWillDisappear:(BOOL)animated {
1247 [self dispatchEvent:@"CydiaViewWillDisappear"];
1248 [super viewWillDisappear:animated];
1249
1250 if ([self hidesNavigationBar])
1251 [self _setHidesNavigationBar:NO animated:animated];
1252
1253 visible_ = false;
1254 }
1255
1256 - (void) viewDidDisappear:(BOOL)animated {
1257 [super viewDidDisappear:animated];
1258 [self dispatchEvent:@"CydiaViewDidDisappear"];
1259 }
1260
1261 - (void) updateHeights:(NSTimer *)timer {
1262 for (WebFrame *frame in (id) registered_)
1263 [frame cydia$updateHeight];
1264 }
1265
1266 - (void) registerFrame:(WebFrame *)frame {
1267 [registered_ addObject:frame];
1268
1269 if (timer_ == nil)
1270 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];
1271 }
1272
1273 @end