summaryrefslogtreecommitdiff
path: root/UICaboodle/BrowserView.mm
blob: 7855dcb30bf908c77d78e4258f6b09f9c8f4115e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
#include <UICaboodle/BrowserView.h>
#include <UICaboodle/UCLocalize.h>

#import <QuartzCore/CALayer.h>
// XXX: fix the minimum requirement
extern NSString * const kCAFilterNearest;

#include <WebCore/WebCoreThread.h>
#include <WebKit/WebPreferences-WebPrivate.h>

#include "substrate.h"

#define ForSaurik 0

static bool Wildcat_;

static CFArrayRef (*$GSSystemCopyCapability)(CFStringRef);
static CFArrayRef (*$GSSystemGetCapability)(CFStringRef);
static Class $UIFormAssistant;
static Class $UIWebBrowserView;

@interface NSString (UIKit)
- (NSString *) stringByAddingPercentEscapes;
@end

/* Indirect Delegate {{{ */
@interface IndirectDelegate : NSObject {
    _transient volatile id delegate_;
}

- (void) setDelegate:(id)delegate;
- (id) initWithDelegate:(id)delegate;
@end

@implementation IndirectDelegate

- (void) setDelegate:(id)delegate {
    delegate_ = delegate;
}

- (id) initWithDelegate:(id)delegate {
    delegate_ = delegate;
    return self;
}

- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
    if (delegate_ != nil)
        return [delegate_ webView:sender didClearWindowObject:window forFrame:frame];
}

- (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
    if (delegate_ != nil)
        return [delegate_ webView:sender didCommitLoadForFrame:frame];
}

- (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
    if (delegate_ != nil)
        return [delegate_ webView:sender didFailLoadWithError:error forFrame:frame];
}

- (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
    if (delegate_ != nil)
        return [delegate_ webView:sender didFailProvisionalLoadWithError:error forFrame:frame];
}

- (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
    if (delegate_ != nil)
        return [delegate_ webView:sender didFinishLoadForFrame:frame];
}

- (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
    if (delegate_ != nil)
        return [delegate_ webView:sender didReceiveTitle:title forFrame:frame];
}

- (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
    if (delegate_ != nil)
        return [delegate_ webView:sender didStartProvisionalLoadForFrame:frame];
}

- (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
    if (delegate_ != nil)
        return [delegate_ webView:sender resource:identifier didReceiveAuthenticationChallenge:challenge fromDataSource:source];
}

- (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
    if (delegate_ != nil)
        return [delegate_ webView:sender resource:identifier willSendRequest:request redirectResponse:redirectResponse fromDataSource:source];
    return nil;
}

- (IMP) methodForSelector:(SEL)sel {
    if (IMP method = [super methodForSelector:sel])
        return method;
    fprintf(stderr, "methodForSelector:[%s] == NULL\n", sel_getName(sel));
    return NULL;
}

- (BOOL) respondsToSelector:(SEL)sel {
    if ([super respondsToSelector:sel])
        return YES;
    // XXX: WebThreadCreateNSInvocation returns nil
    //fprintf(stderr, "[%s]R?%s\n", class_getName(self->isa), sel_getName(sel));
    return delegate_ == nil ? NO : [delegate_ respondsToSelector:sel];
}

- (NSMethodSignature *) methodSignatureForSelector:(SEL)sel {
    if (NSMethodSignature *method = [super methodSignatureForSelector:sel])
        return method;
    //fprintf(stderr, "[%s]S?%s\n", class_getName(self->isa), sel_getName(sel));
    if (delegate_ != nil)
        if (NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel])
            return sig;
    // XXX: I fucking hate Apple so very very bad
    return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}

- (void) forwardInvocation:(NSInvocation *)inv {
    SEL sel = [inv selector];
    if (delegate_ != nil && [delegate_ respondsToSelector:sel])
        [inv invokeWithTarget:delegate_];
}

@end
/* }}} */

@interface WebView (UICaboodle)
- (void) setScriptDebugDelegate:(id)delegate;
- (void) _setFormDelegate:(id)delegate;
- (void) _setUIKitDelegate:(id)delegate;
- (void) setWebMailDelegate:(id)delegate;
- (void) _setLayoutInterval:(float)interval;
@end

@implementation WebScriptObject (UICaboodle)

- (unsigned) count {
    id length([self valueForKey:@"length"]);
    if ([length respondsToSelector:@selector(intValue)])
        return [length intValue];
    else
        return 0;
}

- (id) objectAtIndex:(unsigned)index {
    return [self webScriptValueAtIndex:index];
}

@end

@interface BrowserView : UIView {
@private
    UIWebDocumentView *documentView;
}
@property (nonatomic, retain) UIWebDocumentView *documentView;
@end

@implementation BrowserView

@synthesize documentView;

- (void)dealloc {
    [documentView release];
    [super dealloc];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if ([documentView respondsToSelector:@selector(setMinimumSize:)])
        [documentView setMinimumSize:documentView.bounds.size];
}

@end

#define ShowInternals 0
#define LogBrowser 1

#define lprintf(args...) fprintf(stderr, args)

@implementation BrowserController

#if ShowInternals
#include "UICaboodle/UCInternal.h"
#endif

+ (void) _initialize {
    //[WebView enableWebThread];

    WebPreferences *preferences([WebPreferences standardPreferences]);
    [preferences setCacheModel:WebCacheModelDocumentBrowser];
    [preferences setOfflineWebApplicationCacheEnabled:YES];

    [WebPreferences _setInitialDefaultTextEncodingToSystemEncoding];

    $GSSystemCopyCapability = reinterpret_cast<CFArrayRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
    $GSSystemGetCapability = reinterpret_cast<CFArrayRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
    $UIFormAssistant = objc_getClass("UIFormAssistant");

    $UIWebBrowserView = objc_getClass("UIWebBrowserView");
    if ($UIWebBrowserView == nil) {
        Wildcat_ = false;
        $UIWebBrowserView = objc_getClass("UIWebDocumentView");
    } else {
        Wildcat_ = true;
    }
}

