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