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