]> git.saurik.com Git - cydia.git/blame_incremental - CyteKit/WebViewController.mm
Drop capitalize from CYHex.
[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#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?
38static Class $MFMailComposeViewController;
39
40float CYScrollViewDecelerationRateNormal;
41
42@interface WebView (Apple)
43- (void) _setLayoutInterval:(float)interval;
44- (void) _setAllowsMessaging:(BOOL)allows;
45@end
46
47@interface WebPreferences (Apple)
48+ (void) _setInitialDefaultTextEncodingToSystemEncoding;
49- (void) _setLayoutInterval:(NSInteger)interval;
50- (void) setOfflineWebApplicationCacheEnabled:(BOOL)enabled;
51@end
52
53/* Indirect Delegate {{{ */
54@interface IndirectDelegate : NSObject {
55 _transient volatile id delegate_;
56}
57
58- (void) setDelegate:(id)delegate;
59- (id) initWithDelegate:(id)delegate;
60@end
61
62@implementation IndirectDelegate
63
64- (void) setDelegate:(id)delegate {
65 delegate_ = delegate;
66}
67
68- (id) initWithDelegate:(id)delegate {
69 delegate_ = delegate;
70 return self;
71}
72
73- (IMP) methodForSelector:(SEL)sel {
74 if (IMP method = [super methodForSelector:sel])
75 return method;
76 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
77 return NULL;
78}
79
80- (BOOL) respondsToSelector:(SEL)sel {
81 if ([super respondsToSelector:sel])
82 return YES;
83
84 // XXX: WebThreadCreateNSInvocation returns nil
85
86#if ShowInternals
87 fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
88#endif
89
90 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
91}
92
93- (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
94 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
95 return method;
96
97#if ShowInternals
98 fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
99#endif
100
101 if (delegate_ != nil)
102 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
103 return sig;
104
105 // XXX: I fucking hate Apple so very very bad
106 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
107}
108
109- (void) forwardInvocation:(NSInvocation *)inv {
110 SEL sel = [inv selector];
111 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
112 [inv invokeWithTarget:delegate_];
113}
114
115@end
116/* }}} */
117
118@implementation CyteWebViewController
119
120#if ShowInternals
121#include "CyteKit/UCInternal.h"
122#endif
123
124+ (void) _initialize {
125 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
126
127 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
128 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
129
130 if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
131 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
132 else // XXX: this actually might be fast on some older systems: we should look into this
133 CYScrollViewDecelerationRateNormal = 0.998;
134}
135
136- (void) dealloc {
137#if LogBrowser
138 NSLog(@"[CyteWebViewController dealloc]");
139#endif
140
141 [webview_ setDelegate:nil];
142 [indirect_ setDelegate:nil];
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_ = (id) 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_ = (id) 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 stage2_ = (id) stage1_;
529 stage1_ = nil;
530
531 [self setHidesNavigationBar:NO];
532
533 // XXX: do we still need to do this?
534 [[self navigationItem] setTitle:nil];
535 }
536
537 [self _didStartLoading];
538}
539
540- (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
541#if LogBrowser
542 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
543#endif
544
545 return request;
546}
547
548- (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
549 return [self _allowJavaScriptPanel];
550}
551
552- (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
553 return [self _allowJavaScriptPanel];
554}
555
556- (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
557 return [self _allowJavaScriptPanel];
558}
559
560- (void) webViewClose:(WebView *)view {
561 [self close];
562}
563// }}}
564
565- (void) close {
566 [[self navigationController] dismissModalViewControllerAnimated:YES];
567}
568
569- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
570 NSString *context([alert context]);
571
572 if ([context isEqualToString:@"sensitive"]) {
573 switch (button) {
574 case 1:
575 sensitive_ = [NSNumber numberWithBool:YES];
576 break;
577
578 case 2:
579 sensitive_ = [NSNumber numberWithBool:NO];
580 break;
581 }
582
583 [alert dismissWithClickedButtonIndex:-1 animated:YES];
584 } else if ([context isEqualToString:@"challenge"]) {
585 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
586
587 switch (button) {
588 case 1: {
589 NSString *username([[alert textFieldAtIndex:0] text]);
590 NSString *password([[alert textFieldAtIndex:1] text]);
591
592 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
593
594 [sender useCredential:credential forAuthenticationChallenge:challenge_];
595 } break;
596
597 case 2:
598 [sender cancelAuthenticationChallenge:challenge_];
599 break;
600
601 _nodefault
602 }
603
604 challenge_ = nil;
605
606 [alert dismissWithClickedButtonIndex:-1 animated:YES];
607 } else if ([context isEqualToString:@"submit"]) {
608 if (button == [alert cancelButtonIndex]) {
609 } else if (button == [alert firstOtherButtonIndex]) {
610 if (request_ != nil) {
611 WebThreadLocked lock;
612 [webview_ loadRequest:request_];
613 }
614 }
615
616 [alert dismissWithClickedButtonIndex:-1 animated:YES];
617 }
618}
619
620- (UIBarButtonItemStyle) rightButtonStyle {
621 if (style_ == nil) normal:
622 return UIBarButtonItemStylePlain;
623 else if ([style_ isEqualToString:@"Normal"])
624 return UIBarButtonItemStylePlain;
625 else if ([style_ isEqualToString:@"Highlighted"])
626 return UIBarButtonItemStyleDone;
627 else goto normal;
628}
629
630- (UIBarButtonItem *) customButton {
631 if (custom_ == nil)
632 return nil;
633 else if (custom_ == [NSNull null])
634 return (UIBarButtonItem *) [NSNull null];
635
636 return [[[UIBarButtonItem alloc]
637 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
638 style:[self rightButtonStyle]
639 target:self
640 action:@selector(customButtonClicked)
641 ] autorelease];
642}
643
644- (UIBarButtonItem *) leftButton {
645 UINavigationItem *item([self navigationItem]);
646 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
647 return nil;
648
649 if (UINavigationController *navigation = [self navigationController])
650 if ([[navigation parentViewController] modalViewController] == navigation)
651 return [[[UIBarButtonItem alloc]
652 initWithTitle:UCLocalize("CLOSE")
653 style:UIBarButtonItemStylePlain
654 target:self
655 action:@selector(close)
656 ] autorelease];
657
658 return nil;
659}
660
661- (void) applyLeftButton {
662 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
663}
664
665- (UIBarButtonItem *) rightButton {
666 return reloaditem_;
667}
668
669- (void) applyLoadingTitle {
670 [[self navigationItem] setTitle:UCLocalize("LOADING")];
671}
672
673- (void) layoutRightButton {
674 [[loadingitem_ view] addSubview:indicator_];
675 [[loadingitem_ view] bringSubviewToFront:indicator_];
676}
677
678- (void) applyRightButton {
679 if ([self isLoading]) {
680 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
681 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
682
683 [indicator_ startAnimating];
684 [self applyLoadingTitle];
685 } else {
686 [indicator_ stopAnimating];
687
688 UIBarButtonItem *button([self customButton]);
689 if (button == nil)
690 button = [self rightButton];
691 else if (button == (UIBarButtonItem *) [NSNull null])
692 button = nil;
693
694 [[self navigationItem] setRightBarButtonItem:button];
695 }
696}
697
698- (void) didStartLoading {
699 // Overridden in subclasses.
700}
701
702- (void) _didStartLoading {
703 [self applyRightButton];
704
705 if ([loading_ count] != 1)
706 return;
707
708 [delegate_ retainNetworkActivityIndicator];
709 [self didStartLoading];
710}
711
712- (void) didFinishLoading {
713 // Overridden in subclasses.
714}
715
716- (void) _didFinishLoading {
717 if ([loading_ count] != 0)
718 return;
719
720 [self applyRightButton];
721 [[self navigationItem] setTitle:title_];
722
723 [delegate_ releaseNetworkActivityIndicator];
724 [self didFinishLoading];
725}
726
727- (bool) isLoading {
728 return [loading_ count] != 0;
729}
730
731- (id) initWithWidth:(float)width ofClass:(Class)_class {
732 if ((self = [super init]) != nil) {
733 allowsNavigationAction_ = true;
734
735 class_ = _class;
736 loading_ = [NSMutableSet setWithCapacity:5];
737
738 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
739
740 CGRect bounds([[self view] bounds]);
741
742 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
743 [webview_ setDelegate:self];
744 [self setView:webview_];
745
746 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
747 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
748 else
749 [webview_ setDetectsPhoneNumbers:NO];
750
751 [webview_ setScalesPageToFit:YES];
752
753 UIWebDocumentView *document([webview_ _documentView]);
754
755 // XXX: I think this improves scrolling; the hardcoded-ness sucks
756 [document setTileSize:CGSizeMake(320, 500)];
757
758 [document setBackgroundColor:[UIColor clearColor]];
759
760 // XXX: this is terribly (too?) expensive
761 [document setDrawsBackground:NO];
762
763 WebView *webview([document webView]);
764 WebPreferences *preferences([webview preferences]);
765
766 // XXX: I have no clue if I actually /want/ this modification
767 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
768 [webview _setLayoutInterval:0];
769 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
770 [preferences _setLayoutInterval:0];
771
772 [preferences setCacheModel:WebCacheModelDocumentBrowser];
773 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
774 [preferences setOfflineWebApplicationCacheEnabled:YES];
775
776#if LogMessages
777 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
778 [document setAllowsMessaging:YES];
779 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
780 [webview _setAllowsMessaging:YES];
781#endif
782
783 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
784 scroller_ = [webview_ _scrollView];
785
786 [scroller_ setDirectionalLockEnabled:YES];
787 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
788 [scroller_ setDelaysContentTouches:NO];
789
790 [scroller_ setCanCancelContentTouches:YES];
791 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
792 UIScroller *scroller([webview_ _scroller]);
793 scroller_ = (UIScrollView *) scroller;
794
795 [scroller setDirectionalScrolling:YES];
796 // XXX: we might be better off /not/ setting this on older systems
797 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
798 [scroller setScrollHysteresis:0]; /* 8 */
799
800 [scroller setThumbDetectionEnabled:NO];
801
802 // use NO with UIApplicationUseLegacyEvents(YES)
803 [scroller setEventMode:YES];
804
805 // XXX: this is handled by setBounces, right?
806 //[scroller setAllowsRubberBanding:YES];
807 }
808
809 [scroller_ setFixedBackgroundPattern:YES];
810 [scroller_ setBackgroundColor:[UIColor clearColor]];
811 [scroller_ setClipsSubviews:YES];
812
813 [scroller_ setBounces:YES];
814 [scroller_ setScrollingEnabled:YES];
815 [scroller_ setShowBackgroundShadow:NO];
816
817 [self setViewportWidth:width];
818
819 reloaditem_ = [[[UIBarButtonItem alloc]
820 initWithTitle:UCLocalize("RELOAD")
821 style:[self rightButtonStyle]
822 target:self
823 action:@selector(reloadButtonClicked)
824 ] autorelease];
825
826 loadingitem_ = [[[UIBarButtonItem alloc]
827 initWithTitle:@" "
828 style:UIBarButtonItemStylePlain
829 target:self
830 action:@selector(reloadButtonClicked)
831 ] autorelease];
832
833 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
834 [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
835
836 UITableView *table([[[UITableView alloc] initWithFrame:bounds style:UITableViewStyleGrouped] autorelease]);
837 [webview_ insertSubview:table atIndex:0];
838
839 [self applyLeftButton];
840 [self applyRightButton];
841
842 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
843 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
844 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
845 } return self;
846}
847
848- (id) initWithWidth:(float)width {
849 return [self initWithWidth:width ofClass:[self class]];
850}
851
852- (id) init {
853 return [self initWithWidth:0];
854}
855
856- (id) initWithURL:(NSURL *)url {
857 if ((self = [self init]) != nil) {
858 [self setURL:url];
859 } return self;
860}
861
862- (void) callFunction:(WebScriptObject *)function {
863 WebThreadLocked lock;
864
865 WebView *webview([[webview_ _documentView] webView]);
866 WebFrame *frame([webview mainFrame]);
867
868 JSGlobalContextRef context([frame globalContext]);
869 JSObjectRef object([function JSObject]);
870 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
871}
872
873- (void) reloadButtonClicked {
874 [self reloadURLWithCache:YES];
875}
876
877- (void) _customButtonClicked {
878 [self reloadButtonClicked];
879}
880
881- (void) customButtonClicked {
882#if !AlwaysReload
883 if (function_ != nil)
884 [self callFunction:function_];
885 else
886#endif
887 [self _customButtonClicked];
888}
889
890+ (float) defaultWidth {
891 return 980;
892}
893
894- (void) setNavigationBarStyle:(NSString *)name {
895 UIBarStyle style;
896 if ([name isEqualToString:@"Black"])
897 style = UIBarStyleBlack;
898 else
899 style = UIBarStyleDefault;
900
901 [[[self navigationController] navigationBar] setBarStyle:style];
902}
903
904- (void) setNavigationBarTintColor:(UIColor *)color {
905 [[[self navigationController] navigationBar] setTintColor:color];
906}
907
908- (void) setBadgeValue:(id)value {
909 [[[self navigationController] tabBarItem] setBadgeValue:value];
910}
911
912- (void) setHidesBackButton:(bool)value {
913 [[self navigationItem] setHidesBackButton:value];
914 [self applyLeftButton];
915}
916
917- (void) setHidesBackButtonByNumber:(NSNumber *)value {
918 [self setHidesBackButton:[value boolValue]];
919}
920
921- (void) dispatchEvent:(NSString *)event {
922 [webview_ dispatchEvent:event];
923}
924
925- (bool) hidesNavigationBar {
926 return hidesNavigationBar_;
927}
928
929- (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
930 if (visible_)
931 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
932}
933
934- (void) setHidesNavigationBar:(bool)value {
935 if (hidesNavigationBar_ != value) {
936 hidesNavigationBar_ = value;
937 [self _setHidesNavigationBar:YES animated:YES];
938 }
939}
940
941- (void) setHidesNavigationBarByNumber:(NSNumber *)value {
942 [self setHidesNavigationBar:[value boolValue]];
943}
944
945- (void) viewWillAppear:(BOOL)animated {
946 visible_ = true;
947
948 if ([self hidesNavigationBar])
949 [self _setHidesNavigationBar:YES animated:animated];
950
951 [self dispatchEvent:@"CydiaViewWillAppear"];
952 [super viewWillAppear:animated];
953}
954
955- (void) viewDidAppear:(BOOL)animated {
956 [super viewDidAppear:animated];
957 [self dispatchEvent:@"CydiaViewDidAppear"];
958}
959
960- (void) viewWillDisappear:(BOOL)animated {
961 [self dispatchEvent:@"CydiaViewWillDisappear"];
962 [super viewWillDisappear:animated];
963
964 if ([self hidesNavigationBar])
965 [self _setHidesNavigationBar:NO animated:animated];
966
967 visible_ = false;
968}
969
970- (void) viewDidDisappear:(BOOL)animated {
971 [super viewDidDisappear:animated];
972 [self dispatchEvent:@"CydiaViewDidDisappear"];
973}
974
975@end