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