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