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