- (void) dealloc {
#if LogBrowser
    NSLog(@"[BrowserController dealloc]");
#endif

    if (challenge_ != nil)
        [challenge_ release];

    WebThreadLock();

    WebView *webview = [document_ webView];
    [webview setFrameLoadDelegate:nil];
    [webview setResourceLoadDelegate:nil];
    [webview setUIDelegate:nil];
    [webview setScriptDebugDelegate:nil];
    [webview setPolicyDelegate:nil];

    /* XXX: these are set by UIWebDocumentView
    [webview setDownloadDelegate:nil];
    [webview _setFormDelegate:nil];
    [webview _setUIKitDelegate:nil];
    [webview setEditingDelegate:nil];*/

    /* XXX: no one sets this, ever
    [webview setWebMailDelegate:nil];*/

    [document_ setDelegate:nil];
    [document_ setGestureDelegate:nil];

    if ([document_ respondsToSelector:@selector(setFormEditingDelegate:)])
        [document_ setFormEditingDelegate:nil];

    [document_ setInteractionDelegate:nil];

    [indirect_ setDelegate:nil];

    //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

    [webview close];

#if RecycleWebViews
    [document_ removeFromSuperview];
    [Documents_ addObject:[document_ autorelease]];
#else
    [document_ release];
#endif

    [indirect_ release];

    WebThreadUnlock();

    [scroller_ setDelegate:nil];

    if (button_ != nil)
        [button_ release];
    if (style_ != nil)
        [style_ release];
    if (function_ != nil)
        [function_ release];
    if (finish_ != nil)
        [finish_ release];
    if (closer_ != nil)
        [closer_ release];
    if (special_ != nil)
        [special_ release];

    [scroller_ release];
    [indicator_ release];
    if (confirm_ != nil)
        [confirm_ release];
    if (sensitive_ != nil)
        [sensitive_ release];
    if (title_ != nil)
        [title_ release];
    [super dealloc];
}

- (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
    [self loadRequest:[NSURLRequest
        requestWithURL:url
        cachePolicy:policy
        timeoutInterval:120.0
    ]];
}

- (void) loadURL:(NSURL *)url {
    [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
}

- (void) loadRequest:(NSURLRequest *)request {
    pushed_ = true;
    error_ = false;

    WebThreadLock();
    [document_ loadRequest:request];
    WebThreadUnlock();
}

- (void) reloadURL {
    if (request_ == nil)
        return;

    if ([request_ HTTPBody] == nil && [request_ HTTPBodyStream] == nil)
        [self loadRequest:request_];
    else {
        UIActionSheet *sheet = [[[UIActionSheet alloc]
            initWithTitle:UCLocalize("RESUBMIT_FORM")
            buttons:[NSArray arrayWithObjects:UCLocalize("CANCEL"), UCLocalize("SUBMIT"), nil]
            defaultButtonIndex:0
            delegate:self
            context:@"submit"
        ] autorelease];

        [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];

        [sheet setNumberOfRows:1];
        [sheet popupAlertAnimated:YES];
    }
}

- (WebView *) webView {
    return [document_ webView];
}

- (UIWebDocumentView *) documentView {
    return document_;
}

/* XXX: WebThreadLock? */
- (void) _fixScroller:(CGRect)bounds {
	float extra;

    if (!editing_ || $UIFormAssistant == nil)
        extra = 0;
    else {
        UIFormAssistant *assistant([$UIFormAssistant sharedFormAssistant]);
        CGRect peripheral([assistant peripheralFrame]);
#if LogBrowser
        NSLog(@"per:%f", peripheral.size.height);
#endif
        extra = peripheral.size.height;
    }

    CGRect subrect([scroller_ frame]);
    subrect.size.height -= extra;

    if ([scroller_ respondsToSelector:@selector(setScrollerIndicatorSubrect:)])
        [scroller_ setScrollerIndicatorSubrect:subrect];

    [document_ setValue:[NSValue valueWithSize:NSMakeSize(subrect.size.width, subrect.size.height)] forGestureAttribute:UIGestureAttributeVisibleSize];

    CGSize size(size_);
    size.height += extra;
    [scroller_ setContentSize:size];

    if ([scroller_ respondsToSelector:@selector(releaseRubberBandIfNecessary)])
        [scroller_ releaseRubberBandIfNecessary];
}

- (void) fixScroller {
    CGRect bounds([document_ documentBounds]);
#if TrackResize
    NSLog(@"_fs:(%f,%f+%f,%f)", bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
#endif
    [self _fixScroller:bounds];
}

- (void) view:(UIView *)sender didSetFrame:(CGRect)frame {
    size_ = frame.size;
#if TrackResize
    NSLog(@"dsf:(%f,%f+%f,%f)", frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
#endif
    [self _fixScroller:frame];
}

- (void) view:(UIView *)sender didSetFrame:(CGRect)frame oldFrame:(CGRect)old {
    [self view:sender didSetFrame:frame];
}

- (void) pushPage:(UCViewController *)page {
    [page setDelegate:delegate_];
    [[self navigationItem] setTitle:title_];
    [[self navigationController] pushViewController:page animated:YES];
}

- (void) _pushPage {
    if (pushed_)
        return;
    // WTR: [self autorelease];
    pushed_ = true;
    [[self navigationController] pushViewController:self animated:YES];
}

- (void) swapPage:(UCViewController *)page {
    [page setDelegate:delegate_];
    if (pushed_) [[self navigationController] popViewControllerAnimated:NO];
		
	[[self navigationController] pushViewController:page animated:NO];
}

- (BOOL) getSpecial:(NSURL *)url swap:(BOOL)swap {
#if LogBrowser
    NSLog(@"getSpecial:%@", url);
#endif

    if (UCViewController *page = [delegate_ pageForURL:url hasTag:NULL]) {
        if (swap)
            [self swapPage:page];
        else
            [self pushPage:page];

        return true;
    } else
        return false;
}

- (void) formAssistant:(id)sender didBeginEditingFormNode:(id)node {
}

- (void) formAssistant:(id)sender didEndEditingFormNode:(id)node {
    [self fixScroller];
}

- (void) webViewShow:(WebView *)sender {
    /* XXX: this is where I cry myself to sleep */
}

- (bool) _allowJavaScriptPanel {
    return true;
}

- (bool) allowSensitiveRequests {
    return [self _allowJavaScriptPanel];
}

- (void) _promptForSensitive:(NSMutableArray *)array {
    NSString *name([array objectAtIndex:0]);

    UIActionSheet *sheet = [[[UIActionSheet alloc]
        initWithTitle:nil
        buttons:[NSArray arrayWithObjects:UCLocalize("YES"), UCLocalize("NO"), nil]
        defaultButtonIndex:0
        delegate:indirect_
        context:@"sensitive"
    ] autorelease];

    [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];

    NSString *host(@"XXX");

    [sheet setNumberOfRows:1];
    [sheet setBodyText:[NSString stringWithFormat:@"The website at %@ is requesting your phone's %@. This is almost certainly for product licensing purposes. Will you allow this?", host, name]];
    [sheet popupAlertAnimated:YES];

    NSRunLoop *loop([NSRunLoop currentRunLoop]);
    NSDate *future([NSDate distantFuture]);

    while (sensitive_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);

    NSNumber *sensitive([sensitive_ autorelease]);
    sensitive_ = nil;

    [self autorelease];
    [array replaceObjectAtIndex:0 withObject:sensitive];
}

- (bool) promptForSensitive:(NSString *)name {
    if (![self allowSensitiveRequests])
        return false;

    NSMutableArray *array([NSMutableArray arrayWithCapacity:1]);
    [array addObject:name];

    [self performSelectorOnMainThread:@selector(_promptForSensitive:) withObject:array waitUntilDone:YES];
    return [[array lastObject] boolValue];
}

- (void) webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
    if (![self _allowJavaScriptPanel])
        return;
    [self retain];

    UIActionSheet *sheet = [[[UIActionSheet alloc]
        initWithTitle:nil
        buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
        defaultButtonIndex:0
        delegate:self
        context:@"alert"
    ] autorelease];

    [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];

    [sheet setBodyText:message];
    [sheet popupAlertAnimated:YES];
}

- (BOOL) webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
    if (![self _allowJavaScriptPanel])
        return NO;
    [self retain];

    UIActionSheet *sheet = [[[UIActionSheet alloc]
        initWithTitle:nil
        buttons:[NSArray arrayWithObjects:UCLocalize("OK"), UCLocalize("CANCEL"), nil]
        defaultButtonIndex:0
        delegate:indirect_
        context:@"confirm"
    ] autorelease];

    [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];

    [sheet setNumberOfRows:1];
    [sheet setBodyText:message];
    [sheet popupAlertAnimated:YES];

    NSRunLoop *loop([NSRunLoop currentRunLoop]);
    NSDate *future([NSDate distantFuture]);

    while (confirm_ == nil && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);

    NSNumber *confirm([confirm_ autorelease]);
    confirm_ = nil;

    [self autorelease];
    return [confirm boolValue];
}

- (void) setAutoPopup:(BOOL)popup {
    popup_ = popup;
}

- (void) setSpecial:(id)function {
    if (special_ != nil)
        [special_ autorelease];
    special_ = function == nil ? nil : [function retain];
}

- (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
    if (button_ != nil)
        [button_ autorelease];
    button_ = button == nil ? nil : [[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:button]]] retain];

    if (style_ != nil)
        [style_ autorelease];
    style_ = style == nil ? nil : [style retain];

    if (function_ != nil)
        [function_ autorelease];
    function_ = function == nil ? nil : [function retain];

	[self applyRightButton];
}

