]> git.saurik.com Git - cydia.git/blob - CyteKit/WebViewController.mm
e6f7e45cfaa31fed0644852c261891ae8257f306
[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 *app([UIApplication sharedApplication]);
290 if ([app respondsToSelector:@selector(openURL:asPanel:)])
291 [app openURL:url asPanel:YES];
292 else
293 [app openURL:url];
294 }
295
296 - (bool) _allowJavaScriptPanel {
297 return true;
298 }
299
300 - (bool) allowsNavigationAction {
301 return allowsNavigationAction_;
302 }
303
304 - (void) setAllowsNavigationAction:(bool)value {
305 allowsNavigationAction_ = value;
306 }
307
308 - (void) setAllowsNavigationActionByNumber:(NSNumber *)value {
309 [self setAllowsNavigationAction:[value boolValue]];
310 }
311
312 - (void) popViewControllerWithNumber:(NSNumber *)value {
313 UINavigationController *navigation([self navigationController]);
314 if ([navigation topViewController] == self)
315 [navigation popViewControllerAnimated:[value boolValue]];
316 }
317
318 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
319 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
320 [self _didFinishLoading];
321
322 if ([error code] == NSURLErrorCancelled)
323 return;
324
325 if ([frame parentFrame] == nil) {
326 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
327 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
328 [[error localizedDescription] stringByAddingPercentEscapes]
329 ]]];
330
331 error_ = true;
332 }
333 }
334
335 - (void) pushRequest:(NSURLRequest *)request asPop:(bool)pop {
336 NSURL *url([request URL]);
337
338 // XXX: filter to internal usage?
339 CyteViewController *page([delegate_ pageForURL:url forExternal:NO]);
340
341 if (page == nil) {
342 CyteWebViewController *browser([[[class_ alloc] init] autorelease]);
343 [browser loadRequest:request];
344 page = browser;
345 }
346
347 [page setDelegate:delegate_];
348
349 if (!pop) {
350 [[self navigationItem] setTitle:title_];
351
352 [[self navigationController] pushViewController:page animated:YES];
353 } else {
354 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
355
356 [navigation setDelegate:delegate_];
357
358 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
359 initWithTitle:UCLocalize("CLOSE")
360 style:UIBarButtonItemStylePlain
361 target:page
362 action:@selector(close)
363 ] autorelease]];
364
365 [[self navigationController] presentModalViewController:navigation animated:YES];
366
367 [delegate_ unloadData];
368 }
369 }
370
371 // CyteWebViewDelegate {{{
372 - (void) webView:(WebView *)view addMessageToConsole:(NSDictionary *)message {
373 #if LogMessages
374 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$");
375 if (NSString *data = [message objectForKey:@"message"])
376 if (irritating(data))
377 return;
378
379 NSLog(@"addMessageToConsole:%@", message);
380 #endif
381 }
382
383 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
384 #if LogBrowser
385 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ frame:%@", action, request, frame);
386 #endif
387
388 if ([frame parentFrame] == nil) {
389 if (!error_) {
390 NSURL *url(request == nil ? nil : [request URL]);
391
392 if (request_ == nil || [self allowsNavigationAction] || [[request_ URL] isEqual:url])
393 request_ = request;
394 else {
395 if (url != nil)
396 [self pushRequest:request asPop:NO];
397 [listener ignore];
398 }
399 }
400 }
401 }
402
403 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
404 #if LogBrowser
405 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ newFrameName:%@", action, request, frame);
406 #endif
407
408 NSURL *url([request URL]);
409 if (url == nil)
410 return;
411
412 if ([frame isEqualToString:@"_open"])
413 [delegate_ openURL:url];
414 else {
415 NSString *scheme([[url scheme] lowercaseString]);
416 if ([scheme isEqualToString:@"mailto"])
417 [self _openMailToURL:url];
418 else
419 [self pushRequest:request asPop:[frame isEqualToString:@"_popup"]];
420 }
421
422 [listener ignore];
423 }
424
425 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
426 }
427
428 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
429 #if LogBrowser
430 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
431 #endif
432
433 [self _didFailWithError:error forFrame:frame];
434 }
435
436 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
437 #if LogBrowser
438 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
439 #endif
440
441 [self _didFailWithError:error forFrame:frame];
442 }
443
444 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
445 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
446
447 if ([frame parentFrame] == nil) {
448 if (DOMDocument *document = [frame DOMDocument])
449 if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
450 for (DOMHTMLBodyElement *body in (id) bodies) {
451 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
452
453 UIColor *uic(nil);
454
455 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
456 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
457 DOMRGBColor *rgb([color getRGBColorValue]);
458
459 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
460 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
461 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
462 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
463
464 if (red == 0xc7 && green == 0xce && blue == 0xd5)
465 uic = [UIColor pinStripeColor];
466 else if (alpha != 0)
467 uic = [UIColor
468 colorWithRed:(red / 255)
469 green:(green / 255)
470 blue:(blue / 255)
471 alpha:alpha
472 ];
473 }
474 }
475
476 [scroller_ setBackgroundColor:(uic ?: [UIColor clearColor])];
477 break;
478 }
479 }
480
481 [self _didFinishLoading];
482 }
483
484 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
485 if ([frame parentFrame] != nil)
486 return;
487
488 if (title_ != nil)
489 [title_ autorelease];
490 title_ = [title retain];
491
492 [[self navigationItem] setTitle:title_];
493 }
494
495 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
496 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
497
498 if ([frame parentFrame] == nil) {
499 CYRelease(title_);
500 custom_ = nil;
501 style_ = nil;
502 function_ = nil;
503
504 [self setHidesNavigationBar:NO];
505
506 // XXX: do we still need to do this?
507 [[self navigationItem] setTitle:nil];
508 }
509
510 [self _didStartLoading];
511 }
512
513 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
514 #if LogBrowser
515 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
516 #endif
517
518 return request;
519 }
520
521 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
522 return [self _allowJavaScriptPanel];
523 }
524
525 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
526 return [self _allowJavaScriptPanel];
527 }
528
529 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
530 return [self _allowJavaScriptPanel];
531 }
532
533 - (void) webViewClose:(WebView *)view {
534 [self close];
535 }
536 // }}}
537
538 - (void) close {
539 [[self navigationController] dismissModalViewControllerAnimated:YES];
540 }
541
542 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
543 NSString *context([alert context]);
544
545 if ([context isEqualToString:@"sensitive"]) {
546 switch (button) {
547 case 1:
548 sensitive_ = [NSNumber numberWithBool:YES];
549 break;
550
551 case 2:
552 sensitive_ = [NSNumber numberWithBool:NO];
553 break;
554 }
555
556 [alert dismissWithClickedButtonIndex:-1 animated:YES];
557 } else if ([context isEqualToString:@"challenge"]) {
558 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
559
560 switch (button) {
561 case 1: {
562 NSString *username([[alert textFieldAtIndex:0] text]);
563 NSString *password([[alert textFieldAtIndex:1] text]);
564
565 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
566
567 [sender useCredential:credential forAuthenticationChallenge:challenge_];
568 } break;
569
570 case 2:
571 [sender cancelAuthenticationChallenge:challenge_];
572 break;
573
574 _nodefault
575 }
576
577 [challenge_ release];
578 challenge_ = nil;
579
580 [alert dismissWithClickedButtonIndex:-1 animated:YES];
581 } else if ([context isEqualToString:@"submit"]) {
582 if (button == [alert cancelButtonIndex]) {
583 } else if (button == [alert firstOtherButtonIndex]) {
584 if (request_ != nil) {
585 WebThreadLocked lock;
586 [webview_ loadRequest:request_];
587 }
588 }
589
590 [alert dismissWithClickedButtonIndex:-1 animated:YES];
591 }
592 }
593
594 - (UIBarButtonItemStyle) rightButtonStyle {
595 if (style_ == nil) normal:
596 return UIBarButtonItemStylePlain;
597 else if ([style_ isEqualToString:@"Normal"])
598 return UIBarButtonItemStylePlain;
599 else if ([style_ isEqualToString:@"Highlighted"])
600 return UIBarButtonItemStyleDone;
601 else goto normal;
602 }
603
604 - (UIBarButtonItem *) customButton {
605 if (custom_ == nil)
606 return nil;
607 else if (custom_ == [NSNull null])
608 return (UIBarButtonItem *) [NSNull null];
609
610 return [[[UIBarButtonItem alloc]
611 initWithTitle:static_cast<NSString *>(custom_.operator NSObject *())
612 style:[self rightButtonStyle]
613 target:self
614 action:@selector(customButtonClicked)
615 ] autorelease];
616 }
617
618 - (UIBarButtonItem *) leftButton {
619 UINavigationItem *item([self navigationItem]);
620 if ([item backBarButtonItem] != nil && ![item hidesBackButton])
621 return nil;
622
623 if (UINavigationController *navigation = [self navigationController])
624 if ([[navigation parentViewController] modalViewController] == navigation)
625 return [[[UIBarButtonItem alloc]
626 initWithTitle:UCLocalize("CLOSE")
627 style:UIBarButtonItemStylePlain
628 target:self
629 action:@selector(close)
630 ] autorelease];
631
632 return nil;
633 }
634
635 - (void) applyLeftButton {
636 [[self navigationItem] setLeftBarButtonItem:[self leftButton]];
637 }
638
639 - (UIBarButtonItem *) rightButton {
640 return reloaditem_;
641 }
642
643 - (void) applyLoadingTitle {
644 [[self navigationItem] setTitle:UCLocalize("LOADING")];
645 }
646
647 - (void) layoutRightButton {
648 [[loadingitem_ view] addSubview:indicator_];
649 [[loadingitem_ view] bringSubviewToFront:indicator_];
650 }
651
652 - (void) applyRightButton {
653 if ([self isLoading]) {
654 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
655 [self performSelector:@selector(layoutRightButton) withObject:nil afterDelay:0];
656
657 [indicator_ startAnimating];
658 [self applyLoadingTitle];
659 } else {
660 [indicator_ stopAnimating];
661
662 UIBarButtonItem *button([self customButton]);
663 if (button == nil)
664 button = [self rightButton];
665 else if (button == (UIBarButtonItem *) [NSNull null])
666 button = nil;
667
668 [[self navigationItem] setRightBarButtonItem:button];
669 }
670 }
671
672 - (void) didStartLoading {
673 // Overridden in subclasses.
674 }
675
676 - (void) _didStartLoading {
677 [self applyRightButton];
678
679 if ([loading_ count] != 1)
680 return;
681
682 [delegate_ retainNetworkActivityIndicator];
683 [self didStartLoading];
684 }
685
686 - (void) didFinishLoading {
687 // Overridden in subclasses.
688 }
689
690 - (void) _didFinishLoading {
691 if ([loading_ count] != 0)
692 return;
693
694 [self applyRightButton];
695 [[self navigationItem] setTitle:title_];
696
697 [delegate_ releaseNetworkActivityIndicator];
698 [self didFinishLoading];
699 }
700
701 - (bool) isLoading {
702 return [loading_ count] != 0;
703 }
704
705 - (id) initWithWidth:(float)width ofClass:(Class)_class {
706 if ((self = [super init]) != nil) {
707 allowsNavigationAction_ = true;
708
709 class_ = _class;
710 loading_ = [[NSMutableSet alloc] initWithCapacity:5];
711
712 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
713
714 CGRect bounds([[self view] bounds]);
715
716 webview_ = [[[CyteWebView alloc] initWithFrame:bounds] autorelease];
717 [webview_ setDelegate:self];
718 [self setView:webview_];
719
720 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
721 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
722 else
723 [webview_ setDetectsPhoneNumbers:NO];
724
725 [webview_ setScalesPageToFit:YES];
726
727 UIWebDocumentView *document([webview_ _documentView]);
728
729 // XXX: I think this improves scrolling; the hardcoded-ness sucks
730 [document setTileSize:CGSizeMake(320, 500)];
731
732 [document setBackgroundColor:[UIColor clearColor]];
733
734 // XXX: this is terribly (too?) expensive
735 [document setDrawsBackground:NO];
736
737 WebView *webview([document webView]);
738 WebPreferences *preferences([webview preferences]);
739
740 // XXX: I have no clue if I actually /want/ this modification
741 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
742 [webview _setLayoutInterval:0];
743 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
744 [preferences _setLayoutInterval:0];
745
746 [preferences setCacheModel:WebCacheModelDocumentBrowser];
747 [preferences setOfflineWebApplicationCacheEnabled:YES];
748
749 #if LogMessages
750 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
751 [document setAllowsMessaging:YES];
752 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
753 [webview _setAllowsMessaging:YES];
754 #endif
755
756 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
757 scroller_ = [webview_ _scrollView];
758
759 [scroller_ setDirectionalLockEnabled:YES];
760 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
761 [scroller_ setDelaysContentTouches:NO];
762
763 [scroller_ setCanCancelContentTouches:YES];
764 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
765 UIScroller *scroller([webview_ _scroller]);
766 scroller_ = (UIScrollView *) scroller;
767
768 [scroller setDirectionalScrolling:YES];
769 // XXX: we might be better off /not/ setting this on older systems
770 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
771 [scroller setScrollHysteresis:0]; /* 8 */
772
773 [scroller setThumbDetectionEnabled:NO];
774
775 // use NO with UIApplicationUseLegacyEvents(YES)
776 [scroller setEventMode:YES];
777
778 // XXX: this is handled by setBounces, right?
779 //[scroller setAllowsRubberBanding:YES];
780 }
781
782 [scroller_ setFixedBackgroundPattern:YES];
783 [scroller_ setBackgroundColor:[UIColor clearColor]];
784 [scroller_ setClipsSubviews:YES];
785
786 [scroller_ setBounces:YES];
787 [scroller_ setScrollingEnabled:YES];
788 [scroller_ setShowBackgroundShadow:NO];
789
790 [self setViewportWidth:width];
791
792 reloaditem_ = [[UIBarButtonItem alloc]
793 initWithTitle:UCLocalize("RELOAD")
794 style:[self rightButtonStyle]
795 target:self
796 action:@selector(reloadButtonClicked)
797 ];
798
799 loadingitem_ = [[UIBarButtonItem alloc]
800 initWithTitle:@" "
801 style:UIBarButtonItemStylePlain
802 target:self
803 action:@selector(reloadButtonClicked)
804 ];
805
806 indicator_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
807 [indicator_ setFrame:CGRectMake(15, 5, [indicator_ frame].size.width, [indicator_ frame].size.height)];
808
809 UITableView *table([[[UITableView alloc] initWithFrame:bounds style:UITableViewStyleGrouped] autorelease]);
810 [webview_ insertSubview:table atIndex:0];
811
812 [self applyLeftButton];
813 [self applyRightButton];
814
815 [table setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
816 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
817 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
818 } return self;
819 }
820
821 - (id) initWithWidth:(float)width {
822 return [self initWithWidth:width ofClass:[self class]];
823 }
824
825 - (id) init {
826 return [self initWithWidth:0];
827 }
828
829 - (id) initWithURL:(NSURL *)url {
830 if ((self = [self init]) != nil) {
831 [self setURL:url];
832 } return self;
833 }
834
835 - (void) callFunction:(WebScriptObject *)function {
836 WebThreadLocked lock;
837
838 WebView *webview([[webview_ _documentView] webView]);
839 WebFrame *frame([webview mainFrame]);
840 WebPreferences *preferences([webview preferences]);
841
842 bool maybe([preferences javaScriptCanOpenWindowsAutomatically]);
843 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
844
845 /*id _private(MSHookIvar<id>(webview, "_private"));
846 WebCore::Page *page(_private == nil ? NULL : MSHookIvar<WebCore::Page *>(_private, "page"));
847 WebCore::Settings *settings(page == NULL ? NULL : page->settings());
848
849 bool no;
850 if (settings == NULL)
851 no = 0;
852 else {
853 no = settings->JavaScriptCanOpenWindowsAutomatically();
854 settings->setJavaScriptCanOpenWindowsAutomatically(true);
855 }*/
856
857 if (UIWindow *window = [[self view] window])
858 if (UIResponder *responder = [window firstResponder])
859 [responder resignFirstResponder];
860
861 JSObjectRef object([function JSObject]);
862 JSGlobalContextRef context([frame globalContext]);
863 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
864
865 /*if (settings != NULL)
866 settings->setJavaScriptCanOpenWindowsAutomatically(no);*/
867
868 [preferences setJavaScriptCanOpenWindowsAutomatically:maybe];
869 }
870
871 - (void) reloadButtonClicked {
872 [self reloadURLWithCache:YES];
873 }
874
875 - (void) _customButtonClicked {
876 [self reloadButtonClicked];
877 }
878
879 - (void) customButtonClicked {
880 #if !AlwaysReload
881 if (function_ != nil)
882 [self callFunction:function_];
883 else
884 #endif
885 [self _customButtonClicked];
886 }
887
888 + (float) defaultWidth {
889 return 980;
890 }
891
892 - (void) setNavigationBarStyle:(NSString *)name {
893 UIBarStyle style;
894 if ([name isEqualToString:@"Black"])
895 style = UIBarStyleBlack;
896 else
897 style = UIBarStyleDefault;
898
899 [[[self navigationController] navigationBar] setBarStyle:style];
900 }
901
902 - (void) setNavigationBarTintColor:(UIColor *)color {
903 [[[self navigationController] navigationBar] setTintColor:color];
904 }
905
906 - (void) setBadgeValue:(id)value {
907 [[[self navigationController] tabBarItem] setBadgeValue:value];
908 }
909
910 - (void) setHidesBackButton:(bool)value {
911 [[self navigationItem] setHidesBackButton:value];
912 [self applyLeftButton];
913 }
914
915 - (void) setHidesBackButtonByNumber:(NSNumber *)value {
916 [self setHidesBackButton:[value boolValue]];
917 }
918
919 - (void) dispatchEvent:(NSString *)event {
920 [webview_ dispatchEvent:event];
921 }
922
923 - (bool) hidesNavigationBar {
924 return hidesNavigationBar_;
925 }
926
927 - (void) _setHidesNavigationBar:(bool)value animated:(bool)animated {
928 if (visible_)
929 [[self navigationController] setNavigationBarHidden:(value && [self hidesNavigationBar]) animated:animated];
930 }
931
932 - (void) setHidesNavigationBar:(bool)value {
933 if (hidesNavigationBar_ != value) {
934 hidesNavigationBar_ = value;
935 [self _setHidesNavigationBar:YES animated:YES];
936 }
937 }
938
939 - (void) setHidesNavigationBarByNumber:(NSNumber *)value {
940 [self setHidesNavigationBar:[value boolValue]];
941 }
942
943 - (void) viewWillAppear:(BOOL)animated {
944 visible_ = true;
945
946 if ([self hidesNavigationBar])
947 [self _setHidesNavigationBar:YES animated:animated];
948
949 [self dispatchEvent:@"CydiaViewWillAppear"];
950 [super viewWillAppear:animated];
951 }
952
953 - (void) viewDidAppear:(BOOL)animated {
954 [super viewDidAppear:animated];
955 [self dispatchEvent:@"CydiaViewDidAppear"];
956 }
957
958 - (void) viewWillDisappear:(BOOL)animated {
959 [self dispatchEvent:@"CydiaViewWillDisappear"];
960 [super viewWillDisappear:animated];
961
962 if ([self hidesNavigationBar])
963 [self _setHidesNavigationBar:NO animated:animated];
964
965 visible_ = false;
966 }
967
968 - (void) viewDidDisappear:(BOOL)animated {
969 [super viewDidDisappear:animated];
970 [self dispatchEvent:@"CydiaViewDidDisappear"];
971 }
972
973 @end