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