- (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
    if (button_ != nil)
        [button_ autorelease];
    button_ = button == nil ? nil : [button retain];

    if (style_ != nil)
        [style_ autorelease];
    style_ = style == nil ? nil : [style retain];

    if (function_ != nil)
        [function_ autorelease];
    function_ = function == nil ? nil : [function retain];

	[self applyRightButton];
}

- (void) setFinishHook:(id)function {
    if (finish_ != nil)
        [finish_ autorelease];
    finish_ = function == nil ? nil : [function retain];
}

- (void) setPopupHook:(id)function {
    if (closer_ != nil)
        [closer_ autorelease];
    closer_ = function == nil ? nil : [function retain];
}

- (void) _openMailToURL:(NSURL *)url {
    [UIApp openURL:url];// asPanel:YES];
}

- (void) webView:(WebView *)sender willBeginEditingFormElement:(id)element {
    editing_ = true;
}

- (void) webView:(WebView *)sender didBeginEditingFormElement:(id)element {
    [self fixScroller];
}

- (void) webViewDidEndEditingFormElements:(WebView *)sender {
    editing_ = false;
    [self fixScroller];
}

- (void) webViewClose:(WebView *)sender {
	[self close];
}

- (void) close {
    [[self navigationController] dismissModalViewControllerAnimated:YES];
}

- (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
}

- (void) webView:(WebView *)sender unableToImplementPolicyWithError:(NSError *)error frame:(WebFrame *)frame {
    NSLog(@"err:%@", error);
}

- (void) webView:(WebView *)sender decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)name decisionListener:(id<WebPolicyDecisionListener>)listener {
#if LogBrowser
    NSLog(@"nwa:%@", name);
#endif

    if (NSURL *url = [request URL]) {
        if (name == nil) unknown: {
            if (![self getSpecial:url swap:NO]) {
                NSString *scheme([[url scheme] lowercaseString]);
                if ([scheme isEqualToString:@"mailto"])
                    [self _openMailToURL:url];
                else goto use;
            }
        } else if ([name isEqualToString:@"_open"])
            [delegate_ openURL:url];
        else if ([name isEqualToString:@"_popup"]) {
            NSString *scheme([[url scheme] lowercaseString]);
            if ([scheme isEqualToString:@"mailto"])
                [self _openMailToURL:url];
            else {
                UCNavigationController *navigation([[[UCNavigationController alloc] init] autorelease]);
                [navigation setHook:indirect_];

                UCViewController *page([delegate_ pageForURL:url hasTag:NULL]);
                if (page == nil) {
                    /* XXX: call createWebViewWithRequest instead? */

                    BrowserController *browser([[[class_ alloc] init] autorelease]);
                    [browser loadURL:url];
                    page = browser;
                }

                [navigation setDelegate:delegate_];
                [page setDelegate:delegate_];

                [navigation setViewControllers:[NSArray arrayWithObject:page]];
				UIBarButtonItem *closeItem = [[UIBarButtonItem alloc]
			        initWithTitle:UCLocalize("CLOSE")
					style:UIBarButtonItemStylePlain
			        target:page
			        action:@selector(close)
			    ];
			    [[page navigationItem] setLeftBarButtonItem:closeItem];
			    [closeItem release];
			
                [[self navigationController] presentModalViewController:navigation animated:YES];
            }
        } else goto unknown;

        [listener ignore];
    } else use:
        [listener use];
}

