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