]> git.saurik.com Git - cydia.git/blame - CyteKit/WebViewController.mm
Ignore .dSYM folders I am suddenly ending up with.
[cydia.git] / CyteKit / WebViewController.mm
CommitLineData
819a0ab1 1#include "CyteKit/UCPlatform.h"
c21004b9 2
cfc530e6 3#include "CyteKit/IndirectDelegate.h"
d458596e 4#include "CyteKit/Localize.h"
63755c48 5#include "CyteKit/MFMailComposeViewController-MailToURL.h"
b4fd1197 6#include "CyteKit/RegEx.hpp"
4bcafc01 7#include "CyteKit/WebThreadLocked.hpp"
63755c48
JF
8#include "CyteKit/WebViewController.h"
9
10#include "iPhonePrivate.h"
f8c9fd4c 11#include <Menes/ObjectHandle.h>
43f3d7f6 12
c21004b9 13//#include <QuartzCore/CALayer.h>
43f3d7f6
JF
14// XXX: fix the minimum requirement
15extern NSString * const kCAFilterNearest;
22f8bed9 16
caa427d1 17#include <WebCore/WebCoreThread.h>
c21004b9 18
bf7c998c
JF
19#include <dlfcn.h>
20#include <objc/runtime.h>
21
a3d01a76
JF
22#include "Substrate.hpp"
23
adcb0422 24#define ForSaurik 0
eb09425a 25#define DefaultTimeout_ 120.0
bfc87a4d 26
0815487b
JF
27#define ShowInternals 0
28#define LogBrowser 0
72bdb258 29#define LogMessages 0
0815487b
JF
30
31#define lprintf(args...) fprintf(stderr, args)
32
7c80833f
JF
33JSValueRef (*$JSObjectCallAsFunction)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *);
34
2b2a4e33
JF
35// XXX: centralize these special class things to some file or mechanism?
36static Class $MFMailComposeViewController;
37
9c1605e2
JF
38float CYScrollViewDecelerationRateNormal;
39
aa1e1906
JF
40@interface WebFrame (Cydia)
41- (void) cydia$updateHeight;
42@end
43
dffe1eb1
JF
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
aa1e1906
JF
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
dffe1eb1
JF
58@end
59
300a26c1
JF
60// Diversion {{{
61static _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// }}}
aa5d0de7 111/* Indirect Delegate {{{ */
aa5d0de7
JF
112@implementation IndirectDelegate
113
353dda5b
JF
114- (id) delegate {
115 return delegate_;
116}
117
aa5d0de7
JF
118- (void) setDelegate:(id)delegate {
119 delegate_ = delegate;
120}
121
122- (id) initWithDelegate:(id)delegate {
123 delegate_ = delegate;
124 return self;
125}
126
caa427d1
JF
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
aa5d0de7 134- (BOOL) respondsToSelector:(SEL)sel {
caa427d1
JF
135 if ([super respondsToSelector:sel])
136 return YES;
0815487b 137
caa427d1 138 // XXX: WebThreadCreateNSInvocation returns nil
0815487b
JF
139
140#if ShowInternals
c66799b9 141 fprintf(stderr, "[%s]R?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
0815487b
JF
142#endif
143
caa427d1 144 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
aa5d0de7
JF
145}
146
147- (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
caa427d1
JF
148 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
149 return method;
0815487b
JF
150
151#if ShowInternals
c66799b9 152 fprintf(stderr, "[%s]S?%s\n", class_getName(object_getClass(self)), sel_getName(sel));
0815487b
JF
153#endif
154
aa5d0de7
JF
155 if (delegate_ != nil)
156 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
157 return sig;
0815487b 158
aa5d0de7
JF
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
f8c9fd4c
JF
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}
2634b249
JF
209
210#if ShowInternals
819a0ab1 211#include "CyteKit/UCInternal.h"
22f8bed9
JF
212#endif
213
2634b249
JF
214+ (void) _initialize {
215 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
9c1605e2 216
7c80833f
JF
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
2b2a4e33
JF
225 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
226 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
227
09e03d23 228 if (CGFloat *_UIScrollViewDecelerationRateNormal = reinterpret_cast<CGFloat *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
9c1605e2
JF
229 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
230 else // XXX: this actually might be fast on some older systems: we should look into this
231 CYScrollViewDecelerationRateNormal = 0.998;
300a26c1
JF
232
233 Diversions_ = [NSMutableSet setWithCapacity:0];
2634b249
JF
234}
235
2713be8e
JF
236- (bool) retainsNetworkActivityIndicator {
237 return true;
238}
239
8b74eaff
JF
240- (void) releaseNetworkActivityIndicator {
241 if ([loading_ count] != 0) {
242 [loading_ removeAllObjects];
243
244 if ([self retainsNetworkActivityIndicator])
f8c9fd4c 245 [self.delegate releaseNetworkActivityIndicator];
8b74eaff
JF
246 }
247}
248
2634b249
JF
249- (void) dealloc {
250#if LogBrowser
09e89a8a 251 NSLog(@"[CyteWebViewController dealloc]");
2634b249
JF
252#endif
253
8b74eaff 254 [self releaseNetworkActivityIndicator];
bc11cf5b 255
22f8bed9
JF
256 [super dealloc];
257}
258
e3e0246d
JF
259- (NSString *) description {
260 return [NSString stringWithFormat:@"<%s: %p, %@>", class_getName([self class]), self, [[request_ URL] absoluteString]];
261}
262
6f837280
JF
263- (CyteWebView *) webView {
264 return (CyteWebView *) [self view];
265}
266
f8c9fd4c
JF
267- (CyteWebViewController *) indirect {
268 return (CyteWebViewController *) (IndirectDelegate *) indirect_;
269}
270
300a26c1
JF
271+ (void) addDiversion:(Diversion *)diversion {
272 [Diversions_ addObject:diversion];
273}
274
dd48f2e6 275- (NSURL *) URLWithURL:(NSURL *)url {
300a26c1 276 return [Diversion divertURL:url];
dd48f2e6 277}
eb09425a 278
f050e4d9
JF
279- (NSURLRequest *) requestWithURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy referrer:(NSString *)referrer {
280 NSMutableURLRequest *request([NSMutableURLRequest
dd48f2e6
JF
281 requestWithURL:[self URLWithURL:url]
282 cachePolicy:policy
eb09425a 283 timeoutInterval:DefaultTimeout_
f050e4d9
JF
284 ]);
285
286 [request setValue:referrer forHTTPHeaderField:@"Referer"];
287
288 return request;
eb09425a
JF
289}
290
e8eda555 291- (void) setRequest:(NSURLRequest *)request {
dd48f2e6 292 _assert(request_ == nil);
e8eda555
JF
293 request_ = request;
294}
295
f8c9fd4c
JF
296- (NSURLRequest *) request {
297 return request_;
298}
299
e8eda555 300- (void) setURL:(NSURL *)url {
f050e4d9
JF
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]];
dd48f2e6
JF
306}
307
22f8bed9 308- (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
f050e4d9 309 [self loadRequest:[self requestWithURL:url cachePolicy:policy referrer:nil]];
22f8bed9
JF
310}
311
312- (void) loadURL:(NSURL *)url {
313 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
314}
315
22f8bed9 316- (void) loadRequest:(NSURLRequest *)request {
0352f238
JF
317#if LogBrowser
318 NSLog(@"loadRequest:%@", request);
319#endif
320
fe468f45 321 error_ = false;
d9fc1d37 322 ready_ = true;
caa427d1 323
0893a034 324 WebThreadLocked lock;
6f837280 325 [[self webView] loadRequest:request];
22f8bed9
JF
326}
327
b13b8664 328- (void) reloadURLWithCache:(BOOL)cache {
22f8bed9
JF
329 if (request_ == nil)
330 return;
331
b13b8664
JF
332 NSMutableURLRequest *request([request_ mutableCopy]);
333 [request setCachePolicy:(cache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData)];
334
a374f380 335 request_ = request;
b13b8664 336
d69dbfc5 337 if (cache || [request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
fe468f45 338 [self loadRequest:request_];
22f8bed9 339 else {
79ed082a 340 UIAlertView *alert = [[[UIAlertView alloc]
43f3d7f6 341 initWithTitle:UCLocalize("RESUBMIT_FORM")
79ed082a 342 message:nil
22f8bed9 343 delegate:self
79ed082a 344 cancelButtonTitle:UCLocalize("CANCEL")
1aa29546
JF
345 otherButtonTitles:
346 UCLocalize("SUBMIT"),
347 nil
22f8bed9 348 ] autorelease];
2634b249 349
79ed082a
GP
350 [alert setContext:@"submit"];
351 [alert show];
22f8bed9
JF
352 }
353}
354
eb09425a
JF
355- (void) reloadData {
356 [super reloadData];
d9fc1d37
JF
357
358 if (ready_)
359 [self dispatchEvent:@"CydiaReloadData"];
360 else
361 [self reloadURLWithCache:YES];
eb09425a
JF
362}
363
22f8bed9 364- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
46d3a5cf
JF
365 custom_ = button;
366 style_ = style;
367 function_ = function;
12b59862 368
70a9ff4e 369 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
22f8bed9
JF
370}
371
372- (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
46d3a5cf
JF
373 custom_ = button;
374 style_ = style;
375 function_ = function;
22f8bed9 376
ed5566c7
JF
377 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
378}
12b59862 379
ed5566c7
JF
380- (void) removeButton {
381 custom_ = [NSNull null];
70a9ff4e 382 [self performSelectorOnMainThread:@selector(applyRightButton) withObject:nil waitUntilDone:NO];
22f8bed9 383}
22f8bed9 384
8e3b68d4
JF
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
7e37a676 396- (void) _setViewportWidth {
6f837280 397 [[[self webView] _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
7e37a676
JF
398}
399
2634b249
JF
400- (void) setViewportWidth:(float)width {
401 width_ = width != 0 ? width : [[self class] defaultWidth];
7e37a676
JF
402 [self _setViewportWidth];
403}
404
8dbdaafa
JF
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
7e37a676
JF
413- (void) webViewUpdateViewSettings:(UIWebView *)view {
414 [self _setViewportWidth];
22f8bed9
JF
415}
416
2b2a4e33
JF
417- (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
418 [self dismissModalViewControllerAnimated:YES];
419}
420
22485d93
JF
421- (void) _setupMail:(MFMailComposeViewController *)controller {
422}
423
2634b249 424- (void) _openMailToURL:(NSURL *)url {
2b2a4e33
JF
425 if ($MFMailComposeViewController != nil && [$MFMailComposeViewController canSendMail]) {
426 MFMailComposeViewController *controller([[[$MFMailComposeViewController alloc] init] autorelease]);
427 [controller setMailComposeDelegate:self];
428
429 [controller setMailToURL:url];
430
22485d93
JF
431 [self _setupMail:controller];
432
2b2a4e33
JF
433 [self presentModalViewController:controller animated:YES];
434 return;
435 }
436
8ea72491
JF
437 UIApplication *app([UIApplication sharedApplication]);
438 if ([app respondsToSelector:@selector(openURL:asPanel:)])
439 [app openURL:url asPanel:YES];
440 else
441 [app openURL:url];
22f8bed9
JF
442}
443
2634b249
JF
444- (bool) _allowJavaScriptPanel {
445 return true;
22f8bed9
JF
446}
447
8366df5e
JF
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]];
52498c7e
JF
458}
459
8d497e2a
JF
460- (void) popViewControllerWithNumber:(NSNumber *)value {
461 UINavigationController *navigation([self navigationController]);
462 if ([navigation topViewController] == self)
463 [navigation popViewControllerAnimated:[value boolValue]];
464}
465
2634b249 466- (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
8b74eaff
JF
467 NSValue *object([NSValue valueWithNonretainedObject:frame]);
468 if (![loading_ containsObject:object])
469 return;
470 [loading_ removeObject:object];
471
2634b249 472 [self _didFinishLoading];
22f8bed9 473
46b423a7 474 if ([[error domain] isEqualToString:NSURLErrorDomain] && [error code] == NSURLErrorCancelled)
22f8bed9
JF
475 return;
476
fe2d3954 477 if ([[error domain] isEqualToString:WebKitErrorDomain] && [error code] == WebKitErrorFrameLoadInterruptedByPolicyChange) {
5bb0da03 478 request_ = nil;
fe2d3954
JF
479 return;
480 }
481
caa427d1 482 if ([frame parentFrame] == nil) {
2634b249
JF
483 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
484 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
485 [[error localizedDescription] stringByAddingPercentEscapes]
486 ]]];
22f8bed9 487
2634b249
JF
488 error_ = true;
489 }
490}
caa427d1 491
f050e4d9
JF
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
2634b249 502 NSURL *url([request URL]);
a5938ea5 503
028dbd1c 504 // XXX: filter to internal usage?
f8c9fd4c 505 CyteViewController *page([self.delegate pageForURL:url forExternal:NO withReferrer:referrer]);
2fad210a 506
2634b249 507 if (page == nil) {
09e89a8a 508 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
0620c393 509 [browser setRequest:request];
2634b249 510 page = browser;
bc11cf5b 511 }
ce041f4f 512
f8c9fd4c
JF
513 [page setDelegate:self.delegate];
514 [page setPageColor:self.pageColor];
b5e7eebb 515
52498c7e 516 if (!pop) {
2634b249 517 [[self navigationItem] setTitle:title_];
b5e7eebb 518
2634b249
JF
519 [[self navigationController] pushViewController:page animated:YES];
520 } else {
2e26757e 521 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
22f8bed9 522
f8c9fd4c 523 [navigation setDelegate:self.delegate];
22f8bed9 524
2634b249
JF
525 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
526 initWithTitle:UCLocalize("CLOSE")
527 style:UIBarButtonItemStylePlain
528 target:page
529 action:@selector(close)
530 ] autorelease]];
531
45e66037 532 [[self navigationController] presentModalViewController:navigation animated:YES];
2634b249 533 }
52498c7e
JF
534}
535
1ee69bb4 536// CyteWebViewDelegate {{{
52498c7e
JF
537- (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
538#if LogMessages
b4fd1197 539 static RegEx irritating("(?"
c8f62968
JF
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\\."
b4fd1197 542 ")\\n");
c8f62968 543
c81b955f
JF
544 if (NSString *data = [message objectForKey:@"message"])
545 if (irritating(data))
546 return;
547
52498c7e
JF
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
f050e4d9 554 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ %@ frame:%@", action, request, [request allHTTPHeaderFields], frame);
52498c7e
JF
555#endif
556
1002f4d9 557 NSURL *url(request == nil ? nil : [request URL]);
c623466b
JF
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) {
1002f4d9
JF
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
52498c7e
JF
588 if ([frame parentFrame] == nil) {
589 if (!error_) {
d323285e 590 if (request_ != nil && ![[request_ URL] isEqual:url] && ![self allowsNavigationAction]) {
8366df5e 591 if (url != nil)
f050e4d9 592 [self pushRequest:request forAction:action asPop:NO];
52498c7e
JF
593 [listener ignore];
594 }
595 }
596 }
597}
598
d323285e 599- (void) webView:(WebView *)view didDecidePolicy:(CYWebPolicyDecision)decision forNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame {
77d4e15b 600#if LogBrowser
c66799b9 601 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ %@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
77d4e15b
JF
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 }
d323285e
JF
620}
621
f050e4d9 622- (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
52498c7e 623#if LogBrowser
f050e4d9 624 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
52498c7e
JF
625#endif
626
627 NSURL *url([request URL]);
628 if (url == nil)
629 return;
630
f050e4d9 631 if ([name isEqualToString:@"_open"])
f8c9fd4c 632 [self.delegate openURL:url];
52498c7e
JF
633 else {
634 NSString *scheme([[url scheme] lowercaseString]);
635 if ([scheme isEqualToString:@"mailto"])
636 [self _openMailToURL:url];
637 else
f050e4d9 638 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
52498c7e 639 }
22f8bed9 640
2634b249 641 [listener ignore];
22f8bed9
JF
642}
643
2634b249 644- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
c215c5ed
JF
645#if LogBrowser
646 NSLog(@"didClearWindowObject:%@ forFrame:%@", window, frame);
647#endif
22f8bed9
JF
648}
649
64ffa332
JF
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
2634b249
JF
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];
22f8bed9
JF
665}
666
2634b249
JF
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];
22f8bed9
JF
673}
674
2634b249 675- (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
8b74eaff
JF
676 NSValue *object([NSValue valueWithNonretainedObject:frame]);
677 if (![loading_ containsObject:object])
678 return;
679 [loading_ removeObject:object];
22f8bed9 680
caa427d1 681 if ([frame parentFrame] == nil) {
22f8bed9 682 if (DOMDocument *document = [frame DOMDocument])
4cc9e99a 683 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
96f3833b 684 for (DOMHTMLBodyElement *body in (id) bodies) {
22f8bed9
JF
685 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
686
65ea9562 687 UIColor *uic(nil);
22f8bed9
JF
688
689 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
fe468f45
JF
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
d32f96be
JF
698 if (alpha == 1)
699 uic = [UIColor
700 colorWithRed:(red / 255)
701 green:(green / 255)
702 blue:(blue / 255)
703 alpha:alpha
704 ];
22f8bed9
JF
705 }
706 }
707
77259cab 708 [super setPageColor:uic];
f8c9fd4c 709 [scroller_ setBackgroundColor:self.pageColor];
22f8bed9
JF
710 break;
711 }
712 }
713
2634b249 714 [self _didFinishLoading];
22f8bed9
JF
715}
716
2634b249
JF
717- (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
718 if ([frame parentFrame] != nil)
719 return;
caa427d1 720
7b33d201 721 title_ = title;
3931b718 722
2634b249
JF
723 [[self navigationItem] setTitle:title_];
724}
22f8bed9 725
2634b249 726- (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
a86042fa
JF
727#if LogBrowser
728 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
729#endif
730
2634b249 731 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
7592e053 732
caa427d1 733 if ([frame parentFrame] == nil) {
7b33d201 734 title_ = nil;
46d3a5cf
JF
735 custom_ = nil;
736 style_ = nil;
737 function_ = nil;
2634b249 738
aa1e1906
JF
739 [registered_ removeAllObjects];
740 timer_ = nil;
741
622a9912
JF
742 allowsNavigationAction_ = true;
743
5cdfcd6f 744 [self setHidesNavigationBar:NO];
db698f42 745 [self setScrollAlwaysBounceVertical:true];
4886cc81 746 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
5cdfcd6f 747
2634b249
JF
748 // XXX: do we still need to do this?
749 [[self navigationItem] setTitle:nil];
caa427d1 750 }
fe468f45 751
2634b249 752 [self _didStartLoading];
caa427d1
JF
753}
754
754456f5
JF
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]); {
63755c48 778 NSObject<UITextInputTraits> *traits([username textInputTraits]);
754456f5
JF
779 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
780 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
781 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
782 [traits setReturnKeyType:UIReturnKeyNext];
783 }
784
785 UITextField *password([alert textFieldAtIndex:1]); {
63755c48 786 NSObject<UITextInputTraits> *traits([password textInputTraits]);
754456f5
JF
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
2634b249 798- (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
0352f238
JF
799#if LogBrowser
800 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
801#endif
802
2634b249 803 return request;
22f8bed9
JF
804}
805
92de61aa
JF
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
2634b249
JF
814- (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
815 return [self _allowJavaScriptPanel];
22f8bed9
JF
816}
817
2634b249
JF
818- (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
819 return [self _allowJavaScriptPanel];
600d005d
JF
820}
821
2634b249
JF
822- (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
823 return [self _allowJavaScriptPanel];
600d005d
JF
824}
825
2634b249
JF
826- (void) webViewClose:(WebView *)view {
827 [self close];
600d005d 828}
2634b249 829// }}}
600d005d 830
2634b249 831- (void) close {
19f2d77f 832 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
600d005d
JF
833}
834
2634b249
JF
835- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
836 NSString *context([alert context]);
600d005d 837
2634b249
JF
838 if ([context isEqualToString:@"sensitive"]) {
839 switch (button) {
840 case 1:
841 sensitive_ = [NSNumber numberWithBool:YES];
842 break;
600d005d 843
2634b249
JF
844 case 2:
845 sensitive_ = [NSNumber numberWithBool:NO];
846 break;
847 }
600d005d 848
2634b249
JF
849 [alert dismissWithClickedButtonIndex:-1 animated:YES];
850 } else if ([context isEqualToString:@"challenge"]) {
851 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
caa427d1 852
754456f5
JF
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]);
600d005d 858
754456f5 859 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
600d005d 860
754456f5 861 [sender useCredential:credential forAuthenticationChallenge:challenge_];
2634b249 862 }
600d005d 863
2634b249 864 challenge_ = nil;
600d005d 865
1002f4d9
JF
866 [alert dismissWithClickedButtonIndex:-1 animated:YES];
867 } else if ([context isEqualToString:@"itmsappss"]) {
868 if (button == [alert cancelButtonIndex]) {
869 } else if (button == [alert firstOtherButtonIndex]) {
f8c9fd4c 870 [self.delegate openURL:appstore_];
1002f4d9
JF
871 }
872
2634b249
JF
873 [alert dismissWithClickedButtonIndex:-1 animated:YES];
874 } else if ([context isEqualToString:@"submit"]) {
75b95256
JF
875 if (button == [alert cancelButtonIndex]) {
876 } else if (button == [alert firstOtherButtonIndex]) {
877 if (request_ != nil) {
0893a034 878 WebThreadLocked lock;
6f837280 879 [[self webView] loadRequest:request_];
75b95256 880 }
2634b249 881 }
600d005d 882
2634b249
JF
883 [alert dismissWithClickedButtonIndex:-1 animated:YES];
884 }
600d005d
JF
885}
886
2634b249
JF
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;
600d005d
JF
895}
896
2634b249 897- (UIBarButtonItem *) customButton {
29756674 898 if (custom_ == nil)
f274bb0c 899 return [self rightButton];
4cc9e99a 900 else if ((/*clang:*/id) custom_ == [NSNull null])
f274bb0c 901 return nil;
29756674
JF
902
903 return [[[UIBarButtonItem alloc]
ed5566c7 904 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
2634b249
JF
905 style:[self rightButtonStyle]
906 target:self
907 action:@selector(customButtonClicked)
908 ] autorelease];
caa427d1
JF
909}
910
e6124cb6
JF
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])
19f2d77f 917 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
e6124cb6
JF
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
2634b249
JF
932- (UIBarButtonItem *) rightButton {
933 return reloaditem_;
eb35c522
JF
934}
935
2634b249
JF
936- (void) applyLoadingTitle {
937 [[self navigationItem] setTitle:UCLocalize("LOADING")];
caa427d1
JF
938}
939
c83a464d
JF
940- (void) layoutRightButton {
941 [[loadingitem_ view] addSubview:indicator_];
942 [[loadingitem_ view] bringSubviewToFront:indicator_];
943}
944
2634b249
JF
945- (void) applyRightButton {
946 if ([self isLoading]) {
947 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
c83a464d 948 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
8d603a7d
JF
949
950 [indicator_ startAnimating];
2634b249 951 [self applyLoadingTitle];
2634b249 952 } else {
8d603a7d 953 [indicator_ stopAnimating];
f274bb0c 954 [[self navigationItem] setRightBarButtonItem:[self customButton] animated:YES];
2634b249 955 }
caa427d1
JF
956}
957
df30fbee
GP
958- (void) didStartLoading {
959 // Overridden in subclasses.
960}
961
2634b249
JF
962- (void) _didStartLoading {
963 [self applyRightButton];
54043703
JF
964
965 if ([loading_ count] != 1)
966 return;
df30fbee 967
2713be8e 968 if ([self retainsNetworkActivityIndicator])
f8c9fd4c 969 [self.delegate retainNetworkActivityIndicator];
2713be8e 970
df30fbee
GP
971 [self didStartLoading];
972}
973
974- (void) didFinishLoading {
975 // Overridden in subclasses.
caa427d1
JF
976}
977
2634b249
JF
978- (void) _didFinishLoading {
979 if ([loading_ count] != 0)
980 return;
981
982 [self applyRightButton];
df30fbee 983 [[self navigationItem] setTitle:title_];
2634b249 984
2713be8e 985 if ([self retainsNetworkActivityIndicator])
f8c9fd4c 986 [self.delegate releaseNetworkActivityIndicator];
2713be8e 987
df30fbee 988 [self didFinishLoading];
caa427d1
JF
989}
990
2634b249
JF
991- (bool) isLoading {
992 return [loading_ count] != 0;
caa427d1
JF
993}
994
b5e7eebb
GP
995- (id) initWithWidth:(float)width ofClass:(Class)_class {
996 if ((self = [super init]) != nil) {
6f837280
JF
997 width_ = width;
998 class_ = _class;
999
77259cab 1000 [super setPageColor:nil];
5738f070 1001
df08be87
JF
1002 allowsNavigationAction_ = true;
1003
7b33d201 1004 loading_ = [NSMutableSet setWithCapacity:5];
aa1e1906 1005 registered_ = [NSMutableSet setWithCapacity:5];
7b33d201 1006 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
caa427d1 1007
6f837280
JF
1008 reloaditem_ = [[[UIBarButtonItem alloc]
1009 initWithTitle:UCLocalize("RELOAD")
1010 style:[self rightButtonStyle]
1011 target:self
1012 action:@selector(reloadButtonClicked)
1013 ] autorelease];
65ea9562 1014
6f837280 1015 loadingitem_ = [[[UIBarButtonItem alloc]
5328a9f0 1016 initWithTitle:(kCFCoreFoundationVersionNumber >= 800 ? @" " : @" ")
6f837280
JF
1017 style:UIBarButtonItemStylePlain
1018 target:self
f274bb0c 1019 action:@selector(customButtonClicked)
6f837280 1020 ] autorelease];
22f8bed9 1021
5328a9f0
JF
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)];
6f837280 1034 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
22f8bed9 1035
6f837280
JF
1036 [self applyLeftButton];
1037 [self applyRightButton];
1038 } return self;
1039}
22f8bed9 1040
300a26c1
JF
1041static _H<NSString> UserAgent_;
1042+ (void) setApplicationNameForUserAgent:(NSString *)userAgent {
1043 UserAgent_ = userAgent;
1044}
1045
c6cf66c7 1046- (NSString *) applicationNameForUserAgent {
300a26c1 1047 return UserAgent_;
c6cf66c7
JF
1048}
1049
6f837280
JF
1050- (void) loadView {
1051 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
ea173384 1052
6f837280
JF
1053 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
1054 [webview_ setDelegate:self];
1055 [self setView:webview_];
ea173384 1056
6f837280
JF
1057 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
1058 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
1059 else
1060 [webview_ setDetectsPhoneNumbers:NO];
14f17703 1061
6f837280 1062 [webview_ setScalesPageToFit:YES];
ea173384 1063
6f837280 1064 UIWebDocumentView *document([webview_ _documentView]);
22f8bed9 1065
6f837280
JF
1066 // XXX: I think this improves scrolling; the hardcoded-ness sucks
1067 [document setTileSize:CGSizeMake(320, 500)];
22f8bed9 1068
6f837280
JF
1069 WebView *webview([document webView]);
1070 WebPreferences *preferences([webview preferences]);
72bdb258 1071
6f837280
JF
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];
22f8bed9 1077
6f837280 1078 [preferences setCacheModel:WebCacheModelDocumentBrowser];
d331bfc3 1079 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
64cc10e2
JF
1080
1081 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
1082 [preferences setOfflineWebApplicationCacheEnabled:YES];
22f8bed9 1083
c6cf66c7
JF
1084 if (NSString *agent = [self applicationNameForUserAgent])
1085 [webview setApplicationNameForUserAgent:agent];
1086
6f837280
JF
1087 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
1088 [webview setShouldUpdateWhileOffscreen:NO];
22f8bed9 1089
6f837280
JF
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
3e9c9e85 1096
6f837280
JF
1097 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1098 scroller_ = [webview_ _scrollView];
ea173384 1099
6f837280
JF
1100 [scroller_ setDirectionalLockEnabled:YES];
1101 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
1102 [scroller_ setDelaysContentTouches:NO];
ea173384 1103
6f837280
JF
1104 [scroller_ setCanCancelContentTouches:YES];
1105 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1106 UIScroller *scroller([webview_ _scroller]);
1107 scroller_ = (UIScrollView *) scroller;
bc11cf5b 1108
6f837280
JF
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 */
caa427d1 1113
6f837280 1114 [scroller setThumbDetectionEnabled:NO];
caa427d1 1115
6f837280
JF
1116 // use NO with UIApplicationUseLegacyEvents(YES)
1117 [scroller setEventMode:YES];
bc11cf5b 1118
6f837280
JF
1119 // XXX: this is handled by setBounces, right?
1120 //[scroller setAllowsRubberBanding:YES];
1121 }
bc11cf5b 1122
d32f96be 1123 [webview_ setOpaque:NO];
69b1d328 1124 [webview_ setBackgroundColor:nil];
d32f96be 1125
6f837280 1126 [scroller_ setFixedBackgroundPattern:YES];
f8c9fd4c 1127 [scroller_ setBackgroundColor:self.pageColor];
6f837280 1128 [scroller_ setClipsSubviews:YES];
2634b249 1129
6f837280
JF
1130 [scroller_ setBounces:YES];
1131 [scroller_ setScrollingEnabled:YES];
1132 [scroller_ setShowBackgroundShadow:NO];
22f8bed9 1133
6f837280 1134 [self setViewportWidth:width_];
65ea9562 1135
494216be
JF
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
6f837280 1143 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
47a40da6
JF
1144
1145 ready_ = false;
6f837280
JF
1146}
1147
1148- (void) releaseSubviews {
1149 webview_ = nil;
1150 scroller_ = nil;
7be3eb32 1151
8b74eaff
JF
1152 [self releaseNetworkActivityIndicator];
1153
7be3eb32 1154 [super releaseSubviews];
22f8bed9
JF
1155}
1156
b5e7eebb
GP
1157- (id) initWithWidth:(float)width {
1158 return [self initWithWidth:width ofClass:[self class]];
245cce8a
JF
1159}
1160
b5e7eebb
GP
1161- (id) init {
1162 return [self initWithWidth:0];
3e9c9e85
JF
1163}
1164
eb09425a
JF
1165- (id) initWithURL:(NSURL *)url {
1166 if ((self = [self init]) != nil) {
1167 [self setURL:url];
1168 } return self;
1169}
1170
68bd7c60
JF
1171- (id) initWithRequest:(NSURLRequest *)request {
1172 if ((self = [self init]) != nil) {
1173 [self setRequest:request];
1174 } return self;
1175}
1176
d331bfc3
JF
1177+ (void) _lockJavaScript:(WebPreferences *)preferences {
1178 WebThreadLocked lock;
1179 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1180}
1181
12b59862 1182- (void) callFunction:(WebScriptObject *)function {
0893a034 1183 WebThreadLocked lock;
caa427d1 1184
6f837280 1185 WebView *webview([[[self webView] _documentView] webView]);
d331bfc3 1186 WebPreferences *preferences([webview preferences]);
c21004b9 1187
d331bfc3
JF
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]);
12b59862 1195 JSGlobalContextRef context([frame globalContext]);
d331bfc3 1196
9dbfe708 1197 JSObjectRef object([function JSObject]);
7c80833f
JF
1198 if ($JSObjectCallAsFunction != NULL)
1199 ($JSObjectCallAsFunction)(context, object, NULL, 0, NULL, NULL);
d331bfc3
JF
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];
12b59862
JF
1205}
1206
ce041f4f 1207- (void) reloadButtonClicked {
d69dbfc5 1208 [self reloadURLWithCache:NO];
12b59862
JF
1209}
1210
719d6c2f
DH
1211- (void) _customButtonClicked {
1212 [self reloadButtonClicked];
1213}
1214
ce041f4f 1215- (void) customButtonClicked {
caa427d1
JF
1216#if !AlwaysReload
1217 if (function_ != nil)
12b59862 1218 [self callFunction:function_];
caa427d1
JF
1219 else
1220#endif
719d6c2f 1221 [self _customButtonClicked];
22f8bed9
JF
1222}
1223
3e9c9e85
JF
1224+ (float) defaultWidth {
1225 return 980;
1226}
1227
82406217
JF
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
00984204
JF
1238- (void) setNavigationBarTintColor:(UIColor *)color {
1239 [[[self navigationController] navigationBar] setTintColor:color];
1240}
1241
c31c825d
JF
1242- (void) setBadgeValue:(id)value {
1243 [[[self navigationController] tabBarItem] setBadgeValue:value];
1244}
1245
b8a5d89d
JF
1246- (void) setHidesBackButton:(bool)value {
1247 [[self navigationItem] setHidesBackButton:value];
e6124cb6 1248 [self applyLeftButton];
b8a5d89d
JF
1249}
1250
1251- (void) setHidesBackButtonByNumber:(NSNumber *)value {
1252 [self setHidesBackButton:[value boolValue]];
1253}
1254
f196b921 1255- (void) dispatchEvent:(NSString *)event {
6f837280 1256 [[self webView] dispatchEvent:event];
f196b921
JF
1257}
1258
5cdfcd6f
JF
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
db698f42
JF
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
4886cc81
JF
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
f196b921 1318- (void) viewWillAppear:(BOOL)animated {
5cdfcd6f
JF
1319 visible_ = true;
1320
1321 if ([self hidesNavigationBar])
1322 [self _setHidesNavigationBar:YES animated:animated];
1323
3cf38067
JF
1324 // XXX: why isn't this evern called automatically?
1325 [[self webView] setNeedsLayout];
1326
f196b921
JF
1327 [self dispatchEvent:@"CydiaViewWillAppear"];
1328 [super viewWillAppear:animated];
1329}
1330
1331- (void) viewDidAppear:(BOOL)animated {
f196b921 1332 [super viewDidAppear:animated];
5cdfcd6f 1333 [self dispatchEvent:@"CydiaViewDidAppear"];
f196b921
JF
1334}
1335
1336- (void) viewWillDisappear:(BOOL)animated {
1337 [self dispatchEvent:@"CydiaViewWillDisappear"];
1338 [super viewWillDisappear:animated];
5cdfcd6f
JF
1339
1340 if ([self hidesNavigationBar])
1341 [self _setHidesNavigationBar:NO animated:animated];
1342
1343 visible_ = false;
f196b921
JF
1344}
1345
1346- (void) viewDidDisappear:(BOOL)animated {
f196b921 1347 [super viewDidDisappear:animated];
5cdfcd6f 1348 [self dispatchEvent:@"CydiaViewDidDisappear"];
f196b921
JF
1349}
1350
aa1e1906
JF
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
a5938ea5 1363@end
a3d01a76
JF
1364
1365MSClassHook(WAKWindow)
1366
1367static 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
1375static 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
1381MSClassHook(NSUserDefaults)
1382
1383MSHook(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
1389CYHook(NSUserDefaults, objectForKey$, objectForKey:)