- (void) webView:(WebView *)sender decidePolicyForMIMEType:(NSString *)type request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
    if ([WebView canShowMIMEType:type])
        [listener use];
    else {
        // XXX: handle more mime types!
        [listener ignore];

        WebView *webview([document_ webView]);
        if (frame == [webview mainFrame])
            [UIApp openURL:[request URL]];
    }
}

- (void) webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
    if (request == nil) ignore: {
        [listener ignore];
        return;
    }

    NSURL *url([request URL]);
    NSString *host([url host]);

    if (url == nil) use: {
        if (!error_ && [frame parentFrame] == nil) {
            if (request_ != nil)
                [request_ autorelease];
            request_ = [request retain];
#if LogBrowser
            NSLog(@"dpn:%@", request_);
#endif
        }

        [listener use];

        WebView *webview([document_ webView]);
        if (frame == [webview mainFrame])
            [self _pushPage];
        return;
    }
#if LogBrowser
    else NSLog(@"nav:%@:%@", url, [action description]);
#endif

    const NSArray *capability;

    if ($GSSystemCopyCapability != NULL) {
        capability = reinterpret_cast<const NSArray *>((*$GSSystemCopyCapability)(kGSDisplayIdentifiersCapability));
        capability = [capability autorelease];
    } else if ($GSSystemGetCapability != NULL) {
        capability = reinterpret_cast<const NSArray *>((*$GSSystemGetCapability)(kGSDisplayIdentifiersCapability));
    } else
        capability = nil;

    NSURL *open(nil);

    if (capability != nil && (
        [url isGoogleMapsURL] && [capability containsObject:@"com.apple.Maps"] && (open = [url mapsURL]) != nil||
        [host hasSuffix:@"youtube.com"] && [capability containsObject:@"com.apple.youtube"] && (open = [url youTubeURL]) != nil ||
        [url respondsToSelector:@selector(phobosURL)] && (open = [url phobosURL]) != nil
    )) {
        url = open;
      open:
        [UIApp openURL:url];
        goto ignore;
    }

    int store(_not(int));
    if (NSURL *itms = [url itmsURL:&store]) {
#if LogBrowser
        NSLog(@"itms#%@#%u#%@", url, store, itms);
#endif

        if (capability != nil && (
            store == 1 && [capability containsObject:@"com.apple.MobileStore"] ||
            store == 2 && [capability containsObject:@"com.apple.AppStore"]
        )) {
            url = itms;
            goto open;
        }
    }

    NSString *scheme([[url scheme] lowercaseString]);

    if ([scheme isEqualToString:@"tel"]) {
        // XXX: intelligence
        goto open;
    }

    if ([scheme isEqualToString:@"mailto"]) {
        [self _openMailToURL:url];
        goto ignore;
    }

    if ([self getSpecial:url swap:YES])
        goto ignore;
    else if ([WebView _canHandleRequest:request])
        goto use;
    else if ([url isSpringboardHandledURL])
        goto open;
    else
        goto use;
}

- (void) webView:(WebView *)sender setStatusText:(NSString *)text {
    //lprintf("Status:%s\n", [text UTF8String]);
}

- (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
    NSString *context([sheet context]);

    if ([context isEqualToString:@"alert"]) {
        [self autorelease];
        [sheet dismiss];
    } else if ([context isEqualToString:@"confirm"]) {
        switch (button) {
            case 1:
                confirm_ = [NSNumber numberWithBool:YES];
            break;

            case 2:
                confirm_ = [NSNumber numberWithBool:NO];
            break;
        }

        [sheet dismiss];
    } else if ([context isEqualToString:@"sensitive"]) {
        switch (button) {
            case 1:
                sensitive_ = [NSNumber numberWithBool:YES];
            break;

            case 2:
                sensitive_ = [NSNumber numberWithBool:NO];
            break;
        }

        [sheet dismiss];
    } else if ([context isEqualToString:@"challenge"]) {
        id<NSURLAuthenticationChallengeSender> sender([challenge_ sender]);

        switch (button) {
            case 1: {
                NSString *username([[sheet textFieldAtIndex:0] text]);
                NSString *password([[sheet textFieldAtIndex:1] text]);

                NSURLCredential *credential([NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]);

                [sender useCredential:credential forAuthenticationChallenge:challenge_];
            } break;

            case 2:
                [sender cancelAuthenticationChallenge:challenge_];
            break;

            _nodefault
        }

        [challenge_ release];
        challenge_ = nil;

        [sheet dismiss];
    } else if ([context isEqualToString:@"submit"]) {
        switch (button) {
            case 1:
            break;

            case 2:
                if (request_ != nil) {
                    WebThreadLock();
                    [document_ loadRequest:request_];
                    WebThreadUnlock();
                }
            break;

            _nodefault
        }

        [sheet dismiss];
    }
}

