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