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