]> git.saurik.com Git - cydia.git/blob - CyteKit/WebViewController.mm
Separate out Cydia/ProgressEvent.h.
[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 CYViewController *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 return custom_ == [NSNull null] ? nil : [[[UIBarButtonItem alloc]
602 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
603 style:[self rightButtonStyle]
604 target:self
605 action:@selector(customButtonClicked)
606 ] autorelease];
607 }
608
609 - (UIBarButtonItem *) rightButton {
610 return reloaditem_;
611 }
612
613 - (void) applyLoadingTitle {
614 [[self navigationItem] setTitle:UCLocalize("LOADING")];
615 }
616
617 - (void) layoutRightButton {
618 [[loadingitem_ view] addSubview:indicator_];
619 [[loadingitem_ view] bringSubviewToFront:indicator_];
620 }
621
622 - (void) applyRightButton {
623 if ([self isLoading]) {
624 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
625 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
626
627 [indicator_ startAnimating];
628 [self applyLoadingTitle];
629 } else {
630 [indicator_ stopAnimating];
631
632 [[self navigationItem] setRightBarButtonItem:(
633 custom_ != nil ? [self customButton] : [self rightButton]
634 ) animated:YES];
635 }
636 }
637
638 - (void) didStartLoading {
639 // Overridden in subclasses.
640 }
641
642 - (void) _didStartLoading {
643 [self applyRightButton];
644
645 if ([loading_ count] != 1)
646 return;
647
648 [delegate_ retainNetworkActivityIndicator];
649 [self didStartLoading];
650 }
651
652 - (void) didFinishLoading {
653 // Overridden in subclasses.
654 }
655
656 - (void) _didFinishLoading {
657 if ([loading_ count] != 0)
658 return;
659
660 [self applyRightButton];
661 [[self navigationItem] setTitle:title_];
662
663 [delegate_ releaseNetworkActivityIndicator];
664 [self didFinishLoading];
665 }
666
667 - (bool) isLoading {
668 return [loading_ count] != 0;
669 }
670
671 - (id) initWithWidth:(float)width ofClass:(Class)_class {
672 if ((self = [super init]) != nil) {
673 allowsNavigationAction_ = true;
674
675 class_ = _class;
676 loading_ = [[NSMutableSet alloc] initWithCapacity:5];
677
678 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
679
680 CGRect bounds([[self view] bounds]);
681
682 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
683 [webview_ setDelegate:self];
684 [self setView:webview_];
685
686 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
687 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
688 else
689 [webview_ setDetectsPhoneNumbers:NO];
690
691 [webview_ setScalesPageToFit:YES];
692
693 UIWebDocumentView *document([webview_ _documentView]);
694
695 // XXX: I think this improves scrolling; the hardcoded-ness sucks
696 [document setTileSize:CGSizeMake(320, 500)];
697
698 [document setBackgroundColor:[UIColor clearColor]];
699
700 // XXX: this is terribly (too?) expensive
701 [document setDrawsBackground:NO];
702
703 WebView *webview([document webView]);
704 WebPreferences *preferences([webview preferences]);
705
706 // XXX: I have no clue if I actually /want/ this modification
707 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
708 [webview _setLayoutInterval:0];
709 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
710 [preferences _setLayoutInterval:0];
711
712 [preferences setCacheModel:WebCacheModelDocumentBrowser];
713 [preferences setOfflineWebApplicationCacheEnabled:YES];
714
715 #if LogMessages
716 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
717 [document setAllowsMessaging:YES];
718 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
719 [webview _setAllowsMessaging:YES];
720 #endif
721
722 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
723 scroller_ = [webview_ _scrollView];
724
725 [scroller_ setDirectionalLockEnabled:YES];
726 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
727 [scroller_ setDelaysContentTouches:NO];
728
729 [scroller_ setCanCancelContentTouches:YES];
730 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
731 UIScroller *scroller([webview_ _scroller]);
732 scroller_ = (UIScrollView *) scroller;
733
734 [scroller setDirectionalScrolling:YES];
735 // XXX: we might be better off /not/ setting this on older systems
736 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
737 [scroller setScrollHysteresis:0]; /* 8 */
738
739 [scroller setThumbDetectionEnabled:NO];
740
741 // use NO with UIApplicationUseLegacyEvents(YES)
742 [scroller setEventMode:YES];
743
744 // XXX: this is handled by setBounces, right?
745 //[scroller setAllowsRubberBanding:YES];
746 }
747
748 [scroller_ setFixedBackgroundPattern:YES];
749 [scroller_ setBackgroundColor:[UIColor clearColor]];
750 [scroller_ setClipsSubviews:YES];
751
752 [scroller_ setBounces:YES];
753 [scroller_ setScrollingEnabled:YES];
754 [scroller_ setShowBackgroundShadow:NO];
755
756 [self setViewportWidth:width];
757
758 reloaditem_ = [[UIBarButtonItem alloc]
759 initWithTitle:UCLocalize("RELOAD")
760 style:[self rightButtonStyle]
761 target:self
762 action:@selector(reloadButtonClicked)
763 ];
764
765 loadingitem_ = [[UIBarButtonItem alloc]
766 initWithTitle:@" "
767 style:UIBarButtonItemStylePlain
768 target:self
769 action:@selector(reloadButtonClicked)
770 ];
771
772 indicator_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
773 [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
774
775 UITableView *table([[[UITableView alloc] initWithFrame:bounds style:UITableViewStyleGrouped] autorelease]);
776 [webview_ insertSubview:table atIndex:0];
777
778 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
779 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
780 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
781 } return self;
782 }
783
784 - (id) initWithWidth:(float)width {
785 return [self initWithWidth:width ofClass:[self class]];
786 }
787
788 - (id) init {
789 return [self initWithWidth:0];
790 }
791
792 - (id) initWithURL:(NSURL *)url {
793 if ((self = [self init]) != nil) {
794 [self setURL:url];
795 } return self;
796 }
797
798 - (void) callFunction:(WebScriptObject *)function {
799 WebThreadLocked lock;
800
801 WebView *webview([[webview_ _documentView] webView]);
802 WebFrame *frame([webview mainFrame]);
803 WebPreferences *preferences([webview preferences]);
804
805 bool maybe([preferences javaScriptCanOpenWindowsAutomatically]);
806 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
807
808 /*id _private(MSHookIvar<id>(webview, "_private"));
809 WebCore::Page *page(_private == nil ? NULL : MSHookIvar<WebCore::Page *>(_private, "page"));
810 WebCore::Settings *settings(page == NULL ? NULL : page->settings());
811
812 bool no;
813 if (settings == NULL)
814 no = 0;
815 else {
816 no = settings->JavaScriptCanOpenWindowsAutomatically();
817 settings->setJavaScriptCanOpenWindowsAutomatically(true);
818 }*/
819
820 if (UIWindow *window = [[self view] window])
821 if (UIResponder *responder = [window firstResponder])
822 [responder resignFirstResponder];
823
824 JSObjectRef object([function JSObject]);
825 JSGlobalContextRef context([frame globalContext]);
826 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
827
828 /*if (settings != NULL)
829 settings->setJavaScriptCanOpenWindowsAutomatically(no);*/
830
831 [preferences setJavaScriptCanOpenWindowsAutomatically:maybe];
832 }
833
834 - (void) reloadButtonClicked {
835 [self reloadURLWithCache:YES];
836 }
837
838 - (void) _customButtonClicked {
839 [self reloadButtonClicked];
840 }
841
842 - (void) customButtonClicked {
843 #if !AlwaysReload
844 if (function_ != nil)
845 [self callFunction:function_];
846 else
847 #endif
848 [self _customButtonClicked];
849 }
850
851 + (float) defaultWidth {
852 return 980;
853 }
854
855 - (void) setNavigationBarStyle:(NSString *)name {
856 UIBarStyle style;
857 if ([name isEqualToString:@"Black"])
858 style = UIBarStyleBlack;
859 else
860 style = UIBarStyleDefault;
861
862 [[[self navigationController] navigationBar] setBarStyle:style];
863 }
864
865 - (void) setNavigationBarTintColor:(UIColor *)color {
866 [[[self navigationController] navigationBar] setTintColor:color];
867 }
868
869 - (void) setBadgeValue:(id)value {
870 [[[self navigationController] tabBarItem] setBadgeValue:value];
871 }
872
873 - (void) setHidesBackButton:(bool)value {
874 [[self navigationItem] setHidesBackButton:value];
875 }
876
877 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
878 [self setHidesBackButton:[value boolValue]];
879 }
880
881 - (void) dispatchEvent:(NSString *)event {
882 [webview_ dispatchEvent:event];
883 }
884
885 - (bool) hidesNavigationBar {
886 return hidesNavigationBar_;
887 }
888
889 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
890 if (visible_)
891 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
892 }
893
894 - (void) setHidesNavigationBar:(bool)value {
895 if (hidesNavigationBar_ != value) {
896 hidesNavigationBar_ = value;
897 [self _setHidesNavigationBar:YES animated:YES];
898 }
899 }
900
901 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
902 [self setHidesNavigationBar:[value boolValue]];
903 }
904
905 - (void) viewWillAppear:(BOOL)animated {
906 visible_ = true;
907
908 if ([self hidesNavigationBar])
909 [self _setHidesNavigationBar:YES animated:animated];
910
911 [self dispatchEvent:@"CydiaViewWillAppear"];
912 [super viewWillAppear:animated];
913 }
914
915 - (void) viewDidAppear:(BOOL)animated {
916 [super viewDidAppear:animated];
917 [self dispatchEvent:@"CydiaViewDidAppear"];
918 }
919
920 - (void) viewWillDisappear:(BOOL)animated {
921 [self dispatchEvent:@"CydiaViewWillDisappear"];
922 [super viewWillDisappear:animated];
923
924 if ([self hidesNavigationBar])
925 [self _setHidesNavigationBar:NO animated:animated];
926
927 visible_ = false;
928 }
929
930 - (void) viewDidDisappear:(BOOL)animated {
931 [super viewDidDisappear:animated];
932 [self dispatchEvent:@"CydiaViewDidDisappear"];
933 }
934
935 @end