]> git.saurik.com Git - cydia.git/blame - UICaboodle/BrowserView.m
Reconfigure for chatty internal release.
[cydia.git] / UICaboodle / BrowserView.m
CommitLineData
22f8bed9
JF
1#include <BrowserView.h>
2
aa5d0de7
JF
3/* Indirect Delegate {{{ */
4@interface IndirectDelegate : NSProxy {
5 _transient volatile id delegate_;
6}
7
8- (void) setDelegate:(id)delegate;
9- (id) initWithDelegate:(id)delegate;
10@end
11
12@implementation IndirectDelegate
13
14- (void) setDelegate:(id)delegate {
15 delegate_ = delegate;
16}
17
18- (id) initWithDelegate:(id)delegate {
19 delegate_ = delegate;
20 return self;
21}
22
23- (BOOL) respondsToSelector:(SEL)sel {
24 return delegate_ == nil ? FALSE : [delegate_ respondsToSelector:sel];
25}
26
27- (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
28 if (delegate_ != nil)
29 if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
30 return sig;
31 // XXX: I fucking hate Apple so very very bad
32 return [NSMethodSignature signatureWithObjCTypes:"v@:"];
33}
34
35- (void) forwardInvocation:(NSInvocation *)inv {
36 SEL sel = [inv selector];
37 if (delegate_ != nil && [delegate_ respondsToSelector:sel])
38 [inv invokeWithTarget:delegate_];
39}
40
41@end
42/* }}} */
43
22f8bed9
JF
44@interface WebView (Cydia)
45- (void) setScriptDebugDelegate:(id)delegate;
46- (void) _setFormDelegate:(id)delegate;
47- (void) _setUIKitDelegate:(id)delegate;
48- (void) setWebMailDelegate:(id)delegate;
49- (void) _setLayoutInterval:(float)interval;
50@end
51
374f3d18
JF
52/* Web Scripting {{{ */
53@interface CydiaObject : NSObject {
54 id indirect_;
55}
56
57- (id) initWithDelegate:(IndirectDelegate *)indirect;
58@end
59
60@implementation CydiaObject
61
62- (void) dealloc {
63 [indirect_ release];
64 [super dealloc];
65}
66
67- (id) initWithDelegate:(IndirectDelegate *)indirect {
68 if ((self = [super init]) != nil) {
69 indirect_ = [indirect retain];
70 } return self;
71}
72
73+ (NSString *) webScriptNameForSelector:(SEL)selector {
74 if (selector == @selector(getPackageById:))
75 return @"getPackageById";
3e9c9e85
JF
76 else if (selector == @selector(setAutoPopup:))
77 return @"setAutoPopup";
374f3d18
JF
78 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
79 return @"setButtonImage";
80 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
81 return @"setButtonTitle";
eb35c522
JF
82 else if (selector == @selector(setViewportWidth:))
83 return @"setViewportWidth";
374f3d18
JF
84 else if (selector == @selector(supports:))
85 return @"supports";
86 else if (selector == @selector(du:))
87 return @"du";
88 else if (selector == @selector(statfs:))
89 return @"statfs";
90 else
91 return nil;
92}
93
94+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
95 return [self webScriptNameForSelector:selector] == nil;
96}
97
98- (BOOL) supports:(NSString *)feature {
99 return [feature isEqualToString:@"window.open"];
100}
101
102- (Package *) getPackageById:(NSString *)id {
103 return [[Database sharedInstance] packageWithName:id];
104}
105
106- (NSArray *) statfs:(NSString *)path {
107 struct statfs stat;
108
109 if (path == nil || statfs([path UTF8String], &stat) == -1)
110 return nil;
111
112 return [NSArray arrayWithObjects:
113 [NSNumber numberWithUnsignedLong:stat.f_bsize],
114 [NSNumber numberWithUnsignedLong:stat.f_blocks],
115 [NSNumber numberWithUnsignedLong:stat.f_bfree],
116 nil];
117}
118
119- (NSNumber *) du:(NSString *)path {
120 NSNumber *value(nil);
121
122 int fds[2];
123 _assert(pipe(fds) != -1);
124
125 pid_t pid(ExecFork());
126 if (pid == 0) {
127 _assert(dup2(fds[1], 1) != -1);
128 _assert(close(fds[0]) != -1);
129 _assert(close(fds[1]) != -1);
130 execlp("du", "du", "-s", [path UTF8String], NULL);
131 exit(1);
132 _assert(false);
133 }
134
135 _assert(close(fds[1]) != -1);
136
137 if (FILE *du = fdopen(fds[0], "r")) {
138 char line[1024];
139 while (fgets(line, sizeof(line), du) != NULL) {
140 size_t length(strlen(line));
141 while (length != 0 && line[length - 1] == '\n')
142 line[--length] = '\0';
143 if (char *tab = strchr(line, '\t')) {
144 *tab = '\0';
145 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
146 }
147 }
148
149 fclose(du);
150 } else _assert(close(fds[0]));
151
152 int status;
153 wait:
154 if (waitpid(pid, &status, 0) == -1)
155 if (errno == EINTR)
156 goto wait;
157 else _assert(false);
158
159 return value;
160}
161
3e9c9e85
JF
162- (void) setAutoPopup:(BOOL)popup {
163 [indirect_ setAutoPopup:popup];
164}
165
374f3d18
JF
166- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
167 [indirect_ setButtonImage:button withStyle:style toFunction:function];
168}
169
170- (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
171 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
172}
173
eb35c522
JF
174- (void) setViewportWidth:(float)width {
175 [indirect_ setViewportWidth:width];
176}
177
374f3d18
JF
178@end
179/* }}} */
180
22f8bed9
JF
181@implementation BrowserView
182
1b1b3f4a 183#if ShowInternals
22f8bed9
JF
184#include "Internals.h"
185#endif
186
187- (void) dealloc {
3e9c9e85
JF
188#if ForSaurik
189 NSLog(@"[BrowserView dealloc]");
190#endif
1b1b3f4a 191
22f8bed9
JF
192 if (challenge_ != nil)
193 [challenge_ release];
194
195 WebView *webview = [webview_ webView];
196 [webview setFrameLoadDelegate:nil];
197 [webview setResourceLoadDelegate:nil];
198 [webview setUIDelegate:nil];
199 [webview setScriptDebugDelegate:nil];
200 [webview setPolicyDelegate:nil];
201
202 [webview setDownloadDelegate:nil];
203
204 [webview _setFormDelegate:nil];
205 [webview _setUIKitDelegate:nil];
206 [webview setWebMailDelegate:nil];
207 [webview setEditingDelegate:nil];
208
209 [webview_ setDelegate:nil];
210 [webview_ setGestureDelegate:nil];
eb35c522
JF
211 [webview_ setFormEditingDelegate:nil];
212 [webview_ setInteractionDelegate:nil];
22f8bed9
JF
213
214 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
215
216 [webview close];
217
218#if RecycleWebViews
219 [webview_ removeFromSuperview];
220 [Documents_ addObject:[webview_ autorelease]];
221#else
222 [webview_ release];
223#endif
224
225 [indirect_ setDelegate:nil];
226 [indirect_ release];
227
374f3d18
JF
228 [cydia_ release];
229
22f8bed9
JF
230 [scroller_ setDelegate:nil];
231
232 if (button_ != nil)
233 [button_ release];
234 if (style_ != nil)
235 [style_ release];
236 if (function_ != nil)
237 [function_ release];
238
239 [scroller_ release];
240 [indicator_ release];
241 if (confirm_ != nil)
242 [confirm_ release];
243 if (title_ != nil)
244 [title_ release];
245 [super dealloc];
246}
247
248- (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
249 [self loadRequest:[NSURLRequest
250 requestWithURL:url
251 cachePolicy:policy
252 timeoutInterval:30.0
253 ]];
254}
255
256- (void) loadURL:(NSURL *)url {
257 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
258}
259
260- (NSMutableURLRequest *) _addHeadersToRequest:(NSURLRequest *)request {
261 NSMutableURLRequest *copy = [request mutableCopy];
262
263 if (Machine_ != NULL)
264 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
265 if (UniqueID_ != nil)
266 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
267
268 if (Role_ != nil)
269 [copy setValue:Role_ forHTTPHeaderField:@"X-Role"];
270
271 return copy;
272}
273
274- (void) loadRequest:(NSURLRequest *)request {
275 pushed_ = true;
fe468f45 276 error_ = false;
22f8bed9
JF
277 [webview_ loadRequest:request];
278}
279
280- (void) reloadURL {
22f8bed9
JF
281 if (request_ == nil)
282 return;
283
284 if ([request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
fe468f45 285 [self loadRequest:request_];
22f8bed9
JF
286 else {
287 UIActionSheet *sheet = [[[UIActionSheet alloc]
288 initWithTitle:@"Are you sure you want to submit this form again?"
289 buttons:[NSArray arrayWithObjects:@"Cancel", @"Submit", nil]
290 defaultButtonIndex:0
291 delegate:self
292 context:@"submit"
293 ] autorelease];
294
295 [sheet setNumberOfRows:1];
296 [sheet popupAlertAnimated:YES];
297 }
298}
299
300- (WebView *) webView {
301 return [webview_ webView];
302}
303
1b1b3f4a
JF
304- (UIWebDocumentView *) documentView {
305 return webview_;
306}
307
eb35c522
JF
308- (void) _fixScroller {
309 float extra;
310 if (!editing_)
311 extra = 0;
312 else {
313 UIFormAssistant *assistant([UIFormAssistant sharedFormAssistant]);
314 CGRect peripheral([assistant peripheralFrame]);
315 NSLog(@"per:%f", peripheral.size.height);
316 extra = peripheral.size.height;
317 }
318
319 CGRect subrect([scroller_ frame]);
320 subrect.size.height -= extra;
321 [scroller_ setScrollerIndicatorSubrect:subrect];
322
323 CGSize size(size_);
324 size.height += extra;
325 [scroller_ setContentSize:size];
326}
327
22f8bed9 328- (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
eb35c522
JF
329 size_ = frame.size;
330 [self _fixScroller];
22f8bed9
JF
331}
332
333- (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
334 [self view:sender didSetFrame:frame];
335}
336
337- (void) pushPage:(RVPage *)page {
22f8bed9 338 [page setDelegate:delegate_];
988f99ac 339 [self setBackButtonTitle:title_];
1b1b3f4a 340 [book_ pushPage:page];
22f8bed9
JF
341}
342
bf26e5f3
JF
343- (void) _pushPage {
344 if (pushed_)
345 return;
346 [self autorelease];
347 pushed_ = true;
348 [book_ pushPage:self];
349}
350
22f8bed9 351- (BOOL) getSpecial:(NSURL *)url {
bf26e5f3
JF
352#if ForSaurik
353 NSLog(@"getSpecial:%@", url);
354#endif
355
22f8bed9
JF
356 NSString *href([url absoluteString]);
357 NSString *scheme([[url scheme] lowercaseString]);
358
359 RVPage *page = nil;
360
361 if ([href hasPrefix:@"apptapp://package/"])
362 page = [delegate_ pageForPackage:[href substringFromIndex:18]];
363 else if ([scheme isEqualToString:@"cydia"]) {
364 page = [delegate_ pageForURL:url hasTag:NULL];
365 if (page == nil)
366 return false;
367 } else if (![scheme isEqualToString:@"apptapp"])
368 return false;
369
370 if (page != nil)
371 [self pushPage:page];
372 return true;
373}
374
1b1b3f4a 375- (void) webViewShow:(WebView *)sender {
e8389e3e 376 /* XXX: this is where I cry myself to sleep */
1b1b3f4a
JF
377}
378
3e9c9e85
JF
379- (bool) _allowJavaScriptPanel {
380 return true;
381}
382
22f8bed9 383- (void) webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
8f8f02e9 384 if (![self _allowJavaScriptPanel])
3e9c9e85
JF
385 return;
386
bd0a4099
JF
387 [self retain];
388
22f8bed9
JF
389 UIActionSheet *sheet = [[[UIActionSheet alloc]
390 initWithTitle:nil
391 buttons:[NSArray arrayWithObjects:@"OK", nil]
392 defaultButtonIndex:0
393 delegate:self
394 context:@"alert"
395 ] autorelease];
396
397 [sheet setBodyText:message];
398 [sheet popupAlertAnimated:YES];
399}
400
401- (BOOL) webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
3e9c9e85
JF
402 if (![self _allowJavaScriptPanel])
403 return NO;
404
22f8bed9
JF
405 UIActionSheet *sheet = [[[UIActionSheet alloc]
406 initWithTitle:nil
407 buttons:[NSArray arrayWithObjects:@"OK", @"Cancel", nil]
408 defaultButtonIndex:0
bd0a4099 409 delegate:indirect_
22f8bed9
JF
410 context:@"confirm"
411 ] autorelease];
412
413 [sheet setNumberOfRows:1];
414 [sheet setBodyText:message];
415 [sheet popupAlertAnimated:YES];
416
417 NSRunLoop *loop([NSRunLoop currentRunLoop]);
418 NSDate *future([NSDate distantFuture]);
419
420 while (confirm_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
421
422 NSNumber *confirm([confirm_ autorelease]);
423 confirm_ = nil;
424 return [confirm boolValue];
425}
426
3e9c9e85
JF
427- (void) setAutoPopup:(BOOL)popup {
428 popup_ = popup;
429}
430
22f8bed9
JF
431- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
432 if (button_ != nil)
433 [button_ autorelease];
434 button_ = button == nil ? nil : [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:button]]] retain];
435
436 if (style_ != nil)
437 [style_ autorelease];
438 style_ = style == nil ? nil : [style retain];
439
440 if (function_ != nil)
441 [function_ autorelease];
442 function_ = function == nil ? nil : [function retain];
443}
444
445- (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
446 if (button_ != nil)
447 [button_ autorelease];
448 button_ = button == nil ? nil : [button retain];
449
450 if (style_ != nil)
451 [style_ autorelease];
452 style_ = style == nil ? nil : [style retain];
453
454 if (function_ != nil)
455 [function_ autorelease];
456 function_ = function == nil ? nil : [function retain];
457}
22f8bed9 458
eb35c522
JF
459- (void) webView:(WebView *)sender willBeginEditingFormElement:(id)element {
460 editing_ = true;
461}
462
463- (void) webView:(WebView *)sender didBeginEditingFormElement:(id)element {
464 [self _fixScroller];
465}
466
467- (void) webViewDidEndEditingFormElements:(WebView *)sender {
468 editing_ = false;
469 [self _fixScroller];
470}
471
aa5d0de7
JF
472- (void) webViewClose:(WebView *)sender {
473 [book_ close];
474}
475
22f8bed9 476- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
374f3d18 477 [window setValue:cydia_ forKey:@"cydia"];
22f8bed9
JF
478}
479
480- (void) webView:(WebView *)sender unableToImplementPolicyWithError:(NSError *)error frame:(WebFrame *)frame {
481 NSLog(@"err:%@", error);
482}
483
484- (void) webView:(WebView *)sender decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
3e9c9e85 485#if ForSaurik
1b1b3f4a 486 NSLog(@"nwa:%@", name);
3e9c9e85 487#endif
1b1b3f4a 488
22f8bed9 489 if (NSURL *url = [request URL]) {
aa5d0de7 490 if (name == nil) unknown: {
aa5d0de7
JF
491 if (![self getSpecial:url]) {
492 NSString *scheme([[url scheme] lowercaseString]);
493 if ([scheme isEqualToString:@"mailto"])
494 [delegate_ openMailToURL:url];
495 else goto use;
496 }
497 } else if ([name isEqualToString:@"_open"])
22f8bed9 498 [delegate_ openURL:url];
aa5d0de7
JF
499 else if ([name isEqualToString:@"_popup"]) {
500 RVBook *book([[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
aa5d0de7
JF
501
502 RVPage *page([delegate_ pageForURL:url hasTag:NULL]);
503 if (page == nil) {
3e9c9e85 504 /* XXX: call createWebViewWithRequest instead? */
1b1b3f4a
JF
505
506 [self setBackButtonTitle:title_];
507
aa5d0de7
JF
508 BrowserView *browser([[[BrowserView alloc] initWithBook:book] autorelease]);
509 [browser loadURL:url];
510 page = browser;
511 }
22f8bed9 512
00e2109e
JF
513 [book setDelegate:delegate_];
514 [page setDelegate:delegate_];
515
aa5d0de7
JF
516 [book setPage:page];
517 [book_ pushBook:book];
518 } else goto unknown;
22f8bed9
JF
519
520 [listener ignore];
521 } else use:
522 [listener use];
523}
524
525- (void) webView:(WebView *)webView decidePolicyForMIMEType:(NSString *)type request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
526 if ([WebView canShowMIMEType:type])
527 [listener use];
528 else {
529 // XXX: handle more mime types!
530 [listener ignore];
531 if (frame == [webView mainFrame])
532 [UIApp openURL:[request URL]];
533 }
534}
535
536- (void) webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
537 if (request == nil) ignore: {
538 [listener ignore];
539 return;
540 }
541
542 NSURL *url([request URL]);
543
544 if (url == nil) use: {
fe468f45 545 if (!error_ && [frame parentFrame] == nil) {
22f8bed9
JF
546 if (request_ != nil)
547 [request_ autorelease];
548 request_ = [request retain];
aa5d0de7 549#if ForSaurik
22f8bed9 550 NSLog(@"dpn:%@", request_);
aa5d0de7 551#endif
22f8bed9
JF
552 }
553
554 [listener use];
bf26e5f3
JF
555 /* XXX: maybe only the main frame? */
556 [self _pushPage];
22f8bed9
JF
557 return;
558 }
559#if ForSaurik
560 else NSLog(@"nav:%@:%@", url, [action description]);
561#endif
562
563 const NSArray *capability(reinterpret_cast<const NSArray *>(GSSystemGetCapability(kGSDisplayIdentifiersCapability)));
564
565 if (
566 [capability containsObject:@"com.apple.Maps"] && [url mapsURL] ||
567 [capability containsObject:@"com.apple.youtube"] && [url youTubeURL]
568 ) {
569 open:
570 [UIApp openURL:url];
571 goto ignore;
572 }
573
574 int store(_not(int));
575 if (NSURL *itms = [url itmsURL:&store]) {
3e9c9e85 576#if ForSaurik
22f8bed9 577 NSLog(@"itms#%@#%u#%@", url, store, itms);
3e9c9e85
JF
578#endif
579
22f8bed9
JF
580 if (
581 store == 1 && [capability containsObject:@"com.apple.MobileStore"] ||
582 store == 2 && [capability containsObject:@"com.apple.AppStore"]
583 ) {
584 url = itms;
585 goto open;
586 }
587 }
588
589 NSString *scheme([[url scheme] lowercaseString]);
590
591 if ([scheme isEqualToString:@"tel"]) {
592 // XXX: intelligence
593 goto open;
594 }
595
596 if ([scheme isEqualToString:@"mailto"]) {
597 [delegate_ openMailToURL:url];
598 goto ignore;
599 }
600
601 if ([self getSpecial:url])
602 goto ignore;
603 else if ([WebView _canHandleRequest:request])
604 goto use;
605 else if ([url isSpringboardHandledURL])
606 goto open;
607 else
608 goto use;
609}
610
611- (void) webView:(WebView *)sender setStatusText:(NSString *)text {
612 //lprintf("Status:%s\n", [text UTF8String]);
613}
614
22f8bed9
JF
615- (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
616 NSString *context([sheet context]);
617
bd0a4099
JF
618 if ([context isEqualToString:@"alert"]) {
619 [self autorelease];
22f8bed9 620 [sheet dismiss];
bd0a4099 621 } else if ([context isEqualToString:@"confirm"]) {
22f8bed9
JF
622 switch (button) {
623 case 1:
624 confirm_ = [NSNumber numberWithBool:YES];
625 break;
626
627 case 2:
628 confirm_ = [NSNumber numberWithBool:NO];
629 break;
630 }
631
632 [sheet dismiss];
633 } else if ([context isEqualToString:@"challenge"]) {
634 id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);
635
636 switch (button) {
637 case 1: {
638 NSString *username([[sheet textFieldAtIndex:0] text]);
639 NSString *password([[sheet textFieldAtIndex:1] text]);
640
641 NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);
642
643 [sender useCredential:credential forAuthenticationChallenge:challenge_];
644 } break;
645
646 case 2:
647 [sender cancelAuthenticationChallenge:challenge_];
648 break;
649
650 default:
651 _assert(false);
652 }
653
654 [challenge_ release];
655 challenge_ = nil;
656
657 [sheet dismiss];
658 } else if ([context isEqualToString:@"submit"]) {
659 switch (button) {
660 case 1:
661 break;
662
663 case 2:
664 if (request_ != nil)
665 [webview_ loadRequest:request_];
666 break;
667
668 default:
669 _assert(false);
670 }
671
672 [sheet dismiss];
673 }
674}
675
676- (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
677 challenge_ = [challenge retain];
678
679 NSURLProtectionSpace *space([challenge protectionSpace]);
680 NSString *realm([space realm]);
681 if (realm == nil)
682 realm = @"";
683
684 UIActionSheet *sheet = [[[UIActionSheet alloc]
685 initWithTitle:realm
686 buttons:[NSArray arrayWithObjects:@"Login", @"Cancel", nil]
687 defaultButtonIndex:0
688 delegate:self
689 context:@"challenge"
690 ] autorelease];
691
692 [sheet setNumberOfRows:1];
693
694 [sheet addTextFieldWithValue:@"" label:@"username"];
695 [sheet addTextFieldWithValue:@"" label:@"password"];
696
697 UITextField *username([sheet textFieldAtIndex:0]); {
698 UITextInputTraits *traits([username textInputTraits]);
699 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
700 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
701 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
702 [traits setReturnKeyType:UIReturnKeyNext];
703 }
704
705 UITextField *password([sheet textFieldAtIndex:1]); {
706 UITextInputTraits *traits([password textInputTraits]);
707 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
708 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
709 [traits setKeyboardType:UIKeyboardTypeASCIICapable];
710 // XXX: UIReturnKeyDone
711 [traits setReturnKeyType:UIReturnKeyNext];
712 [traits setSecureTextEntry:YES];
713 }
714
715 [sheet popupAlertAnimated:YES];
716}
717
718- (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
22f8bed9
JF
719 return [self _addHeadersToRequest:request];
720}
721
1b1b3f4a 722- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request windowFeatures:(NSDictionary *)features {
3e9c9e85 723//- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request userGesture:(BOOL)gesture {
1b1b3f4a 724#if ForSaurik
3e9c9e85
JF
725 NSLog(@"cwv:%@ (%@): %@", request, title_, features == nil ? @"{}" : [features description]);
726 //NSLog(@"cwv:%@ (%@): %@", request, title_, gesture ? @"Yes" : @"No");
1b1b3f4a 727#endif
22f8bed9 728
3e9c9e85
JF
729 NSNumber *value([features objectForKey:@"width"]);
730 float width(value == nil ? [BrowserView defaultWidth] : [value floatValue]);
731
732 RVBook *book(!popup_ ? book_ : [[[RVPopUpBook alloc] initWithFrame:[delegate_ popUpBounds]] autorelease]);
733
734 /* XXX: deal with cydia:// pages */
735 BrowserView *browser([[[BrowserView alloc] initWithBook:book forWidth:width] autorelease]);
736
bd0a4099 737 if (features != nil && popup_) {
3e9c9e85
JF
738 [book setDelegate:delegate_];
739 [browser setDelegate:delegate_];
740
741 [browser loadRequest:request];
bf26e5f3 742
3e9c9e85
JF
743 [book setPage:browser];
744 [book_ pushBook:book];
745 } else if (request == nil) {
bf26e5f3
JF
746 [self setBackButtonTitle:title_];
747 [browser setDelegate:delegate_];
748 [browser retain];
749 } else {
750 [self pushPage:browser];
751 [browser loadRequest:request];
752 }
753
22f8bed9
JF
754 return [browser webView];
755}
756
757- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
1b1b3f4a 758 return [self webView:sender createWebViewWithRequest:request windowFeatures:nil];
3e9c9e85 759 //return [self webView:sender createWebViewWithRequest:request userGesture:YES];
22f8bed9
JF
760}
761
762- (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
763 if ([frame parentFrame] != nil)
764 return;
765
766 title_ = [title retain];
767 [book_ reloadTitleForPage:self];
768}
769
770- (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
771 if ([frame parentFrame] != nil)
772 return;
773
774 reloading_ = false;
775 loading_ = true;
776 [self reloadButtons];
777
778 if (title_ != nil) {
779 [title_ release];
780 title_ = nil;
781 }
782
783 if (button_ != nil) {
784 [button_ release];
785 button_ = nil;
786 }
787
788 if (style_ != nil) {
789 [style_ release];
790 style_ = nil;
791 }
792
793 if (function_ != nil) {
794 [function_ release];
795 function_ = nil;
796 }
797
798 [book_ reloadTitleForPage:self];
799
800 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
801
802 CGRect webrect = [scroller_ bounds];
803 webrect.size.height = 0;
804 [webview_ setFrame:webrect];
805}
806
807- (void) _finishLoading {
808 if (!reloading_) {
809 loading_ = false;
810 [self reloadButtons];
811 }
812}
813
814- (bool) _loading {
815 return loading_;
816}
817
818- (void) reloadButtons {
819 if ([self _loading])
820 [indicator_ startAnimation];
821 else
822 [indicator_ stopAnimation];
823 [super reloadButtons];
824}
825
826- (BOOL) webView:(WebView *)sender shouldScrollToPoint:(struct CGPoint)point forFrame:(WebFrame *)frame {
827 return [webview_ webView:sender shouldScrollToPoint:point forFrame:frame];
828}
829
830- (void) webView:(WebView *)sender didReceiveViewportArguments:(id)arguments forFrame:(WebFrame *)frame {
831 return [webview_ webView:sender didReceiveViewportArguments:arguments forFrame:frame];
832}
833
834- (void) webView:(WebView *)sender needsScrollNotifications:(id)notifications forFrame:(WebFrame *)frame {
835 return [webview_ webView:sender needsScrollNotifications:notifications forFrame:frame];
836}
837
838- (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
839 return [webview_ webView:sender didCommitLoadForFrame:frame];
840}
841
842- (void) webView:(WebView *)sender didReceiveDocTypeForFrame:(WebFrame *)frame {
843 return [webview_ webView:sender didReceiveDocTypeForFrame:frame];
844}
845
846- (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
847 if ([frame parentFrame] == nil) {
848 [self _finishLoading];
849
850 if (DOMDocument *document = [frame DOMDocument])
851 if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
852 for (DOMHTMLBodyElement *body in bodies) {
853 DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);
854
855 bool colored(false);
856
857 if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
fe468f45
JF
858 if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
859 DOMRGBColor *rgb([color getRGBColorValue]);
860
861 float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
862 float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
863 float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
864 float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);
865
866 UIColor *uic(nil);
867
868 if (red == 0xc7 && green == 0xce && blue == 0xd5)
869 uic = [UIColor pinStripeColor];
870 else if (alpha != 0)
871 uic = [UIColor
872 colorWithRed:(red / 255)
873 green:(green / 255)
874 blue:(blue / 255)
875 alpha:alpha
876 ];
877
878 if (uic != nil) {
879 colored = true;
880 [scroller_ setBackgroundColor:uic];
881 }
22f8bed9
JF
882 }
883 }
884
885 if (!colored)
886 [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
887 break;
888 }
889 }
890
891 return [webview_ webView:sender didFinishLoadForFrame:frame];
892}
893
894- (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
895 if ([frame parentFrame] != nil)
896 return;
988f99ac
JF
897 if (reloading_)
898 return;
22f8bed9
JF
899 [self _finishLoading];
900
901 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
902 [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
903 [[error localizedDescription] stringByAddingPercentEscapes]
904 ]]];
fe468f45
JF
905
906 error_ = true;
22f8bed9
JF
907}
908
909- (void) webView:(WebView *)sender addMessageToConsole:(NSDictionary *)dictionary {
910#if ForSaurik
911 lprintf("Console:%s\n", [[dictionary description] UTF8String]);
912#endif
913}
914
eb35c522
JF
915- (void) setViewportWidth:(float)width {
916 width_ = width;
917 [webview_ setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
918}
919
3e9c9e85 920- (id) initWithBook:(RVBook *)book forWidth:(float)width {
22f8bed9
JF
921 if ((self = [super initWithBook:book]) != nil) {
922 loading_ = false;
3e9c9e85 923 popup_ = false;
22f8bed9
JF
924
925 struct CGRect bounds = [self bounds];
926
927 scroller_ = [[UIScroller alloc] initWithFrame:bounds];
928 [self addSubview:scroller_];
929
930 [scroller_ setShowBackgroundShadow:NO];
931 [scroller_ setFixedBackgroundPattern:YES];
932 [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
933
934 [scroller_ setScrollingEnabled:YES];
935 [scroller_ setAdjustForContentSizeChange:YES];
936 [scroller_ setClipsSubviews:YES];
937 [scroller_ setAllowsRubberBanding:YES];
938 [scroller_ setScrollDecelerationFactor:0.99];
939 [scroller_ setDelegate:self];
940
941 CGRect webrect = [scroller_ bounds];
942 webrect.size.height = 0;
943
944 WebView *webview;
945
946#if RecycleWebViews
947 webview_ = [Documents_ lastObject];
948 if (webview_ != nil) {
949 webview_ = [webview_ retain];
950 webview = [webview_ webView];
951 [Documents_ removeLastObject];
952 [webview_ setFrame:webrect];
953 } else {
954#else
955 if (true) {
956#endif
957 webview_ = [[UIWebDocumentView alloc] initWithFrame:webrect];
958 webview = [webview_ webView];
959
960 // XXX: this is terribly (too?) expensive
961 //[webview_ setDrawsBackground:NO];
962 [webview setPreferencesIdentifier:@"Cydia"];
963
964 [webview_ setTileSize:CGSizeMake(webrect.size.width, 500)];
965
966 [webview_ setAllowsMessaging:YES];
967
968 [webview_ setTilingEnabled:YES];
969 [webview_ setDrawsGrid:NO];
970 [webview_ setLogsTilingChanges:NO];
971 [webview_ setTileMinificationFilter:kCAFilterNearest];
972 [webview_ setDetectsPhoneNumbers:NO];
973 [webview_ setAutoresizes:YES];
974
975 [webview_ setMinimumScale:0.25f forDocumentTypes:0x10];
3e9c9e85 976 [webview_ setMaximumScale:5.00f forDocumentTypes:0x10];
22f8bed9 977 [webview_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x10];
3e9c9e85 978 //[webview_ setViewportSize:CGSizeMake(980, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
22f8bed9
JF
979
980 [webview_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x2];
981
3e9c9e85 982 [webview_ setMinimumScale:1.00f forDocumentTypes:0x8];
22f8bed9
JF
983 [webview_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x8];
984 [webview_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x8];
985
986 [webview_ _setDocumentType:0x4];
987
988 [webview_ setZoomsFocusedFormControl:YES];
989 [webview_ setContentsPosition:7];
990 [webview_ setEnabledGestures:0xa];
991 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeIsZoomRubberBandEnabled];
992 [webview_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeUpdatesScroller];
993
994 [webview_ setSmoothsFonts:YES];
3e9c9e85 995 [webview_ setAllowsImageSheet:YES];
22f8bed9 996 [webview _setUsesLoaderCache:YES];
3e9c9e85
JF
997
998 [webview setGroupName:@"CydiaGroup"];
22f8bed9
JF
999 [webview _setLayoutInterval:0];
1000 }
1001
eb35c522 1002 [self setViewportWidth:width];
3e9c9e85 1003
22f8bed9
JF
1004 [webview_ setDelegate:self];
1005 [webview_ setGestureDelegate:self];
eb35c522
JF
1006 [webview_ setFormEditingDelegate:self];
1007 [webview_ setInteractionDelegate:self];
1008
22f8bed9
JF
1009 [scroller_ addSubview:webview_];
1010
1011 //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
1012
1013 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite];
1014 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(281, 12, indsize.width, indsize.height)];
1015 [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
1016
1017 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
1018 NSString *application = package == nil ? @"Cydia" : [NSString
1019 stringWithFormat:@"Cydia/%@",
1020 [package installed]
ad5d065e
JF
1021 ];
1022
3e9c9e85
JF
1023 if (Product_ != nil)
1024 application = [NSString stringWithFormat:@"%@ Version/%@", application, Product_];
ad5d065e 1025 if (Build_ != nil)
3e9c9e85
JF
1026 application = [NSString stringWithFormat:@"%@ Mobile/%@", application, Build_];
1027 if (Safari_ != nil)
1028 application = [NSString stringWithFormat:@"%@ Safari/%@", application, Safari_];
ad5d065e
JF
1029
1030 /* XXX: lookup application directory? */
1031 /*if (NSDictionary *safari = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"])
1032 if (NSString *version = [safari objectForKey:@"SafariProductVersion"])
1033 application = [NSString stringWithFormat:@"Version/%@ %@", version, application];*/
1034
1035 [webview setApplicationNameForUserAgent:application];
22f8bed9
JF
1036
1037 indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];
374f3d18 1038 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
22f8bed9
JF
1039
1040 [webview setFrameLoadDelegate:self];
1041 [webview setResourceLoadDelegate:indirect_];
1042 [webview setUIDelegate:self];
1043 [webview setScriptDebugDelegate:self];
1044 [webview setPolicyDelegate:self];
1045
1046 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
1047 [scroller_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
1048 } return self;
1049}
1050
3e9c9e85
JF
1051- (id) initWithBook:(RVBook *)book {
1052 return [self initWithBook:book forWidth:[[self class] defaultWidth]];
1053}
1054
22f8bed9
JF
1055- (void) didFinishGesturesInView:(UIView *)view forEvent:(id)event {
1056 [webview_ redrawScaledDocument];
1057}
1058
1059- (void) _rightButtonClicked {
1060 if (function_ == nil) {
1061 reloading_ = true;
1062 [self reloadURL];
1063 } else {
1064 WebView *webview([webview_ webView]);
1065 WebFrame *frame([webview mainFrame]);
1066
1067 id _private(MSHookIvar<id>(webview, "_private"));
1068 WebCore::Page *page(_private == nil ? NULL : MSHookIvar<WebCore::Page *>(_private, "page"));
1069 WebCore::Settings *settings(page == NULL ? NULL : page->settings());
1070
1071 bool no;
1072 if (settings == NULL)
1073 no = 0;
1074 else {
1075 no = settings->JavaScriptCanOpenWindowsAutomatically();
1076 settings->setJavaScriptCanOpenWindowsAutomatically(true);
1077 }
1078
1079 [delegate_ clearFirstResponder];
1080 JSObjectRef function([function_ JSObject]);
1081 JSGlobalContextRef context([frame globalContext]);
1082 JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL);
1083
1084 if (settings != NULL)
1085 settings->setJavaScriptCanOpenWindowsAutomatically(no);
1086 }
1087}
1088
1089- (id) _rightButtonTitle {
1090 return button_ != nil ? button_ : @"Reload";
1091}
1092
1093- (id) rightButtonTitle {
1094 return [self _loading] ? @"" : [self _rightButtonTitle];
1095}
1096
1097- (UINavigationButtonStyle) rightButtonStyle {
1098 if (style_ == nil) normal:
1099 return UINavigationButtonStyleNormal;
1100 else if ([style_ isEqualToString:@"Normal"])
1101 return UINavigationButtonStyleNormal;
1102 else if ([style_ isEqualToString:@"Back"])
1103 return UINavigationButtonStyleBack;
1104 else if ([style_ isEqualToString:@"Highlighted"])
1105 return UINavigationButtonStyleHighlighted;
1106 else if ([style_ isEqualToString:@"Destructive"])
1107 return UINavigationButtonStyleDestructive;
1108 else goto normal;
1109}
1110
1111- (NSString *) title {
1112 return title_ == nil ? @"Loading" : title_;
1113}
1114
1115- (NSString *) backButtonTitle {
1116 return @"Browser";
1117}
1118
1119- (void) setPageActive:(BOOL)active {
1120 if (!active)
1121 [indicator_ removeFromSuperview];
1122 else
1123 [[book_ navigationBar] addSubview:indicator_];
1124}
1125
1126- (void) resetViewAnimated:(BOOL)animated {
1127}
1128
1129- (void) setPushed:(bool)pushed {
1130 pushed_ = pushed;
1131}
1132
3e9c9e85
JF
1133+ (float) defaultWidth {
1134 return 980;
1135}
1136
22f8bed9 1137@end