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