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