]> git.saurik.com Git - cydia.git/blob - CyteKit/WebViewController.mm
If we go by the book, sec.s could seem like min.s.
[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 if ([[url scheme] isEqualToString:@"itms-appss"] || [[url absoluteString] hasPrefix:@"https://itunes.apple.com/app/"]) {
466 appstore_ = url;
467
468 UIAlertView *alert = [[[UIAlertView alloc]
469 initWithTitle:UCLocalize("APP_STORE_REDIRECT")
470 message:nil
471 delegate:self
472 cancelButtonTitle:UCLocalize("CANCEL")
473 otherButtonTitles:
474 UCLocalize("ALLOW"),
475 nil
476 ] autorelease];
477
478 [alert setContext:@"itmsappss"];
479 [alert show];
480
481 [listener ignore];
482 return;
483 }
484
485 if ([frame parentFrame] == nil) {
486 if (!error_) {
487 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
488 if (url != nil)
489 [self pushRequest:request forAction:action asPop:NO];
490 [listener ignore];
491 }
492 }
493 }
494 }
495
496 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
497 #if LogBrowser
498 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
499 #endif
500
501 if ([frame parentFrame] == nil) {
502 switch (decision) {
503 case CYWebPolicyDecisionIgnore:
504 if ([[request_ URL] isEqual:[request URL]])
505 request_ = nil;
506 break;
507
508 case CYWebPolicyDecisionUse:
509 if (!error_)
510 request_ = request;
511 break;
512
513 default:
514 break;
515 }
516 }
517 }
518
519 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
520 #if LogBrowser
521 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
522 #endif
523
524 NSURL *url([request URL]);
525 if (url == nil)
526 return;
527
528 if ([name isEqualToString:@"_open"])
529 [delegate_ openURL:url];
530 else {
531 NSString *scheme([[url scheme] lowercaseString]);
532 if ([scheme isEqualToString:@"mailto"])
533 [self _openMailToURL:url];
534 else
535 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
536 }
537
538 [listener ignore];
539 }
540
541 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
542 #if LogBrowser
543 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
544 #endif
545 }
546
547 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
548 #if LogBrowser
549 NSLog(@"didCommitLoadForFrame:%@", frame);
550 #endif
551
552 if ([frame parentFrame] == nil) {
553 loaded_ = true;
554 }
555 }
556
557 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
558 #if LogBrowser
559 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
560 #endif
561
562 [self _didFailWithError:error forFrame:frame];
563 }
564
565 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
566 #if LogBrowser
567 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
568 #endif
569
570 [self _didFailWithError:error forFrame:frame];
571 }
572
573 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
574 NSValue *object([NSValue valueWithNonretainedObject:frame]);
575 if (![loading_ containsObject:object])
576 return;
577 [loading_ removeObject:object];
578
579 if ([frame parentFrame] == nil) {
580 if (DOMDocument *document = [frame DOMDocument])
581 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
582 for (DOMHTMLBodyElement *body in (id) bodies) {
583 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
584
585 UIColor *uic(nil);
586
587 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
588 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
589 DOMRGBColor *rgb([color getRGBColorValue]);
590
591 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
592 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
593 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
594 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
595
596 if (alpha == 1)
597 uic = [UIColor
598 colorWithRed:(red / 255)
599 green:(green / 255)
600 blue:(blue / 255)
601 alpha:alpha
602 ];
603 }
604 }
605
606 [super setPageColor:uic];
607 [scroller_ setBackgroundColor:color_];
608 break;
609 }
610 }
611
612 [self _didFinishLoading];
613 }
614
615 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
616 if ([frame parentFrame] != nil)
617 return;
618
619 title_ = title;
620
621 [[self navigationItem] setTitle:title_];
622 }
623
624 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
625 #if LogBrowser
626 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
627 #endif
628
629 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
630
631 if ([frame parentFrame] == nil) {
632 title_ = nil;
633 custom_ = nil;
634 style_ = nil;
635 function_ = nil;
636
637 [registered_ removeAllObjects];
638 timer_ = nil;
639
640 allowsNavigationAction_ = true;
641
642 [self setHidesNavigationBar:NO];
643 [self setScrollAlwaysBounceVertical:true];
644 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
645
646 // XXX: do we still need to do this?
647 [[self navigationItem] setTitle:nil];
648 }
649
650 [self _didStartLoading];
651 }
652
653 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
654 challenge_ = [challenge retain];
655
656 NSURLProtectionSpace *space([challenge protectionSpace]);
657 NSString *realm([space realm]);
658 if (realm == nil)
659 realm = @"";
660
661 UIAlertView *alert = [[[UIAlertView alloc]
662 initWithTitle:realm
663 message:nil
664 delegate:self
665 cancelButtonTitle:UCLocalize("CANCEL")
666 otherButtonTitles:UCLocalize("LOGIN"), nil
667 ] autorelease];
668
669 [alert setContext:@"challenge"];
670 [alert setNumberOfRows:1];
671
672 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
673 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
674
675 UITextField *username([alert textFieldAtIndex:0]); {
676 UITextInputTraits *traits([username textInputTraits]);
677 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
678 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
679 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
680 [traits setReturnKeyType:UIReturnKeyNext];
681 }
682
683 UITextField *password([alert textFieldAtIndex:1]); {
684 UITextInputTraits *traits([password textInputTraits]);
685 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
686 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
687 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
688 // XXX: UIReturnKeyDone
689 [traits setReturnKeyType:UIReturnKeyNext];
690 [traits setSecureTextEntry:YES];
691 }
692
693 [alert show];
694 }
695
696 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
697 #if LogBrowser
698 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
699 #endif
700
701 return request;
702 }
703
704 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
705 return [self _allowJavaScriptPanel];
706 }
707
708 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
709 return [self _allowJavaScriptPanel];
710 }
711
712 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
713 return [self _allowJavaScriptPanel];
714 }
715
716 - (void) webViewClose:(WebView *)view {
717 [self close];
718 }
719 // }}}
720
721 - (void) close {
722 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
723 }
724
725 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
726 NSString *context([alert context]);
727
728 if ([context isEqualToString:@"sensitive"]) {
729 switch (button) {
730 case 1:
731 sensitive_ = [NSNumber numberWithBool:YES];
732 break;
733
734 case 2:
735 sensitive_ = [NSNumber numberWithBool:NO];
736 break;
737 }
738
739 [alert dismissWithClickedButtonIndex:-1 animated:YES];
740 } else if ([context isEqualToString:@"challenge"]) {
741 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
742
743 if (button == [alert cancelButtonIndex])
744 [sender cancelAuthenticationChallenge:challenge_];
745 else if (button == [alert firstOtherButtonIndex]) {
746 NSString *username([[alert textFieldAtIndex:0] text]);
747 NSString *password([[alert textFieldAtIndex:1] text]);
748
749 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
750
751 [sender useCredential:credential forAuthenticationChallenge:challenge_];
752 }
753
754 challenge_ = nil;
755
756 [alert dismissWithClickedButtonIndex:-1 animated:YES];
757 } else if ([context isEqualToString:@"itmsappss"]) {
758 if (button == [alert cancelButtonIndex]) {
759 } else if (button == [alert firstOtherButtonIndex]) {
760 [delegate_ openURL:appstore_];
761 }
762
763 [alert dismissWithClickedButtonIndex:-1 animated:YES];
764 } else if ([context isEqualToString:@"submit"]) {
765 if (button == [alert cancelButtonIndex]) {
766 } else if (button == [alert firstOtherButtonIndex]) {
767 if (request_ != nil) {
768 WebThreadLocked lock;
769 [[self webView] loadRequest:request_];
770 }
771 }
772
773 [alert dismissWithClickedButtonIndex:-1 animated:YES];
774 }
775 }
776
777 - (UIBarButtonItemStyle) rightButtonStyle {
778 if (style_ == nil) normal:
779 return UIBarButtonItemStylePlain;
780 else if ([style_ isEqualToString:@"Normal"])
781 return UIBarButtonItemStylePlain;
782 else if ([style_ isEqualToString:@"Highlighted"])
783 return UIBarButtonItemStyleDone;
784 else goto normal;
785 }
786
787 - (UIBarButtonItem *) customButton {
788 if (custom_ == nil)
789 return nil;
790 else if ((/*clang:*/id) custom_ == [NSNull null])
791 return (UIBarButtonItem *) [NSNull null];
792
793 return [[[UIBarButtonItem alloc]
794 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
795 style:[self rightButtonStyle]
796 target:self
797 action:@selector(customButtonClicked)
798 ] autorelease];
799 }
800
801 - (UIBarButtonItem *) leftButton {
802 UINavigationItem *item([self navigationItem]);
803 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
804 return nil;
805
806 if (UINavigationController *navigation = [self navigationController])
807 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
808 return [[[UIBarButtonItem alloc]
809 initWithTitle:UCLocalize("CLOSE")
810 style:UIBarButtonItemStylePlain
811 target:self
812 action:@selector(close)
813 ] autorelease];
814
815 return nil;
816 }
817
818 - (void) applyLeftButton {
819 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
820 }
821
822 - (UIBarButtonItem *) rightButton {
823 return reloaditem_;
824 }
825
826 - (void) applyLoadingTitle {
827 [[self navigationItem] setTitle:UCLocalize("LOADING")];
828 }
829
830 - (void) layoutRightButton {
831 [[loadingitem_ view] addSubview:indicator_];
832 [[loadingitem_ view] bringSubviewToFront:indicator_];
833 }
834
835 - (void) applyRightButton {
836 if ([self isLoading]) {
837 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
838 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
839
840 [indicator_ startAnimating];
841 [self applyLoadingTitle];
842 } else {
843 [indicator_ stopAnimating];
844
845 UIBarButtonItem *button([self customButton]);
846 if (button == nil)
847 button = [self rightButton];
848 else if (button == (UIBarButtonItem *) [NSNull null])
849 button = nil;
850
851 [[self navigationItem] setRightBarButtonItem:button animated:YES];
852 }
853 }
854
855 - (void) didStartLoading {
856 // Overridden in subclasses.
857 }
858
859 - (void) _didStartLoading {
860 [self applyRightButton];
861
862 if ([loading_ count] != 1)
863 return;
864
865 if ([self retainsNetworkActivityIndicator])
866 [delegate_ retainNetworkActivityIndicator];
867
868 [self didStartLoading];
869 }
870
871 - (void) didFinishLoading {
872 // Overridden in subclasses.
873 }
874
875 - (void) _didFinishLoading {
876 if ([loading_ count] != 0)
877 return;
878
879 [self applyRightButton];
880 [[self navigationItem] setTitle:title_];
881
882 if ([self retainsNetworkActivityIndicator])
883 [delegate_ releaseNetworkActivityIndicator];
884
885 [self didFinishLoading];
886 }
887
888 - (bool) isLoading {
889 return [loading_ count] != 0;
890 }
891
892 - (id) initWithWidth:(float)width ofClass:(Class)_class {
893 if ((self = [super init]) != nil) {
894 width_ = width;
895 class_ = _class;
896
897 [super setPageColor:nil];
898
899 allowsNavigationAction_ = true;
900
901 loading_ = [NSMutableSet setWithCapacity:5];
902 registered_ = [NSMutableSet setWithCapacity:5];
903 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
904
905 reloaditem_ = [[[UIBarButtonItem alloc]
906 initWithTitle:UCLocalize("RELOAD")
907 style:[self rightButtonStyle]
908 target:self
909 action:@selector(reloadButtonClicked)
910 ] autorelease];
911
912 loadingitem_ = [[[UIBarButtonItem alloc]
913 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
914 style:UIBarButtonItemStylePlain
915 target:self
916 action:@selector(reloadButtonClicked)
917 ] autorelease];
918
919 UIActivityIndicatorViewStyle style;
920 float left;
921 if (kCFCoreFoundationVersionNumber >= 800) {
922 style = UIActivityIndicatorViewStyleGray;
923 left = 7;
924 } else {
925 style = UIActivityIndicatorViewStyleWhite;
926 left = 15;
927 }
928
929 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style] autorelease];
930 [indicator_ setFrame:CGRectMake(left, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
931 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
932
933 [self applyLeftButton];
934 [self applyRightButton];
935 } return self;
936 }
937
938 - (NSString *) applicationNameForUserAgent {
939 return nil;
940 }
941
942 - (void) loadView {
943 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
944
945 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
946 [webview_ setDelegate:self];
947 [self setView:webview_];
948
949 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
950 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
951 else
952 [webview_ setDetectsPhoneNumbers:NO];
953
954 [webview_ setScalesPageToFit:YES];
955
956 UIWebDocumentView *document([webview_ _documentView]);
957
958 // XXX: I think this improves scrolling; the hardcoded-ness sucks
959 [document setTileSize:CGSizeMake(320, 500)];
960
961 WebView *webview([document webView]);
962 WebPreferences *preferences([webview preferences]);
963
964 // XXX: I have no clue if I actually /want/ this modification
965 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
966 [webview _setLayoutInterval:0];
967 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
968 [preferences _setLayoutInterval:0];
969
970 [preferences setCacheModel:WebCacheModelDocumentBrowser];
971 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
972
973 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
974 [preferences setOfflineWebApplicationCacheEnabled:YES];
975
976 if (NSString *agent = [self applicationNameForUserAgent])
977 [webview setApplicationNameForUserAgent:agent];
978
979 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
980 [webview setShouldUpdateWhileOffscreen:NO];
981
982 #if LogMessages
983 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
984 [document setAllowsMessaging:YES];
985 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
986 [webview _setAllowsMessaging:YES];
987 #endif
988
989 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
990 scroller_ = [webview_ _scrollView];
991
992 [scroller_ setDirectionalLockEnabled:YES];
993 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
994 [scroller_ setDelaysContentTouches:NO];
995
996 [scroller_ setCanCancelContentTouches:YES];
997 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
998 UIScroller *scroller([webview_ _scroller]);
999 scroller_ = (UIScrollView *) scroller;
1000
1001 [scroller setDirectionalScrolling:YES];
1002 // XXX: we might be better off /not/ setting this on older systems
1003 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
1004 [scroller setScrollHysteresis:0]; /* 8 */
1005
1006 [scroller setThumbDetectionEnabled:NO];
1007
1008 // use NO with UIApplicationUseLegacyEvents(YES)
1009 [scroller setEventMode:YES];
1010
1011 // XXX: this is handled by setBounces, right?
1012 //[scroller setAllowsRubberBanding:YES];
1013 }
1014
1015 [webview_ setOpaque:NO];
1016 [webview_ setBackgroundColor:nil];
1017
1018 [scroller_ setFixedBackgroundPattern:YES];
1019 [scroller_ setBackgroundColor:color_];
1020 [scroller_ setClipsSubviews:YES];
1021
1022 [scroller_ setBounces:YES];
1023 [scroller_ setScrollingEnabled:YES];
1024 [scroller_ setShowBackgroundShadow:NO];
1025
1026 [self setViewportWidth:width_];
1027
1028 if ([[UIColor groupTableViewBackgroundColor] isEqual:[UIColor clearColor]]) {
1029 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
1030 [table setScrollsToTop:NO];
1031 [webview_ insertSubview:table atIndex:0];
1032 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1033 }
1034
1035 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1036
1037 ready_ = false;
1038 }
1039
1040 - (void) releaseSubviews {
1041 webview_ = nil;
1042 scroller_ = nil;
1043
1044 [self releaseNetworkActivityIndicator];
1045
1046 [super releaseSubviews];
1047 }
1048
1049 - (id) initWithWidth:(float)width {
1050 return [self initWithWidth:width ofClass:[self class]];
1051 }
1052
1053 - (id) init {
1054 return [self initWithWidth:0];
1055 }
1056
1057 - (id) initWithURL:(NSURL *)url {
1058 if ((self = [self init]) != nil) {
1059 [self setURL:url];
1060 } return self;
1061 }
1062
1063 - (id) initWithRequest:(NSURLRequest *)request {
1064 if ((self = [self init]) != nil) {
1065 [self setRequest:request];
1066 } return self;
1067 }
1068
1069 + (void) _lockJavaScript:(WebPreferences *)preferences {
1070 WebThreadLocked lock;
1071 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1072 }
1073
1074 - (void) callFunction:(WebScriptObject *)function {
1075 WebThreadLocked lock;
1076
1077 WebView *webview([[[self webView] _documentView] webView]);
1078 WebPreferences *preferences([webview preferences]);
1079
1080 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
1081 if ([webview respondsToSelector:@selector(_preferencesChanged:)])
1082 [webview _preferencesChanged:preferences];
1083 else
1084 [webview _preferencesChangedNotification:[NSNotification notificationWithName:@"" object:preferences]];
1085
1086 WebFrame *frame([webview mainFrame]);
1087 JSGlobalContextRef context([frame globalContext]);
1088
1089 JSObjectRef object([function JSObject]);
1090 if ($JSObjectCallAsFunction != NULL)
1091 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
1092
1093 // XXX: the JavaScript code submits a form, which seems to happen asynchronously
1094 NSObject *target([CyteWebViewController class]);
1095 [NSObject cancelPreviousPerformRequestsWithTarget:target selector:@selector(_lockJavaScript:) object:preferences];
1096 [target performSelector:@selector(_lockJavaScript:) withObject:preferences afterDelay:1];
1097 }
1098
1099 - (void) reloadButtonClicked {
1100 [self reloadURLWithCache:NO];
1101 }
1102
1103 - (void) _customButtonClicked {
1104 [self reloadButtonClicked];
1105 }
1106
1107 - (void) customButtonClicked {
1108 #if !AlwaysReload
1109 if (function_ != nil)
1110 [self callFunction:function_];
1111 else
1112 #endif
1113 [self _customButtonClicked];
1114 }
1115
1116 + (float) defaultWidth {
1117 return 980;
1118 }
1119
1120 - (void) setNavigationBarStyle:(NSString *)name {
1121 UIBarStyle style;
1122 if ([name isEqualToString:@"Black"])
1123 style = UIBarStyleBlack;
1124 else
1125 style = UIBarStyleDefault;
1126
1127 [[[self navigationController] navigationBar] setBarStyle:style];
1128 }
1129
1130 - (void) setNavigationBarTintColor:(UIColor *)color {
1131 [[[self navigationController] navigationBar] setTintColor:color];
1132 }
1133
1134 - (void) setBadgeValue:(id)value {
1135 [[[self navigationController] tabBarItem] setBadgeValue:value];
1136 }
1137
1138 - (void) setHidesBackButton:(bool)value {
1139 [[self navigationItem] setHidesBackButton:value];
1140 [self applyLeftButton];
1141 }
1142
1143 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1144 [self setHidesBackButton:[value boolValue]];
1145 }
1146
1147 - (void) dispatchEvent:(NSString *)event {
1148 [[self webView] dispatchEvent:event];
1149 }
1150
1151 - (bool) hidesNavigationBar {
1152 return hidesNavigationBar_;
1153 }
1154
1155 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1156 if (visible_)
1157 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1158 }
1159
1160 - (void) setHidesNavigationBar:(bool)value {
1161 if (hidesNavigationBar_ != value) {
1162 hidesNavigationBar_ = value;
1163 [self _setHidesNavigationBar:YES animated:YES];
1164 }
1165 }
1166
1167 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1168 [self setHidesNavigationBar:[value boolValue]];
1169 }
1170
1171 - (void) setScrollAlwaysBounceVertical:(bool)value {
1172 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1173 UIScrollView *scroller([webview_ _scrollView]);
1174 [scroller setAlwaysBounceVertical:value];
1175 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1176 //UIScroller *scroller([webview_ _scroller]);
1177 // XXX: I am sad here.
1178 } else return;
1179 }
1180
1181 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1182 [self setScrollAlwaysBounceVertical:[value boolValue]];
1183 }
1184
1185 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1186 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1187 UIScrollView *scroller([webview_ _scrollView]);
1188 [scroller setIndicatorStyle:style];
1189 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1190 UIScroller *scroller([webview_ _scroller]);
1191 [scroller setScrollerIndicatorStyle:style];
1192 } else return;
1193 }
1194
1195 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1196 UIScrollViewIndicatorStyle value;
1197
1198 if (false);
1199 else if ([style isEqualToString:@"default"])
1200 value = UIScrollViewIndicatorStyleDefault;
1201 else if ([style isEqualToString:@"black"])
1202 value = UIScrollViewIndicatorStyleBlack;
1203 else if ([style isEqualToString:@"white"])
1204 value = UIScrollViewIndicatorStyleWhite;
1205 else return;
1206
1207 [self setScrollIndicatorStyle:value];
1208 }
1209
1210 - (void) viewWillAppear:(BOOL)animated {
1211 visible_ = true;
1212
1213 if ([self hidesNavigationBar])
1214 [self _setHidesNavigationBar:YES animated:animated];
1215
1216 // XXX: why isn't this evern called automatically?
1217 [[self webView] setNeedsLayout];
1218
1219 [self dispatchEvent:@"CydiaViewWillAppear"];
1220 [super viewWillAppear:animated];
1221 }
1222
1223 - (void) viewDidAppear:(BOOL)animated {
1224 [super viewDidAppear:animated];
1225 [self dispatchEvent:@"CydiaViewDidAppear"];
1226 }
1227
1228 - (void) viewWillDisappear:(BOOL)animated {
1229 [self dispatchEvent:@"CydiaViewWillDisappear"];
1230 [super viewWillDisappear:animated];
1231
1232 if ([self hidesNavigationBar])
1233 [self _setHidesNavigationBar:NO animated:animated];
1234
1235 visible_ = false;
1236 }
1237
1238 - (void) viewDidDisappear:(BOOL)animated {
1239 [super viewDidDisappear:animated];
1240 [self dispatchEvent:@"CydiaViewDidDisappear"];
1241 }
1242
1243 - (void) updateHeights:(NSTimer *)timer {
1244 for (WebFrame *frame in (id) registered_)
1245 [frame cydia$updateHeight];
1246 }
1247
1248 - (void) registerFrame:(WebFrame *)frame {
1249 [registered_ addObject:frame];
1250
1251 if (timer_ == nil)
1252 timer_ = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateHeights:) userInfo:nil repeats:YES];
1253 }
1254
1255 @end