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