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