- (void) webView:(WebView *)sender resource:(id)identifier didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)source {
    challenge_ = [challenge retain];

    NSURLProtectionSpace *space([challenge protectionSpace]);
    NSString *realm([space realm]);
    if (realm == nil)
        realm = @"";

    UIActionSheet *sheet = [[[UIActionSheet alloc]
        initWithTitle:realm
        buttons:[NSArray arrayWithObjects:UCLocalize("LOGIN"), UCLocalize("CANCEL"), nil]
        defaultButtonIndex:0
        delegate:self
        context:@"challenge"
    ] autorelease];

    [sheet setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];

    [sheet setNumberOfRows:1];

    [sheet addTextFieldWithValue:@"" label:UCLocalize("USERNAME")];
    [sheet addTextFieldWithValue:@"" label:UCLocalize("PASSWORD")];

    UITextField *username([sheet textFieldAtIndex:0]); {
        UITextInputTraits *traits([username textInputTraits]);
        [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
        [traits setKeyboardType:UIKeyboardTypeASCIICapable];
        [traits setReturnKeyType:UIReturnKeyNext];
    }

    UITextField *password([sheet textFieldAtIndex:1]); {
        UITextInputTraits *traits([password textInputTraits]);
        [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
        [traits setKeyboardType:UIKeyboardTypeASCIICapable];
        // XXX: UIReturnKeyDone
        [traits setReturnKeyType:UIReturnKeyNext];
        [traits setSecureTextEntry:YES];
    }

    [sheet popupAlertAnimated:YES];
}

- (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
    return request;
}

- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request windowFeatures:(NSDictionary *)features {
//- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request userGesture:(BOOL)gesture {
#if LogBrowser
    NSLog(@"cwv:%@ (%@): %@", request, title_, features == nil ? @"{}" : [features description]);
    //NSLog(@"cwv:%@ (%@): %@", request, title_, gesture ? @"Yes" : @"No");
#endif

    NSNumber *value([features objectForKey:@"width"]);
    float width(value == nil ? 0 : [value floatValue]);

    UCNavigationController *navigation(!popup_ ? [self navigationController] : [[[UCNavigationController alloc] init] autorelease]);

    /* XXX: deal with cydia:// pages */
    BrowserController *browser([[[class_ alloc] initWithWidth:width] autorelease]);

    if (features != nil && popup_) {
        [navigation setDelegate:delegate_];
        [navigation setHook:indirect_];
        [browser setDelegate:delegate_];

        [browser loadRequest:request];

        [navigation setViewControllers:[NSArray arrayWithObject:browser]];
		UIBarButtonItem *closeItem = [[UIBarButtonItem alloc]
	        initWithTitle:UCLocalize("CLOSE")
			style:UIBarButtonItemStylePlain
	        target:browser
	        action:@selector(close)
	    ];
	    [[browser navigationItem] setLeftBarButtonItem:closeItem];
	    [closeItem release];
	
        [[self navigationController] presentModalViewController:navigation animated:YES];
    } /*else if (request == nil) {
        [[self navigationItem] setTitle:title_];
        [browser setDelegate:delegate_];
        [browser retain];
    }*/ else {
        [self pushPage:browser];
        [browser loadRequest:request];
    }

    return [browser webView];
}

- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {
    return [self webView:sender createWebViewWithRequest:request windowFeatures:nil];
    //return [self webView:sender createWebViewWithRequest:request userGesture:YES];
}

- (void) webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame {
    if ([frame parentFrame] != nil)
        return;

    title_ = [title retain];
    [[self navigationItem] setTitle:title_];
}

- (void) webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
    /*if ([loading_ count] == 0)
        [self retain];*/
    [loading_ addObject:[NSValue valueWithNonretainedObject:frame]];

    if ([frame parentFrame] == nil) {
        [document_ resignFirstResponder];

        reloading_ = false;

        if (title_ != nil) {
            [title_ release];
            title_ = nil;
        }

        if (button_ != nil) {
            [button_ release];
            button_ = nil;
        }

        if (style_ != nil) {
            [style_ release];
            style_ = nil;
        }

        if (function_ != nil) {
            [function_ release];
            function_ = nil;
        }

        if (finish_ != nil) {
            [finish_ release];
            finish_ = nil;
        }

        if (closer_ != nil) {
            [closer_ release];
            closer_ = nil;
        }

        if (special_ != nil) {
            [special_ release];
            special_ = nil;
        }

        [[self navigationItem] setTitle:title_];

        if (Wildcat_) {
            CGRect webrect = [scroller_ bounds];
            webrect.size.height = 1;
            [document_ setFrame:webrect];
        }

        if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
            [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
        else
            [scroller_ scrollRectToVisible:CGRectZero animated:NO];

        if ([scroller_ respondsToSelector:@selector(setZoomScale:duration:)])
            [scroller_ setZoomScale:1 duration:0];
        else if ([scroller_ respondsToSelector:@selector(_setZoomScale:duration:)])
            [scroller_ _setZoomScale:1 duration:0];
        /*else if ([scroller_ respondsToSelector:@selector(setZoomScale:animated:)])
            [scroller_ setZoomScale:1 animated:NO];*/

        if (!Wildcat_) {
            CGRect webrect = [scroller_ bounds];
            webrect.size.height = 0;
            [document_ setFrame:webrect];
        }
    }

	[self _startLoading];
}

- (void) applyRightButton {
	if ([self isLoading]) {
        UIBarButtonItem *reloadItem = [[UIBarButtonItem alloc]
	        initWithTitle:@" "
	        style:UIBarButtonItemStylePlain
	        target:self
	        action:@selector(reloadButtonClicked)
	    ];
	    [[self navigationItem] setRightBarButtonItem:reloadItem];
		[[reloadItem view] addSubview:indicator_];
		[[self navigationItem] setTitle:UCLocalize("LOADING")];
	    [reloadItem release];
    } else {
		UIBarButtonItem *reloadItem = [[UIBarButtonItem alloc]
			initWithTitle:button_ ?: UCLocalize("RELOAD")
			style:[self rightButtonStyle]
			target:self
			action:button_ ? @selector(customButtonClicked) : @selector(reloadButtonClicked)
		];
		[[self navigationItem] setRightBarButtonItem:reloadItem animated:YES];
		[[self navigationItem] setTitle:title_];
		[reloadItem release];
	}
}

- (void) _startLoading {
    [self applyRightButton];
}

- (void) _finishLoading {
    size_t count([loading_ count]);
    /*if (count == 0)
        [self autorelease];*/
    if (reloading_ || count != 0)
        return;
    if (finish_ != nil)
        [self callFunction:finish_];

	[self applyRightButton];
}

- (bool) isLoading {
    return [loading_ count] != 0;
}

- (BOOL) webView:(WebView *)sender shouldScrollToPoint:(struct CGPoint)point forFrame:(WebFrame *)frame {
    return [document_ webView:sender shouldScrollToPoint:point forFrame:frame];
}

- (void) webView:(WebView *)sender didReceiveViewportArguments:(id)arguments forFrame:(WebFrame *)frame {
    return [document_ webView:sender didReceiveViewportArguments:arguments forFrame:frame];
}

- (void) webView:(WebView *)sender needsScrollNotifications:(id)notifications forFrame:(WebFrame *)frame {
    return [document_ webView:sender needsScrollNotifications:notifications forFrame:frame];
}

- (void) webView:(WebView *)sender didCommitLoadForFrame:(WebFrame *)frame {
    [self _pushPage];
    return [document_ webView:sender didCommitLoadForFrame:frame];
}

- (void) webView:(WebView *)sender didReceiveDocTypeForFrame:(WebFrame *)frame {
    return [document_ webView:sender didReceiveDocTypeForFrame:frame];
}

- (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
    [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
    [self _finishLoading];

    if ([frame parentFrame] == nil) {
        if (DOMDocument *document = [frame DOMDocument])
            if (DOMNodeList<NSFastEnumeration> *bodies = [document getElementsByTagName:@"body"])
                for (DOMHTMLBodyElement *body in bodies) {
                    DOMCSSStyleDeclaration *style([document getComputedStyle:body pseudoElement:nil]);

                    bool colored(false);

                    if (DOMCSSPrimitiveValue *color = static_cast<DOMCSSPrimitiveValue *>([style getPropertyCSSValue:@"background-color"])) {
                        if ([color primitiveType] == DOM_CSS_RGBCOLOR) {
                            DOMRGBColor *rgb([color getRGBColorValue]);

                            float red([[rgb red] getFloatValue:DOM_CSS_NUMBER]);
                            float green([[rgb green] getFloatValue:DOM_CSS_NUMBER]);
                            float blue([[rgb blue] getFloatValue:DOM_CSS_NUMBER]);
                            float alpha([[rgb alpha] getFloatValue:DOM_CSS_NUMBER]);

                            UIColor *uic(nil);

                            if (red == 0xc7 && green == 0xce && blue == 0xd5)
                                uic = [UIColor pinStripeColor];
                            else if (alpha != 0)
                                uic = [UIColor
                                    colorWithRed:(red / 255)
                                    green:(green / 255)
                                    blue:(blue / 255)
                                    alpha:alpha
                                ];

                            if (uic != nil) {
                                colored = true;
                                [scroller_ setBackgroundColor:uic];
                            }
                        }
                    }

                    if (!colored)
                        [scroller_ setBackgroundColor:[UIColor pinStripeColor]];
                    break;
                }
    }

    return [document_ webView:sender didFinishLoadForFrame:frame];
}

- (void) _didFailWithError:(NSError *)error forFrame:(WebFrame *)frame {
    _trace();
    /*if ([frame parentFrame] == nil)
        [self autorelease];*/

    [loading_ removeObject:[NSValue valueWithNonretainedObject:frame]];
    [self _finishLoading];

    if (reloading_)
        return;

    if ([frame parentFrame] == nil) {
        [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@",
            [[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"error" ofType:@"html"]] absoluteString],
            [[error localizedDescription] stringByAddingPercentEscapes]
        ]]];

        error_ = true;
    }
}

