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