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