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