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