]> git.saurik.com Git - cydia.git/blob - UICaboodle/BrowserView.mm
update mapping
[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) _updateViewSettings {
380 [super _updateViewSettings];
381
382 id<CYWebViewDelegate> delegate([self delegate]);
383 if ([delegate respondsToSelector:@selector(webViewUpdateViewSettings:)])
384 [delegate webViewUpdateViewSettings:self];
385 }
386
387 + (void) initialize {
388 if (Class $UIWebViewWebViewDelegate = objc_getClass("UIWebViewWebViewDelegate")) {
389 class_addMethod($UIWebViewWebViewDelegate, @selector(webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:), (IMP) &$UIWebViewWebViewDelegate$webView$decidePolicyForNewWindowAction$request$newFrameName$decisionListener$, "v28@0:4@8@12@16@20@24");
390 class_addMethod($UIWebViewWebViewDelegate, @selector(webView:didClearWindowObject:forFrame:), (IMP) &$UIWebViewWebViewDelegate$webView$didClearWindowObject$forFrame$, "v20@0:4@8@12@16");
391 class_addMethod($UIWebViewWebViewDelegate, @selector(webView:didReceiveTitle:forFrame:), (IMP) &$UIWebViewWebViewDelegate$webView$didReceiveTitle$forFrame$, "v20@0:4@8@12@16");
392 class_addMethod($UIWebViewWebViewDelegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:), (IMP) &$UIWebViewWebViewDelegate$webView$resource$willSendRequest$redirectResponse$fromDataSource$, "@28@0:4@8@12@16@20@24");
393 class_addMethod($UIWebViewWebViewDelegate, @selector(webViewClose:), (IMP) &$UIWebViewWebViewDelegate$webViewClose$, "v12@0:4@8");
394 }
395 }
396
397 @end
398
399 #define ShowInternals 0
400 #define LogBrowser 0
401
402 #define lprintf(args...) fprintf(stderr, args)
403
404 @implementation BrowserController
405
406 #if ShowInternals
407 #include "UICaboodle/UCInternal.h"
408 #endif
409
410 + (void) _initialize {
411 [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];
412
413 if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
414 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
415 else // XXX: this actually might be fast on some older systems: we should look into this
416 CYScrollViewDecelerationRateNormal = 0.998;
417 }
418
419 - (void) dealloc {
420 #if LogBrowser
421 NSLog(@"[BrowserController dealloc]");
422 #endif
423
424 [webview_ setDelegate:nil];
425
426 [indirect_ setDelegate:nil];
427 [indirect_ release];
428
429 if (challenge_ != nil)
430 [challenge_ release];
431
432 if (request_ != nil)
433 [request_ release];
434
435 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
436
437 if (custom_ != nil)
438 [custom_ release];
439 if (style_ != nil)
440 [style_ release];
441
442 if (function_ != nil)
443 [function_ release];
444 if (closer_ != nil)
445 [closer_ release];
446
447 if (title_ != nil)
448 [title_ release];
449
450 [loading_ release];
451
452 [reloaditem_ release];
453 [loadingitem_ release];
454
455 [indicator_ release];
456
457 [super dealloc];
458 }
459
460 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
461 [self loadRequest:[NSURLRequest
462 requestWithURL:url
463 cachePolicy:policy
464 timeoutInterval:120.0
465 ]];
466 }
467
468 - (void) loadURL:(NSURL *)url {
469 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
470 }
471
472 - (void) loadRequest:(NSURLRequest *)request {
473 #if LogBrowser
474 NSLog(@"loadRequest:%@", request);
475 #endif
476
477 error_ = false;
478
479 WebThreadLock();
480 [webview_ loadRequest:request];
481 WebThreadUnlock();
482 }
483
484 - (void) reloadURL {
485 if (request_ == nil)
486 return;
487
488 if ([request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
489 [self loadRequest:request_];
490 else {
491 UIAlertView *alert = [[[UIAlertView alloc]
492 initWithTitle:UCLocalize("RESUBMIT_FORM")
493 message:nil
494 delegate:self
495 cancelButtonTitle:UCLocalize("CANCEL")
496 otherButtonTitles:UCLocalize("SUBMIT"), nil
497 ] autorelease];
498
499 [alert setContext:@"submit"];
500 [alert show];
501 }
502 }
503
504 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
505 if (custom_ != nil)
506 [custom_ autorelease];
507 if (button == nil)
508 custom_ = nil;
509 else
510 custom_ = [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:button]]] retain];
511
512 if (style_ != nil)
513 [style_ autorelease];
514 if (style == nil)
515 style_ = nil;
516 else
517 style_ = [style retain];
518
519 if (function_ != nil)
520 [function_ autorelease];
521 if (function == nil)
522 function_ = nil;
523 else
524 function_ = [function retain];
525
526 [self applyRightButton];
527 }
528
529 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
530 if (custom_ != nil)
531 [custom_ autorelease];
532 if (button == nil)
533 custom_ = nil;
534 else
535 custom_ = [button retain];
536
537 if (style_ != nil)
538 [style_ autorelease];
539 if (style == nil)
540 style_ = nil;
541 else
542 style_ = [style retain];
543
544 if (function_ != nil)
545 [function_ autorelease];
546 if (function == nil)
547 function_ = nil;
548 else
549 function_ = [function retain];
550
551 [self applyRightButton];
552 }
553
554 - (void) setPopupHook:(id)function {
555 if (closer_ != nil)
556 [closer_ autorelease];
557 if (function == nil)
558 closer_ = nil;
559 else
560 closer_ = [function retain];
561 }
562
563 - (void) _setViewportWidth {
564 [[webview_ _documentView] setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
565 }
566
567 - (void) setViewportWidth:(float)width {
568 width_ = width != 0 ? width : [[self class] defaultWidth];
569 [self _setViewportWidth];
570 }
571
572 - (void) webViewUpdateViewSettings:(UIWebView *)view {
573 [self _setViewportWidth];
574 }
575
576 - (void) _openMailToURL:(NSURL *)url {
577 [[UIApplication sharedApplication] openURL:url];// asPanel:YES];
578 }
579
580 - (bool) _allowJavaScriptPanel {
581 return true;
582 }
583
584 - (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
585 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
586 [self _didFinishLoading];
587
588 if ([error code] == NSURLErrorCancelled)
589 return;
590
591 if ([frame parentFrame] == nil) {
592 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
593 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
594 [[error localizedDescription] stringByAddingPercentEscapes]
595 ]]];
596
597 error_ = true;
598 }
599 }
600
601 // CYWebViewDelegate {{{
602 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
603 #if LogBrowser
604 NSLog(@"decidePolicyForNavigationAction:%@ request:%@ frame:%@", action, request, frame);
605 #endif
606
607 if ([frame parentFrame] == nil) {
608 if (!error_) {
609 if (request_ != nil)
610 [request_ autorelease];
611 if (request == nil)
612 request_ = nil;
613 else
614 request_ = [request retain];
615 }
616 }
617 }
618
619 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
620 #if LogBrowser
621 NSLog(@"decidePolicyForNewWindowAction:%@ request:%@ newFrameName:%@", action, request, frame);
622 #endif
623
624 NSURL *url([request URL]);
625 if (url == nil)
626 return;
627
628 if ([frame isEqualToString:@"_open"])
629 [delegate_ openURL:url];
630
631 NSString *scheme([[url scheme] lowercaseString]);
632 if ([scheme isEqualToString:@"mailto"])
633 [self _openMailToURL:url];
634
635 CYViewController *page([delegate_ pageForURL:url hasTag:NULL]);
636
637 if (page == nil) {
638 BrowserController *browser([[[class_ alloc] init] autorelease]);
639 [browser loadRequest:request];
640 page = browser;
641 }
642
643 [page setDelegate:delegate_];
644
645 if (![frame isEqualToString:@"_popup"]) {
646 [[self navigationItem] setTitle:title_];
647
648 [[self navigationController] pushViewController:page animated:YES];
649 } else {
650 UCNavigationController *navigation([[[UCNavigationController alloc] init] autorelease]);
651
652 [navigation setHook:indirect_];
653 [navigation setDelegate:delegate_];
654
655 [navigation setViewControllers:[NSArray arrayWithObject:page]];
656
657 [[page navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
658 initWithTitle:UCLocalize("CLOSE")
659 style:UIBarButtonItemStylePlain
660 target:page
661 action:@selector(close)
662 ] autorelease]];
663
664 [[self navigationController] presentModalViewController:navigation animated:YES];
665 }
666
667 [listener ignore];
668 }
669
670 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
671 }
672
673 - (void) webView:(WebView *)view didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
674 #if LogBrowser
675 NSLog(@"didFailLoadWithError:%@ forFrame:%@", error, frame);
676 #endif
677
678 [self _didFailWithError:error forFrame:frame];
679 }
680
681 - (void) webView:(WebView *)view didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
682 #if LogBrowser
683 NSLog(@"didFailProvisionalLoadWithError:%@ forFrame:%@", error, frame);
684 #endif
685
686 [self _didFailWithError:error forFrame:frame];
687 }
688
689 - (void) webView:(WebView *)view didFinishLoadForFrame:(WebFrame *)frame {
690 [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
691
692 if ([frame parentFrame] == nil) {
693 if (DOMDocument *document = [frame DOMDocument])
694 if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
695 for (DOMHTMLBodyElement *body in (id) bodies) {
696 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
697
698 bool colored(false);
699
700 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
701 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
702 DOMRGBColor *rgb([color getRGBColorValue]);
703
704 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
705 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
706 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
707 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
708
709 UIColor *uic(nil);
710
711 if (red == 0xc7 && green == 0xce && blue == 0xd5)
712 uic = [UIColor groupTableViewBackgroundColor];
713 else if (alpha != 0)
714 uic = [UIColor
715 colorWithRed:(red / 255)
716 green:(green / 255)
717 blue:(blue / 255)
718 alpha:alpha
719 ];
720
721 if (uic != nil) {
722 colored = true;
723 [scroller_ setBackgroundColor:uic];
724 }
725 }
726 }
727
728 if (!colored)
729 [scroller_ setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
730 break;
731 }
732 }
733
734 [self _didFinishLoading];
735 }
736
737 - (void) webView:(WebView *)view didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
738 if ([frame parentFrame] != nil)
739 return;
740
741 if (title_ != nil)
742 [title_ autorelease];
743 title_ = [title retain];
744
745 [[self navigationItem] setTitle:title_];
746 }
747
748 - (void) webView:(WebView *)view didStartProvisionalLoadForFrame:(WebFrame *)frame {
749 [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];
750
751 if ([frame parentFrame] == nil) {
752 CYRelease(title_);
753 CYRelease(custom_);
754 CYRelease(style_);
755 CYRelease(function_);
756 CYRelease(closer_);
757
758 // XXX: do we still need to do this?
759 [[self navigationItem] setTitle:nil];
760 }
761
762 [self _didStartLoading];
763 }
764
765 - (NSURLRequest *) webView:(WebView *)view resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
766 #if LogBrowser
767 NSLog(@"resource:%@ willSendRequest:%@ redirectResponse:%@ fromDataSource:%@", identifier, request, response, source);
768 #endif
769
770 return request;
771 }
772
773 - (bool) webView:(WebView *)view shouldRunJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
774 return [self _allowJavaScriptPanel];
775 }
776
777 - (bool) webView:(WebView *)view shouldRunJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
778 return [self _allowJavaScriptPanel];
779 }
780
781 - (bool) webView:(WebView *)view shouldRunJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)text initiatedByFrame:(WebFrame *)frame {
782 return [self _allowJavaScriptPanel];
783 }
784
785 - (void) webViewClose:(WebView *)view {
786 [self close];
787 }
788 // }}}
789
790 - (void) close {
791 [[self navigationController] dismissModalViewControllerAnimated:YES];
792 }
793
794 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
795 NSString *context([alert context]);
796
797 if ([context isEqualToString:@"sensitive"]) {
798 switch (button) {
799 case 1:
800 sensitive_ = [NSNumber numberWithBool:YES];
801 break;
802
803 case 2:
804 sensitive_ = [NSNumber numberWithBool:NO];
805 break;
806 }
807
808 [alert dismissWithClickedButtonIndex:-1 animated:YES];
809 } else if ([context isEqualToString:@"challenge"]) {
810 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
811
812 switch (button) {
813 case 1: {
814 NSString *username([[alert textFieldAtIndex:0] text]);
815 NSString *password([[alert textFieldAtIndex:1] text]);
816
817 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
818
819 [sender useCredential:credential forAuthenticationChallenge:challenge_];
820 } break;
821
822 case 2:
823 [sender cancelAuthenticationChallenge:challenge_];
824 break;
825
826 _nodefault
827 }
828
829 [challenge_ release];
830 challenge_ = nil;
831
832 [alert dismissWithClickedButtonIndex:-1 animated:YES];
833 } else if ([context isEqualToString:@"submit"]) {
834 switch (button) {
835 case 1:
836 break;
837
838 case 2:
839 if (request_ != nil) {
840 WebThreadLock();
841 [webview_ loadRequest:request_];
842 WebThreadUnlock();
843 }
844 break;
845
846 _nodefault
847 }
848
849 [alert dismissWithClickedButtonIndex:-1 animated:YES];
850 }
851 }
852
853 - (UIBarButtonItemStyle) rightButtonStyle {
854 if (style_ == nil) normal:
855 return UIBarButtonItemStylePlain;
856 else if ([style_ isEqualToString:@"Normal"])
857 return UIBarButtonItemStylePlain;
858 else if ([style_ isEqualToString:@"Highlighted"])
859 return UIBarButtonItemStyleDone;
860 else goto normal;
861 }
862
863 - (UIBarButtonItem *) customButton {
864 return [[[UIBarButtonItem alloc]
865 initWithTitle:custom_
866 style:[self rightButtonStyle]
867 target:self
868 action:@selector(customButtonClicked)
869 ] autorelease];
870 }
871
872 - (UIBarButtonItem *) rightButton {
873 return reloaditem_;
874 }
875
876 - (void) applyLoadingTitle {
877 [[self navigationItem] setTitle:UCLocalize("LOADING")];
878 }
879
880 - (void) applyRightButton {
881 if ([self isLoading]) {
882 [[self navigationItem] setRightBarButtonItem:loadingitem_ animated:YES];
883 // XXX: why do we do this again here? (if we don't, just remove indicator_)
884 [[loadingitem_ view] addSubview:indicator_];
885 [self applyLoadingTitle];
886 } else if (custom_ != nil) {
887 [[self navigationItem] setRightBarButtonItem:[self customButton] animated:YES];
888 } else {
889 [[self navigationItem] setRightBarButtonItem:[self rightButton] animated:YES];
890 }
891 }
892
893 - (void) _didStartLoading {
894 [self applyRightButton];
895 }
896
897 - (void) _didFinishLoading {
898 if ([loading_ count] != 0)
899 return;
900
901 [self applyRightButton];
902
903 // XXX: wtf?
904 if (![self isLoading])
905 [[self navigationItem] setTitle:title_];
906 }
907
908 - (bool) isLoading {
909 return [loading_ count] != 0;
910 }
911
912 - (id) initWithWidth:(float)width ofClass:(Class)_class {
913 if ((self = [super init]) != nil) {
914 class_ = _class;
915 loading_ = [[NSMutableSet alloc] initWithCapacity:5];
916
917 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
918
919 webview_ = [[[CYWebView alloc] initWithFrame:[[self view] bounds]] autorelease];
920 [webview_ setDelegate:self];
921 [self setView:webview_];
922
923 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
924 [webview_ setDataDetectorTypes:UIDataDetectorTypeAutomatic];
925 else
926 [webview_ setDetectsPhoneNumbers:NO];
927
928 [webview_ setScalesPageToFit:YES];
929
930 UIWebDocumentView *document([webview_ _documentView]);
931
932 // XXX: I think this improves scrolling; the hardcoded-ness sucks
933 [document setTileSize:CGSizeMake(320, 500)];
934
935 [document setBackgroundColor:[UIColor clearColor]];
936 [document setDrawsBackground:NO];
937
938 WebView *webview([document webView]);
939 WebPreferences *preferences([webview preferences]);
940
941 // XXX: I have no clue if I actually /want/ this modification
942 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
943 [webview _setLayoutInterval:0];
944 else if ([preferences respondsToSelector:@selector(_setLayoutInterval:)])
945 [preferences _setLayoutInterval:0];
946
947 [preferences setCacheModel:WebCacheModelDocumentBrowser];
948 [preferences setOfflineWebApplicationCacheEnabled:YES];
949
950 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
951 scroller_ = [webview_ _scrollView];
952
953 [scroller_ setDirectionalLockEnabled:YES];
954 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
955 [scroller_ setDelaysContentTouches:NO];
956
957 [scroller_ setCanCancelContentTouches:YES];
958 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
959 UIScroller *scroller([webview_ _scroller]);
960 scroller_ = (UIScrollView *) scroller;
961
962 [scroller setDirectionalScrolling:YES];
963 // XXX: we might be better off /not/ setting this on older systems
964 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
965 [scroller setScrollHysteresis:0]; /* 8 */
966
967 [scroller setThumbDetectionEnabled:NO];
968
969 // use NO with UIApplicationUseLegacyEvents(YES)
970 [scroller setEventMode:YES];
971
972 // XXX: this is handled by setBounces, right?
973 //[scroller setAllowsRubberBanding:YES];
974 }
975
976 [scroller_ setFixedBackgroundPattern:YES];
977 [scroller_ setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
978 [scroller_ setClipsSubviews:YES];
979
980 [scroller_ setBounces:YES];
981 [scroller_ setScrollingEnabled:YES];
982 [scroller_ setShowBackgroundShadow:NO];
983
984 [self setViewportWidth:width];
985
986 reloaditem_ = [[UIBarButtonItem alloc]
987 initWithTitle:UCLocalize("RELOAD")
988 style:[self rightButtonStyle]
989 target:self
990 action:@selector(reloadButtonClicked)
991 ];
992
993 loadingitem_ = [[UIBarButtonItem alloc]
994 initWithTitle:@" "
995 style:UIBarButtonItemStylePlain
996 target:self
997 action:@selector(reloadButtonClicked)
998 ];
999
1000 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite];
1001 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(15, 5, indsize.width, indsize.height)];
1002 [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
1003 [indicator_ startAnimation];
1004 [[loadingitem_ view] addSubview:indicator_];
1005
1006 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
1007 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
1008 } return self;
1009 }
1010
1011 - (id) initWithWidth:(float)width {
1012 return [self initWithWidth:width ofClass:[self class]];
1013 }
1014
1015 - (id) init {
1016 return [self initWithWidth:0];
1017 }
1018
1019 - (void) didDismissModalViewController {
1020 if (closer_ != nil)
1021 [self callFunction:closer_];
1022 }
1023
1024 - (void) callFunction:(WebScriptObject *)function {
1025 WebThreadLock();
1026
1027 WebView *webview([[webview_ _documentView] webView]);
1028 WebFrame *frame([webview mainFrame]);
1029 WebPreferences *preferences([webview preferences]);
1030
1031 bool maybe([preferences javaScriptCanOpenWindowsAutomatically]);
1032 [preferences setJavaScriptCanOpenWindowsAutomatically:NO];
1033
1034 /*id _private(MSHookIvar<id>(webview, "_private"));
1035 WebCore::Page *page(_private == nil ? NULL : MSHookIvar<WebCore::Page *>(_private, "page"));
1036 WebCore::Settings *settings(page == NULL ? NULL : page->settings());
1037
1038 bool no;
1039 if (settings == NULL)
1040 no = 0;
1041 else {
1042 no = settings->JavaScriptCanOpenWindowsAutomatically();
1043 settings->setJavaScriptCanOpenWindowsAutomatically(true);
1044 }*/
1045
1046 if (UIWindow *window = [[self view] window])
1047 if (UIResponder *responder = [window firstResponder])
1048 [responder resignFirstResponder];
1049
1050 JSObjectRef object([function JSObject]);
1051 JSGlobalContextRef context([frame globalContext]);
1052 JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);
1053
1054 /*if (settings != NULL)
1055 settings->setJavaScriptCanOpenWindowsAutomatically(no);*/
1056
1057 [preferences setJavaScriptCanOpenWindowsAutomatically:maybe];
1058
1059 WebThreadUnlock();
1060 }
1061
1062 - (void) reloadButtonClicked {
1063 [self reloadURL];
1064 }
1065
1066 - (void) _customButtonClicked {
1067 [self reloadButtonClicked];
1068 }
1069
1070 - (void) customButtonClicked {
1071 #if !AlwaysReload
1072 if (function_ != nil)
1073 [self callFunction:function_];
1074 else
1075 #endif
1076 [self _customButtonClicked];
1077 }
1078
1079 + (float) defaultWidth {
1080 return 980;
1081 }
1082
1083 @end