]> git.saurik.com Git - cydia.git/blob - CyteKit/WebViewController.mm
4f11b5d01c2b6050b7e8a217f65bb7214974414b
[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 loaded_ = true;
553 }
554 }
555
556 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
557 #if LogBrowser
558 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
559 #endif
560
561 [self _didFailWithError:error forFrame:frame];
562 }
563
564 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
565 #if LogBrowser
566 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
567 #endif
568
569 [self _didFailWithError:error forFrame:frame];
570 }
571
572 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
573 NSValue *object([NSValue valueWithNonretainedObject:frame]);
574 if (![loading_ containsObject:object])
575 return;
576 [loading_ removeObject:object];
577
578 if ([frame parentFrame] == nil) {
579 if (DOMDocument *document = [frame DOMDocument])
580 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
581 for (DOMHTMLBodyElement *body in (id) bodies) {
582 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
583
584 UIColor *uic(nil);
585
586 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
587 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
588 DOMRGBColor *rgb([color getRGBColorValue]);
589
590 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
591 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
592 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
593 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
594
595 if (alpha == 1)
596 uic = [UIColor
597 colorWithRed:(red / 255)
598 green:(green / 255)
599 blue:(blue / 255)
600 alpha:alpha
601 ];
602 }
603 }
604
605 [super setPageColor:uic];
606 [scroller_ setBackgroundColor:color_];
607 break;
608 }
609 }
610
611 [self _didFinishLoading];
612 }
613
614 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
615 if ([frame parentFrame] != nil)
616 return;
617
618 title_ = title;
619
620 [[self navigationItem] setTitle:title_];
621 }
622
623 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
624 #if LogBrowser
625 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
626 #endif
627
628 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
629
630 if ([frame parentFrame] == nil) {
631 title_ = nil;
632 custom_ = nil;
633 style_ = nil;
634 function_ = nil;
635
636 [registered_ removeAllObjects];
637 timer_ = nil;
638
639 allowsNavigationAction_ = true;
640
641 [self setHidesNavigationBar:NO];
642 [self setScrollAlwaysBounceVertical:true];
643 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
644
645 // XXX: do we still need to do this?
646 [[self navigationItem] setTitle:nil];
647 }
648
649 [self _didStartLoading];
650 }
651
652 - (void) webView:(WebView *)view resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
653 challenge_ = [challenge retain];
654
655 NSURLProtectionSpace *space([challenge protectionSpace]);
656 NSString *realm([space realm]);
657 if (realm == nil)
658 realm = @"";
659
660 UIAlertView *alert = [[[UIAlertView alloc]
661 initWithTitle:realm
662 message:nil
663 delegate:self
664 cancelButtonTitle:UCLocalize("CANCEL")
665 otherButtonTitles:UCLocalize("LOGIN"), nil
666 ] autorelease];
667
668 [alert setContext:@"challenge"];
669 [alert setNumberOfRows:1];
670
671 [alert addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
672 [alert addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];
673
674 UITextField *username([alert textFieldAtIndex:0]); {
675 NSObject<UITextInputTraits> *traits([username textInputTraits]);
676 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
677 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
678 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
679 [traits setReturnKeyType:UIReturnKeyNext];
680 }
681
682 UITextField *password([alert textFieldAtIndex:1]); {
683 NSObject<UITextInputTraits> *traits([password textInputTraits]);
684 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
685 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
686 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
687 // XXX: UIReturnKeyDone
688 [traits setReturnKeyType:UIReturnKeyNext];
689 [traits setSecureTextEntry:YES];
690 }
691
692 [alert show];
693 }
694
695 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
696 #if LogBrowser
697 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
698 #endif
699
700 return request;
701 }
702
703 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
704 #if LogBrowser
705 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
706 #endif
707
708 return request;
709 }
710
711 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
712 return [self _allowJavaScriptPanel];
713 }
714
715 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
716 return [self _allowJavaScriptPanel];
717 }
718
719 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
720 return [self _allowJavaScriptPanel];
721 }
722
723 - (void) webViewClose:(WebView *)view {
724 [self close];
725 }
726 // }}}
727
728 - (void) close {
729 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
730 }
731
732 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
733 NSString *context([alert context]);
734
735 if ([context isEqualToString:@"sensitive"]) {
736 switch (button) {
737 case 1:
738 sensitive_ = [NSNumber numberWithBool:YES];
739 break;
740
741 case 2:
742 sensitive_ = [NSNumber numberWithBool:NO];
743 break;
744 }
745
746 [alert dismissWithClickedButtonIndex:-1 animated:YES];
747 } else if ([context isEqualToString:@"challenge"]) {
748 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
749
750 if (button == [alert cancelButtonIndex])
751 [sender cancelAuthenticationChallenge:challenge_];
752 else if (button == [alert firstOtherButtonIndex]) {
753 NSString *username([[alert textFieldAtIndex:0] text]);
754 NSString *password([[alert textFieldAtIndex:1] text]);
755
756 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
757
758 [sender useCredential:credential forAuthenticationChallenge:challenge_];
759 }
760
761 challenge_ = nil;
762
763 [alert dismissWithClickedButtonIndex:-1 animated:YES];
764 } else if ([context isEqualToString:@"itmsappss"]) {
765 if (button == [alert cancelButtonIndex]) {
766 } else if (button == [alert firstOtherButtonIndex]) {
767 [delegate_ openURL:appstore_];
768 }
769
770 [alert dismissWithClickedButtonIndex:-1 animated:YES];
771 } else if ([context isEqualToString:@"submit"]) {
772 if (button == [alert cancelButtonIndex]) {
773 } else if (button == [alert firstOtherButtonIndex]) {
774 if (request_ != nil) {
775 WebThreadLocked lock;
776 [[self webView] loadRequest:request_];
777 }
778 }
779
780 [alert dismissWithClickedButtonIndex:-1 animated:YES];
781 }
782 }
783
784 - (UIBarButtonItemStyle) rightButtonStyle {
785 if (style_ == nil) normal:
786 return UIBarButtonItemStylePlain;
787 else if ([style_ isEqualToString:@"Normal"])
788 return UIBarButtonItemStylePlain;
789 else if ([style_ isEqualToString:@"Highlighted"])
790 return UIBarButtonItemStyleDone;
791 else goto normal;
792 }
793
794 - (UIBarButtonItem *) customButton {
795 if (custom_ == nil)
796 return [self rightButton];
797 else if ((/*clang:*/id) custom_ == [NSNull null])
798 return nil;
799
800 return [[[UIBarButtonItem alloc]
801 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
802 style:[self rightButtonStyle]
803 target:self
804 action:@selector(customButtonClicked)
805 ] autorelease];
806 }
807
808 - (UIBarButtonItem *) leftButton {
809 UINavigationItem *item([self navigationItem]);
810 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
811 return nil;
812
813 if (UINavigationController *navigation = [self navigationController])
814 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
815 return [[[UIBarButtonItem alloc]
816 initWithTitle:UCLocalize("CLOSE")
817 style:UIBarButtonItemStylePlain
818 target:self
819 action:@selector(close)
820 ] autorelease];
821
822 return nil;
823 }
824
825 - (void) applyLeftButton {
826 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
827 }
828
829 - (UIBarButtonItem *) rightButton {
830 return reloaditem_;
831 }
832
833 - (void) applyLoadingTitle {
834 [[self navigationItem] setTitle:UCLocalize("LOADING")];
835 }
836
837 - (void) layoutRightButton {
838 [[loadingitem_ view] addSubview:indicator_];
839 [[loadingitem_ view] bringSubviewToFront:indicator_];
840 }
841
842 - (void) applyRightButton {
843 if ([self isLoading]) {
844 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
845 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
846
847 [indicator_ startAnimating];
848 [self applyLoadingTitle];
849 } else {
850 [indicator_ stopAnimating];
851 [[self navigationItem] setRightBarButtonItem:[self customButton] 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(customButtonClicked)
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