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