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