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