]> git.saurik.com Git - cydia.git/blob - CyteKit/WebViewController.mm
We should rebuild the package if Library/startup changes.
[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 LogBrowser
457 NSLog(@"didDecidePolicy:%u forNavigationAction:%@ request:%@ frame:%@", decision, action, request, [request allHTTPHeaderFields], frame);
458 #endif
459
460 if ([frame parentFrame] == nil) {
461 switch (decision) {
462 case CYWebPolicyDecisionIgnore:
463 if ([[request_ URL] isEqual:[request URL]])
464 request_ = nil;
465 break;
466
467 case CYWebPolicyDecisionUse:
468 if (!error_)
469 request_ = request;
470 break;
471
472 default:
473 break;
474 }
475 }
476 }
477
478 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
479 #if LogBrowser
480 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ %@ newFrameName:%@", action, request, [request allHTTPHeaderFields], name);
481 #endif
482
483 NSURL *url([request URL]);
484 if (url == nil)
485 return;
486
487 if ([name isEqualToString:@"_open"])
488 [delegate_ openURL:url];
489 else {
490 NSString *scheme([[url scheme] lowercaseString]);
491 if ([scheme isEqualToString:@"mailto"])
492 [self _openMailToURL:url];
493 else
494 [self pushRequest:request forAction:action asPop:[name isEqualToString:@"_popup"]];
495 }
496
497 [listener ignore];
498 }
499
500 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
501 }
502
503 - (void) webView:(WebView *)view didCommitLoadForFrame:(WebFrame *)frame {
504 #if LogBrowser
505 NSLog(@"didCommitLoadForFrame:%@", frame);
506 #endif
507
508 if ([frame parentFrame] == nil) {
509 loaded_ = true;
510 }
511 }
512
513 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
514 #if LogBrowser
515 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
516 #endif
517
518 [self _didFailWithError:error forFrame:frame];
519 }
520
521 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
522 #if LogBrowser
523 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
524 #endif
525
526 [self _didFailWithError:error forFrame:frame];
527 }
528
529 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
530 NSValue *object([NSValue valueWithNonretainedObject:frame]);
531 if (![loading_ containsObject:object])
532 return;
533 [loading_ removeObject:object];
534
535 if ([frame parentFrame] == nil) {
536 if (DOMDocument *document = [frame DOMDocument])
537 if (DOMNodeList *bodies = [document getElementsByTagName:@"body"])
538 for (DOMHTMLBodyElement *body in (id) bodies) {
539 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
540
541 UIColor *uic(nil);
542
543 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
544 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
545 DOMRGBColor *rgb([color getRGBColorValue]);
546
547 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
548 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
549 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
550 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
551
552 if (red == 0xc7 && green == 0xce && blue == 0xd5)
553 uic = [UIColor pinStripeColor];
554 else if (alpha != 0)
555 uic = [UIColor
556 colorWithRed:(red / 255)
557 green:(green / 255)
558 blue:(blue / 255)
559 alpha:alpha
560 ];
561 }
562 }
563
564 [scroller_ setBackgroundColor:(uic ?: [UIColor clearColor])];
565 break;
566 }
567 }
568
569 [self _didFinishLoading];
570 }
571
572 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
573 if ([frame parentFrame] != nil)
574 return;
575
576 title_ = title;
577
578 [[self navigationItem] setTitle:title_];
579 }
580
581 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
582 #if LogBrowser
583 NSLog(@"didStartProvisionalLoadForFrame:%@", frame);
584 #endif
585
586 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
587
588 if ([frame parentFrame] == nil) {
589 title_ = nil;
590 custom_ = nil;
591 style_ = nil;
592 function_ = nil;
593
594 allowsNavigationAction_ = true;
595
596 [self setHidesNavigationBar:NO];
597 [self setScrollAlwaysBounceVertical:true];
598 [self setScrollIndicatorStyle:UIScrollViewIndicatorStyleDefault];
599
600 // XXX: do we still need to do this?
601 [[self navigationItem] setTitle:nil];
602 }
603
604 [self _didStartLoading];
605 }
606
607 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
608 #if LogBrowser
609 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
610 #endif
611
612 return request;
613 }
614
615 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
616 return [self _allowJavaScriptPanel];
617 }
618
619 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
620 return [self _allowJavaScriptPanel];
621 }
622
623 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
624 return [self _allowJavaScriptPanel];
625 }
626
627 - (void) webViewClose:(WebView *)view {
628 [self close];
629 }
630 // }}}
631
632 - (void) close {
633 [[[self navigationController] parentOrPresentingViewController] dismissModalViewControllerAnimated:YES];
634 }
635
636 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
637 NSString *context([alert context]);
638
639 if ([context isEqualToString:@"sensitive"]) {
640 switch (button) {
641 case 1:
642 sensitive_ = [NSNumber numberWithBool:YES];
643 break;
644
645 case 2:
646 sensitive_ = [NSNumber numberWithBool:NO];
647 break;
648 }
649
650 [alert dismissWithClickedButtonIndex:-1 animated:YES];
651 } else if ([context isEqualToString:@"challenge"]) {
652 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
653
654 switch (button) {
655 case 1: {
656 NSString *username([[alert textFieldAtIndex:0] text]);
657 NSString *password([[alert textFieldAtIndex:1] text]);
658
659 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
660
661 [sender useCredential:credential forAuthenticationChallenge:challenge_];
662 } break;
663
664 case 2:
665 [sender cancelAuthenticationChallenge:challenge_];
666 break;
667
668 _nodefault
669 }
670
671 challenge_ = nil;
672
673 [alert dismissWithClickedButtonIndex:-1 animated:YES];
674 } else if ([context isEqualToString:@"submit"]) {
675 if (button == [alert cancelButtonIndex]) {
676 } else if (button == [alert firstOtherButtonIndex]) {
677 if (request_ != nil) {
678 WebThreadLocked lock;
679 [[self webView] loadRequest:request_];
680 }
681 }
682
683 [alert dismissWithClickedButtonIndex:-1 animated:YES];
684 }
685 }
686
687 - (UIBarButtonItemStyle) rightButtonStyle {
688 if (style_ == nil) normal:
689 return UIBarButtonItemStylePlain;
690 else if ([style_ isEqualToString:@"Normal"])
691 return UIBarButtonItemStylePlain;
692 else if ([style_ isEqualToString:@"Highlighted"])
693 return UIBarButtonItemStyleDone;
694 else goto normal;
695 }
696
697 - (UIBarButtonItem *) customButton {
698 if (custom_ == nil)
699 return nil;
700 else if ((/*clang:*/id) custom_ == [NSNull null])
701 return (UIBarButtonItem *) [NSNull null];
702
703 return [[[UIBarButtonItem alloc]
704 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
705 style:[self rightButtonStyle]
706 target:self
707 action:@selector(customButtonClicked)
708 ] autorelease];
709 }
710
711 - (UIBarButtonItem *) leftButton {
712 UINavigationItem *item([self navigationItem]);
713 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
714 return nil;
715
716 if (UINavigationController *navigation = [self navigationController])
717 if ([[navigation parentOrPresentingViewController] modalViewController] == navigation)
718 return [[[UIBarButtonItem alloc]
719 initWithTitle:UCLocalize("CLOSE")
720 style:UIBarButtonItemStylePlain
721 target:self
722 action:@selector(close)
723 ] autorelease];
724
725 return nil;
726 }
727
728 - (void) applyLeftButton {
729 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
730 }
731
732 - (UIBarButtonItem *) rightButton {
733 return reloaditem_;
734 }
735
736 - (void) applyLoadingTitle {
737 [[self navigationItem] setTitle:UCLocalize("LOADING")];
738 }
739
740 - (void) layoutRightButton {
741 [[loadingitem_ view] addSubview:indicator_];
742 [[loadingitem_ view] bringSubviewToFront:indicator_];
743 }
744
745 - (void) applyRightButton {
746 if ([self isLoading]) {
747 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
748 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
749
750 [indicator_ startAnimating];
751 [self applyLoadingTitle];
752 } else {
753 [indicator_ stopAnimating];
754
755 UIBarButtonItem *button([self customButton]);
756 if (button == nil)
757 button = [self rightButton];
758 else if (button == (UIBarButtonItem *) [NSNull null])
759 button = nil;
760
761 [[self navigationItem] setRightBarButtonItem:button animated:YES];
762 }
763 }
764
765 - (void) didStartLoading {
766 // Overridden in subclasses.
767 }
768
769 - (void) _didStartLoading {
770 [self applyRightButton];
771
772 if ([loading_ count] != 1)
773 return;
774
775 if ([self retainsNetworkActivityIndicator])
776 [delegate_ retainNetworkActivityIndicator];
777
778 [self didStartLoading];
779 }
780
781 - (void) didFinishLoading {
782 // Overridden in subclasses.
783 }
784
785 - (void) _didFinishLoading {
786 if ([loading_ count] != 0)
787 return;
788
789 [self applyRightButton];
790 [[self navigationItem] setTitle:title_];
791
792 if ([self retainsNetworkActivityIndicator])
793 [delegate_ releaseNetworkActivityIndicator];
794
795 [self didFinishLoading];
796 }
797
798 - (bool) isLoading {
799 return [loading_ count] != 0;
800 }
801
802 - (id) initWithWidth:(float)width ofClass:(Class)_class {
803 if ((self = [super init]) != nil) {
804 width_ = width;
805 class_ = _class;
806
807 allowsNavigationAction_ = true;
808
809 loading_ = [NSMutableSet setWithCapacity:5];
810 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
811
812 reloaditem_ = [[[UIBarButtonItem alloc]
813 initWithTitle:UCLocalize("RELOAD")
814 style:[self rightButtonStyle]
815 target:self
816 action:@selector(reloadButtonClicked)
817 ] autorelease];
818
819 loadingitem_ = [[[UIBarButtonItem alloc]
820 initWithTitle:@" "
821 style:UIBarButtonItemStylePlain
822 target:self
823 action:@selector(reloadButtonClicked)
824 ] autorelease];
825
826 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
827 [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
828 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
829
830 [self applyLeftButton];
831 [self applyRightButton];
832 } return self;
833 }
834
835 - (NSString *) applicationNameForUserAgent {
836 return nil;
837 }
838
839 - (void) loadView {
840 CGRect bounds([[UIScreen mainScreen] applicationFrame]);
841
842 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
843 [webview_ setDelegate:self];
844 [self setView:webview_];
845
846 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
847 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
848 else
849 [webview_ setDetectsPhoneNumbers:NO];
850
851 [webview_ setScalesPageToFit:YES];
852
853 UIWebDocumentView *document([webview_ _documentView]);
854
855 // XXX: I think this improves scrolling; the hardcoded-ness sucks
856 [document setTileSize:CGSizeMake(320, 500)];
857
858 [document setBackgroundColor:[UIColor clearColor]];
859
860 // XXX: this is terribly (too?) expensive
861 [document setDrawsBackground:NO];
862
863 WebView *webview([document webView]);
864 WebPreferences *preferences([webview preferences]);
865
866 // XXX: I have no clue if I actually /want/ this modification
867 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
868 [webview _setLayoutInterval:0];
869 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
870 [preferences _setLayoutInterval:0];
871
872 [preferences setCacheModel:WebCacheModelDocumentBrowser];
873 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
874
875 if ([preferences respondsToSelector:@selector(setOfflineWebApplicationCacheEnabled:)])
876 [preferences setOfflineWebApplicationCacheEnabled:YES];
877
878 if (NSString *agent = [self applicationNameForUserAgent])
879 [webview setApplicationNameForUserAgent:agent];
880
881 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
882 [webview setShouldUpdateWhileOffscreen:NO];
883
884 #if LogMessages
885 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
886 [document setAllowsMessaging:YES];
887 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
888 [webview _setAllowsMessaging:YES];
889 #endif
890
891 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
892 scroller_ = [webview_ _scrollView];
893
894 [scroller_ setDirectionalLockEnabled:YES];
895 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
896 [scroller_ setDelaysContentTouches:NO];
897
898 [scroller_ setCanCancelContentTouches:YES];
899 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
900 UIScroller *scroller([webview_ _scroller]);
901 scroller_ = (UIScrollView *) scroller;
902
903 [scroller setDirectionalScrolling:YES];
904 // XXX: we might be better off /not/ setting this on older systems
905 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
906 [scroller setScrollHysteresis:0]; /* 8 */
907
908 [scroller setThumbDetectionEnabled:NO];
909
910 // use NO with UIApplicationUseLegacyEvents(YES)
911 [scroller setEventMode:YES];
912
913 // XXX: this is handled by setBounces, right?
914 //[scroller setAllowsRubberBanding:YES];
915 }
916
917 [scroller_ setFixedBackgroundPattern:YES];
918 [scroller_ setBackgroundColor:[UIColor clearColor]];
919 [scroller_ setClipsSubviews:YES];
920
921 [scroller_ setBounces:YES];
922 [scroller_ setScrollingEnabled:YES];
923 [scroller_ setShowBackgroundShadow:NO];
924
925 [self setViewportWidth:width_];
926
927 UITableView *table([[[UITableView alloc] initWithFrame:[webview_ bounds] style:UITableViewStyleGrouped] autorelease]);
928 [table setScrollsToTop:NO];
929 [webview_ insertSubview:table atIndex:0];
930
931 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
932 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
933
934 ready_ = false;
935 }
936
937 - (void) releaseSubviews {
938 webview_ = nil;
939 scroller_ = nil;
940
941 [self releaseNetworkActivityIndicator];
942
943 [super releaseSubviews];
944 }
945
946 - (id) initWithWidth:(float)width {
947 return [self initWithWidth:width ofClass:[self class]];
948 }
949
950 - (id) init {
951 return [self initWithWidth:0];
952 }
953
954 - (id) initWithURL:(NSURL *)url {
955 if ((self = [self init]) != nil) {
956 [self setURL:url];
957 } return self;
958 }
959
960 - (id) initWithRequest:(NSURLRequest *)request {
961 if ((self = [self init]) != nil) {
962 [self setRequest:request];
963 } return self;
964 }
965
966 - (void) callFunction:(WebScriptObject *)function {
967 WebThreadLocked lock;
968
969 WebView *webview([[[self webView] _documentView] webView]);
970 WebFrame *frame([webview mainFrame]);
971
972 JSGlobalContextRef context([frame globalContext]);
973 JSObjectRef object([function JSObject]);
974 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
975 }
976
977 - (void) reloadButtonClicked {
978 [self reloadURLWithCache:NO];
979 }
980
981 - (void) _customButtonClicked {
982 [self reloadButtonClicked];
983 }
984
985 - (void) customButtonClicked {
986 #if !AlwaysReload
987 if (function_ != nil)
988 [self callFunction:function_];
989 else
990 #endif
991 [self _customButtonClicked];
992 }
993
994 + (float) defaultWidth {
995 return 980;
996 }
997
998 - (void) setNavigationBarStyle:(NSString *)name {
999 UIBarStyle style;
1000 if ([name isEqualToString:@"Black"])
1001 style = UIBarStyleBlack;
1002 else
1003 style = UIBarStyleDefault;
1004
1005 [[[self navigationController] navigationBar] setBarStyle:style];
1006 }
1007
1008 - (void) setNavigationBarTintColor:(UIColor *)color {
1009 [[[self navigationController] navigationBar] setTintColor:color];
1010 }
1011
1012 - (void) setBadgeValue:(id)value {
1013 [[[self navigationController] tabBarItem] setBadgeValue:value];
1014 }
1015
1016 - (void) setHidesBackButton:(bool)value {
1017 [[self navigationItem] setHidesBackButton:value];
1018 [self applyLeftButton];
1019 }
1020
1021 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
1022 [self setHidesBackButton:[value boolValue]];
1023 }
1024
1025 - (void) dispatchEvent:(NSString *)event {
1026 [[self webView] dispatchEvent:event];
1027 }
1028
1029 - (bool) hidesNavigationBar {
1030 return hidesNavigationBar_;
1031 }
1032
1033 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
1034 if (visible_)
1035 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
1036 }
1037
1038 - (void) setHidesNavigationBar:(bool)value {
1039 if (hidesNavigationBar_ != value) {
1040 hidesNavigationBar_ = value;
1041 [self _setHidesNavigationBar:YES animated:YES];
1042 }
1043 }
1044
1045 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
1046 [self setHidesNavigationBar:[value boolValue]];
1047 }
1048
1049 - (void) setScrollAlwaysBounceVertical:(bool)value {
1050 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1051 UIScrollView *scroller([webview_ _scrollView]);
1052 [scroller setAlwaysBounceVertical:value];
1053 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1054 //UIScroller *scroller([webview_ _scroller]);
1055 // XXX: I am sad here.
1056 } else return;
1057 }
1058
1059 - (void) setScrollAlwaysBounceVerticalNumber:(NSNumber *)value {
1060 [self setScrollAlwaysBounceVertical:[value boolValue]];
1061 }
1062
1063 - (void) setScrollIndicatorStyle:(UIScrollViewIndicatorStyle)style {
1064 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
1065 UIScrollView *scroller([webview_ _scrollView]);
1066 [scroller setIndicatorStyle:style];
1067 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
1068 UIScroller *scroller([webview_ _scroller]);
1069 [scroller setScrollerIndicatorStyle:style];
1070 } else return;
1071 }
1072
1073 - (void) setScrollIndicatorStyleWithName:(NSString *)style {
1074 UIScrollViewIndicatorStyle value;
1075
1076 if (false);
1077 else if ([style isEqualToString:@"default"])
1078 value = UIScrollViewIndicatorStyleDefault;
1079 else if ([style isEqualToString:@"black"])
1080 value = UIScrollViewIndicatorStyleBlack;
1081 else if ([style isEqualToString:@"white"])
1082 value = UIScrollViewIndicatorStyleWhite;
1083 else return;
1084
1085 [self setScrollIndicatorStyle:value];
1086 }
1087
1088 - (void) viewWillAppear:(BOOL)animated {
1089 visible_ = true;
1090
1091 if ([self hidesNavigationBar])
1092 [self _setHidesNavigationBar:YES animated:animated];
1093
1094 // XXX: why isn't this evern called automatically?
1095 [[self webView] setNeedsLayout];
1096
1097 [self dispatchEvent:@"CydiaViewWillAppear"];
1098 [super viewWillAppear:animated];
1099 }
1100
1101 - (void) viewDidAppear:(BOOL)animated {
1102 [super viewDidAppear:animated];
1103 [self dispatchEvent:@"CydiaViewDidAppear"];
1104 }
1105
1106 - (void) viewWillDisappear:(BOOL)animated {
1107 [self dispatchEvent:@"CydiaViewWillDisappear"];
1108 [super viewWillDisappear:animated];
1109
1110 if ([self hidesNavigationBar])
1111 [self _setHidesNavigationBar:NO animated:animated];
1112
1113 visible_ = false;
1114 }
1115
1116 - (void) viewDidDisappear:(BOOL)animated {
1117 [super viewDidDisappear:animated];
1118 [self dispatchEvent:@"CydiaViewDidDisappear"];
1119 }
1120
1121 @end