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