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