- (void) webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
    [self _didFailWithError:error forFrame:frame];
    if ([document_ respondsToSelector:@selector(webView:didFailLoadWithError:forFrame:)])
        [document_ webView:sender didFailLoadWithError:error forFrame:frame];
}

- (void) webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
    [self _didFailWithError:error forFrame:frame];
}

- (void) webView:(WebView *)sender addMessageToConsole:(NSDictionary *)dictionary {
#if LogBrowser || ForSaurik
    lprintf("Console:%s\n", [[dictionary description] UTF8String]);
#endif
}

- (void) webView:(WebView *)sender didReceiveMessage:(NSDictionary *)dictionary {
#if LogBrowser || ForSaurik
    lprintf("Console:%s\n", [[dictionary description] UTF8String]);
#endif
    if ([document_ respondsToSelector:@selector(webView:didReceiveMessage:)])
        [document_ webView:sender didReceiveMessage:dictionary];
}

- (void) webView:(id)sender willCloseFrame:(id)frame {
    if ([document_ respondsToSelector:@selector(webView:willCloseFrame:)])
        [document_ webView:sender willCloseFrame:frame];
}

- (void) webView:(id)sender didFinishDocumentLoadForFrame:(id)frame {
    if ([document_ respondsToSelector:@selector(webView:didFinishDocumentLoadForFrame:)])
        [document_ webView:sender didFinishDocumentLoadForFrame:frame];
}

- (void) webView:(id)sender didFirstLayoutInFrame:(id)frame {
    if ([document_ respondsToSelector:@selector(webView:didFirstLayoutInFrame:)])
        [document_ webView:sender didFirstLayoutInFrame:frame];
}

- (void) webViewFormEditedStatusHasChanged:(id)changed {
    if ([document_ respondsToSelector:@selector(webViewFormEditedStatusHasChanged:)])
        [document_ webViewFormEditedStatusHasChanged:changed];
}

- (void) webView:(id)sender formStateDidFocusNode:(id)formState {
    if ([document_ respondsToSelector:@selector(webView:formStateDidFocusNode:)])
        [document_ webView:sender formStateDidFocusNode:formState];
}

- (void) webView:(id)sender formStateDidBlurNode:(id)formState {
    if ([document_ respondsToSelector:@selector(webView:formStateDidBlurNode:)])
        [document_ webView:sender formStateDidBlurNode:formState];
}

