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