/
WebView.mm
6405 lines (5378 loc) · 225 KB
/
WebView.mm
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
/*
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
* Copyright (C) 2006 David Smith (catfish.man@gmail.com)
* Copyright (C) 2010 Igalia S.L
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WebViewInternal.h"
#import "WebViewData.h"
#import "DOMCSSStyleDeclarationInternal.h"
#import "DOMNodeInternal.h"
#import "DOMRangeInternal.h"
#import "WebApplicationCache.h"
#import "WebBackForwardListInternal.h"
#import "WebBaseNetscapePluginView.h"
#import "WebCache.h"
#import "WebChromeClient.h"
#import "WebContextMenuClient.h"
#import "WebDOMOperationsPrivate.h"
#import "WebDataSourceInternal.h"
#import "WebDatabaseManagerInternal.h"
#import "WebDefaultEditingDelegate.h"
#import "WebDefaultPolicyDelegate.h"
#import "WebDefaultUIDelegate.h"
#import "WebDelegateImplementationCaching.h"
#import "WebDeviceOrientationClient.h"
#import "WebDeviceOrientationProvider.h"
#import "WebDocument.h"
#import "WebDocumentInternal.h"
#import "WebDownload.h"
#import "WebDownloadInternal.h"
#import "WebDragClient.h"
#import "WebDynamicScrollBarsViewInternal.h"
#import "WebEditingDelegate.h"
#import "WebEditorClient.h"
#import "WebFormDelegatePrivate.h"
#import "WebFrameInternal.h"
#import "WebFrameViewInternal.h"
#import "WebFullScreenController.h"
#import "WebGeolocationClient.h"
#import "WebGeolocationPositionInternal.h"
#import "WebHTMLRepresentation.h"
#import "WebHTMLViewInternal.h"
#import "WebHistoryItemInternal.h"
#import "WebIconDatabaseInternal.h"
#import "WebInspector.h"
#import "WebInspectorClient.h"
#import "WebKitErrors.h"
#import "WebKitLogging.h"
#import "WebKitNSStringExtras.h"
#import "WebKitStatisticsPrivate.h"
#import "WebKitSystemBits.h"
#import "WebKitVersionChecks.h"
#import "WebLocalizableStrings.h"
#import "WebNSDataExtras.h"
#import "WebNSDataExtrasPrivate.h"
#import "WebNSDictionaryExtras.h"
#import "WebNSEventExtras.h"
#import "WebNSObjectExtras.h"
#import "WebNSPasteboardExtras.h"
#import "WebNSPrintOperationExtras.h"
#import "WebNSURLExtras.h"
#import "WebNSURLRequestExtras.h"
#import "WebNSViewExtras.h"
#import "WebNodeHighlight.h"
#import "WebPDFView.h"
#import "WebPanelAuthenticationHandler.h"
#import "WebPlatformStrategies.h"
#import "WebPluginDatabase.h"
#import "WebPluginHalterClient.h"
#import "WebPolicyDelegate.h"
#import "WebPreferenceKeysPrivate.h"
#import "WebPreferencesPrivate.h"
#import "WebScriptDebugDelegate.h"
#import "WebScriptWorldInternal.h"
#import "WebStorageManagerInternal.h"
#import "WebSystemInterface.h"
#import "WebTextCompletionController.h"
#import "WebTextIterator.h"
#import "WebUIDelegate.h"
#import "WebUIDelegatePrivate.h"
#import "WebVideoFullscreenController.h"
#import <CoreFoundation/CFSet.h>
#import <Foundation/NSURLConnection.h>
#import <JavaScriptCore/APICast.h>
#import <JavaScriptCore/JSValueRef.h>
#import <WebCore/AbstractDatabase.h>
#import <WebCore/ApplicationCacheStorage.h>
#import <WebCore/BackForwardListImpl.h>
#import <WebCore/MemoryCache.h>
#import <WebCore/ColorMac.h>
#import <WebCore/CSSComputedStyleDeclaration.h>
#import <WebCore/Cursor.h>
#import <WebCore/Document.h>
#import <WebCore/DocumentLoader.h>
#import <WebCore/DragController.h>
#import <WebCore/DragData.h>
#import <WebCore/Editor.h>
#import <WebCore/EventHandler.h>
#import <WebCore/ExceptionHandlers.h>
#import <WebCore/FocusController.h>
#import <WebCore/Frame.h>
#import <WebCore/FrameLoader.h>
#import <WebCore/FrameTree.h>
#import <WebCore/FrameView.h>
#import <WebCore/GCController.h>
#import <WebCore/HTMLMediaElement.h>
#import <WebCore/HTMLNames.h>
#import <WebCore/HistoryItem.h>
#import <WebCore/IconDatabase.h>
#import <WebCore/JSCSSStyleDeclaration.h>
#import <WebCore/JSDocument.h>
#import <WebCore/JSElement.h>
#import <WebCore/JSNodeList.h>
#import <WebCore/Logging.h>
#import <WebCore/MIMETypeRegistry.h>
#import <WebCore/NodeList.h>
#import <WebCore/Page.h>
#import <WebCore/PageCache.h>
#import <WebCore/PageGroup.h>
#import <WebCore/PlatformMouseEvent.h>
#import <WebCore/ProgressTracker.h>
#import <WebCore/RenderView.h>
#import <WebCore/RenderWidget.h>
#import <WebCore/ResourceHandle.h>
#import <WebCore/ResourceLoadScheduler.h>
#import <WebCore/ResourceRequest.h>
#import <WebCore/RuntimeApplicationChecks.h>
#import <WebCore/SchemeRegistry.h>
#import <WebCore/ScriptController.h>
#import <WebCore/ScriptValue.h>
#import <WebCore/SecurityOrigin.h>
#import <WebCore/SelectionController.h>
#import <WebCore/Settings.h>
#import <WebCore/TextResourceDecoder.h>
#import <WebCore/ThreadCheck.h>
#import <WebCore/WebCoreObjCExtras.h>
#import <WebCore/WebCoreView.h>
#import <WebCore/Widget.h>
#import <WebKit/DOM.h>
#import <WebKit/DOMExtensions.h>
#import <WebKit/DOMPrivate.h>
#import <WebKitSystemInterface.h>
#import <mach-o/dyld.h>
#import <objc/objc-auto.h>
#import <objc/objc-runtime.h>
#import <runtime/ArrayPrototype.h>
#import <runtime/DateInstance.h>
#import <runtime/InitializeThreading.h>
#import <runtime/JSLock.h>
#import <runtime/JSValue.h>
#import <wtf/Assertions.h>
#import <wtf/HashTraits.h>
#import <wtf/RefCountedLeakCounter.h>
#import <wtf/RefPtr.h>
#import <wtf/StdLibExtras.h>
#import <wtf/Threading.h>
#if ENABLE(DASHBOARD_SUPPORT)
#import <WebKit/WebDashboardRegion.h>
#endif
#if ENABLE(CLIENT_BASED_GEOLOCATION)
#import <WebCore/GeolocationController.h>
#import <WebCore/GeolocationError.h>
#endif
#if ENABLE(GLIB_SUPPORT)
#import <glib.h>
#endif
@interface NSSpellChecker (WebNSSpellCheckerDetails)
- (void)_preflightChosenSpellServer;
@end
@interface NSView (WebNSViewDetails)
- (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
- (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
- (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
@end
@interface NSWindow (WebNSWindowDetails)
- (id)_oldFirstResponderBeforeBecoming;
- (void)_enableScreenUpdatesIfNeeded;
- (BOOL)_wrapsCarbonWindow;
@end
using namespace WebCore;
using namespace JSC;
#if defined(__ppc__) || defined(__ppc64__)
#define PROCESSOR "PPC"
#elif defined(__i386__) || defined(__x86_64__)
#define PROCESSOR "Intel"
#else
#error Unknown architecture
#endif
#define FOR_EACH_RESPONDER_SELECTOR(macro) \
macro(alignCenter) \
macro(alignJustified) \
macro(alignLeft) \
macro(alignRight) \
macro(capitalizeWord) \
macro(centerSelectionInVisibleArea) \
macro(changeAttributes) \
macro(changeBaseWritingDirection) \
macro(changeBaseWritingDirectionToLTR) \
macro(changeBaseWritingDirectionToRTL) \
macro(changeColor) \
macro(changeDocumentBackgroundColor) \
macro(changeFont) \
macro(changeSpelling) \
macro(checkSpelling) \
macro(complete) \
macro(copy) \
macro(copyFont) \
macro(cut) \
macro(delete) \
macro(deleteBackward) \
macro(deleteBackwardByDecomposingPreviousCharacter) \
macro(deleteForward) \
macro(deleteToBeginningOfLine) \
macro(deleteToBeginningOfParagraph) \
macro(deleteToEndOfLine) \
macro(deleteToEndOfParagraph) \
macro(deleteToMark) \
macro(deleteWordBackward) \
macro(deleteWordForward) \
macro(ignoreSpelling) \
macro(indent) \
macro(insertBacktab) \
macro(insertLineBreak) \
macro(insertNewline) \
macro(insertNewlineIgnoringFieldEditor) \
macro(insertParagraphSeparator) \
macro(insertTab) \
macro(insertTabIgnoringFieldEditor) \
macro(lowercaseWord) \
macro(makeBaseWritingDirectionLeftToRight) \
macro(makeBaseWritingDirectionRightToLeft) \
macro(makeTextWritingDirectionLeftToRight) \
macro(makeTextWritingDirectionNatural) \
macro(makeTextWritingDirectionRightToLeft) \
macro(moveBackward) \
macro(moveBackwardAndModifySelection) \
macro(moveDown) \
macro(moveDownAndModifySelection) \
macro(moveForward) \
macro(moveForwardAndModifySelection) \
macro(moveLeft) \
macro(moveLeftAndModifySelection) \
macro(moveParagraphBackwardAndModifySelection) \
macro(moveParagraphForwardAndModifySelection) \
macro(moveRight) \
macro(moveRightAndModifySelection) \
macro(moveToBeginningOfDocument) \
macro(moveToBeginningOfDocumentAndModifySelection) \
macro(moveToBeginningOfLine) \
macro(moveToBeginningOfLineAndModifySelection) \
macro(moveToBeginningOfParagraph) \
macro(moveToBeginningOfParagraphAndModifySelection) \
macro(moveToBeginningOfSentence) \
macro(moveToBeginningOfSentenceAndModifySelection) \
macro(moveToEndOfDocument) \
macro(moveToEndOfDocumentAndModifySelection) \
macro(moveToEndOfLine) \
macro(moveToEndOfLineAndModifySelection) \
macro(moveToEndOfParagraph) \
macro(moveToEndOfParagraphAndModifySelection) \
macro(moveToEndOfSentence) \
macro(moveToEndOfSentenceAndModifySelection) \
macro(moveToLeftEndOfLine) \
macro(moveToLeftEndOfLineAndModifySelection) \
macro(moveToRightEndOfLine) \
macro(moveToRightEndOfLineAndModifySelection) \
macro(moveUp) \
macro(moveUpAndModifySelection) \
macro(moveWordBackward) \
macro(moveWordBackwardAndModifySelection) \
macro(moveWordForward) \
macro(moveWordForwardAndModifySelection) \
macro(moveWordLeft) \
macro(moveWordLeftAndModifySelection) \
macro(moveWordRight) \
macro(moveWordRightAndModifySelection) \
macro(outdent) \
macro(orderFrontSubstitutionsPanel) \
macro(pageDown) \
macro(pageDownAndModifySelection) \
macro(pageUp) \
macro(pageUpAndModifySelection) \
macro(paste) \
macro(pasteAsPlainText) \
macro(pasteAsRichText) \
macro(pasteFont) \
macro(performFindPanelAction) \
macro(scrollLineDown) \
macro(scrollLineUp) \
macro(scrollPageDown) \
macro(scrollPageUp) \
macro(scrollToBeginningOfDocument) \
macro(scrollToEndOfDocument) \
macro(selectAll) \
macro(selectLine) \
macro(selectParagraph) \
macro(selectSentence) \
macro(selectToMark) \
macro(selectWord) \
macro(setMark) \
macro(showGuessPanel) \
macro(startSpeaking) \
macro(stopSpeaking) \
macro(subscript) \
macro(superscript) \
macro(swapWithMark) \
macro(takeFindStringFromSelection) \
macro(toggleBaseWritingDirection) \
macro(transpose) \
macro(underline) \
macro(unscript) \
macro(uppercaseWord) \
macro(yank) \
macro(yankAndSelect) \
#define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
#define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
#define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
#define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
#define UniversalAccessDomain CFSTR("com.apple.universalaccess")
static BOOL s_didSetCacheModel;
static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
#ifndef NDEBUG
static const char webViewIsOpen[] = "At least one WebView is still open.";
#endif
@interface NSObject (WebValidateWithoutDelegate)
- (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
@end
@interface _WebSafeForwarder : NSObject
{
id target; // Non-retained. Don't retain delegates.
id defaultTarget;
BOOL catchExceptions;
}
- (id)initWithTarget:(id)target defaultTarget:(id)defaultTarget catchExceptions:(BOOL)catchExceptions;
@end
@interface WebView (WebFileInternal)
- (BOOL)_isLoading;
- (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
- (WebFrame *)_focusedFrame;
+ (void)_preflightSpellChecker;
- (BOOL)_continuousCheckingAllowed;
- (NSResponder *)_responderForResponderOperations;
#if USE(ACCELERATED_COMPOSITING)
- (void)_clearLayerSyncLoopObserver;
#endif
#if ENABLE(GLIB_SUPPORT)
- (void)_clearGlibLoopObserver;
#endif
@end
static void patchMailRemoveAttributesMethod();
NSString *WebElementDOMNodeKey = @"WebElementDOMNode";
NSString *WebElementFrameKey = @"WebElementFrame";
NSString *WebElementImageKey = @"WebElementImage";
NSString *WebElementImageAltStringKey = @"WebElementImageAltString";
NSString *WebElementImageRectKey = @"WebElementImageRect";
NSString *WebElementImageURLKey = @"WebElementImageURL";
NSString *WebElementIsSelectedKey = @"WebElementIsSelected";
NSString *WebElementLinkLabelKey = @"WebElementLinkLabel";
NSString *WebElementLinkTargetFrameKey = @"WebElementTargetFrame";
NSString *WebElementLinkTitleKey = @"WebElementLinkTitle";
NSString *WebElementLinkURLKey = @"WebElementLinkURL";
NSString *WebElementMediaURLKey = @"WebElementMediaURL";
NSString *WebElementSpellingToolTipKey = @"WebElementSpellingToolTip";
NSString *WebElementTitleKey = @"WebElementTitle";
NSString *WebElementLinkIsLiveKey = @"WebElementLinkIsLive";
NSString *WebElementIsInScrollBarKey = @"WebElementIsInScrollBar";
NSString *WebElementIsContentEditableKey = @"WebElementIsContentEditableKey";
NSString *WebViewProgressStartedNotification = @"WebProgressStartedNotification";
NSString *WebViewProgressEstimateChangedNotification = @"WebProgressEstimateChangedNotification";
NSString *WebViewProgressFinishedNotification = @"WebProgressFinishedNotification";
NSString * const WebViewDidBeginEditingNotification = @"WebViewDidBeginEditingNotification";
NSString * const WebViewDidChangeNotification = @"WebViewDidChangeNotification";
NSString * const WebViewDidEndEditingNotification = @"WebViewDidEndEditingNotification";
NSString * const WebViewDidChangeTypingStyleNotification = @"WebViewDidChangeTypingStyleNotification";
NSString * const WebViewDidChangeSelectionNotification = @"WebViewDidChangeSelectionNotification";
enum { WebViewVersion = 4 };
#define timedLayoutSize 4096
static NSMutableSet *schemesWithRepresentationsSet;
NSString *_WebCanGoBackKey = @"canGoBack";
NSString *_WebCanGoForwardKey = @"canGoForward";
NSString *_WebEstimatedProgressKey = @"estimatedProgress";
NSString *_WebIsLoadingKey = @"isLoading";
NSString *_WebMainFrameIconKey = @"mainFrameIcon";
NSString *_WebMainFrameTitleKey = @"mainFrameTitle";
NSString *_WebMainFrameURLKey = @"mainFrameURL";
NSString *_WebMainFrameDocumentKey = @"mainFrameDocument";
NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
@interface WebProgressItem : NSObject
{
@public
long long bytesReceived;
long long estimatedLength;
}
@end
@implementation WebProgressItem
@end
static BOOL continuousSpellCheckingEnabled;
#ifndef BUILDING_ON_TIGER
static BOOL grammarCheckingEnabled;
#endif
#if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
static BOOL automaticQuoteSubstitutionEnabled;
static BOOL automaticLinkDetectionEnabled;
static BOOL automaticDashSubstitutionEnabled;
static BOOL automaticTextReplacementEnabled;
static BOOL automaticSpellingCorrectionEnabled;
#endif
@implementation WebView (AllWebViews)
static CFSetCallBacks NonRetainingSetCallbacks = {
0,
NULL,
NULL,
CFCopyDescription,
CFEqual,
CFHash
};
static CFMutableSetRef allWebViewsSet;
+ (void)_makeAllWebViewsPerformSelector:(SEL)selector
{
if (!allWebViewsSet)
return;
[(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
}
- (void)_removeFromAllWebViewsSet
{
if (allWebViewsSet)
CFSetRemoveValue(allWebViewsSet, self);
}
- (void)_addToAllWebViewsSet
{
if (!allWebViewsSet)
allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
CFSetSetValue(allWebViewsSet, self);
}
@end
@implementation WebView (WebPrivate)
static inline int callGestalt(OSType selector)
{
SInt32 value = 0;
Gestalt(selector, &value);
return value;
}
// Uses underscores instead of dots because if "4." ever appears in a user agent string, old DHTML libraries treat it as Netscape 4.
static NSString *createMacOSXVersionString()
{
// Can't use -[NSProcessInfo operatingSystemVersionString] because it has too much stuff we don't want.
int major = callGestalt(gestaltSystemVersionMajor);
ASSERT(major);
int minor = callGestalt(gestaltSystemVersionMinor);
int bugFix = callGestalt(gestaltSystemVersionBugFix);
if (bugFix)
return [[NSString alloc] initWithFormat:@"%d_%d_%d", major, minor, bugFix];
if (minor)
return [[NSString alloc] initWithFormat:@"%d_%d", major, minor];
return [[NSString alloc] initWithFormat:@"%d", major];
}
static NSString *createUserVisibleWebKitVersionString()
{
// If the version is 4 digits long or longer, then the first digit represents
// the version of the OS. Our user agent string should not include this first digit,
// so strip it off and report the rest as the version. <rdar://problem/4997547>
NSString *fullVersion = [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
NSRange nonDigitRange = [fullVersion rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
if (nonDigitRange.location == NSNotFound && [fullVersion length] >= 4)
return [[fullVersion substringFromIndex:1] copy];
if (nonDigitRange.location != NSNotFound && nonDigitRange.location >= 4)
return [[fullVersion substringFromIndex:1] copy];
return [fullVersion copy];
}
+ (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
{
// Note: Do *not* move the initialization of osVersion nor webKitVersion into the declaration.
// Garbage collection won't correctly mark the global variable in that case <rdar://problem/5733674>.
static NSString *osVersion;
static NSString *webKitVersion;
if (!osVersion)
osVersion = createMacOSXVersionString();
if (!webKitVersion)
webKitVersion = createUserVisibleWebKitVersionString();
if ([applicationName length])
return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; " PROCESSOR " Mac OS X %@) AppleWebKit/%@ (KHTML, like Gecko) %@", osVersion, webKitVersion, applicationName];
return [NSString stringWithFormat:@"Mozilla/5.0 (Macintosh; " PROCESSOR " Mac OS X %@) AppleWebKit/%@ (KHTML, like Gecko)", osVersion, webKitVersion];
}
+ (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
{
if (!exception || !context)
return;
JSLock lock(SilenceAssertionsOnly);
JSC::ExecState* execState = toJS(context);
// Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
if (!toJSDOMWindow(execState->lexicalGlobalObject()))
return;
reportException(execState, toJS(execState, exception));
}
static void WebKitInitializeApplicationCachePathIfNecessary()
{
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
static BOOL initialized = NO;
if (initialized)
return;
NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
if (!appName)
appName = [[NSProcessInfo processInfo] processName];
ASSERT(appName);
NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
cacheStorage().setCacheDirectory(cacheDir);
initialized = YES;
#endif
}
static bool runningLeopardMail()
{
#ifdef BUILDING_ON_LEOPARD
return applicationIsAppleMail();
#endif
return NO;
}
static bool runningTigerMail()
{
#ifdef BUILDING_ON_TIGER
return applicationIsAppleMail();
#endif
return NO;
}
static bool coreVideoHas7228836Fix()
{
#ifdef BUILDING_ON_LEOPARD
NSBundle* coreVideoFrameworkBundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/CoreVideo.framework"];
double version = [[coreVideoFrameworkBundle objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey] doubleValue];
return (version >= 48);
#endif
return true;
}
static bool shouldEnableLoadDeferring()
{
return !applicationIsAdobeInstaller();
}
- (void)_dispatchPendingLoadRequests
{
resourceLoadScheduler()->servePendingRequests();
}
- (void)_registerDraggedTypes
{
NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
[types addObjectsFromArray:URLTypes];
[self registerForDraggedTypes:[types allObjects]];
[types release];
}
- (BOOL)_usesDocumentViews
{
return _private->usesDocumentViews;
}
static NSString *leakMailQuirksUserScriptContents()
{
NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"MailQuirksUserScript" ofType:@"js"];
NSStringEncoding encoding;
return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
}
- (void)_injectMailQuirksScript
{
static NSString *mailQuirksScriptContents = leakMailQuirksUserScriptContents();
core(self)->group().addUserScriptToWorld(core([WebScriptWorld world]),
mailQuirksScriptContents, KURL(), 0, 0, InjectAtDocumentEnd, InjectInAllFrames);
}
static bool needsOutlookQuirksScript()
{
static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
&& applicationIsMicrosoftOutlook();
return isOutlookNeedingQuirksScript;
}
static NSString *leakOutlookQuirksUserScriptContents()
{
NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
NSStringEncoding encoding;
return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
}
-(void)_injectOutlookQuirksScript
{
static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
core(self)->group().addUserScriptToWorld(core([WebScriptWorld world]),
outlookQuirksScriptContents, KURL(), 0, 0, InjectAtDocumentEnd, InjectInAllFrames);
}
- (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName usesDocumentViews:(BOOL)usesDocumentViews
{
WebCoreThreadViolationCheckRoundTwo();
#ifndef NDEBUG
WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
#endif
WebPreferences *standardPreferences = [WebPreferences standardPreferences];
[standardPreferences willAddToWebView];
_private->preferences = [standardPreferences retain];
_private->catchesDelegateExceptions = YES;
_private->mainFrameDocumentReady = NO;
_private->drawsBackground = YES;
_private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
_private->usesDocumentViews = usesDocumentViews;
_private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
WebFrameView *frameView = nil;
if (_private->usesDocumentViews) {
NSRect f = [self frame];
frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
[frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[self addSubview:frameView];
[frameView release];
}
static bool didOneTimeInitialization = false;
if (!didOneTimeInitialization) {
WebKitInitializeLoggingChannelsIfNecessary();
WebCore::InitializeLoggingChannelsIfNecessary();
[WebHistoryItem initWindowWatcherIfNecessary];
#if ENABLE(DATABASE)
WebKitInitializeDatabasesIfNecessary();
#endif
#if ENABLE(DOM_STORAGE)
WebKitInitializeStorageIfNecessary();
#endif
WebKitInitializeApplicationCachePathIfNecessary();
patchMailRemoveAttributesMethod();
// Initialize our platform strategies.
WebPlatformStrategies::initialize();
Settings::setDefaultMinDOMTimerInterval(0.004);
didOneTimeInitialization = true;
}
Page::PageClients pageClients;
pageClients.chromeClient = new WebChromeClient(self);
pageClients.contextMenuClient = new WebContextMenuClient(self);
pageClients.editorClient = new WebEditorClient(self);
pageClients.dragClient = new WebDragClient(self);
pageClients.inspectorClient = new WebInspectorClient(self);
pageClients.pluginHalterClient = new WebPluginHalterClient(self);
#if ENABLE(CLIENT_BASED_GEOLOCATION)
pageClients.geolocationClient = new WebGeolocationClient(self);
#endif
#if ENABLE(DEVICE_ORIENTATION)
pageClients.deviceOrientationClient = new WebDeviceOrientationClient(self);
#endif
_private->page = new Page(pageClients);
_private->page->setCanStartMedia([self window]);
_private->page->settings()->setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
if (needsOutlookQuirksScript()) {
_private->page->settings()->setShouldInjectUserScriptsInInitialEmptyDocument(true);
[self _injectOutlookQuirksScript];
}
[WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
#ifndef BUILDING_ON_TIGER
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
#else
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
#endif
if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
[self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
else
[self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
[self _addToAllWebViewsSet];
[self setGroupName:groupName];
// If there's already a next key view (e.g., from a nib), wire it up to our
// contained frame view. In any case, wire our next key view up to the our
// contained frame view. This works together with our becomeFirstResponder
// and setNextKeyView overrides.
NSView *nextKeyView = [self nextKeyView];
if (nextKeyView && nextKeyView != frameView)
[frameView setNextKeyView:nextKeyView];
[super setNextKeyView:frameView];
if ([[self class] shouldIncludeInWebKitStatistics])
++WebViewCount;
[self _registerDraggedTypes];
WebPreferences *prefs = [self preferences];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
name:WebPreferencesChangedInternalNotification object:prefs];
[self _preferencesChanged:[self preferences]];
[[self preferences] _postPreferencesChangedAPINotification];
if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
// Originally, we allowed all local loads.
SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForAll);
} else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
// Later, we allowed local loads for local URLs and documents loaded
// with substitute data.
SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForLocalAndSubstituteData);
}
if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
ResourceHandle::forceContentSniffing();
#if ENABLE(GLIB_SUPPORT)
[self _scheduleGlibContextIterations];
#endif
if (runningTigerMail() || runningLeopardMail())
[self _injectMailQuirksScript];
}
- (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName usesDocumentViews:(BOOL)usesDocumentViews
{
self = [super initWithFrame:f];
if (!self)
return nil;
#ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
// DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
// may not work with other WebKit applications. Unsetting DYLD_FRAMEWORK_PATH removes the
// need for Safari to unset it to prevent it from being passed to applications it launches.
// Unsetting it when a WebView is first created is as good a place as any.
// See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
unsetenv("DYLD_FRAMEWORK_PATH");
unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
}
#endif
_private = [[WebViewPrivate alloc] init];
[self _commonInitializationWithFrameName:frameName groupName:groupName usesDocumentViews:usesDocumentViews];
[self setMaintainsBackForwardList: YES];
return self;
}
- (BOOL)_mustDrawUnionedRect:(NSRect)rect singleRects:(const NSRect *)rects count:(NSInteger)count
{
// If count == 0 here, use the rect passed in for drawing. This is a workaround for:
// <rdar://problem/3908282> REGRESSION (Mail): No drag image dragging selected text in Blot and Mail
// The reason for the workaround is that this method is called explicitly from the code
// to generate a drag image, and at that time, getRectsBeingDrawn:count: will return a zero count.
const int cRectThreshold = 10;
const float cWastedSpaceThreshold = 0.75f;
BOOL useUnionedRect = (count <= 1) || (count > cRectThreshold);
if (!useUnionedRect) {
// Attempt to guess whether or not we should use the unioned rect or the individual rects.
// We do this by computing the percentage of "wasted space" in the union. If that wasted space
// is too large, then we will do individual rect painting instead.
float unionPixels = (rect.size.width * rect.size.height);
float singlePixels = 0;
for (int i = 0; i < count; ++i)
singlePixels += rects[i].size.width * rects[i].size.height;
float wastedSpace = 1 - (singlePixels / unionPixels);
if (wastedSpace <= cWastedSpaceThreshold)
useUnionedRect = YES;
}
return useUnionedRect;
}
- (void)drawSingleRect:(NSRect)rect
{
ASSERT(!_private->usesDocumentViews);
[NSGraphicsContext saveGraphicsState];
NSRectClip(rect);
@try {
[[self mainFrame] _drawRect:rect contentsOnly:NO];
[[self _UIDelegateForwarder] webView:self didDrawRect:rect];
if (WebNodeHighlight *currentHighlight = [self currentNodeHighlight])
[currentHighlight setNeedsUpdateInTargetViewRect:rect];
[NSGraphicsContext restoreGraphicsState];
} @catch (NSException *localException) {
[NSGraphicsContext restoreGraphicsState];
LOG_ERROR("Exception caught while drawing: %@", localException);
[localException raise];
}
}
- (BOOL)isFlipped
{
return _private && !_private->usesDocumentViews;
}
- (void)setFrameSize:(NSSize)size
{
if (!_private->usesDocumentViews && !NSEqualSizes(_private->lastLayoutSize, size)) {
Frame* frame = [self _mainCoreFrame];
// FIXME: Viewless WebKit is broken with Safari banners (e.g., the Find banner). We'll have to figure out a way for
// Safari to communicate that this space is being consumed. For WebKit with document views, there's no
// need to do an explicit resize, since WebFrameViews have auto resizing turned on and will handle changing
// their bounds automatically. See <rdar://problem/6835573> for details.
frame->view()->resize(IntSize(size));
frame->view()->setNeedsLayout();
[self setNeedsDisplay:YES];
_private->lastLayoutSize = size;
}
[super setFrameSize:size];
}
#if USE(ACCELERATED_COMPOSITING) || !defined(BUILDING_ON_TIGER)
- (void)_viewWillDrawInternal
{
Frame* frame = [self _mainCoreFrame];
if (frame && frame->view())
frame->view()->updateLayoutAndStyleIfNeededRecursive();
}
#endif
#ifndef BUILDING_ON_TIGER
- (void)viewWillDraw
{
if (!_private->usesDocumentViews)
[self _viewWillDrawInternal];
[super viewWillDraw];
}
#endif
- (void)drawRect:(NSRect)rect
{
if (_private->usesDocumentViews)
return [super drawRect:rect];
ASSERT_MAIN_THREAD();
const NSRect *rects;
NSInteger count;
[self getRectsBeingDrawn:&rects count:&count];
if ([self _mustDrawUnionedRect:rect singleRects:rects count:count])
[self drawSingleRect:rect];
else
for (int i = 0; i < count; ++i)
[self drawSingleRect:rects[i]];
}
+ (NSArray *)_supportedMIMETypes
{
// Load the plug-in DB allowing plug-ins to install types.
[WebPluginDatabase sharedDatabase];
return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
}
+ (NSArray *)_supportedFileExtensions
{
NSMutableSet *extensions = [[NSMutableSet alloc] init];
NSArray *MIMETypes = [self _supportedMIMETypes];
NSEnumerator *enumerator = [MIMETypes objectEnumerator];
NSString *MIMEType;
while ((MIMEType = [enumerator nextObject]) != nil) {
NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
if (extensionsForType) {
[extensions addObjectsFromArray:extensionsForType];
}
}
NSArray *uniqueExtensions = [extensions allObjects];
[extensions release];
return uniqueExtensions;
}
static NSMutableSet *knownPluginMIMETypes()
{
static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
return mimeTypes;
}
+ (void)_registerPluginMIMEType:(NSString *)MIMEType
{
[WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
[knownPluginMIMETypes() addObject:MIMEType];
}
+ (void)_unregisterPluginMIMEType:(NSString *)MIMEType
{
[self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
[knownPluginMIMETypes() removeObject:MIMEType];
}
+ (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
{
MIMEType = [MIMEType lowercaseString];
Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
// Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
if (allowPlugins) {
// Load the plug-in DB allowing plug-ins to install types.
[WebPluginDatabase sharedDatabase];
}
// Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
}