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