]> git.saurik.com Git - cydia.git/blob - CyteKit/WebViewController.mm
08839728ee15fc75734b8dc99f723b24fbe5f4a8
[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 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
541
542 if ([frame parentFrame] == nil) {
543 CYRelease(title_);
544 custom_ = nil;
545 style_ = nil;
546 function_ = nil;
547
548 stage2_ = (id) stage1_;
549 stage1_ = nil;
550
551 [self setHidesNavigationBar:NO];
552
553 // XXX: do we still need to do this?
554 [[self navigationItem] setTitle:nil];
555 }
556
557 [self _didStartLoading];
558 }
559
560 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
561 #if LogBrowser
562 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
563 #endif
564
565 return request;
566 }
567
568 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
569 return [self _allowJavaScriptPanel];
570 }
571
572 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
573 return [self _allowJavaScriptPanel];
574 }
575
576 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
577 return [self _allowJavaScriptPanel];
578 }
579
580 - (void) webViewClose:(WebView *)view {
581 [self close];
582 }
583 // }}}
584
585 - (void) close {
586 [[self navigationController] dismissModalViewControllerAnimated:YES];
587 }
588
589 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
590 NSString *context([alert context]);
591
592 if ([context isEqualToString:@"sensitive"]) {
593 switch (button) {
594 case 1:
595 sensitive_ = [NSNumber numberWithBool:YES];
596 break;
597
598 case 2:
599 sensitive_ = [NSNumber numberWithBool:NO];
600 break;
601 }
602
603 [alert dismissWithClickedButtonIndex:-1 animated:YES];
604 } else if ([context isEqualToString:@"challenge"]) {
605 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
606
607 switch (button) {
608 case 1: {
609 NSString *username([[alert textFieldAtIndex:0] text]);
610 NSString *password([[alert textFieldAtIndex:1] text]);
611
612 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
613
614 [sender useCredential:credential forAuthenticationChallenge:challenge_];
615 } break;
616
617 case 2:
618 [sender cancelAuthenticationChallenge:challenge_];
619 break;
620
621 _nodefault
622 }
623
624 [challenge_ release];
625 challenge_ = nil;
626
627 [alert dismissWithClickedButtonIndex:-1 animated:YES];
628 } else if ([context isEqualToString:@"submit"]) {
629 if (button == [alert cancelButtonIndex]) {
630 } else if (button == [alert firstOtherButtonIndex]) {
631 if (request_ != nil) {
632 WebThreadLocked lock;
633 [webview_ loadRequest:request_];
634 }
635 }
636
637 [alert dismissWithClickedButtonIndex:-1 animated:YES];
638 }
639 }
640
641 - (UIBarButtonItemStyle) rightButtonStyle {
642 if (style_ == nil) normal:
643 return UIBarButtonItemStylePlain;
644 else if ([style_ isEqualToString:@"Normal"])
645 return UIBarButtonItemStylePlain;
646 else if ([style_ isEqualToString:@"Highlighted"])
647 return UIBarButtonItemStyleDone;
648 else goto normal;
649 }
650
651 - (UIBarButtonItem *) customButton {
652 if (custom_ == nil)
653 return nil;
654 else if (custom_ == [NSNull null])
655 return (UIBarButtonItem *) [NSNull null];
656
657 return [[[UIBarButtonItem alloc]
658 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
659 style:[self rightButtonStyle]
660 target:self
661 action:@selector(customButtonClicked)
662 ] autorelease];
663 }
664
665 - (UIBarButtonItem *) leftButton {
666 UINavigationItem *item([self navigationItem]);
667 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
668 return nil;
669
670 if (UINavigationController *navigation = [self navigationController])
671 if ([[navigation parentViewController] modalViewController] == navigation)
672 return [[[UIBarButtonItem alloc]
673 initWithTitle:UCLocalize("CLOSE")
674 style:UIBarButtonItemStylePlain
675 target:self
676 action:@selector(close)
677 ] autorelease];
678
679 return nil;
680 }
681
682 - (void) applyLeftButton {
683 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
684 }
685
686 - (UIBarButtonItem *) rightButton {
687 return reloaditem_;
688 }
689
690 - (void) applyLoadingTitle {
691 [[self navigationItem] setTitle:UCLocalize("LOADING")];
692 }
693
694 - (void) layoutRightButton {
695 [[loadingitem_ view] addSubview:indicator_];
696 [[loadingitem_ view] bringSubviewToFront:indicator_];
697 }
698
699 - (void) applyRightButton {
700 if ([self isLoading]) {
701 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
702 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
703
704 [indicator_ startAnimating];
705 [self applyLoadingTitle];
706 } else {
707 [indicator_ stopAnimating];
708
709 UIBarButtonItem *button([self customButton]);
710 if (button == nil)
711 button = [self rightButton];
712 else if (button == (UIBarButtonItem *) [NSNull null])
713 button = nil;
714
715 [[self navigationItem] setRightBarButtonItem:button];
716 }
717 }
718
719 - (void) didStartLoading {
720 // Overridden in subclasses.
721 }
722
723 - (void) _didStartLoading {
724 [self applyRightButton];
725
726 if ([loading_ count] != 1)
727 return;
728
729 [delegate_ retainNetworkActivityIndicator];
730 [self didStartLoading];
731 }
732
733 - (void) didFinishLoading {
734 // Overridden in subclasses.
735 }
736
737 - (void) _didFinishLoading {
738 if ([loading_ count] != 0)
739 return;
740
741 [self applyRightButton];
742 [[self navigationItem] setTitle:title_];
743
744 [delegate_ releaseNetworkActivityIndicator];
745 [self didFinishLoading];
746 }
747
748 - (bool) isLoading {
749 return [loading_ count] != 0;
750 }
751
752 - (id) initWithWidth:(float)width ofClass:(Class)_class {
753 if ((self = [super init]) != nil) {
754 allowsNavigationAction_ = true;
755
756 class_ = _class;
757 loading_ = [[NSMutableSet alloc] initWithCapacity:5];
758
759 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
760
761 CGRect bounds([[self view] bounds]);
762
763 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
764 [webview_ setDelegate:self];
765 [self setView:webview_];
766
767 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
768 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
769 else
770 [webview_ setDetectsPhoneNumbers:NO];
771
772 [webview_ setScalesPageToFit:YES];
773
774 UIWebDocumentView *document([webview_ _documentView]);
775
776 // XXX: I think this improves scrolling; the hardcoded-ness sucks
777 [document setTileSize:CGSizeMake(320, 500)];
778
779 [document setBackgroundColor:[UIColor clearColor]];
780
781 // XXX: this is terribly (too?) expensive
782 [document setDrawsBackground:NO];
783
784 WebView *webview([document webView]);
785 WebPreferences *preferences([webview preferences]);
786
787 // XXX: I have no clue if I actually /want/ this modification
788 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
789 [webview _setLayoutInterval:0];
790 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
791 [preferences _setLayoutInterval:0];
792
793 [preferences setCacheModel:WebCacheModelDocumentBrowser];
794 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
795 [preferences setOfflineWebApplicationCacheEnabled:YES];
796
797 #if LogMessages
798 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
799 [document setAllowsMessaging:YES];
800 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
801 [webview _setAllowsMessaging:YES];
802 #endif
803
804 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
805 scroller_ = [webview_ _scrollView];
806
807 [scroller_ setDirectionalLockEnabled:YES];
808 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
809 [scroller_ setDelaysContentTouches:NO];
810
811 [scroller_ setCanCancelContentTouches:YES];
812 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
813 UIScroller *scroller([webview_ _scroller]);
814 scroller_ = (UIScrollView *) scroller;
815
816 [scroller setDirectionalScrolling:YES];
817 // XXX: we might be better off /not/ setting this on older systems
818 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
819 [scroller setScrollHysteresis:0]; /* 8 */
820
821 [scroller setThumbDetectionEnabled:NO];
822
823 // use NO with UIApplicationUseLegacyEvents(YES)
824 [scroller setEventMode:YES];
825
826 // XXX: this is handled by setBounces, right?
827 //[scroller setAllowsRubberBanding:YES];
828 }
829
830 [scroller_ setFixedBackgroundPattern:YES];
831 [scroller_ setBackgroundColor:[UIColor clearColor]];
832 [scroller_ setClipsSubviews:YES];
833
834 [scroller_ setBounces:YES];
835 [scroller_ setScrollingEnabled:YES];
836 [scroller_ setShowBackgroundShadow:NO];
837
838 [self setViewportWidth:width];
839
840 reloaditem_ = [[UIBarButtonItem alloc]
841 initWithTitle:UCLocalize("RELOAD")
842 style:[self rightButtonStyle]
843 target:self
844 action:@selector(reloadButtonClicked)
845 ];
846
847 loadingitem_ = [[UIBarButtonItem alloc]
848 initWithTitle:@" "
849 style:UIBarButtonItemStylePlain
850 target:self
851 action:@selector(reloadButtonClicked)
852 ];
853
854 indicator_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
855 [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
856
857 UITableView *table([[[UITableView alloc] initWithFrame:bounds style:UITableViewStyleGrouped] autorelease]);
858 [webview_ insertSubview:table atIndex:0];
859
860 [self applyLeftButton];
861 [self applyRightButton];
862
863 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
864 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
865 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
866 } return self;
867 }
868
869 - (id) initWithWidth:(float)width {
870 return [self initWithWidth:width ofClass:[self class]];
871 }
872
873 - (id) init {
874 return [self initWithWidth:0];
875 }
876
877 - (id) initWithURL:(NSURL *)url {
878 if ((self = [self init]) != nil) {
879 [self setURL:url];
880 } return self;
881 }
882
883 - (void) callFunction:(WebScriptObject *)function {
884 WebThreadLocked lock;
885
886 WebView *webview([[webview_ _documentView] webView]);
887 WebFrame *frame([webview mainFrame]);
888
889 JSGlobalContextRef context([frame globalContext]);
890 JSObjectRef object([function JSObject]);
891 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
892 }
893
894 - (void) reloadButtonClicked {
895 [self reloadURLWithCache:YES];
896 }
897
898 - (void) _customButtonClicked {
899 [self reloadButtonClicked];
900 }
901
902 - (void) customButtonClicked {
903 #if !AlwaysReload
904 if (function_ != nil)
905 [self callFunction:function_];
906 else
907 #endif
908 [self _customButtonClicked];
909 }
910
911 + (float) defaultWidth {
912 return 980;
913 }
914
915 - (void) setNavigationBarStyle:(NSString *)name {
916 UIBarStyle style;
917 if ([name isEqualToString:@"Black"])
918 style = UIBarStyleBlack;
919 else
920 style = UIBarStyleDefault;
921
922 [[[self navigationController] navigationBar] setBarStyle:style];
923 }
924
925 - (void) setNavigationBarTintColor:(UIColor *)color {
926 [[[self navigationController] navigationBar] setTintColor:color];
927 }
928
929 - (void) setBadgeValue:(id)value {
930 [[[self navigationController] tabBarItem] setBadgeValue:value];
931 }
932
933 - (void) setHidesBackButton:(bool)value {
934 [[self navigationItem] setHidesBackButton:value];
935 [self applyLeftButton];
936 }
937
938 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
939 [self setHidesBackButton:[value boolValue]];
940 }
941
942 - (void) dispatchEvent:(NSString *)event {
943 [webview_ dispatchEvent:event];
944 }
945
946 - (bool) hidesNavigationBar {
947 return hidesNavigationBar_;
948 }
949
950 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
951 if (visible_)
952 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
953 }
954
955 - (void) setHidesNavigationBar:(bool)value {
956 if (hidesNavigationBar_ != value) {
957 hidesNavigationBar_ = value;
958 [self _setHidesNavigationBar:YES animated:YES];
959 }
960 }
961
962 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
963 [self setHidesNavigationBar:[value boolValue]];
964 }
965
966 - (void) viewWillAppear:(BOOL)animated {
967 visible_ = true;
968
969 if ([self hidesNavigationBar])
970 [self _setHidesNavigationBar:YES animated:animated];
971
972 [self dispatchEvent:@"CydiaViewWillAppear"];
973 [super viewWillAppear:animated];
974 }
975
976 - (void) viewDidAppear:(BOOL)animated {
977 [super viewDidAppear:animated];
978 [self dispatchEvent:@"CydiaViewDidAppear"];
979 }
980
981 - (void) viewWillDisappear:(BOOL)animated {
982 [self dispatchEvent:@"CydiaViewWillDisappear"];
983 [super viewWillDisappear:animated];
984
985 if ([self hidesNavigationBar])
986 [self _setHidesNavigationBar:NO animated:animated];
987
988 visible_ = false;
989 }
990
991 - (void) viewDidDisappear:(BOOL)animated {
992 [super viewDidDisappear:animated];
993 [self dispatchEvent:@"CydiaViewDidDisappear"];
994 }
995
996 @end