]> git.saurik.com Git - cydia.git/blame - CyteKit/WebViewController.mm
Add output filename parameter to pngcrush.sh.
[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
adcb0422 28#define ForSaurik 0
eb09425a 29#define DefaultTimeout_ 120.0
bfc87a4d 30
0815487b
JF
31#define ShowInternals 0
32#define LogBrowser 0
72bdb258 33#define LogMessages 0
0815487b
JF
34
35#define lprintf(args...) fprintf(stderr, args)
36
2b2a4e33
JF
37// XXX: centralize these special class things to some file or mechanism?
38static Class $MFMailComposeViewController;
39
9c1605e2
JF
40float CYScrollViewDecelerationRateNormal;
41
2634b249
JF
42@interface WebView (Apple)
43- (void) _setLayoutInterval:(float)interval;
72bdb258 44- (void) _setAllowsMessaging:(BOOL)allows;
2634b249
JF
45@end
46
47@interface WebPreferences (Apple)
48+ (void) _setInitialDefaultTextEncodingToSystemEncoding;
49- (void) _setLayoutInterval:(NSInteger)interval;
50- (void) setOfflineWebApplicationCacheEnabled:(BOOL)enabled;
51@end
327624b6 52
aa5d0de7 53/* Indirect Delegate {{{ */
2e26757e 54@interface IndirectDelegate : NSObject {
aa5d0de7
JF
55 _transient volatile id delegate_;
56}
57
58- (void) setDelegate:(id)delegate;
59- (id) initWithDelegate:(id)delegate;
60@end
61
62@implementation IndirectDelegate
63
64- (void) setDelegate:(id)delegate {
65 delegate_ = delegate;
66}
67
68- (id) initWithDelegate:(id)delegate {
69 delegate_ = delegate;
70 return self;
71}
72
caa427d1
JF
73- (IMP) methodForSelector:(SEL)sel {
74 if (IMP method = [super methodForSelector:sel])
75 return method;
76 fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
77 return NULL;
78}
79
aa5d0de7 80- (BOOL) respondsToSelector:(SEL)sel {
caa427d1
JF
81 if ([super respondsToSelector:sel])
82 return YES;
0815487b 83
caa427d1 84 // XXX: WebThreadCreateNSInvocation returns nil
0815487b
JF
85
86#if ShowInternals
87 fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
88#endif
89
caa427d1 90 return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
aa5d0de7
JF
91}
92
93- (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
caa427d1
JF
94 if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
95 return method;
0815487b
JF
96
97#if ShowInternals
98 fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
99#endif
100
aa5d0de7
JF
101 if (delegate_ != nil)
102 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
103 return sig;
0815487b 104
aa5d0de7
JF
105 // XXX: I fucking hate Apple so very very bad
106 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
107}
108
109- (void) forwardInvocation:(NSInvocation *)inv {
110 SEL sel = [inv selector];
111 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
112 [inv invokeWithTarget:delegate_];
113}
114
115@end
116/* }}} */
117
09e89a8a 118@implementation CyteWebViewController
2634b249
JF
119
120#if ShowInternals
819a0ab1 121#include "CyteKit/UCInternal.h"
22f8bed9
JF
122#endif
123
2634b249
JF
124+ (void) _initialize {
125 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
9c1605e2 126
2b2a4e33
JF
127 dlopen("/System/Library/Frameworks/MessageUI.framework/MessageUI", RTLD_GLOBAL | RTLD_LAZY);
128 $MFMailComposeViewController = objc_getClass("MFMailComposeViewController");
129
9c1605e2
JF
130 if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
131 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
132 else // XXX: this actually might be fast on some older systems: we should look into this
133 CYScrollViewDecelerationRateNormal = 0.998;
2634b249
JF
134}
135
136- (void) dealloc {
137#if LogBrowser
09e89a8a 138 NSLog(@"[CyteWebViewController dealloc]");
2634b249
JF
139#endif
140
141 [webview_ setDelegate:nil];
2634b249 142 [indirect_ setDelegate:nil];
2634b249 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
JF
326 if ([[error domain] isEqualToString:WebKitErrorDomain] && [error code] == WebKitErrorFrameLoadInterruptedByPolicyChange) {
327 request_ = (id) stage2_;
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_) {
417 stage1_ = (id) request_;
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
fe2d3954
JF
528 stage2_ = (id) stage1_;
529 stage1_ = nil;
530
5cdfcd6f
JF
531 [self setHidesNavigationBar:NO];
532
2634b249
JF
533 // XXX: do we still need to do this?
534 [[self navigationItem] setTitle:nil];
caa427d1 535 }
fe468f45 536
2634b249 537 [self _didStartLoading];
caa427d1
JF
538}
539
2634b249 540- (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
0352f238
JF
541#if LogBrowser
542 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
543#endif
544
2634b249 545 return request;
22f8bed9
JF
546}
547
2634b249
JF
548- (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
549 return [self _allowJavaScriptPanel];
22f8bed9
JF
550}
551
2634b249
JF
552- (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
553 return [self _allowJavaScriptPanel];
600d005d
JF
554}
555
2634b249
JF
556- (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
557 return [self _allowJavaScriptPanel];
600d005d
JF
558}
559
2634b249
JF
560- (void) webViewClose:(WebView *)view {
561 [self close];
600d005d 562}
2634b249 563// }}}
600d005d 564
2634b249
JF
565- (void) close {
566 [[self navigationController] dismissModalViewControllerAnimated:YES];
600d005d
JF
567}
568
2634b249
JF
569- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
570 NSString *context([alert context]);
600d005d 571
2634b249
JF
572 if ([context isEqualToString:@"sensitive"]) {
573 switch (button) {
574 case 1:
575 sensitive_ = [NSNumber numberWithBool:YES];
576 break;
600d005d 577
2634b249
JF
578 case 2:
579 sensitive_ = [NSNumber numberWithBool:NO];
580 break;
581 }
600d005d 582
2634b249
JF
583 [alert dismissWithClickedButtonIndex:-1 animated:YES];
584 } else if ([context isEqualToString:@"challenge"]) {
585 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
caa427d1 586
2634b249
JF
587 switch (button) {
588 case 1: {
589 NSString *username([[alert textFieldAtIndex:0] text]);
590 NSString *password([[alert textFieldAtIndex:1] text]);
600d005d 591
2634b249 592 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
600d005d 593
2634b249
JF
594 [sender useCredential:credential forAuthenticationChallenge:challenge_];
595 } break;
600d005d 596
2634b249
JF
597 case 2:
598 [sender cancelAuthenticationChallenge:challenge_];
599 break;
600d005d 600
2634b249
JF
601 _nodefault
602 }
600d005d 603
2634b249 604 challenge_ = nil;
600d005d 605
2634b249
JF
606 [alert dismissWithClickedButtonIndex:-1 animated:YES];
607 } else if ([context isEqualToString:@"submit"]) {
75b95256
JF
608 if (button == [alert cancelButtonIndex]) {
609 } else if (button == [alert firstOtherButtonIndex]) {
610 if (request_ != nil) {
0893a034 611 WebThreadLocked lock;
75b95256 612 [webview_ loadRequest:request_];
75b95256 613 }
2634b249 614 }
600d005d 615
2634b249
JF
616 [alert dismissWithClickedButtonIndex:-1 animated:YES];
617 }
600d005d
JF
618}
619
2634b249
JF
620- (UIBarButtonItemStyle) rightButtonStyle {
621 if (style_ == nil) normal:
622 return UIBarButtonItemStylePlain;
623 else if ([style_ isEqualToString:@"Normal"])
624 return UIBarButtonItemStylePlain;
625 else if ([style_ isEqualToString:@"Highlighted"])
626 return UIBarButtonItemStyleDone;
627 else goto normal;
600d005d
JF
628}
629
2634b249 630- (UIBarButtonItem *) customButton {
29756674
JF
631 if (custom_ == nil)
632 return nil;
633 else if (custom_ == [NSNull null])
634 return (UIBarButtonItem *) [NSNull null];
635
636 return [[[UIBarButtonItem alloc]
ed5566c7 637 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
2634b249
JF
638 style:[self rightButtonStyle]
639 target:self
640 action:@selector(customButtonClicked)
641 ] autorelease];
caa427d1
JF
642}
643
e6124cb6
JF
644- (UIBarButtonItem *) leftButton {
645 UINavigationItem *item([self navigationItem]);
646 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
647 return nil;
648
649 if (UINavigationController *navigation = [self navigationController])
650 if ([[navigation parentViewController] modalViewController] == navigation)
651 return [[[UIBarButtonItem alloc]
652 initWithTitle:UCLocalize("CLOSE")
653 style:UIBarButtonItemStylePlain
654 target:self
655 action:@selector(close)
656 ] autorelease];
657
658 return nil;
659}
660
661- (void) applyLeftButton {
662 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
663}
664
2634b249
JF
665- (UIBarButtonItem *) rightButton {
666 return reloaditem_;
eb35c522
JF
667}
668
2634b249
JF
669- (void) applyLoadingTitle {
670 [[self navigationItem] setTitle:UCLocalize("LOADING")];
caa427d1
JF
671}
672
c83a464d
JF
673- (void) layoutRightButton {
674 [[loadingitem_ view] addSubview:indicator_];
675 [[loadingitem_ view] bringSubviewToFront:indicator_];
676}
677
2634b249
JF
678- (void) applyRightButton {
679 if ([self isLoading]) {
680 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
c83a464d 681 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
8d603a7d
JF
682
683 [indicator_ startAnimating];
2634b249 684 [self applyLoadingTitle];
2634b249 685 } else {
8d603a7d
JF
686 [indicator_ stopAnimating];
687
29756674
JF
688 UIBarButtonItem *button([self customButton]);
689 if (button == nil)
690 button = [self rightButton];
691 else if (button == (UIBarButtonItem *) [NSNull null])
692 button = nil;
693
694 [[self navigationItem] setRightBarButtonItem:button];
2634b249 695 }
caa427d1
JF
696}
697
df30fbee
GP
698- (void) didStartLoading {
699 // Overridden in subclasses.
700}
701
2634b249
JF
702- (void) _didStartLoading {
703 [self applyRightButton];
54043703
JF
704
705 if ([loading_ count] != 1)
706 return;
df30fbee 707
54043703 708 [delegate_ retainNetworkActivityIndicator];
df30fbee
GP
709 [self didStartLoading];
710}
711
712- (void) didFinishLoading {
713 // Overridden in subclasses.
caa427d1
JF
714}
715
2634b249
JF
716- (void) _didFinishLoading {
717 if ([loading_ count] != 0)
718 return;
719
720 [self applyRightButton];
df30fbee 721 [[self navigationItem] setTitle:title_];
2634b249 722
df30fbee
GP
723 [delegate_ releaseNetworkActivityIndicator];
724 [self didFinishLoading];
caa427d1
JF
725}
726
2634b249
JF
727- (bool) isLoading {
728 return [loading_ count] != 0;
caa427d1
JF
729}
730
b5e7eebb
GP
731- (id) initWithWidth:(float)width ofClass:(Class)_class {
732 if ((self = [super init]) != nil) {
df08be87
JF
733 allowsNavigationAction_ = true;
734
245cce8a 735 class_ = _class;
7b33d201 736 loading_ = [NSMutableSet setWithCapacity:5];
bc11cf5b 737
7b33d201 738 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
caa427d1 739
65ea9562
JF
740 CGRect bounds([[self view] bounds]);
741
1ee69bb4 742 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
2634b249
JF
743 [webview_ setDelegate:self];
744 [self setView:webview_];
22f8bed9 745
2634b249
JF
746 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
747 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
748 else
749 [webview_ setDetectsPhoneNumbers:NO];
22f8bed9 750
2634b249 751 [webview_ setScalesPageToFit:YES];
22f8bed9 752
2634b249 753 UIWebDocumentView *document([webview_ _documentView]);
ea173384 754
2634b249
JF
755 // XXX: I think this improves scrolling; the hardcoded-ness sucks
756 [document setTileSize:CGSizeMake(320, 500)];
ea173384 757
2634b249 758 [document setBackgroundColor:[UIColor clearColor]];
14f17703
JF
759
760 // XXX: this is terribly (too?) expensive
2634b249 761 [document setDrawsBackground:NO];
ea173384 762
2634b249
JF
763 WebView *webview([document webView]);
764 WebPreferences *preferences([webview preferences]);
22f8bed9 765
2634b249
JF
766 // XXX: I have no clue if I actually /want/ this modification
767 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
768 [webview _setLayoutInterval:0];
769 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
770 [preferences _setLayoutInterval:0];
22f8bed9 771
2634b249 772 [preferences setCacheModel:WebCacheModelDocumentBrowser];
9dbfe708 773 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
2634b249 774 [preferences setOfflineWebApplicationCacheEnabled:YES];
22f8bed9 775
72bdb258
JF
776#if LogMessages
777 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
778 [document setAllowsMessaging:YES];
779 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
780 [webview _setAllowsMessaging:YES];
781#endif
782
2634b249
JF
783 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
784 scroller_ = [webview_ _scrollView];
22f8bed9 785
2634b249 786 [scroller_ setDirectionalLockEnabled:YES];
9c1605e2 787 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
2634b249 788 [scroller_ setDelaysContentTouches:NO];
22f8bed9 789
2634b249
JF
790 [scroller_ setCanCancelContentTouches:YES];
791 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
792 UIScroller *scroller([webview_ _scroller]);
793 scroller_ = (UIScrollView *) scroller;
22f8bed9 794
2634b249 795 [scroller setDirectionalScrolling:YES];
9c1605e2
JF
796 // XXX: we might be better off /not/ setting this on older systems
797 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
2634b249 798 [scroller setScrollHysteresis:0]; /* 8 */
3e9c9e85 799
2634b249 800 [scroller setThumbDetectionEnabled:NO];
ea173384 801
2634b249
JF
802 // use NO with UIApplicationUseLegacyEvents(YES)
803 [scroller setEventMode:YES];
ea173384 804
2634b249
JF
805 // XXX: this is handled by setBounces, right?
806 //[scroller setAllowsRubberBanding:YES];
22f8bed9 807 }
bc11cf5b 808
2634b249 809 [scroller_ setFixedBackgroundPattern:YES];
65ea9562 810 [scroller_ setBackgroundColor:[UIColor clearColor]];
2634b249 811 [scroller_ setClipsSubviews:YES];
caa427d1 812
2634b249
JF
813 [scroller_ setBounces:YES];
814 [scroller_ setScrollingEnabled:YES];
815 [scroller_ setShowBackgroundShadow:NO];
caa427d1 816
2634b249 817 [self setViewportWidth:width];
bc11cf5b 818
7b33d201 819 reloaditem_ = [[[UIBarButtonItem alloc]
bc11cf5b
JF
820 initWithTitle:UCLocalize("RELOAD")
821 style:[self rightButtonStyle]
822 target:self
823 action:@selector(reloadButtonClicked)
7b33d201 824 ] autorelease];
bc11cf5b 825
7b33d201 826 loadingitem_ = [[[UIBarButtonItem alloc]
bc11cf5b
JF
827 initWithTitle:@" "
828 style:UIBarButtonItemStylePlain
829 target:self
830 action:@selector(reloadButtonClicked)
7b33d201 831 ] autorelease];
2634b249 832
7b33d201 833 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
7a11fbb9 834 [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
22f8bed9 835
65ea9562
JF
836 UITableView *table([[[UITableView alloc] initWithFrame:bounds style:UITableViewStyleGrouped] autorelease]);
837 [webview_ insertSubview:table atIndex:0];
838
e6124cb6 839 [self applyLeftButton];
63ae52be 840 [self applyRightButton];
e6124cb6 841
65ea9562 842 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
2634b249 843 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
04fe1349 844 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
22f8bed9
JF
845 } return self;
846}
847
b5e7eebb
GP
848- (id) initWithWidth:(float)width {
849 return [self initWithWidth:width ofClass:[self class]];
245cce8a
JF
850}
851
b5e7eebb
GP
852- (id) init {
853 return [self initWithWidth:0];
3e9c9e85
JF
854}
855
eb09425a
JF
856- (id) initWithURL:(NSURL *)url {
857 if ((self = [self init]) != nil) {
858 [self setURL:url];
859 } return self;
860}
861
12b59862 862- (void) callFunction:(WebScriptObject *)function {
0893a034 863 WebThreadLocked lock;
caa427d1 864
2634b249 865 WebView *webview([[webview_ _documentView] webView]);
12b59862 866 WebFrame *frame([webview mainFrame]);
c21004b9 867
12b59862 868 JSGlobalContextRef context([frame globalContext]);
9dbfe708 869 JSObjectRef object([function JSObject]);
12b59862 870 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
12b59862
JF
871}
872
ce041f4f 873- (void) reloadButtonClicked {
b13b8664 874 [self reloadURLWithCache:YES];
12b59862
JF
875}
876
719d6c2f
DH
877- (void) _customButtonClicked {
878 [self reloadButtonClicked];
879}
880
ce041f4f 881- (void) customButtonClicked {
caa427d1
JF
882#if !AlwaysReload
883 if (function_ != nil)
12b59862 884 [self callFunction:function_];
caa427d1
JF
885 else
886#endif
719d6c2f 887 [self _customButtonClicked];
22f8bed9
JF
888}
889
3e9c9e85
JF
890+ (float) defaultWidth {
891 return 980;
892}
893
82406217
JF
894- (void) setNavigationBarStyle:(NSString *)name {
895 UIBarStyle style;
896 if ([name isEqualToString:@"Black"])
897 style = UIBarStyleBlack;
898 else
899 style = UIBarStyleDefault;
900
901 [[[self navigationController] navigationBar] setBarStyle:style];
902}
903
00984204
JF
904- (void) setNavigationBarTintColor:(UIColor *)color {
905 [[[self navigationController] navigationBar] setTintColor:color];
906}
907
c31c825d
JF
908- (void) setBadgeValue:(id)value {
909 [[[self navigationController] tabBarItem] setBadgeValue:value];
910}
911
b8a5d89d
JF
912- (void) setHidesBackButton:(bool)value {
913 [[self navigationItem] setHidesBackButton:value];
e6124cb6 914 [self applyLeftButton];
b8a5d89d
JF
915}
916
917- (void) setHidesBackButtonByNumber:(NSNumber *)value {
918 [self setHidesBackButton:[value boolValue]];
919}
920
f196b921 921- (void) dispatchEvent:(NSString *)event {
4bcafc01 922 [webview_ dispatchEvent:event];
f196b921
JF
923}
924
5cdfcd6f
JF
925- (bool) hidesNavigationBar {
926 return hidesNavigationBar_;
927}
928
929- (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
930 if (visible_)
931 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
932}
933
934- (void) setHidesNavigationBar:(bool)value {
935 if (hidesNavigationBar_ != value) {
936 hidesNavigationBar_ = value;
937 [self _setHidesNavigationBar:YES animated:YES];
938 }
939}
940
941- (void) setHidesNavigationBarByNumber:(NSNumber *)value {
942 [self setHidesNavigationBar:[value boolValue]];
943}
944
f196b921 945- (void) viewWillAppear:(BOOL)animated {
5cdfcd6f
JF
946 visible_ = true;
947
948 if ([self hidesNavigationBar])
949 [self _setHidesNavigationBar:YES animated:animated];
950
f196b921
JF
951 [self dispatchEvent:@"CydiaViewWillAppear"];
952 [super viewWillAppear:animated];
953}
954
955- (void) viewDidAppear:(BOOL)animated {
f196b921 956 [super viewDidAppear:animated];
5cdfcd6f 957 [self dispatchEvent:@"CydiaViewDidAppear"];
f196b921
JF
958}
959
960- (void) viewWillDisappear:(BOOL)animated {
961 [self dispatchEvent:@"CydiaViewWillDisappear"];
962 [super viewWillDisappear:animated];
5cdfcd6f
JF
963
964 if ([self hidesNavigationBar])
965 [self _setHidesNavigationBar:NO animated:animated];
966
967 visible_ = false;
f196b921
JF
968}
969
970- (void) viewDidDisappear:(BOOL)animated {
f196b921 971 [super viewDidDisappear:animated];
5cdfcd6f 972 [self dispatchEvent:@"CydiaViewDidDisappear"];
f196b921
JF
973}
974
a5938ea5 975@end