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