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