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