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