/* XXX: fix this stupid include file
- (void) webView:(WebView *)sender frame:(WebFrame *)frame exceededDatabaseQuotaForSecurityOrigin:(WebSecurityOrigin *)origin database:(NSString *)database {
    [origin setQuota:0x500000];
}*/

- (void) webViewDidLayout:(id)sender {
    [document_ webViewDidLayout:sender];
}

- (void) webView:(id)sender didFirstVisuallyNonEmptyLayoutInFrame:(id)frame {
    [document_ webView:sender didFirstVisuallyNonEmptyLayoutInFrame:frame];
}

- (void) webView:(id)sender saveStateToHistoryItem:(id)item forFrame:(id)frame {
    [document_ webView:sender saveStateToHistoryItem:item forFrame:frame];
}

- (void) webView:(id)sender restoreStateFromHistoryItem:(id)item forFrame:(id)frame force:(BOOL)force {
    [document_ webView:sender restoreStateFromHistoryItem:item forFrame:frame force:force];
}

- (void) webView:(id)sender attachRootLayer:(id)layer {
    [document_ webView:sender attachRootLayer:layer];
}

- (id) webView:(id)sender plugInViewWithArguments:(id)arguments fromPlugInPackage:(id)package {
    return [document_ webView:sender plugInViewWithArguments:arguments fromPlugInPackage:package];
}

- (void) webView:(id)sender willShowFullScreenForPlugInView:(id)view {
    [document_ webView:sender willShowFullScreenForPlugInView:view];
}

- (void) webView:(id)sender didHideFullScreenForPlugInView:(id)view {
    [document_ webView:sender didHideFullScreenForPlugInView:view];
}

- (void) webView:(id)sender willAddPlugInView:(id)view {
    [document_ webView:sender willAddPlugInView:view];
}

- (void) webView:(id)sender didObserveDeferredContentChange:(int)change forFrame:(id)frame {
    [document_ webView:sender didObserveDeferredContentChange:change forFrame:frame];
}

- (void) webViewDidPreventDefaultForEvent:(id)sender {
    [document_ webViewDidPreventDefaultForEvent:sender];
}

- (void) _setTileDrawingEnabled:(BOOL)enabled {
    //[document_ setTileDrawingEnabled:enabled];
}

- (void) setViewportWidth:(float)width {
    width_ = width != 0 ? width : [[self class] defaultWidth];
    [document_ setViewportSize:CGSizeMake(width_, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];
}

- (void) willStartGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
    [self _setTileDrawingEnabled:NO];
}

- (void) didFinishGesturesInView:(UIView *)view forEvent:(GSEventRef)event {
    [self _setTileDrawingEnabled:YES];
    [document_ redrawScaledDocument];
}

- (void) scrollerWillStartDragging:(UIScroller *)scroller {
    [self _setTileDrawingEnabled:NO];
}

- (void) scrollerDidEndDragging:(UIScroller *)scroller willSmoothScroll:(BOOL)smooth {
    [self _setTileDrawingEnabled:YES];
}

- (void) scrollerDidEndDragging:(UIScroller *)scroller {
    [self _setTileDrawingEnabled:YES];
}

