]> git.saurik.com Git - cydia.git/blob - CyteKit/WebViewController.mm
622328fe2c90026441738144b8149541df66875a
[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("^(?"
405 ":" "The page at .* displayed insecure content from .*\\."
406 "|" "Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\."
407 ")\\n$");
408
409 if (NSString *data = [message objectForKey:@"message"])
410 if (irritating(data))
411 return;
412
413 NSLog(@"addMessageToConsole:%@", message);
414 #endif
415 }
416
417 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
418 #if LogBrowser
419 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ frame:%@", action, request, frame);
420 #endif
421
422 if ([frame parentFrame] == nil) {
423 if (!error_) {
424 NSURL *url(request == nil ? nil : [request URL]);
425
426 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
427 if (url != nil)
428 [self pushRequest:request asPop:NO];
429 [listener ignore];
430 }
431 }
432 }
433 }
434
435 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
436 if ([frame parentFrame] == nil)
437 if (decision == CYWebPolicyDecisionUse)
438 if (!error_) {
439 stage1_ = (id) request_;
440 request_ = request;
441 }
442 }
443
444 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
445 #if LogBrowser
446 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ newFrameName:%@", action, request, frame);
447 #endif
448
449 NSURL *url([request URL]);
450 if (url == nil)
451 return;
452
453 if ([frame isEqualToString:@"_open"])
454 [delegate_ openURL:url];
455 else {
456 NSString *scheme([[url scheme] lowercaseString]);
457 if ([scheme isEqualToString:@"mailto"])
458 [self _openMailToURL:url];
459 else
460 [self pushRequest:request asPop:[frame isEqualToString:@"_popup"]];
461 }
462
463 [listener ignore];
464 }
465
466 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
467 }
468
469 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
470 #if LogBrowser
471 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
472 #endif
473
474 [self _didFailWithError:error forFrame:frame];
475 }
476
477 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
478 #if LogBrowser
479 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
480 #endif
481
482 [self _didFailWithError:error forFrame:frame];
483 }
484
485 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
486 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
487
488 if ([frame parentFrame] == nil) {
489 stage1_ = nil;
490 stage2_ = nil;
491
492 if (DOMDocument *document = [frame DOMDocument])
493 if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
494 for (DOMHTMLBodyElement *body in (id) bodies) {
495 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
496
497 UIColor *uic(nil);
498
499 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
500 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
501 DOMRGBColor *rgb([color getRGBColorValue]);
502
503 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
504 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
505 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
506 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
507
508 if (red == 0xc7 && green == 0xce && blue == 0xd5)
509 uic = [UIColor pinStripeColor];
510 else if (alpha != 0)
511 uic = [UIColor
512 colorWithRed:(red / 255)
513 green:(green / 255)
514 blue:(blue / 255)
515 alpha:alpha
516 ];
517 }
518 }
519
520 [scroller_ setBackgroundColor:(uic ?: [UIColor clearColor])];
521 break;
522 }
523 }
524
525 [self _didFinishLoading];
526 }
527
528 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
529 if ([frame parentFrame] != nil)
530 return;
531
532 if (title_ != nil)
533 [title_ autorelease];
534 title_ = [title retain];
535
536 [[self navigationItem] setTitle:title_];
537 }
538
539 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
540 #if LogBrowser
541 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
542 #endif
543
544 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
545
546 if ([frame parentFrame] == nil) {
547 CYRelease(title_);
548 custom_ = nil;
549 style_ = nil;
550 function_ = nil;
551
552 stage2_ = (id) stage1_;
553 stage1_ = nil;
554
555 [self setHidesNavigationBar:NO];
556
557 // XXX: do we still need to do this?
558 [[self navigationItem] setTitle:nil];
559 }
560
561 [self _didStartLoading];
562 }
563
564 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
565 #if LogBrowser
566 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
567 #endif
568
569 return request;
570 }
571
572 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
573 return [self _allowJavaScriptPanel];
574 }
575
576 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
577 return [self _allowJavaScriptPanel];
578 }
579
580 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
581 return [self _allowJavaScriptPanel];
582 }
583
584 - (void) webViewClose:(WebView *)view {
585 [self close];
586 }
587 // }}}
588
589 - (void) close {
590 [[self navigationController] dismissModalViewControllerAnimated:YES];
591 }
592
593 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
594 NSString *context([alert context]);
595
596 if ([context isEqualToString:@"sensitive"]) {
597 switch (button) {
598 case 1:
599 sensitive_ = [NSNumber numberWithBool:YES];
600 break;
601
602 case 2:
603 sensitive_ = [NSNumber numberWithBool:NO];
604 break;
605 }
606
607 [alert dismissWithClickedButtonIndex:-1 animated:YES];
608 } else if ([context isEqualToString:@"challenge"]) {
609 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
610
611 switch (button) {
612 case 1: {
613 NSString *username([[alert textFieldAtIndex:0] text]);
614 NSString *password([[alert textFieldAtIndex:1] text]);
615
616 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
617
618 [sender useCredential:credential forAuthenticationChallenge:challenge_];
619 } break;
620
621 case 2:
622 [sender cancelAuthenticationChallenge:challenge_];
623 break;
624
625 _nodefault
626 }
627
628 [challenge_ release];
629 challenge_ = nil;
630
631 [alert dismissWithClickedButtonIndex:-1 animated:YES];
632 } else if ([context isEqualToString:@"submit"]) {
633 if (button == [alert cancelButtonIndex]) {
634 } else if (button == [alert firstOtherButtonIndex]) {
635 if (request_ != nil) {
636 WebThreadLocked lock;
637 [webview_ loadRequest:request_];
638 }
639 }
640
641 [alert dismissWithClickedButtonIndex:-1 animated:YES];
642 }
643 }
644
645 - (UIBarButtonItemStyle) rightButtonStyle {
646 if (style_ == nil) normal:
647 return UIBarButtonItemStylePlain;
648 else if ([style_ isEqualToString:@"Normal"])
649 return UIBarButtonItemStylePlain;
650 else if ([style_ isEqualToString:@"Highlighted"])
651 return UIBarButtonItemStyleDone;
652 else goto normal;
653 }
654
655 - (UIBarButtonItem *) customButton {
656 if (custom_ == nil)
657 return nil;
658 else if (custom_ == [NSNull null])
659 return (UIBarButtonItem *) [NSNull null];
660
661 return [[[UIBarButtonItem alloc]
662 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
663 style:[self rightButtonStyle]
664 target:self
665 action:@selector(customButtonClicked)
666 ] autorelease];
667 }
668
669 - (UIBarButtonItem *) leftButton {
670 UINavigationItem *item([self navigationItem]);
671 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
672 return nil;
673
674 if (UINavigationController *navigation = [self navigationController])
675 if ([[navigation parentViewController] modalViewController] == navigation)
676 return [[[UIBarButtonItem alloc]
677 initWithTitle:UCLocalize("CLOSE")
678 style:UIBarButtonItemStylePlain
679 target:self
680 action:@selector(close)
681 ] autorelease];
682
683 return nil;
684 }
685
686 - (void) applyLeftButton {
687 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
688 }
689
690 - (UIBarButtonItem *) rightButton {
691 return reloaditem_;
692 }
693
694 - (void) applyLoadingTitle {
695 [[self navigationItem] setTitle:UCLocalize("LOADING")];
696 }
697
698 - (void) layoutRightButton {
699 [[loadingitem_ view] addSubview:indicator_];
700 [[loadingitem_ view] bringSubviewToFront:indicator_];
701 }
702
703 - (void) applyRightButton {
704 if ([self isLoading]) {
705 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
706 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
707
708 [indicator_ startAnimating];
709 [self applyLoadingTitle];
710 } else {
711 [indicator_ stopAnimating];
712
713 UIBarButtonItem *button([self customButton]);
714 if (button == nil)
715 button = [self rightButton];
716 else if (button == (UIBarButtonItem *) [NSNull null])
717 button = nil;
718
719 [[self navigationItem] setRightBarButtonItem:button];
720 }
721 }
722
723 - (void) didStartLoading {
724 // Overridden in subclasses.
725 }
726
727 - (void) _didStartLoading {
728 [self applyRightButton];
729
730 if ([loading_ count] != 1)
731 return;
732
733 [delegate_ retainNetworkActivityIndicator];
734 [self didStartLoading];
735 }
736
737 - (void) didFinishLoading {
738 // Overridden in subclasses.
739 }
740
741 - (void) _didFinishLoading {
742 if ([loading_ count] != 0)
743 return;
744
745 [self applyRightButton];
746 [[self navigationItem] setTitle:title_];
747
748 [delegate_ releaseNetworkActivityIndicator];
749 [self didFinishLoading];
750 }
751
752 - (bool) isLoading {
753 return [loading_ count] != 0;
754 }
755
756 - (id) initWithWidth:(float)width ofClass:(Class)_class {
757 if ((self = [super init]) != nil) {
758 allowsNavigationAction_ = true;
759
760 class_ = _class;
761 loading_ = [[NSMutableSet alloc] initWithCapacity:5];
762
763 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
764
765 CGRect bounds([[self view] bounds]);
766
767 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
768 [webview_ setDelegate:self];
769 [self setView:webview_];
770
771 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
772 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
773 else
774 [webview_ setDetectsPhoneNumbers:NO];
775
776 [webview_ setScalesPageToFit:YES];
777
778 UIWebDocumentView *document([webview_ _documentView]);
779
780 // XXX: I think this improves scrolling; the hardcoded-ness sucks
781 [document setTileSize:CGSizeMake(320, 500)];
782
783 [document setBackgroundColor:[UIColor clearColor]];
784
785 // XXX: this is terribly (too?) expensive
786 [document setDrawsBackground:NO];
787
788 WebView *webview([document webView]);
789 WebPreferences *preferences([webview preferences]);
790
791 // XXX: I have no clue if I actually /want/ this modification
792 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
793 [webview _setLayoutInterval:0];
794 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
795 [preferences _setLayoutInterval:0];
796
797 [preferences setCacheModel:WebCacheModelDocumentBrowser];
798 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
799 [preferences setOfflineWebApplicationCacheEnabled:YES];
800
801 #if LogMessages
802 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
803 [document setAllowsMessaging:YES];
804 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
805 [webview _setAllowsMessaging:YES];
806 #endif
807
808 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
809 scroller_ = [webview_ _scrollView];
810
811 [scroller_ setDirectionalLockEnabled:YES];
812 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
813 [scroller_ setDelaysContentTouches:NO];
814
815 [scroller_ setCanCancelContentTouches:YES];
816 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
817 UIScroller *scroller([webview_ _scroller]);
818 scroller_ = (UIScrollView *) scroller;
819
820 [scroller setDirectionalScrolling:YES];
821 // XXX: we might be better off /not/ setting this on older systems
822 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
823 [scroller setScrollHysteresis:0]; /* 8 */
824
825 [scroller setThumbDetectionEnabled:NO];
826
827 // use NO with UIApplicationUseLegacyEvents(YES)
828 [scroller setEventMode:YES];
829
830 // XXX: this is handled by setBounces, right?
831 //[scroller setAllowsRubberBanding:YES];
832 }
833
834 [scroller_ setFixedBackgroundPattern:YES];
835 [scroller_ setBackgroundColor:[UIColor clearColor]];
836 [scroller_ setClipsSubviews:YES];
837
838 [scroller_ setBounces:YES];
839 [scroller_ setScrollingEnabled:YES];
840 [scroller_ setShowBackgroundShadow:NO];
841
842 [self setViewportWidth:width];
843
844 reloaditem_ = [[UIBarButtonItem alloc]
845 initWithTitle:UCLocalize("RELOAD")
846 style:[self rightButtonStyle]
847 target:self
848 action:@selector(reloadButtonClicked)
849 ];
850
851 loadingitem_ = [[UIBarButtonItem alloc]
852 initWithTitle:@" "
853 style:UIBarButtonItemStylePlain
854 target:self
855 action:@selector(reloadButtonClicked)
856 ];
857
858 indicator_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
859 [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
860
861 UITableView *table([[[UITableView alloc] initWithFrame:bounds style:UITableViewStyleGrouped] autorelease]);
862 [webview_ insertSubview:table atIndex:0];
863
864 [self applyLeftButton];
865 [self applyRightButton];
866
867 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
868 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
869 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
870 } return self;
871 }
872
873 - (id) initWithWidth:(float)width {
874 return [self initWithWidth:width ofClass:[self class]];
875 }
876
877 - (id) init {
878 return [self initWithWidth:0];
879 }
880
881 - (id) initWithURL:(NSURL *)url {
882 if ((self = [self init]) != nil) {
883 [self setURL:url];
884 } return self;
885 }
886
887 - (void) callFunction:(WebScriptObject *)function {
888 WebThreadLocked lock;
889
890 WebView *webview([[webview_ _documentView] webView]);
891 WebFrame *frame([webview mainFrame]);
892
893 JSGlobalContextRef context([frame globalContext]);
894 JSObjectRef object([function JSObject]);
895 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
896 }
897
898 - (void) reloadButtonClicked {
899 [self reloadURLWithCache:YES];
900 }
901
902 - (void) _customButtonClicked {
903 [self reloadButtonClicked];
904 }
905
906 - (void) customButtonClicked {
907 #if !AlwaysReload
908 if (function_ != nil)
909 [self callFunction:function_];
910 else
911 #endif
912 [self _customButtonClicked];
913 }
914
915 + (float) defaultWidth {
916 return 980;
917 }
918
919 - (void) setNavigationBarStyle:(NSString *)name {
920 UIBarStyle style;
921 if ([name isEqualToString:@"Black"])
922 style = UIBarStyleBlack;
923 else
924 style = UIBarStyleDefault;
925
926 [[[self navigationController] navigationBar] setBarStyle:style];
927 }
928
929 - (void) setNavigationBarTintColor:(UIColor *)color {
930 [[[self navigationController] navigationBar] setTintColor:color];
931 }
932
933 - (void) setBadgeValue:(id)value {
934 [[[self navigationController] tabBarItem] setBadgeValue:value];
935 }
936
937 - (void) setHidesBackButton:(bool)value {
938 [[self navigationItem] setHidesBackButton:value];
939 [self applyLeftButton];
940 }
941
942 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
943 [self setHidesBackButton:[value boolValue]];
944 }
945
946 - (void) dispatchEvent:(NSString *)event {
947 [webview_ dispatchEvent:event];
948 }
949
950 - (bool) hidesNavigationBar {
951 return hidesNavigationBar_;
952 }
953
954 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
955 if (visible_)
956 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
957 }
958
959 - (void) setHidesNavigationBar:(bool)value {
960 if (hidesNavigationBar_ != value) {
961 hidesNavigationBar_ = value;
962 [self _setHidesNavigationBar:YES animated:YES];
963 }
964 }
965
966 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
967 [self setHidesNavigationBar:[value boolValue]];
968 }
969
970 - (void) viewWillAppear:(BOOL)animated {
971 visible_ = true;
972
973 if ([self hidesNavigationBar])
974 [self _setHidesNavigationBar:YES animated:animated];
975
976 [self dispatchEvent:@"CydiaViewWillAppear"];
977 [super viewWillAppear:animated];
978 }
979
980 - (void) viewDidAppear:(BOOL)animated {
981 [super viewDidAppear:animated];
982 [self dispatchEvent:@"CydiaViewDidAppear"];
983 }
984
985 - (void) viewWillDisappear:(BOOL)animated {
986 [self dispatchEvent:@"CydiaViewWillDisappear"];
987 [super viewWillDisappear:animated];
988
989 if ([self hidesNavigationBar])
990 [self _setHidesNavigationBar:NO animated:animated];
991
992 visible_ = false;
993 }
994
995 - (void) viewDidDisappear:(BOOL)animated {
996 [super viewDidDisappear:animated];
997 [self dispatchEvent:@"CydiaViewDidDisappear"];
998 }
999
1000 @end