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