- (id) initWithWidth:(float)width ofClass:(Class)_class {
    if ((self = [super init]) != nil) {
        class_ = _class;
        loading_ = [[NSMutableSet alloc] initWithCapacity:3];
        popup_ = false;

        BrowserView *actualView = [[BrowserView alloc] initWithFrame:CGRectZero];
        [self setView:actualView];
        
        struct CGRect bounds = [[self view] bounds];

        scroller_ = [[objc_getClass(Wildcat_ ? "UIScrollView" : "UIScroller") alloc] initWithFrame:bounds];
        [[self view] addSubview:scroller_];

        [scroller_ setFixedBackgroundPattern:YES];
        [scroller_ setBackgroundColor:[UIColor pinStripeColor]];

        [scroller_ setScrollingEnabled:YES];
        [scroller_ setClipsSubviews:YES];

        if (!Wildcat_)
            [scroller_ setAllowsRubberBanding:YES];

        [scroller_ setDelegate:self];
        [scroller_ setBounces:YES];

        if (!Wildcat_) {
            [scroller_ setScrollHysteresis:8];
            [scroller_ setThumbDetectionEnabled:NO];
            [scroller_ setDirectionalScrolling:YES];
            //[scroller_ setScrollDecelerationFactor:0.99]; /* 0.989324 */
            [scroller_ setEventMode:YES];
        }

        if (Wildcat_) {
            UIScrollView *scroller((UIScrollView *)scroller_);
            //[scroller setDirectionalLockEnabled:NO];
            [scroller setDelaysContentTouches:NO];
            //[scroller setScrollsToTop:NO];
            //[scroller setCanCancelContentTouches:NO];
        }

        [scroller_ setShowBackgroundShadow:NO]; /* YES */
        //[scroller_ setAllowsRubberBanding:YES]; /* Vertical */

        if (!Wildcat_)
            [scroller_ setAdjustForContentSizeChange:YES]; /* NO */

        CGRect webrect = [scroller_ bounds];
        webrect.size.height = 0;

        WebView *webview;

        WebThreadLock();

#if RecycleWebViews
        document_ = [Documents_ lastObject];
        if (document_ != nil) {
            document_ = [document_ retain];
            webview = [document_ webView];
            [Documents_ removeLastObject];
            [document_ setFrame:webrect];
        } else {
#else
        if (true) {
#endif
            document_ = [[$UIWebBrowserView alloc] initWithFrame:webrect];
            webview = [document_ webView];

            // XXX: this is terribly (too?) expensive
            //[document_ setDrawsBackground:NO];
            [webview setPreferencesIdentifier:@"Cydia"];

            [document_ setTileSize:CGSizeMake(webrect.size.width, 500)];

            if ([document_ respondsToSelector:@selector(enableReachability)])
                [document_ enableReachability];
            if ([document_ respondsToSelector:@selector(setAllowsMessaging:)])
                [document_ setAllowsMessaging:YES];
            if ([document_ respondsToSelector:@selector(useSelectionAssistantWithMode:)])
                [document_ useSelectionAssistantWithMode:0];

            [document_ setTilingEnabled:YES];
            [document_ setDrawsGrid:NO];
            [document_ setLogsTilingChanges:NO];
            [document_ setTileMinificationFilter:kCAFilterNearest];

            if ([document_ respondsToSelector:@selector(setDataDetectorTypes:)])
                /* XXX: abstractify */
                [document_ setDataDetectorTypes:0x80000000];
            else
                [document_ setDetectsPhoneNumbers:NO];

            [document_ setAutoresizes:YES];

            [document_ setMinimumScale:0.25f forDocumentTypes:0x10];
            [document_ setMaximumScale:5.00f forDocumentTypes:0x10];
            [document_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x10];
            //[document_ setViewportSize:CGSizeMake(980, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x10];

            [document_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x2];

            [document_ setMinimumScale:1.00f forDocumentTypes:0x8];
            [document_ setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:0x8];
            [document_ setViewportSize:CGSizeMake(320, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:0x8];

            [document_ _setDocumentType:0x4];

            if ([document_ respondsToSelector:@selector(setZoomsFocusedFormControl:)])
                [document_ setZoomsFocusedFormControl:YES];
            [document_ setContentsPosition:7];
            [document_ setEnabledGestures:0xa];
            [document_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeIsZoomRubberBandEnabled];
            [document_ setValue:[NSNumber numberWithBool:YES] forGestureAttribute:UIGestureAttributeUpdatesScroller];

            [document_ setSmoothsFonts:YES];
            [document_ setAllowsImageSheet:YES];
            [webview _setUsesLoaderCache:YES];

            [webview setGroupName:@"CydiaGroup"];

            WebPreferences *preferences([webview preferences]);

            if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
                [webview _setLayoutInterval:0];
            else
                [preferences _setLayoutInterval:0];
        }
        
        actualView.documentView = document_;
        [actualView release];

        [self setViewportWidth:width];

        [document_ setDelegate:self];
        [document_ setGestureDelegate:self];

        if ([document_ respondsToSelector:@selector(setFormEditingDelegate:)])
            [document_ setFormEditingDelegate:self];

        [document_ setInteractionDelegate:self];

        [scroller_ addSubview:document_];

        //NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

        indirect_ = [[IndirectDelegate alloc] initWithDelegate:self];

        [webview setFrameLoadDelegate:indirect_];
        [webview setPolicyDelegate:indirect_];
        [webview setResourceLoadDelegate:indirect_];
        [webview setUIDelegate:indirect_];

        /* XXX: do not turn this on under penalty of extreme pain */
        [webview setScriptDebugDelegate:nil];

        WebThreadUnlock();

        CGSize indsize = [UIProgressIndicator defaultSizeForStyle:UIProgressIndicatorStyleMediumWhite];
        indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(15, 5, indsize.width, indsize.height)];
        [indicator_ setStyle:UIProgressIndicatorStyleMediumWhite];
		[indicator_ startAnimation];

        [scroller_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
        [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
        [document_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];

        /*UIWebView *test([[[UIWebView alloc] initWithFrame:[[self view] bounds]] autorelease]);
        [test loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.saurik.com/"]]];
        [[self view] addSubview:test];*/
    } return self;
}

- (id) initWithWidth:(float)width {
    return [self initWithWidth:width ofClass:[self class]];
}

- (id) init {
    return [self initWithWidth:0];
}

- (NSString *) stringByEvaluatingJavaScriptFromString:(NSString *)script {
    WebThreadLock();
    WebView *webview([document_ webView]);
    NSString *string([webview stringByEvaluatingJavaScriptFromString:script]);
    WebThreadUnlock();
    return string;
}

- (void) callFunction:(WebScriptObject *)function {
    WebThreadLock();

    WebView *webview([document_ webView]);
    WebFrame *frame([webview mainFrame]);

    id _private(MSHookIvar<id>(webview, "_private"));
    WebCore::Page *page(_private == nil ? NULL : MSHookIvar<WebCore::Page *>(_private, "page"));
    WebCore::Settings *settings(page == NULL ? NULL : page->settings());

    bool no;
    if (settings == NULL)
        no = 0;
    else {
        no = settings->JavaScriptCanOpenWindowsAutomatically();
        settings->setJavaScriptCanOpenWindowsAutomatically(true);
    }

    if (UIWindow *window = [[self view] window])
        if (UIResponder *responder = [window firstResponder])
            [responder resignFirstResponder];

    JSObjectRef object([function JSObject]);
    JSGlobalContextRef context([frame globalContext]);
    JSObjectCallAsFunction(context, object, NULL, 0, NULL, NULL);

    if (settings != NULL)
        settings->setJavaScriptCanOpenWindowsAutomatically(no);

    WebThreadUnlock();
}

- (void) didDismissModalViewController {
    if (closer_ != nil)
        [self callFunction:closer_];
}

- (void) reloadButtonClicked {
    reloading_ = true;
    [self reloadURL];
}

- (void) customButtonClicked {
#if !AlwaysReload
    if (function_ != nil)
        [self callFunction:function_];
    else
#endif
		[self reloadButtonClicked];
}

- (UINavigationButtonStyle) rightButtonStyle {
    if (style_ == nil) normal:
        return UINavigationButtonStyleNormal;
    else if ([style_ isEqualToString:@"Normal"])
        return UINavigationButtonStyleNormal;
    else if ([style_ isEqualToString:@"Back"])
        return UINavigationButtonStyleBack;
    else if ([style_ isEqualToString:@"Highlighted"])
        return UINavigationButtonStyleHighlighted;
    else if ([style_ isEqualToString:@"Destructive"])
        return UINavigationButtonStyleDestructive;
    else goto normal;
}

- (void) setPageActive:(BOOL)active {
    if (!active)
        [indicator_ removeFromSuperview];
    else
		[[[[self navigationItem] rightBarButtonItem] view] addSubview:indicator_];
}

- (void) resetViewAnimated:(BOOL)animated {
}

- (void) setPushed:(bool)pushed {
    pushed_ = pushed;
}

+ (float) defaultWidth {
    return 980;
}

@end