]> git.saurik.com Git - cydia.git/blob - CyteKit/WebViewController.mm
Restart SpringBoard in the case that we MoveStash.
[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/PerlCompatibleRegEx.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(self->isa), 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(self->isa), 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 Pcre 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 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
715 return [self _allowJavaScriptPanel];
716 }
717
718 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
719 return [self _allowJavaScriptPanel];
720 }
721
722 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
723 return [self _allowJavaScriptPanel];
724 }
725
726 - (void) webViewClose:(WebView *)view {
727 [self close];
728 }
729 // }}}
730
731 - (void) close {
732 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
733 }
734
735 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
736 NSString *context([alert context]);
737
738 if ([context isEqualToString:@"sensitive"]) {
739 switch (button) {
740 case 1:
741 sensitive_ = [NSNumber numberWithBool:YES];
742 break;
743
744 case 2:
745 sensitive_ = [NSNumber numberWithBool:NO];
746 break;
747 }
748
749 [alert dismissWithClickedButtonIndex:-1 animated:YES];
750 } else if ([context isEqualToString:@"challenge"]) {
751 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
752
753 if (button == [alert cancelButtonIndex])
754 [sender cancelAuthenticationChallenge:challenge_];
755 else if (button == [alert firstOtherButtonIndex]) {
756 NSString *username([[alert textFieldAtIndex:0] text]);
757 NSString *password([[alert textFieldAtIndex:1] text]);
758
759 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
760
761 [sender useCredential:credential forAuthenticationChallenge:challenge_];
762 }
763
764 challenge_ = nil;
765
766 [alert dismissWithClickedButtonIndex:-1 animated:YES];
767 } else if ([context isEqualToString:@"itmsappss"]) {
768 if (button == [alert cancelButtonIndex]) {
769 } else if (button == [alert firstOtherButtonIndex]) {
770 [delegate_ openURL:appstore_];
771 }
772
773 [alert dismissWithClickedButtonIndex:-1 animated:YES];
774 } else if ([context isEqualToString:@"submit"]) {
775 if (button == [alert cancelButtonIndex]) {
776 } else if (button == [alert firstOtherButtonIndex]) {
777 if (request_ != nil) {
778 WebThreadLocked lock;
779 [[self webView] loadRequest:request_];
780 }
781 }
782
783 [alert dismissWithClickedButtonIndex:-1 animated:YES];
784 }
785 }
786
787 - (UIBarButtonItemStyle) rightButtonStyle {
788 if (style_ == nil) normal:
789 return UIBarButtonItemStylePlain;
790 else if ([style_ isEqualToString:@"Normal"])
791 return UIBarButtonItemStylePlain;
792 else if ([style_ isEqualToString:@"Highlighted"])
793 return UIBarButtonItemStyleDone;
794 else goto normal;
795 }
796
797 - (UIBarButtonItem *) customButton {
798 if (custom_ == nil)
799 return nil;
800 else if ((/*clang:*/id) custom_ == [NSNull null])
801 return (UIBarButtonItem *) [NSNull null];
802
803 return [[[UIBarButtonItem alloc]
804 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
805 style:[self rightButtonStyle]
806 target:self
807 action:@selector(customButtonClicked)
808 ] autorelease];
809 }
810
811 - (UIBarButtonItem *) leftButton {
812 UINavigationItem *item([self navigationItem]);
813 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
814 return nil;
815
816 if (UINavigationController *navigation = [self navigationController])
817 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
818 return [[[UIBarButtonItem alloc]
819 initWithTitle:UCLocalize("CLOSE")
820 style:UIBarButtonItemStylePlain
821 target:self
822 action:@selector(close)
823 ] autorelease];
824
825 return nil;
826 }
827
828 - (void) applyLeftButton {
829 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
830 }
831
832 - (UIBarButtonItem *) rightButton {
833 return reloaditem_;
834 }
835
836 - (void) applyLoadingTitle {
837 [[self navigationItem] setTitle:UCLocalize("LOADING")];
838 }
839
840 - (void) layoutRightButton {
841 [[loadingitem_ view] addSubview:indicator_];
842 [[loadingitem_ view] bringSubviewToFront:indicator_];
843 }
844
845 - (void) applyRightButton {
846 if ([self isLoading]) {
847 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
848 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
849
850 [indicator_ startAnimating];
851 [self applyLoadingTitle];
852 } else {
853 [indicator_ stopAnimating];
854
855 UIBarButtonItem *button([self customButton]);
856 if (button == nil)
857 button = [self rightButton];
858 else if (button == (UIBarButtonItem *) [NSNull null])
859 button = nil;
860
861 [[self navigationItem] setRightBarButtonItem:button animated:YES];
862 }
863 }
864
865 - (void) didStartLoading {
866 // Overridden in subclasses.
867 }
868
869 - (void) _didStartLoading {
870 [self applyRightButton];
871
872 if ([loading_ count] != 1)
873 return;
874
875 if ([self retainsNetworkActivityIndicator])
876 [delegate_ retainNetworkActivityIndicator];
877
878 [self didStartLoading];
879 }
880
881 - (void) didFinishLoading {
882 // Overridden in subclasses.
883 }
884
885 - (void) _didFinishLoading {
886 if ([loading_ count] != 0)
887 return;
888
889 [self applyRightButton];
890 [[self navigationItem] setTitle:title_];
891
892 if ([self retainsNetworkActivityIndicator])
893 [delegate_ releaseNetworkActivityIndicator];
894
895 [self didFinishLoading];
896 }
897
898 - (bool) isLoading {
899 return [loading_ count] != 0;
900 }
901
902 - (id) initWithWidth:(float)width ofClass:(Class)_class {
903 if ((self = [super init]) != nil) {
904 width_ = width;
905 class_ = _class;
906
907 [super setPageColor:nil];
908
909 allowsNavigationAction_ = true;
910
911 loading_ = [NSMutableSet setWithCapacity:5];
912 registered_ = [NSMutableSet setWithCapacity:5];
913 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
914
915 reloaditem_ = [[[UIBarButtonItem alloc]
916 initWithTitle:UCLocalize("RELOAD")
917 style:[self rightButtonStyle]
918 target:self
919 action:@selector(reloadButtonClicked)
920 ] autorelease];
921
922 loadingitem_ = [[[UIBarButtonItem alloc]
923 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
924 style:UIBarButtonItemStylePlain
925 target:self
926 action:@selector(reloadButtonClicked)
927 ] autorelease];
928
929 UIActivityIndicatorViewStyle style;
930 float left;
931 if (kCFCoreFoundationVersionNumber >= 800) {
932 style = UIActivityIndicatorViewStyleGray;
933 left = 7;
934 } else {
935 style = UIActivityIndicatorViewStyleWhite;
936 left = 15;
937 }
938
939 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
940 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
941 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
942
943 [self applyLeftButton];
944 [self applyRightButton];
945 } return self;
946 }
947
948 - (NSString *) applicationNameForUserAgent {
949 return nil;
950 }
951
952 - (void) loadView {
953 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
954
955 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
956 [webview_ setDelegate:self];
957 [self setView:webview_];
958
959 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
960 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
961 else
962 [webview_ setDetectsPhoneNumbers:NO];
963
964 [webview_ setScalesPageToFit:YES];
965
966 UIWebDocumentView *document([webview_ _documentView]);
967
968 // XXX: I think this improves scrolling; the hardcoded-ness sucks
969 [document setTileSize:CGSizeMake(320, 500)];
970
971 WebView *webview([document webView]);
972 WebPreferences *preferences([webview preferences]);
973
974 // XXX: I have no clue if I actually /want/ this modification
975 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
976 [webview _setLayoutInterval:0];
977 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
978 [preferences _setLayoutInterval:0];
979
980 [preferences setCacheModel:WebCacheModelDocumentBrowser];
981 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
982
983 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
984 [preferences setOfflineWebApplicationCacheEnabled:YES];
985
986 if (NSString *agent = [self applicationNameForUserAgent])
987 [webview setApplicationNameForUserAgent:agent];
988
989 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
990 [webview setShouldUpdateWhileOffscreen:NO];
991
992 #if LogMessages
993 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
994 [document setAllowsMessaging:YES];
995 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
996 [webview _setAllowsMessaging:YES];
997 #endif
998
999 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1000 scroller_ = [webview_ _scrollView];
1001
1002 [scroller_ setDirectionalLockEnabled:YES];
1003 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
1004 [scroller_ setDelaysContentTouches:NO];
1005
1006 [scroller_ setCanCancelContentTouches:YES];
1007 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1008 UIScroller *scroller([webview_ _scroller]);
1009 scroller_ = (UIScrollView *) scroller;
1010
1011 [scroller setDirectionalScrolling:YES];
1012 // XXX: we might be better off /not/ setting this on older systems
1013 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
1014 [scroller setScrollHysteresis:0]; /* 8 */
1015
1016 [scroller setThumbDetectionEnabled:NO];
1017
1018 // use NO with UIApplicationUseLegacyEvents(YES)
1019 [scroller setEventMode:YES];
1020
1021 // XXX: this is handled by setBounces, right?
1022 //[scroller setAllowsRubberBanding:YES];
1023 }
1024
1025 [webview_ setOpaque:NO];
1026 [webview_ setBackgroundColor:nil];
1027
1028 [scroller_ setFixedBackgroundPattern:YES];
1029 [scroller_ setBackgroundColor:color_];
1030 [scroller_ setClipsSubviews:YES];
1031
1032 [scroller_ setBounces:YES];
1033 [scroller_ setScrollingEnabled:YES];
1034 [scroller_ setShowBackgroundShadow:NO];
1035
1036 [self setViewportWidth:width_];
1037
1038 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1039 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1040 [table setScrollsToTop:NO];
1041 [webview_ insertSubview:table atIndex:0];
1042 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1043 }
1044
1045 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1046
1047 ready_ = false;
1048 }
1049
1050 - (void) releaseSubviews {
1051 webview_ = nil;
1052 scroller_ = nil;
1053
1054 [self releaseNetworkActivityIndicator];
1055
1056 [super releaseSubviews];
1057 }
1058
1059 - (id) initWithWidth:(float)width {
1060 return [self initWithWidth:width ofClass:[self class]];
1061 }
1062
1063 - (id) init {
1064 return [self initWithWidth:0];
1065 }
1066
1067 - (id) initWithURL:(NSURL *)url {
1068 if ((self = [self init]) != nil) {
1069 [self setURL:url];
1070 } return self;
1071 }
1072
1073 - (id) initWithRequest:(NSURLRequest *)request {
1074 if ((self = [self init]) != nil) {
1075 [self setRequest:request];
1076 } return self;
1077 }
1078
1079 + (void) _lockJavaScript:(WebPreferences *)preferences {
1080 WebThreadLocked lock;
1081 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1082 }
1083
1084 - (void) callFunction:(WebScriptObject *)function {
1085 WebThreadLocked lock;
1086
1087 WebView *webview([[[self webView] _documentView] webView]);
1088 WebPreferences *preferences([webview preferences]);
1089
1090 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
1091 if ([webview respondsToSelector:@selector(_preferencesChanged:)])
1092 [webview _preferencesChanged:preferences];
1093 else
1094 [webview _preferencesChangedNotification:[NSNotification notificationWithName:@"" object:preferences]];
1095
1096 WebFrame *frame([webview mainFrame]);
1097 JSGlobalContextRef context([frame globalContext]);
1098
1099 JSObjectRef object([function JSObject]);
1100 if ($JSObjectCallAsFunction != NULL)
1101 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1102
1103 // XXX: the JavaScript code submits a form, which seems to happen asynchronously
1104 NSObject *target([CyteWebViewController class]);
1105 [NSObject cancelPreviousPerformRequestsWithTarget:target selector:@selector(_lockJavaScript:) object:preferences];
1106 [target performSelector:@selector(_lockJavaScript:) withObject:preferences afterDelay:1];
1107 }
1108
1109 - (void) reloadButtonClicked {
1110 [self reloadURLWithCache:NO];
1111 }
1112
1113 - (void) _customButtonClicked {
1114 [self reloadButtonClicked];
1115 }
1116
1117 - (void) customButtonClicked {
1118 #if !AlwaysReload
1119 if (function_ != nil)
1120 [self callFunction:function_];
1121 else
1122 #endif
1123 [self _customButtonClicked];
1124 }
1125
1126 + (float) defaultWidth {
1127 return 980;
1128 }
1129
1130 - (void) setNavigationBarStyle:(NSString *)name {
1131 UIBarStyle style;
1132 if ([name isEqualToString:@"Black"])
1133 style = UIBarStyleBlack;
1134 else
1135 style = UIBarStyleDefault;
1136
1137 [[[self navigationController] navigationBar] setBarStyle:style];
1138 }
1139
1140 - (void) setNavigationBarTintColor:(UIColor *)color {
1141 [[[self navigationController] navigationBar] setTintColor:color];
1142 }
1143
1144 - (void) setBadgeValue:(id)value {
1145 [[[self navigationController] tabBarItem] setBadgeValue:value];
1146 }
1147
1148 - (void) setHidesBackButton:(bool)value {
1149 [[self navigationItem] setHidesBackButton:value];
1150 [self applyLeftButton];
1151 }
1152
1153 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1154 [self setHidesBackButton:[value boolValue]];
1155 }
1156
1157 - (void) dispatchEvent:(NSString *)event {
1158 [[self webView] dispatchEvent:event];
1159 }
1160
1161 - (bool) hidesNavigationBar {
1162 return hidesNavigationBar_;
1163 }
1164
1165 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1166 if (visible_)
1167 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1168 }
1169
1170 - (void) setHidesNavigationBar:(bool)value {
1171 if (hidesNavigationBar_ != value) {
1172 hidesNavigationBar_ = value;
1173 [self _setHidesNavigationBar:YES animated:YES];
1174 }
1175 }
1176
1177 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1178 [self setHidesNavigationBar:[value boolValue]];
1179 }
1180
1181 - (void) setScrollAlwaysBounceVertical:(bool)value {
1182 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1183 UIScrollView *scroller([webview_ _scrollView]);
1184 [scroller setAlwaysBounceVertical:value];
1185 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1186 //UIScroller *scroller([webview_ _scroller]);
1187 // XXX: I am sad here.
1188 } else return;
1189 }
1190
1191 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1192 [self setScrollAlwaysBounceVertical:[value boolValue]];
1193 }
1194
1195 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1196 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1197 UIScrollView *scroller([webview_ _scrollView]);
1198 [scroller setIndicatorStyle:style];
1199 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1200 UIScroller *scroller([webview_ _scroller]);
1201 [scroller setScrollerIndicatorStyle:style];
1202 } else return;
1203 }
1204
1205 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1206 UIScrollViewIndicatorStyle value;
1207
1208 if (false);
1209 else if ([style isEqualToString:@"default"])
1210 value = UIScrollViewIndicatorStyleDefault;
1211 else if ([style isEqualToString:@"black"])
1212 value = UIScrollViewIndicatorStyleBlack;
1213 else if ([style isEqualToString:@"white"])
1214 value = UIScrollViewIndicatorStyleWhite;
1215 else return;
1216
1217 [self setScrollIndicatorStyle:value];
1218 }
1219
1220 - (void) viewWillAppear:(BOOL)animated {
1221 visible_ = true;
1222
1223 if ([self hidesNavigationBar])
1224 [self _setHidesNavigationBar:YES animated:animated];
1225
1226 // XXX: why isn't this evern called automatically?
1227 [[self webView] setNeedsLayout];
1228
1229 [self dispatchEvent:@"CydiaViewWillAppear"];
1230 [super viewWillAppear:animated];
1231 }
1232
1233 - (void) viewDidAppear:(BOOL)animated {
1234 [super viewDidAppear:animated];
1235 [self dispatchEvent:@"CydiaViewDidAppear"];
1236 }
1237
1238 - (void) viewWillDisappear:(BOOL)animated {
1239 [self dispatchEvent:@"CydiaViewWillDisappear"];
1240 [super viewWillDisappear:animated];
1241
1242 if ([self hidesNavigationBar])
1243 [self _setHidesNavigationBar:NO animated:animated];
1244
1245 visible_ = false;
1246 }
1247
1248 - (void) viewDidDisappear:(BOOL)animated {
1249 [super viewDidDisappear:animated];
1250 [self dispatchEvent:@"CydiaViewDidDisappear"];
1251 }
1252
1253 - (void) updateHeights:(NSTimer *)timer {
1254 for (WebFrame *frame in (id) registered_)
1255 [frame cydia$updateHeight];
1256 }
1257
1258 - (void) registerFrame:(WebFrame *)frame {
1259 [registered_ addObject:frame];
1260
1261 if (timer_ == nil)
1262 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];
1263 }
1264
1265 @end