]> git.saurik.com Git - cydia.git/blob - CyteKit/WebViewController.mm
Consider a WebView loaded when it commits.
[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_ = stage2_;
358 stage1_ = nil;
359 stage2_ = nil;
360 return;
361 }
362
363 if ([frame parentFrame] == nil) {
364 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
365 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
366 [[error localizedDescription] stringByAddingPercentEscapes]
367 ]]];
368
369 error_ = true;
370 }
371 }
372
373 - (void) pushRequest:(NSURLRequest *)request asPop:(bool)pop {
374 NSURL *url([request URL]);
375
376 // XXX: filter to internal usage?
377 CyteViewController *page([delegate_ pageForURL:url forExternal:NO]);
378
379 if (page == nil) {
380 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
381 [browser setRequest:request];
382 page = browser;
383 }
384
385 [page setDelegate:delegate_];
386
387 if (!pop) {
388 [[self navigationItem] setTitle:title_];
389
390 [[self navigationController] pushViewController:page animated:YES];
391 } else {
392 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
393
394 [navigation setDelegate:delegate_];
395
396 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
397 initWithTitle:UCLocalize("CLOSE")
398 style:UIBarButtonItemStylePlain
399 target:page
400 action:@selector(close)
401 ] autorelease]];
402
403 [[self navigationController] presentModalViewController:navigation animated:YES];
404 }
405 }
406
407 // CyteWebViewDelegate {{{
408 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
409 #if LogMessages
410 static Pcre irritating("^(?"
411 ":" "The page at .* displayed insecure content from .*\\."
412 "|" "Unsafe JavaScript attempt to access frame with URL .* from frame with URL .*\\. Domains, protocols and ports must match\\."
413 ")\\n$");
414
415 if (NSString *data = [message objectForKey:@"message"])
416 if (irritating(data))
417 return;
418
419 NSLog(@"addMessageToConsole:%@", message);
420 #endif
421 }
422
423 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
424 #if LogBrowser
425 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ frame:%@", action, request, frame);
426 #endif
427
428 if ([frame parentFrame] == nil) {
429 if (!error_) {
430 NSURL *url(request == nil ? nil : [request URL]);
431
432 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
433 if (url != nil)
434 [self pushRequest:request asPop:NO];
435 [listener ignore];
436 }
437 }
438 }
439 }
440
441 - (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
442 if ([frame parentFrame] == nil)
443 if (decision == CYWebPolicyDecisionUse)
444 if (!error_) {
445 stage1_ = request_;
446 request_ = request;
447 }
448 }
449
450 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
451 #if LogBrowser
452 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ newFrameName:%@", action, request, frame);
453 #endif
454
455 NSURL *url([request URL]);
456 if (url == nil)
457 return;
458
459 if ([frame isEqualToString:@"_open"])
460 [delegate_ openURL:url];
461 else {
462 NSString *scheme([[url scheme] lowercaseString]);
463 if ([scheme isEqualToString:@"mailto"])
464 [self _openMailToURL:url];
465 else
466 [self pushRequest:request asPop:[frame isEqualToString:@"_popup"]];
467 }
468
469 [listener ignore];
470 }
471
472 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
473 }
474
475 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
476 #if LogBrowser
477 NSLog(@"didCommitLoadForFrame:%@", frame);
478 #endif
479
480 if ([frame parentFrame] == nil) {
481 loaded_ = true;
482 }
483 }
484
485 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
486 #if LogBrowser
487 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
488 #endif
489
490 [self _didFailWithError:error forFrame:frame];
491 }
492
493 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
494 #if LogBrowser
495 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
496 #endif
497
498 [self _didFailWithError:error forFrame:frame];
499 }
500
501 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
502 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
503
504 if ([frame parentFrame] == nil) {
505 stage1_ = nil;
506 stage2_ = nil;
507
508 if (DOMDocument *document = [frame DOMDocument])
509 if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
510 for (DOMHTMLBodyElement *body in (id) bodies) {
511 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
512
513 UIColor *uic(nil);
514
515 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
516 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
517 DOMRGBColor *rgb([color getRGBColorValue]);
518
519 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
520 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
521 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
522 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
523
524 if (red == 0xc7 && green == 0xce && blue == 0xd5)
525 uic = [UIColor pinStripeColor];
526 else if (alpha != 0)
527 uic = [UIColor
528 colorWithRed:(red / 255)
529 green:(green / 255)
530 blue:(blue / 255)
531 alpha:alpha
532 ];
533 }
534 }
535
536 [scroller_ setBackgroundColor:(uic ?: [UIColor clearColor])];
537 break;
538 }
539 }
540
541 [self _didFinishLoading];
542 }
543
544 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
545 if ([frame parentFrame] != nil)
546 return;
547
548 title_ = title;
549
550 [[self navigationItem] setTitle:title_];
551 }
552
553 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
554 #if LogBrowser
555 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
556 #endif
557
558 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
559
560 if ([frame parentFrame] == nil) {
561 title_ = nil;
562 custom_ = nil;
563 style_ = nil;
564 function_ = nil;
565
566 allowsNavigationAction_ = true;
567
568 stage2_ = stage1_;
569 stage1_ = nil;
570
571 [self setHidesNavigationBar:NO];
572
573 // XXX: do we still need to do this?
574 [[self navigationItem] setTitle:nil];
575 }
576
577 [self _didStartLoading];
578 }
579
580 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
581 #if LogBrowser
582 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
583 #endif
584
585 return request;
586 }
587
588 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
589 return [self _allowJavaScriptPanel];
590 }
591
592 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
593 return [self _allowJavaScriptPanel];
594 }
595
596 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
597 return [self _allowJavaScriptPanel];
598 }
599
600 - (void) webViewClose:(WebView *)view {
601 [self close];
602 }
603 // }}}
604
605 - (void) close {
606 [[[self navigationController] parentViewController] dismissModalViewControllerAnimated:YES];
607 }
608
609 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
610 NSString *context([alert context]);
611
612 if ([context isEqualToString:@"sensitive"]) {
613 switch (button) {
614 case 1:
615 sensitive_ = [NSNumber numberWithBool:YES];
616 break;
617
618 case 2:
619 sensitive_ = [NSNumber numberWithBool:NO];
620 break;
621 }
622
623 [alert dismissWithClickedButtonIndex:-1 animated:YES];
624 } else if ([context isEqualToString:@"challenge"]) {
625 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
626
627 switch (button) {
628 case 1: {
629 NSString *username([[alert textFieldAtIndex:0] text]);
630 NSString *password([[alert textFieldAtIndex:1] text]);
631
632 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
633
634 [sender useCredential:credential forAuthenticationChallenge:challenge_];
635 } break;
636
637 case 2:
638 [sender cancelAuthenticationChallenge:challenge_];
639 break;
640
641 _nodefault
642 }
643
644 challenge_ = nil;
645
646 [alert dismissWithClickedButtonIndex:-1 animated:YES];
647 } else if ([context isEqualToString:@"submit"]) {
648 if (button == [alert cancelButtonIndex]) {
649 } else if (button == [alert firstOtherButtonIndex]) {
650 if (request_ != nil) {
651 WebThreadLocked lock;
652 [[self webView] loadRequest:request_];
653 }
654 }
655
656 [alert dismissWithClickedButtonIndex:-1 animated:YES];
657 }
658 }
659
660 - (UIBarButtonItemStyle) rightButtonStyle {
661 if (style_ == nil) normal:
662 return UIBarButtonItemStylePlain;
663 else if ([style_ isEqualToString:@"Normal"])
664 return UIBarButtonItemStylePlain;
665 else if ([style_ isEqualToString:@"Highlighted"])
666 return UIBarButtonItemStyleDone;
667 else goto normal;
668 }
669
670 - (UIBarButtonItem *) customButton {
671 if (custom_ == nil)
672 return nil;
673 else if (custom_ == [NSNull null])
674 return (UIBarButtonItem *) [NSNull null];
675
676 return [[[UIBarButtonItem alloc]
677 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
678 style:[self rightButtonStyle]
679 target:self
680 action:@selector(customButtonClicked)
681 ] autorelease];
682 }
683
684 - (UIBarButtonItem *) leftButton {
685 UINavigationItem *item([self navigationItem]);
686 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
687 return nil;
688
689 if (UINavigationController *navigation = [self navigationController])
690 if ([[navigation parentViewController] modalViewController] == navigation)
691 return [[[UIBarButtonItem alloc]
692 initWithTitle:UCLocalize("CLOSE")
693 style:UIBarButtonItemStylePlain
694 target:self
695 action:@selector(close)
696 ] autorelease];
697
698 return nil;
699 }
700
701 - (void) applyLeftButton {
702 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
703 }
704
705 - (UIBarButtonItem *) rightButton {
706 return reloaditem_;
707 }
708
709 - (void) applyLoadingTitle {
710 [[self navigationItem] setTitle:UCLocalize("LOADING")];
711 }
712
713 - (void) layoutRightButton {
714 [[loadingitem_ view] addSubview:indicator_];
715 [[loadingitem_ view] bringSubviewToFront:indicator_];
716 }
717
718 - (void) applyRightButton {
719 if ([self isLoading]) {
720 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
721 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
722
723 [indicator_ startAnimating];
724 [self applyLoadingTitle];
725 } else {
726 [indicator_ stopAnimating];
727
728 UIBarButtonItem *button([self customButton]);
729 if (button == nil)
730 button = [self rightButton];
731 else if (button == (UIBarButtonItem *) [NSNull null])
732 button = nil;
733
734 [[self navigationItem] setRightBarButtonItem:button animated:YES];
735 }
736 }
737
738 - (void) didStartLoading {
739 // Overridden in subclasses.
740 }
741
742 - (void) _didStartLoading {
743 [self applyRightButton];
744
745 if ([loading_ count] != 1)
746 return;
747
748 [delegate_ retainNetworkActivityIndicator];
749 [self didStartLoading];
750 }
751
752 - (void) didFinishLoading {
753 // Overridden in subclasses.
754 }
755
756 - (void) _didFinishLoading {
757 if ([loading_ count] != 0)
758 return;
759
760 [self applyRightButton];
761 [[self navigationItem] setTitle:title_];
762
763 [delegate_ releaseNetworkActivityIndicator];
764 [self didFinishLoading];
765 }
766
767 - (bool) isLoading {
768 return [loading_ count] != 0;
769 }
770
771 - (id) initWithWidth:(float)width ofClass:(Class)_class {
772 if ((self = [super init]) != nil) {
773 width_ = width;
774 class_ = _class;
775
776 allowsNavigationAction_ = true;
777
778 loading_ = [NSMutableSet setWithCapacity:5];
779 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
780
781 reloaditem_ = [[[UIBarButtonItem alloc]
782 initWithTitle:UCLocalize("RELOAD")
783 style:[self rightButtonStyle]
784 target:self
785 action:@selector(reloadButtonClicked)
786 ] autorelease];
787
788 loadingitem_ = [[[UIBarButtonItem alloc]
789 initWithTitle:@" "
790 style:UIBarButtonItemStylePlain
791 target:self
792 action:@selector(reloadButtonClicked)
793 ] autorelease];
794
795 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
796 [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
797 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
798
799 [self applyLeftButton];
800 [self applyRightButton];
801 } return self;
802 }
803
804 - (NSString *) applicationNameForUserAgent {
805 return nil;
806 }
807
808 - (void) loadView {
809 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
810
811 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
812 [webview_ setDelegate:self];
813 [self setView:webview_];
814
815 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
816 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
817 else
818 [webview_ setDetectsPhoneNumbers:NO];
819
820 [webview_ setScalesPageToFit:YES];
821
822 UIWebDocumentView *document([webview_ _documentView]);
823
824 // XXX: I think this improves scrolling; the hardcoded-ness sucks
825 [document setTileSize:CGSizeMake(320, 500)];
826
827 [document setBackgroundColor:[UIColor clearColor]];
828
829 // XXX: this is terribly (too?) expensive
830 [document setDrawsBackground:NO];
831
832 WebView *webview([document webView]);
833 WebPreferences *preferences([webview preferences]);
834
835 // XXX: I have no clue if I actually /want/ this modification
836 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
837 [webview _setLayoutInterval:0];
838 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
839 [preferences _setLayoutInterval:0];
840
841 [preferences setCacheModel:WebCacheModelDocumentBrowser];
842 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
843 [preferences setOfflineWebApplicationCacheEnabled:YES];
844
845 if (NSString *agent = [self applicationNameForUserAgent])
846 [webview setApplicationNameForUserAgent:agent];
847
848 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
849 [webview setShouldUpdateWhileOffscreen:NO];
850
851 #if LogMessages
852 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
853 [document setAllowsMessaging:YES];
854 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
855 [webview _setAllowsMessaging:YES];
856 #endif
857
858 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
859 scroller_ = [webview_ _scrollView];
860
861 [scroller_ setDirectionalLockEnabled:YES];
862 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
863 [scroller_ setDelaysContentTouches:NO];
864
865 [scroller_ setCanCancelContentTouches:YES];
866 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
867 UIScroller *scroller([webview_ _scroller]);
868 scroller_ = (UIScrollView *) scroller;
869
870 [scroller setDirectionalScrolling:YES];
871 // XXX: we might be better off /not/ setting this on older systems
872 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
873 [scroller setScrollHysteresis:0]; /* 8 */
874
875 [scroller setThumbDetectionEnabled:NO];
876
877 // use NO with UIApplicationUseLegacyEvents(YES)
878 [scroller setEventMode:YES];
879
880 // XXX: this is handled by setBounces, right?
881 //[scroller setAllowsRubberBanding:YES];
882 }
883
884 [scroller_ setFixedBackgroundPattern:YES];
885 [scroller_ setBackgroundColor:[UIColor clearColor]];
886 [scroller_ setClipsSubviews:YES];
887
888 [scroller_ setBounces:YES];
889 [scroller_ setScrollingEnabled:YES];
890 [scroller_ setShowBackgroundShadow:NO];
891
892 [self setViewportWidth:width_];
893
894 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
895 [table setScrollsToTop:NO];
896 [webview_ insertSubview:table atIndex:0];
897
898 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
899 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
900
901 ready_ = false;
902 }
903
904 - (void) releaseSubviews {
905 webview_ = nil;
906 scroller_ = nil;
907
908 [super releaseSubviews];
909 }
910
911 - (id) initWithWidth:(float)width {
912 return [self initWithWidth:width ofClass:[self class]];
913 }
914
915 - (id) init {
916 return [self initWithWidth:0];
917 }
918
919 - (id) initWithURL:(NSURL *)url {
920 if ((self = [self init]) != nil) {
921 [self setURL:url];
922 } return self;
923 }
924
925 - (void) callFunction:(WebScriptObject *)function {
926 WebThreadLocked lock;
927
928 WebView *webview([[[self webView] _documentView] webView]);
929 WebFrame *frame([webview mainFrame]);
930
931 JSGlobalContextRef context([frame globalContext]);
932 JSObjectRef object([function JSObject]);
933 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
934 }
935
936 - (void) reloadButtonClicked {
937 [self reloadURLWithCache:YES];
938 }
939
940 - (void) _customButtonClicked {
941 [self reloadButtonClicked];
942 }
943
944 - (void) customButtonClicked {
945 #if !AlwaysReload
946 if (function_ != nil)
947 [self callFunction:function_];
948 else
949 #endif
950 [self _customButtonClicked];
951 }
952
953 + (float) defaultWidth {
954 return 980;
955 }
956
957 - (void) setNavigationBarStyle:(NSString *)name {
958 UIBarStyle style;
959 if ([name isEqualToString:@"Black"])
960 style = UIBarStyleBlack;
961 else
962 style = UIBarStyleDefault;
963
964 [[[self navigationController] navigationBar] setBarStyle:style];
965 }
966
967 - (void) setNavigationBarTintColor:(UIColor *)color {
968 [[[self navigationController] navigationBar] setTintColor:color];
969 }
970
971 - (void) setBadgeValue:(id)value {
972 [[[self navigationController] tabBarItem] setBadgeValue:value];
973 }
974
975 - (void) setHidesBackButton:(bool)value {
976 [[self navigationItem] setHidesBackButton:value];
977 [self applyLeftButton];
978 }
979
980 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
981 [self setHidesBackButton:[value boolValue]];
982 }
983
984 - (void) dispatchEvent:(NSString *)event {
985 [[self webView] dispatchEvent:event];
986 }
987
988 - (bool) hidesNavigationBar {
989 return hidesNavigationBar_;
990 }
991
992 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
993 if (visible_)
994 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
995 }
996
997 - (void) setHidesNavigationBar:(bool)value {
998 if (hidesNavigationBar_ != value) {
999 hidesNavigationBar_ = value;
1000 [self _setHidesNavigationBar:YES animated:YES];
1001 }
1002 }
1003
1004 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1005 [self setHidesNavigationBar:[value boolValue]];
1006 }
1007
1008 - (void) viewWillAppear:(BOOL)animated {
1009 visible_ = true;
1010
1011 if ([self hidesNavigationBar])
1012 [self _setHidesNavigationBar:YES animated:animated];
1013
1014 [self dispatchEvent:@"CydiaViewWillAppear"];
1015 [super viewWillAppear:animated];
1016 }
1017
1018 - (void) viewDidAppear:(BOOL)animated {
1019 [super viewDidAppear:animated];
1020 [self dispatchEvent:@"CydiaViewDidAppear"];
1021 }
1022
1023 - (void) viewWillDisappear:(BOOL)animated {
1024 [self dispatchEvent:@"CydiaViewWillDisappear"];
1025 [super viewWillDisappear:animated];
1026
1027 if ([self hidesNavigationBar])
1028 [self _setHidesNavigationBar:NO animated:animated];
1029
1030 visible_ = false;
1031 }
1032
1033 - (void) viewDidDisappear:(BOOL)animated {
1034 [super viewDidDisappear:animated];
1035 [self dispatchEvent:@"CydiaViewDidDisappear"];
1036 }
1037
1038 @end