Implement yellow highlight for WebKit1 data detectors
[WebKit-https.git] / Source / WebKit / mac / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005-2013 Apple Inc. All rights reserved.
3  * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4  * Copyright (C) 2010 Igalia S.L
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer. 
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution. 
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission. 
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #import "WebViewInternal.h"
32 #import "WebViewData.h"
33
34 #import "DOMCSSStyleDeclarationInternal.h"
35 #import "DOMDocumentInternal.h"
36 #import "DOMNodeInternal.h"
37 #import "DOMRangeInternal.h"
38 #import "WebAlternativeTextClient.h"
39 #import "WebApplicationCache.h"
40 #import "WebBackForwardListInternal.h"
41 #import "WebBaseNetscapePluginView.h"
42 #import "WebCache.h"
43 #import "WebChromeClient.h"
44 #import "WebDOMOperationsPrivate.h"
45 #import "WebDataSourceInternal.h"
46 #import "WebDatabaseManagerPrivate.h"
47 #import "WebDefaultEditingDelegate.h"
48 #import "WebDefaultPolicyDelegate.h"
49 #import "WebDefaultUIDelegate.h"
50 #import "WebDelegateImplementationCaching.h"
51 #import "WebDeviceOrientationClient.h"
52 #import "WebDeviceOrientationProvider.h"
53 #import "WebDocument.h"
54 #import "WebDocumentInternal.h"
55 #import "WebDownload.h"
56 #import "WebDownloadInternal.h"
57 #import "WebDragClient.h"
58 #import "WebDynamicScrollBarsViewInternal.h"
59 #import "WebEditingDelegate.h"
60 #import "WebEditorClient.h"
61 #import "WebFormDelegatePrivate.h"
62 #import "WebFrameInternal.h"
63 #import "WebFrameLoaderClient.h"
64 #import "WebFrameNetworkingContext.h"
65 #import "WebFrameViewInternal.h"
66 #import "WebGeolocationClient.h"
67 #import "WebGeolocationPositionInternal.h"
68 #import "WebHTMLRepresentation.h"
69 #import "WebHTMLViewInternal.h"
70 #import "WebHistoryItemInternal.h"
71 #import "WebIconDatabaseInternal.h"
72 #import "WebInspector.h"
73 #import "WebInspectorClient.h"
74 #import "WebKitErrors.h"
75 #import "WebKitFullScreenListener.h"
76 #import "WebKitLogging.h"
77 #import "WebKitNSStringExtras.h"
78 #import "WebKitStatisticsPrivate.h"
79 #import "WebKitSystemBits.h"
80 #import "WebKitVersionChecks.h"
81 #import "WebLocalizableStrings.h"
82 #import "WebNSDataExtras.h"
83 #import "WebNSDataExtrasPrivate.h"
84 #import "WebNSDictionaryExtras.h"
85 #import "WebNSURLExtras.h"
86 #import "WebNSURLRequestExtras.h"
87 #import "WebNSViewExtras.h"
88 #import "WebNodeHighlight.h"
89 #import "WebNotificationClient.h"
90 #import "WebPDFView.h"
91 #import "WebPanelAuthenticationHandler.h"
92 #import "WebPlatformStrategies.h"
93 #import "WebPluginDatabase.h"
94 #import "WebPolicyDelegate.h"
95 #import "WebPreferenceKeysPrivate.h"
96 #import "WebPreferencesPrivate.h"
97 #import "WebProgressTrackerClient.h"
98 #import "WebScriptDebugDelegate.h"
99 #import "WebScriptWorldInternal.h"
100 #import "WebSelectionServiceController.h"
101 #import "WebStorageManagerInternal.h"
102 #import "WebSystemInterface.h"
103 #import "WebTextCompletionController.h"
104 #import "WebTextIterator.h"
105 #import "WebUIDelegate.h"
106 #import "WebUIDelegatePrivate.h"
107 #import "WebUserMediaClient.h"
108 #import "WebViewGroup.h"
109 #import "WebVisitedLinkStore.h"
110 #import <CoreFoundation/CFSet.h>
111 #import <Foundation/NSURLConnection.h>
112 #import <JavaScriptCore/APICast.h>
113 #import <JavaScriptCore/JSValueRef.h>
114 #import <WebCore/AlternativeTextUIController.h>
115 #import <WebCore/AnimationController.h>
116 #import <WebCore/ApplicationCacheStorage.h>
117 #import <WebCore/BackForwardController.h>
118 #import <WebCore/BackForwardList.h>
119 #import <WebCore/CFNetworkSPI.h>
120 #import <WebCore/Chrome.h>
121 #import <WebCore/ColorMac.h>
122 #import <WebCore/Cursor.h>
123 #import <WebCore/DatabaseManager.h>
124 #import <WebCore/Document.h>
125 #import <WebCore/DocumentLoader.h>
126 #import <WebCore/DragController.h>
127 #import <WebCore/DragData.h>
128 #import <WebCore/Editor.h>
129 #import <WebCore/EventHandler.h>
130 #import <WebCore/ExceptionHandlers.h>
131 #import <WebCore/FocusController.h>
132 #import <WebCore/FrameLoader.h>
133 #import <WebCore/FrameSelection.h>
134 #import <WebCore/FrameTree.h>
135 #import <WebCore/FrameView.h>
136 #import <WebCore/GCController.h>
137 #import <WebCore/GeolocationController.h>
138 #import <WebCore/GeolocationError.h>
139 #import <WebCore/HTMLNames.h>
140 #import <WebCore/HTMLVideoElement.h>
141 #import <WebCore/HistoryController.h>
142 #import <WebCore/HistoryItem.h>
143 #import <WebCore/IconDatabase.h>
144 #import <WebCore/JSCSSStyleDeclaration.h>
145 #import <WebCore/JSDocument.h>
146 #import <WebCore/JSElement.h>
147 #import <WebCore/JSNodeList.h>
148 #import <WebCore/JSNotification.h>
149 #import <WebCore/Logging.h>
150 #import <WebCore/MIMETypeRegistry.h>
151 #import <WebCore/MainFrame.h>
152 #import <WebCore/MemoryCache.h>
153 #import <WebCore/MemoryPressureHandler.h>
154 #import <WebCore/NSURLFileTypeMappingsSPI.h>
155 #import <WebCore/NodeList.h>
156 #import <WebCore/Notification.h>
157 #import <WebCore/NotificationController.h>
158 #import <WebCore/Page.h>
159 #import <WebCore/PageCache.h>
160 #import <WebCore/PageConfiguration.h>
161 #import <WebCore/PageGroup.h>
162 #import <WebCore/PlatformEventFactoryMac.h>
163 #import <WebCore/ProgressTracker.h>
164 #import <WebCore/RenderView.h>
165 #import <WebCore/RenderWidget.h>
166 #import <WebCore/ResourceHandle.h>
167 #import <WebCore/ResourceLoadScheduler.h>
168 #import <WebCore/ResourceRequest.h>
169 #import <WebCore/RuntimeApplicationChecks.h>
170 #import <WebCore/RuntimeEnabledFeatures.h>
171 #import <WebCore/SchemeRegistry.h>
172 #import <WebCore/ScriptController.h>
173 #import <WebCore/SecurityOrigin.h>
174 #import <WebCore/SecurityPolicy.h>
175 #import <WebCore/Settings.h>
176 #import <WebCore/StyleProperties.h>
177 #import <WebCore/TextResourceDecoder.h>
178 #import <WebCore/ThreadCheck.h>
179 #import <WebCore/UserAgent.h>
180 #import <WebCore/UserContentController.h>
181 #import <WebCore/WebCoreObjCExtras.h>
182 #import <WebCore/WebCoreView.h>
183 #import <WebCore/Widget.h>
184 #import <WebKitLegacy/DOM.h>
185 #import <WebKitLegacy/DOMExtensions.h>
186 #import <WebKitLegacy/DOMPrivate.h>
187 #import <WebKitSystemInterface.h>
188 #import <bindings/ScriptValue.h>
189 #import <mach-o/dyld.h>
190 #import <objc/objc-auto.h>
191 #import <objc/runtime.h>
192 #import <runtime/ArrayPrototype.h>
193 #import <runtime/DateInstance.h>
194 #import <runtime/InitializeThreading.h>
195 #import <runtime/JSCJSValue.h>
196 #import <runtime/JSLock.h>
197 #import <wtf/Assertions.h>
198 #import <wtf/HashTraits.h>
199 #import <wtf/MainThread.h>
200 #import <wtf/ObjcRuntimeExtras.h>
201 #import <wtf/RefCountedLeakCounter.h>
202 #import <wtf/RefPtr.h>
203 #import <wtf/RunLoop.h>
204 #import <wtf/StdLibExtras.h>
205
206 #if !PLATFORM(IOS)
207 #import "WebActionMenuController.h"
208 #import "WebContextMenuClient.h"
209 #import "WebFullScreenController.h"
210 #import "WebNSEventExtras.h"
211 #import "WebNSObjectExtras.h"
212 #import "WebNSPasteboardExtras.h"
213 #import "WebNSPrintOperationExtras.h"
214 #import "WebPDFView.h"
215 #import <WebCore/NSViewSPI.h>
216 #import <WebCore/TextIndicator.h>
217 #import <WebCore/TextIndicatorWindow.h>
218 #import <WebCore/WebVideoFullscreenController.h>
219 #else
220 #import "MemoryMeasure.h"
221 #import "WebCaretChangeListener.h"
222 #import "WebChromeClientIOS.h"
223 #import "WebDefaultFormDelegate.h"
224 #import "WebDefaultFrameLoadDelegate.h"
225 #import "WebDefaultResourceLoadDelegate.h"
226 #import "WebDefaultUIKitDelegate.h"
227 #import "WebFixedPositionContent.h"
228 #import "WebMailDelegate.h"
229 #import "WebNSUserDefaultsExtras.h"
230 #import "WebPDFViewIOS.h"
231 #import "WebPlainWhiteView.h"
232 #import "WebPluginController.h"
233 #import "WebPolicyDelegatePrivate.h"
234 #import "WebSQLiteDatabaseTrackerClient.h"
235 #import "WebStorageManagerPrivate.h"
236 #import "WebUIKitSupport.h"
237 #import "WebVisiblePosition.h"
238 #import <WebCore/DispatchSPI.h>
239 #import <WebCore/EventNames.h>
240 #import <WebCore/FontCache.h>
241 #import <WebCore/GraphicsLayer.h>
242 #import <WebCore/IconController.h>
243 #import <WebCore/LegacyTileCache.h>
244 #import <WebCore/MobileGestaltSPI.h>
245 #import <WebCore/NetworkStateNotifier.h>
246 #import <WebCore/RuntimeApplicationChecksIOS.h>
247 #import <WebCore/SQLiteDatabaseTracker.h>
248 #import <WebCore/SmartReplace.h>
249 #import <WebCore/TextRun.h>
250 #import <WebCore/TileControllerMemoryHandlerIOS.h>
251 #import <WebCore/WAKWindow.h>
252 #import <WebCore/WKView.h>
253 #import <WebCore/WebCoreThread.h>
254 #import <WebCore/WebCoreThreadMessage.h>
255 #import <WebCore/WebCoreThreadRun.h>
256 #import <WebCore/WebEvent.h>
257 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
258 #import <wtf/FastMalloc.h>
259 #endif // !PLATFORM(IOS)
260
261 #if ENABLE(DASHBOARD_SUPPORT)
262 #import <WebKitLegacy/WebDashboardRegion.h>
263 #endif
264
265 #if ENABLE(REMOTE_INSPECTOR)
266 #import <JavaScriptCore/RemoteInspector.h>
267 #if PLATFORM(IOS)
268 #import "WebIndicateLayer.h"
269 #endif
270 #endif
271
272 #if USE(GLIB)
273 #import <glib.h>
274 #endif
275
276 #if USE(QUICK_LOOK)
277 #include <WebCore/QuickLook.h>
278 #endif
279
280 #if ENABLE(IOS_TOUCH_EVENTS)
281 #import <WebCore/WebEventRegion.h>
282 #endif
283
284 #if ENABLE(GAMEPAD)
285 #import <WebCore/HIDGamepadProvider.h>
286 #endif
287
288 #if !PLATFORM(IOS)
289 @interface NSSpellChecker (WebNSSpellCheckerDetails)
290 - (void)_preflightChosenSpellServer;
291 @end
292
293 @interface NSView (WebNSViewDetails)
294 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
295 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
296 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
297 - (void)_windowChangedKeyState;
298 @end
299
300 @interface NSWindow (WebNSWindowDetails)
301 - (id)_oldFirstResponderBeforeBecoming;
302 - (void)_enableScreenUpdatesIfNeeded;
303 - (BOOL)_wrapsCarbonWindow;
304 - (BOOL)_hasKeyAppearance;
305 @end
306 #endif
307
308 using namespace JSC;
309 using namespace Inspector;
310 using namespace WebCore;
311
312 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
313 macro(alignCenter) \
314 macro(alignJustified) \
315 macro(alignLeft) \
316 macro(alignRight) \
317 macro(capitalizeWord) \
318 macro(centerSelectionInVisibleArea) \
319 macro(changeAttributes) \
320 macro(changeBaseWritingDirection) \
321 macro(changeBaseWritingDirectionToLTR) \
322 macro(changeBaseWritingDirectionToRTL) \
323 macro(changeColor) \
324 macro(changeDocumentBackgroundColor) \
325 macro(changeFont) \
326 macro(changeSpelling) \
327 macro(checkSpelling) \
328 macro(complete) \
329 macro(copy) \
330 macro(copyFont) \
331 macro(cut) \
332 macro(delete) \
333 macro(deleteBackward) \
334 macro(deleteBackwardByDecomposingPreviousCharacter) \
335 macro(deleteForward) \
336 macro(deleteToBeginningOfLine) \
337 macro(deleteToBeginningOfParagraph) \
338 macro(deleteToEndOfLine) \
339 macro(deleteToEndOfParagraph) \
340 macro(deleteToMark) \
341 macro(deleteWordBackward) \
342 macro(deleteWordForward) \
343 macro(ignoreSpelling) \
344 macro(indent) \
345 macro(insertBacktab) \
346 macro(insertLineBreak) \
347 macro(insertNewline) \
348 macro(insertNewlineIgnoringFieldEditor) \
349 macro(insertParagraphSeparator) \
350 macro(insertTab) \
351 macro(insertTabIgnoringFieldEditor) \
352 macro(lowercaseWord) \
353 macro(makeBaseWritingDirectionLeftToRight) \
354 macro(makeBaseWritingDirectionRightToLeft) \
355 macro(makeTextWritingDirectionLeftToRight) \
356 macro(makeTextWritingDirectionNatural) \
357 macro(makeTextWritingDirectionRightToLeft) \
358 macro(moveBackward) \
359 macro(moveBackwardAndModifySelection) \
360 macro(moveDown) \
361 macro(moveDownAndModifySelection) \
362 macro(moveForward) \
363 macro(moveForwardAndModifySelection) \
364 macro(moveLeft) \
365 macro(moveLeftAndModifySelection) \
366 macro(moveParagraphBackwardAndModifySelection) \
367 macro(moveParagraphForwardAndModifySelection) \
368 macro(moveRight) \
369 macro(moveRightAndModifySelection) \
370 macro(moveToBeginningOfDocument) \
371 macro(moveToBeginningOfDocumentAndModifySelection) \
372 macro(moveToBeginningOfLine) \
373 macro(moveToBeginningOfLineAndModifySelection) \
374 macro(moveToBeginningOfParagraph) \
375 macro(moveToBeginningOfParagraphAndModifySelection) \
376 macro(moveToBeginningOfSentence) \
377 macro(moveToBeginningOfSentenceAndModifySelection) \
378 macro(moveToEndOfDocument) \
379 macro(moveToEndOfDocumentAndModifySelection) \
380 macro(moveToEndOfLine) \
381 macro(moveToEndOfLineAndModifySelection) \
382 macro(moveToEndOfParagraph) \
383 macro(moveToEndOfParagraphAndModifySelection) \
384 macro(moveToEndOfSentence) \
385 macro(moveToEndOfSentenceAndModifySelection) \
386 macro(moveToLeftEndOfLine) \
387 macro(moveToLeftEndOfLineAndModifySelection) \
388 macro(moveToRightEndOfLine) \
389 macro(moveToRightEndOfLineAndModifySelection) \
390 macro(moveUp) \
391 macro(moveUpAndModifySelection) \
392 macro(moveWordBackward) \
393 macro(moveWordBackwardAndModifySelection) \
394 macro(moveWordForward) \
395 macro(moveWordForwardAndModifySelection) \
396 macro(moveWordLeft) \
397 macro(moveWordLeftAndModifySelection) \
398 macro(moveWordRight) \
399 macro(moveWordRightAndModifySelection) \
400 macro(orderFrontSubstitutionsPanel) \
401 macro(outdent) \
402 macro(overWrite) \
403 macro(pageDown) \
404 macro(pageDownAndModifySelection) \
405 macro(pageUp) \
406 macro(pageUpAndModifySelection) \
407 macro(paste) \
408 macro(pasteAsPlainText) \
409 macro(pasteAsRichText) \
410 macro(pasteFont) \
411 macro(performFindPanelAction) \
412 macro(scrollLineDown) \
413 macro(scrollLineUp) \
414 macro(scrollPageDown) \
415 macro(scrollPageUp) \
416 macro(scrollToBeginningOfDocument) \
417 macro(scrollToEndOfDocument) \
418 macro(selectAll) \
419 macro(selectLine) \
420 macro(selectParagraph) \
421 macro(selectSentence) \
422 macro(selectToMark) \
423 macro(selectWord) \
424 macro(setMark) \
425 macro(showGuessPanel) \
426 macro(startSpeaking) \
427 macro(stopSpeaking) \
428 macro(subscript) \
429 macro(superscript) \
430 macro(swapWithMark) \
431 macro(takeFindStringFromSelection) \
432 macro(toggleBaseWritingDirection) \
433 macro(transpose) \
434 macro(underline) \
435 macro(unscript) \
436 macro(uppercaseWord) \
437 macro(yank) \
438 macro(yankAndSelect) \
439
440 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
441 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
442
443 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
444 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
445
446 static BOOL s_didSetCacheModel;
447 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
448
449 #if PLATFORM(IOS)
450 static Class s_pdfRepresentationClass;
451 static Class s_pdfViewClass;
452 #endif
453
454 #ifndef NDEBUG
455 static const char webViewIsOpen[] = "At least one WebView is still open.";
456 #endif
457
458 #if PLATFORM(IOS)
459 @interface WebView(WebViewPrivate)
460 - (void)_preferencesChanged:(WebPreferences *)preferences;
461 - (void)_updateScreenScaleFromWindow;
462 @end
463
464 @interface NSURLCache (WebPrivate)
465 - (CFURLCacheRef)_CFURLCache;
466 @end
467 #endif
468
469 #if !PLATFORM(IOS)
470 @interface NSObject (WebValidateWithoutDelegate)
471 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
472 @end
473 #endif
474
475 #if PLATFORM(IOS)
476 @class _WebSafeForwarder;
477
478 @interface _WebSafeAsyncForwarder : NSObject {
479     _WebSafeForwarder *_forwarder;
480 }
481 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
482 @end
483 #endif
484
485 @interface _WebSafeForwarder : NSObject
486 {
487     id target; // Non-retained. Don't retain delegates.
488     id defaultTarget;
489 #if PLATFORM(IOS)
490     _WebSafeAsyncForwarder *asyncForwarder;
491     dispatch_once_t asyncForwarderPred;
492 #endif
493 }
494 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
495 #if PLATFORM(IOS)
496 - (void)clearTarget;
497 - (id)asyncForwarder;
498 #endif
499 @end
500
501 FindOptions coreOptions(WebFindOptions options)
502 {
503     return (options & WebFindOptionsCaseInsensitive ? CaseInsensitive : 0)
504         | (options & WebFindOptionsAtWordStarts ? AtWordStarts : 0)
505         | (options & WebFindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
506         | (options & WebFindOptionsBackwards ? Backwards : 0)
507         | (options & WebFindOptionsWrapAround ? WrapAround : 0)
508         | (options & WebFindOptionsStartInSelection ? StartInSelection : 0);
509 }
510
511 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
512 {
513     return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
514         | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
515         | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
516 }
517
518 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
519 {
520     return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
521         | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
522         | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
523 }
524
525 static WebPageVisibilityState kit(PageVisibilityState visibilityState)
526 {
527     switch (visibilityState) {
528     case PageVisibilityStateVisible:
529         return WebPageVisibilityStateVisible;
530     case PageVisibilityStateHidden:
531         return WebPageVisibilityStateHidden;
532     case PageVisibilityStatePrerender:
533         return WebPageVisibilityStatePrerender;
534     }
535
536     ASSERT_NOT_REACHED();
537     return WebPageVisibilityStateVisible;
538 }
539
540 @interface WebView (WebFileInternal)
541 #if !PLATFORM(IOS)
542 - (float)_deviceScaleFactor;
543 #endif
544 - (BOOL)_isLoading;
545 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
546 - (WebFrame *)_focusedFrame;
547 + (void)_preflightSpellChecker;
548 - (BOOL)_continuousCheckingAllowed;
549 - (NSResponder *)_responderForResponderOperations;
550 #if USE(GLIB)
551 - (void)_clearGlibLoopObserver;
552 #endif
553 @end
554
555 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
556 NSString *WebElementFrameKey =              @"WebElementFrame";
557 NSString *WebElementImageKey =              @"WebElementImage";
558 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
559 NSString *WebElementImageRectKey =          @"WebElementImageRect";
560 NSString *WebElementImageURLKey =           @"WebElementImageURL";
561 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
562 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
563 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
564 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
565 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
566 NSString *WebElementMediaURLKey =           @"WebElementMediaURL";
567 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
568 NSString *WebElementTitleKey =              @"WebElementTitle";
569 NSString *WebElementLinkIsLiveKey =         @"WebElementLinkIsLive";
570 NSString *WebElementIsInScrollBarKey =      @"WebElementIsInScrollBar";
571 NSString *WebElementIsContentEditableKey =  @"WebElementIsContentEditableKey";
572
573 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
574 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
575 #if !PLATFORM(IOS)
576 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
577 #else
578 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
579 NSString * const WebViewProgressBackgroundColorKey =   @"WebProgressBackgroundColorKey";
580 #endif
581
582 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
583 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
584 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
585 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
586 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
587
588 enum { WebViewVersion = 4 };
589
590 #define timedLayoutSize 4096
591
592 static NSMutableSet *schemesWithRepresentationsSet;
593
594 #if !PLATFORM(IOS)
595 NSString *_WebCanGoBackKey =            @"canGoBack";
596 NSString *_WebCanGoForwardKey =         @"canGoForward";
597 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
598 NSString *_WebIsLoadingKey =            @"isLoading";
599 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
600 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
601 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
602 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
603 #endif
604
605 #if USE(QUICK_LOOK)
606 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
607 NSString *WebQuickLookUTIKey      = @"WebQuickLookUTIKey";
608 #endif
609
610 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
611 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
612
613 #if ENABLE(REMOTE_INSPECTOR)
614 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
615 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
616 #endif
617
618 NSString *WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey = @"WebKitKerningAndLigaturesEnabledByDefault";
619
620 @interface WebProgressItem : NSObject
621 {
622 @public
623     long long bytesReceived;
624     long long estimatedLength;
625 }
626 @end
627
628 @implementation WebProgressItem
629 @end
630
631 static BOOL continuousSpellCheckingEnabled;
632 #if !PLATFORM(IOS)
633 static BOOL grammarCheckingEnabled;
634 static BOOL automaticQuoteSubstitutionEnabled;
635 static BOOL automaticLinkDetectionEnabled;
636 static BOOL automaticDashSubstitutionEnabled;
637 static BOOL automaticTextReplacementEnabled;
638 static BOOL automaticSpellingCorrectionEnabled;
639 #endif
640
641 @implementation WebView (AllWebViews)
642
643 static CFSetCallBacks NonRetainingSetCallbacks = {
644     0,
645     NULL,
646     NULL,
647     CFCopyDescription,
648     CFEqual,
649     CFHash
650 };
651
652 static CFMutableSetRef allWebViewsSet;
653
654 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
655 {
656     if (!allWebViewsSet)
657         return;
658
659     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
660 }
661
662 - (void)_removeFromAllWebViewsSet
663 {
664     if (allWebViewsSet)
665         CFSetRemoveValue(allWebViewsSet, self);
666 }
667
668 - (void)_addToAllWebViewsSet
669 {
670     if (!allWebViewsSet)
671         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
672
673     CFSetSetValue(allWebViewsSet, self);
674 }
675
676 @end
677
678 @implementation WebView (WebPrivate)
679
680 static String webKitBundleVersionString()
681 {
682     return [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
683 }
684
685 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
686 {
687     return standardUserAgentWithApplicationName(applicationName, webKitBundleVersionString());
688 }
689
690 #if PLATFORM(IOS)
691 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
692 {
693     [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/%@ Safari/%@", productVersion, buildVersion, bundleVersion]];
694 }
695
696 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
697 {
698     [self setApplicationNameForUserAgent:[@"Mobile/" stringByAppendingString:buildVersion]];
699 }
700 #endif // PLATFORM(IOS)
701
702 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
703 {
704     if (!exception || !context)
705         return;
706
707     JSC::ExecState* execState = toJS(context);
708     JSLockHolder lock(execState);
709
710     // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
711     if (!toJSDOMWindow(execState->lexicalGlobalObject()))
712         return;
713
714     reportException(execState, toJS(execState, exception));
715 }
716
717 static void WebKitInitializeApplicationCachePathIfNecessary()
718 {
719     static BOOL initialized = NO;
720     if (initialized)
721         return;
722
723     NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
724     if (!appName)
725         appName = [[NSProcessInfo processInfo] processName];
726 #if PLATFORM(IOS)
727     if (WebCore::applicationIsMobileSafari() || WebCore::applicationIsWebApp())
728         appName = @"com.apple.WebAppCache";
729 #endif
730
731     ASSERT(appName);
732
733     NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
734
735     cacheStorage().setCacheDirectory(cacheDir);
736     initialized = YES;
737 }
738
739 static bool shouldEnableLoadDeferring()
740 {
741     return !applicationIsAdobeInstaller();
742 }
743
744 static bool shouldRestrictWindowFocus()
745 {
746 #if PLATFORM(IOS)
747     return true;
748 #else
749     return !applicationIsHRBlock();
750 #endif
751 }
752
753 - (void)_dispatchPendingLoadRequests
754 {
755     resourceLoadScheduler()->servePendingRequests();
756 }
757
758 #if !PLATFORM(IOS)
759 - (void)_registerDraggedTypes
760 {
761     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
762     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
763     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
764     [types addObjectsFromArray:URLTypes];
765     [self registerForDraggedTypes:[types allObjects]];
766     [types release];
767 }
768
769 static bool needsOutlookQuirksScript()
770 {
771     static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
772         && applicationIsMicrosoftOutlook();
773     return isOutlookNeedingQuirksScript;
774 }
775
776 static NSString *leakOutlookQuirksUserScriptContents()
777 {
778     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
779     NSStringEncoding encoding;
780     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
781 }
782
783 -(void)_injectOutlookQuirksScript
784 {
785     static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
786     _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), std::make_unique<UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames));
787
788 }
789 #endif
790
791 static bool shouldRespectPriorityInCSSAttributeSetters()
792 {
793 #if PLATFORM(IOS)
794     static bool isStanzaNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
795         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.lexcycle.stanza"];
796     return isStanzaNeedingAttributeSetterQuirk;
797 #else
798     static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
799         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
800     return isIAdProducerNeedingAttributeSetterQuirk;
801 #endif
802 }
803
804 #if PLATFORM(IOS)
805 static bool shouldTransformsAffectOverflow()
806 {
807     static bool shouldTransformsAffectOverflow = !applicationIsOkCupid() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_TRANSFORMS_AFFECTING_OVERFLOW);
808     return shouldTransformsAffectOverflow;
809 }
810
811 static bool shouldDispatchJavaScriptWindowOnErrorEvents()
812 {
813     static bool shouldDispatchJavaScriptWindowOnErrorEvents = !applicationIsFacebook() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_WINDOW_ON_ERROR);
814     return shouldDispatchJavaScriptWindowOnErrorEvents;
815 }
816
817 static bool isInternalInstall()
818 {
819     static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
820     return isInternal;
821 }
822
823 static bool didOneTimeInitialization = false;
824 #endif
825
826 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
827 {
828 #if PLATFORM(IOS)
829     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
830 #else
831     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = applicationIsVersions()
832         && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
833 #endif
834     return shouldUseLegacyBackgroundSizeShorthandBehavior;
835 }
836
837 #if ENABLE(GAMEPAD)
838 static void WebKitInitializeGamepadProviderIfNecessary()
839 {
840     static bool initialized = false;
841     if (initialized)
842         return;
843
844     GamepadProvider::shared().setSharedProvider(HIDGamepadProvider::shared());
845     initialized = true;
846 }
847 #endif
848
849 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
850 {
851     WebCoreThreadViolationCheckRoundTwo();
852
853 #ifndef NDEBUG
854     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
855 #endif
856     
857     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
858     [standardPreferences willAddToWebView];
859
860     _private->preferences = [standardPreferences retain];
861     _private->mainFrameDocumentReady = NO;
862     _private->drawsBackground = YES;
863 #if !PLATFORM(IOS)
864     _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
865 #else
866     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white, ColorSpaceDeviceRGB));
867 #endif
868     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
869
870     NSRect f = [self frame];
871     WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
872     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
873     [self addSubview:frameView];
874     [frameView release];
875
876 #if !PLATFORM(IOS)
877     if ([self respondsToSelector:@selector(setActionMenu:)]) {
878         RetainPtr<NSMenu> actionMenu = adoptNS([[NSMenu alloc] init]);
879         self.actionMenu = actionMenu.get();
880         _private->actionMenuController = [[WebActionMenuController alloc] initWithWebView:self];
881     }
882
883     static bool didOneTimeInitialization = false;
884 #endif
885     if (!didOneTimeInitialization) {
886 #if !LOG_DISABLED
887         WebKitInitializeLoggingChannelsIfNecessary();
888         WebCore::initializeLoggingChannelsIfNecessary();
889 #endif // !LOG_DISABLED
890
891         // Initialize our platform strategies first before invoking the rest
892         // of the initialization code which may depend on the strategies.
893         WebPlatformStrategies::initializeIfNecessary();
894
895 #if ENABLE(SQL_DATABASE)
896 #if PLATFORM(IOS)
897         // Set the WebSQLiteDatabaseTrackerClient.
898         SQLiteDatabaseTracker::setClient(WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
899
900         if ([standardPreferences databasesEnabled])
901 #endif
902         [WebDatabaseManager sharedWebDatabaseManager];
903 #endif
904
905 #if PLATFORM(IOS)        
906         if ([standardPreferences storageTrackerEnabled])
907 #endif
908         WebKitInitializeStorageIfNecessary();
909         WebKitInitializeApplicationCachePathIfNecessary();
910 #if ENABLE(GAMEPAD)
911         WebKitInitializeGamepadProviderIfNecessary();
912 #endif
913         
914         Settings::setDefaultMinDOMTimerInterval(0.004);
915         
916         Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
917
918 #if PLATFORM(IOS)
919         if (applicationIsMobileSafari())
920             Settings::setShouldManageAudioSessionCategory(true);
921 #endif
922
923         didOneTimeInitialization = true;
924     }
925
926     _private->group = WebViewGroup::getOrCreate(groupName);
927     _private->group->addWebView(self);
928
929     PageConfiguration pageConfiguration;
930 #if !PLATFORM(IOS)
931     pageConfiguration.chromeClient = new WebChromeClient(self);
932     pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
933 #if ENABLE(DRAG_SUPPORT)
934     pageConfiguration.dragClient = new WebDragClient(self);
935 #endif
936     pageConfiguration.inspectorClient = new WebInspectorClient(self);
937 #else
938     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
939     pageConfiguration.inspectorClient = new WebInspectorClient(self);
940 #endif
941     pageConfiguration.editorClient = new WebEditorClient(self);
942     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
943     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
944     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
945     pageConfiguration.userContentController = &_private->group->userContentController();
946     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
947     _private->page = new Page(pageConfiguration);
948
949     _private->page->setGroupName(groupName);
950
951 #if ENABLE(GEOLOCATION)
952     WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
953 #endif
954 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
955     WebCore::provideNotification(_private->page, new WebNotificationClient(self));
956 #endif
957 #if ENABLE(DEVICE_ORIENTATION)
958 #if !PLATFORM(IOS)
959     WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
960 #endif
961 #endif
962 #if ENABLE(MEDIA_STREAM)
963     WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
964 #endif
965
966 #if ENABLE(REMOTE_INSPECTOR)
967     _private->page->setRemoteInspectionAllowed(true);
968 #endif
969
970     _private->page->setCanStartMedia([self window]);
971     _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
972     _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
973
974 #if !PLATFORM(IOS)
975     if (needsOutlookQuirksScript()) {
976         _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
977         [self _injectOutlookQuirksScript];
978     }
979 #endif
980
981 #if PLATFORM(IOS)
982     // Preserve the behavior we had before <rdar://problem/7580867>
983     // by enforcing a 5MB limit for session storage.
984     _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
985
986     [self _updateScreenScaleFromWindow];
987     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
988     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
989     _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
990 #endif
991
992     if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
993         [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
994
995     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
996
997 #if !PLATFORM(IOS)
998     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
999
1000     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1001         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1002     else
1003         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1004 #endif
1005
1006     [self _addToAllWebViewsSet];
1007     
1008     // If there's already a next key view (e.g., from a nib), wire it up to our
1009     // contained frame view. In any case, wire our next key view up to the our
1010     // contained frame view. This works together with our becomeFirstResponder 
1011     // and setNextKeyView overrides.
1012     NSView *nextKeyView = [self nextKeyView];
1013     if (nextKeyView && nextKeyView != frameView)
1014         [frameView setNextKeyView:nextKeyView];
1015     [super setNextKeyView:frameView];
1016
1017     if ([[self class] shouldIncludeInWebKitStatistics])
1018         ++WebViewCount;
1019
1020 #if !PLATFORM(IOS)
1021     [self _registerDraggedTypes];
1022 #endif
1023
1024     [self _setIsVisible:[self _isViewVisible]];
1025
1026     WebPreferences *prefs = [self preferences];
1027     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1028                                                  name:WebPreferencesChangedInternalNotification object:prefs];
1029
1030 #if !PLATFORM(IOS)
1031     [self _preferencesChanged:[self preferences]];
1032     [[self preferences] _postPreferencesChangedAPINotification];
1033 #else
1034     // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1035     // and prefs need to be changed synchronously <rdar://problem/5841558>
1036     [self _preferencesChanged:prefs];
1037     _private->page->settings().setFontFallbackPrefersPictographs(true);
1038 #endif
1039
1040     memoryPressureHandler().install();
1041
1042     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1043         // Originally, we allowed all local loads.
1044         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1045     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1046         // Later, we allowed local loads for local URLs and documents loaded
1047         // with substitute data.
1048         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1049     }
1050
1051 #if !PLATFORM(IOS)
1052     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1053         ResourceHandle::forceContentSniffing();
1054 #endif
1055
1056 #if USE(GLIB)
1057     [self _scheduleGlibContextIterations];
1058 #endif
1059 }
1060
1061 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1062 {
1063     self = [super initWithFrame:f];
1064     if (!self)
1065         return nil;
1066
1067 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1068     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1069     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1070     // need for Safari to unset it to prevent it from being passed to applications it launches.
1071     // Unsetting it when a WebView is first created is as good a place as any.
1072     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1073     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1074         unsetenv("DYLD_FRAMEWORK_PATH");
1075         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1076     }
1077 #endif
1078
1079     _private = [[WebViewPrivate alloc] init];
1080     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1081     [self setMaintainsBackForwardList: YES];
1082 #if !PLATFORM(IOS)
1083     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1084 #endif
1085     return self;
1086 }
1087
1088 - (void)_viewWillDrawInternal
1089 {
1090     Frame* frame = [self _mainCoreFrame];
1091     if (frame && frame->view())
1092         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1093 }
1094
1095 + (NSArray *)_supportedMIMETypes
1096 {
1097     // Load the plug-in DB allowing plug-ins to install types.
1098     [WebPluginDatabase sharedDatabase];
1099     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1100 }
1101
1102 #if !PLATFORM(IOS)
1103 + (NSArray *)_supportedFileExtensions
1104 {
1105     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1106     NSArray *MIMETypes = [self _supportedMIMETypes];
1107     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1108     NSString *MIMEType;
1109     while ((MIMEType = [enumerator nextObject]) != nil) {
1110         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1111         if (extensionsForType) {
1112             [extensions addObjectsFromArray:extensionsForType];
1113         }
1114     }
1115     NSArray *uniqueExtensions = [extensions allObjects];
1116     [extensions release];
1117     return uniqueExtensions;
1118 }
1119 #endif
1120
1121 #if PLATFORM(IOS)
1122 + (void)enableWebThread
1123 {
1124     static BOOL isWebThreadEnabled = NO;
1125     if (!isWebThreadEnabled) {
1126         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1127         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1128         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1129         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1130         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1131         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1132         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1133         WebCoreObjCDeallocOnWebThread([WebView class]);
1134         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1135         if (applicationIsTheEconomistOnIPhone() && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_DELEGATE_CALLS_IN_COMMON_RUNLOOP_MODES))
1136             WebThreadSetDelegateSourceRunLoopMode(kCFRunLoopDefaultMode);
1137         WebThreadEnable();
1138         isWebThreadEnabled = YES;
1139     }
1140 }
1141
1142 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1143 {
1144     self = [super initWithFrame:frame];
1145     if (!self)
1146         return nil;
1147     
1148     _private = [[WebViewPrivate alloc] init];
1149     
1150 #ifndef NDEBUG
1151     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1152 #endif
1153     
1154     if (!preferences)
1155         preferences = [WebPreferences standardPreferences];
1156     [preferences willAddToWebView];
1157     
1158     _private->preferences = [preferences retain];
1159     _private->mainFrameDocumentReady = NO;
1160     _private->drawsBackground = YES;
1161     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white, ColorSpaceDeviceRGB));
1162     
1163     WebFrameView *frameView = nil;
1164     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1165     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1166     [self addSubview:frameView];
1167     [frameView release];
1168
1169     _private->group = WebViewGroup::getOrCreate(groupName);
1170     _private->group->addWebView(self);
1171
1172     PageConfiguration pageConfiguration;
1173     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1174 #if ENABLE(DRAG_SUPPORT)
1175     pageConfiguration.dragClient = new WebDragClient(self);
1176 #endif
1177     pageConfiguration.editorClient = new WebEditorClient(self);
1178     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1179     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1180     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1181     pageConfiguration.userContentController = &_private->group->userContentController();
1182
1183     _private->page = new Page(pageConfiguration);
1184     
1185     [self setSmartInsertDeleteEnabled:YES];
1186     
1187     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1188     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1189     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1190     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1191     _private->page->settings().setMinimumLogicalFontSize(9);
1192     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1193     _private->page->settings().setDefaultFixedFontSize(13);
1194     _private->page->settings().setDownloadableBinaryFontsEnabled(false);
1195     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1196     _private->page->settings().setScreenFontSubstitutionEnabled(false);
1197     
1198     // FIXME: <rdar://problem/7394370> Always use primary font baseline in text field base line calculation, ignore fallback fonts.
1199     _private->page->settings().setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
1200
1201     _private->page->settings().setFontFallbackPrefersPictographs(true);
1202     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1203     
1204     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1205     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1206     
1207     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1208     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1209
1210     _private->page->setGroupName(groupName);
1211
1212 #if ENABLE(REMOTE_INSPECTOR)
1213     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1214 #endif
1215     
1216     [self _updateScreenScaleFromWindow];
1217     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1218     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1219
1220     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1221     
1222     [self _addToAllWebViewsSet];
1223     
1224     ++WebViewCount;
1225     
1226     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1227     
1228     return self;
1229 }
1230
1231 + (void)_handleMemoryWarning
1232 {
1233     ASSERT(WebThreadIsCurrent());
1234     WebKit::MemoryMeasure totalMemory("Memory warning: Overall memory change from [WebView _handleMemoryWarning].");
1235
1236     // Always peform the following.
1237     [WebView purgeInactiveFontData];
1238
1239     // Only perform the remaining if a non-simple document was created.
1240     if (!didOneTimeInitialization)
1241         return;
1242
1243     tileControllerMemoryHandler().trimUnparentedTilesToTarget(0);
1244
1245     [WebStorageManager closeIdleLocalStorageDatabases];
1246
1247     [WebView _releaseMemoryNow];
1248 }
1249
1250 + (void)registerForMemoryNotifications
1251 {
1252     BOOL shouldAutoClearPressureOnMemoryRelease = !WebCore::applicationIsMobileSafari();
1253
1254     memoryPressureHandler().installMemoryReleaseBlock(^{
1255         [WebView _handleMemoryWarning];
1256     }, shouldAutoClearPressureOnMemoryRelease);
1257
1258 #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
1259     static dispatch_source_t memoryNotificationEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYSTATUS, 0, DISPATCH_MEMORYSTATUS_PRESSURE_WARN, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1260 #else
1261     static dispatch_source_t memoryNotificationEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_VM, 0, DISPATCH_VM_PRESSURE, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1262 #endif
1263     dispatch_source_set_event_handler(memoryNotificationEventSource, ^{
1264         // Set memory pressure flag and schedule releasing memory in web thread runloop exit.
1265         memoryPressureHandler().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMPressure);
1266     });
1267
1268     dispatch_resume(memoryNotificationEventSource);
1269
1270     if (!shouldAutoClearPressureOnMemoryRelease) {
1271         // Listen to memory status notification to reset the memory pressure flag.
1272         static dispatch_source_t memoryStatusEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYSTATUS,
1273                                                                                     0,
1274                                                                                     DISPATCH_MEMORYSTATUS_PRESSURE_WARN | DISPATCH_MEMORYSTATUS_PRESSURE_NORMAL,
1275                                                                                     dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1276         dispatch_source_set_event_handler(memoryStatusEventSource, ^{
1277             unsigned long currentStatus = dispatch_source_get_data(memoryStatusEventSource);
1278             if (currentStatus == DISPATCH_MEMORYSTATUS_PRESSURE_NORMAL)
1279                 memoryPressureHandler().clearMemoryPressure();
1280             else if (currentStatus == DISPATCH_MEMORYSTATUS_PRESSURE_WARN)
1281                 memoryPressureHandler().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMStatus);
1282         });
1283
1284         dispatch_resume(memoryStatusEventSource);
1285     }
1286 }
1287
1288 + (void)_releaseMemoryNow
1289 {
1290     ASSERT(WebThreadIsCurrent());
1291     [WebView discardAllCompiledCode];
1292     [WebView garbageCollectNow];
1293     [WebView purgeInactiveFontData];
1294     [WebView drainLayerPool];
1295     [WebCache emptyInMemoryResources];
1296     [WebView releaseFastMallocMemoryOnCurrentThread];
1297
1298     dispatch_async(dispatch_get_main_queue(), ^{
1299         // Clear the main thread's TCMalloc thread cache.
1300         [WebView releaseFastMallocMemoryOnCurrentThread];
1301     });
1302 }
1303
1304 + (void)_clearPrivateBrowsingSessionCookieStorage
1305 {
1306     WebFrameNetworkingContext::clearPrivateBrowsingSessionCookieStorage();
1307 }
1308
1309 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1310 {
1311     Frame* frame = [self _mainCoreFrame];
1312     if (frame)
1313         frame->loader().history().replaceCurrentItem(core(item));
1314 }
1315
1316 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1317 {
1318     WebThreadRun(^{
1319         [WebView _releaseMemoryNow];
1320         dispatch_async(dispatch_get_main_queue(), handler);
1321     });
1322 }
1323
1324 + (void)releaseFastMallocMemoryOnCurrentThread
1325 {
1326     WebKit::MemoryMeasure measurer("Memory warning: Releasing fast malloc memory to system.");
1327     WTF::releaseFastMallocFreeMemory();
1328 }
1329
1330 + (void)garbageCollectNow
1331 {
1332     ASSERT(WebThreadIsCurrent());
1333     WebKit::MemoryMeasure measurer("Memory warning: Calling JavaScript GC.");
1334     gcController().garbageCollectNow();
1335 }
1336
1337 + (void)purgeInactiveFontData
1338 {
1339     ASSERT(WebThreadIsCurrent());
1340     WebKit::MemoryMeasure measurer("Memory warning: Purging inactive font data.");
1341     fontCache().purgeInactiveFontData();
1342 }
1343
1344 + (void)drainLayerPool
1345 {
1346     ASSERT(WebThreadIsCurrent());
1347     WebKit::MemoryMeasure measurer("Memory warning: Draining layer pool.");
1348     WebCore::LegacyTileCache::drainLayerPool();
1349 }
1350
1351 + (void)discardAllCompiledCode
1352 {
1353     ASSERT(WebThreadIsCurrent());
1354     WebKit::MemoryMeasure measurer("Memory warning: Discarding JIT'ed code.");
1355     gcController().discardAllCompiledCode();
1356 }
1357
1358 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1359 {
1360     return WebCore::isCharacterSmartReplaceExempt(character, b);
1361 }
1362
1363 - (void)updateLayoutIgnorePendingStyleSheets
1364 {
1365     WebThreadRun(^{
1366         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1367             Document *document = frame->document();
1368             if (document)
1369                 document->updateLayoutIgnorePendingStylesheets();
1370         }
1371     });
1372 }
1373 #endif // PLATFORM(IOS)
1374
1375 static NSMutableSet *knownPluginMIMETypes()
1376 {
1377     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
1378     
1379     return mimeTypes;
1380 }
1381
1382 + (void)_registerPluginMIMEType:(NSString *)MIMEType
1383 {
1384     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
1385     [knownPluginMIMETypes() addObject:MIMEType];
1386 }
1387
1388 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
1389 {
1390     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
1391     [knownPluginMIMETypes() removeObject:MIMEType];
1392 }
1393
1394 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
1395 {
1396     MIMEType = [MIMEType lowercaseString];
1397     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1398     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1399
1400 #if PLATFORM(IOS)
1401 #define WebPDFView ([WebView _getPDFViewClass])
1402 #endif
1403     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
1404 #if PLATFORM(IOS)
1405 #undef WebPDFView
1406 #endif
1407         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
1408
1409         if (allowPlugins) {
1410             // Load the plug-in DB allowing plug-ins to install types.
1411             [WebPluginDatabase sharedDatabase];
1412         }
1413
1414         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
1415         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1416         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1417     }
1418     
1419     if (viewClass && repClass) {
1420         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
1421             // Special-case WebHTMLView for text types that shouldn't be shown.
1422             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
1423                 return NO;
1424
1425             // If the MIME type is a known plug-in we might not want to load it.
1426             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
1427                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
1428                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
1429                 
1430                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
1431                 if (!isSupportedByWebKit)
1432                     return NO;
1433             }
1434         }
1435         if (vClass)
1436             *vClass = viewClass;
1437         if (rClass)
1438             *rClass = repClass;
1439         return YES;
1440     }
1441     
1442     return NO;
1443 }
1444
1445 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
1446 {
1447     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
1448         return YES;
1449 #if !PLATFORM(IOS)
1450     if (_private->pluginDatabase) {
1451         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
1452         if (pluginPackage) {
1453             if (vClass)
1454                 *vClass = [WebHTMLView class];
1455             if (rClass)
1456                 *rClass = [WebHTMLRepresentation class];
1457             return YES;
1458         }
1459     }
1460 #endif
1461     return NO;
1462 }
1463
1464 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1465 {
1466     Font::setCodePath(f ? Font::Complex : Font::Auto);
1467 }
1468
1469 + (void)_setAllowsRoundingHacks:(BOOL)allowsRoundingHacks
1470 {
1471     TextRun::setAllowsRoundingHacks(allowsRoundingHacks);
1472 }
1473
1474 + (BOOL)_allowsRoundingHacks
1475 {
1476     return TextRun::allowsRoundingHacks();
1477 }
1478
1479 + (BOOL)canCloseAllWebViews
1480 {
1481     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1482 }
1483
1484 + (void)closeAllWebViews
1485 {
1486     DOMWindow::dispatchAllPendingUnloadEvents();
1487
1488     // This will close the WebViews in a random order. Change this if close order is important.
1489     // Make a new set to avoid mutating the set we are enumerating.
1490     NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet]; 
1491     NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1492     while (WebView *webView = [enumerator nextObject])
1493         [webView close];
1494 }
1495
1496 + (BOOL)canShowFile:(NSString *)path
1497 {
1498     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1499 }
1500
1501 #if !PLATFORM(IOS)
1502 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1503 {
1504     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
1505 }
1506 #endif
1507
1508 - (BOOL)_isClosed
1509 {
1510     return !_private || _private->closed;
1511 }
1512
1513 #if PLATFORM(IOS)
1514 - (void)_dispatchUnloadEvent
1515 {
1516     WebThreadRun(^{
1517         WebFrame *mainFrame = [self mainFrame];
1518         Frame *coreMainFrame = core(mainFrame);
1519         if (coreMainFrame) {
1520             Document *document = coreMainFrame->document();
1521             if (document)
1522                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
1523         }
1524     });
1525 }
1526
1527 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
1528 {
1529     WebFrame *mainFrame = [self mainFrame];
1530     Frame *coreMainFrame = core(mainFrame);
1531     if (!coreMainFrame)
1532         return nil;
1533     return coreMainFrame->styleAtSelectionStart();
1534 }
1535
1536 - (NSUInteger)_renderTreeSize
1537 {
1538     if (!_private->page)
1539         return 0;
1540     return _private->page->renderTreeSize();
1541 }
1542
1543 - (void)_dispatchTileDidDraw:(CALayer*)tile
1544 {
1545     id mailDelegate = [self _webMailDelegate];
1546     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
1547         [mailDelegate _webthread_webView:self tileDidDraw:tile];
1548         return;
1549     }
1550
1551     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
1552         return;
1553
1554     WebThreadLock();
1555
1556     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
1557 }
1558
1559 - (void)_willStartScrollingOrZooming
1560 {
1561     // Pause timers during top level interaction
1562     if (_private->mainViewIsScrollingOrZooming)
1563         return;
1564     _private->mainViewIsScrollingOrZooming = YES;
1565
1566     // This suspends active DOM objects like timers, but not media.
1567     [[self mainFrame] setTimeoutsPaused:YES];
1568
1569     // This defers loading callbacks only.
1570     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
1571     [self setDefersCallbacks:YES];
1572 }
1573
1574 - (void)_didFinishScrollingOrZooming
1575 {
1576     if (!_private->mainViewIsScrollingOrZooming)
1577         return;
1578     _private->mainViewIsScrollingOrZooming = NO;
1579     [self setDefersCallbacks:NO];
1580     [[self mainFrame] setTimeoutsPaused:NO];
1581     if (FrameView* view = [self _mainCoreFrame]->view())
1582         view->resumeVisibleImageAnimationsIncludingSubframes();
1583 }
1584
1585 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
1586 {
1587     if (suspend)
1588         resourceLoadScheduler()->suspendPendingRequests();
1589     else
1590         resourceLoadScheduler()->resumePendingRequests();
1591 }
1592
1593 + (void)_setAllowCookies:(BOOL)allow
1594 {
1595     ResourceRequestBase::setDefaultAllowCookies(allow);
1596 }
1597
1598 + (BOOL)_allowCookies
1599 {
1600     return ResourceRequestBase::defaultAllowCookies();
1601 }
1602
1603 + (BOOL)_isUnderMemoryPressure
1604 {
1605     return memoryPressureHandler().isUnderMemoryPressure();
1606 }
1607
1608 + (void)_clearMemoryPressure
1609 {
1610     memoryPressureHandler().clearMemoryPressure();
1611 }
1612
1613 + (BOOL)_shouldWaitForMemoryClearMessage
1614 {
1615     return memoryPressureHandler().shouldWaitForMemoryClearMessage();
1616 }
1617 #endif // PLATFORM(IOS)
1618
1619 - (void)_closePluginDatabases
1620 {
1621     pluginDatabaseClientCount--;
1622
1623     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
1624
1625 #if !PLATFORM(IOS)
1626     // Unload the WebView local plug-in database. 
1627     if (_private->pluginDatabase) {
1628         [_private->pluginDatabase destroyAllPluginInstanceViews];
1629         [_private->pluginDatabase close];
1630         [_private->pluginDatabase release];
1631         _private->pluginDatabase = nil;
1632     }
1633 #endif
1634     
1635     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
1636     if (!pluginDatabaseClientCount && applicationIsTerminating)
1637         [WebPluginDatabase closeSharedDatabase];
1638 }
1639
1640 - (void)_closeWithFastTeardown 
1641 {
1642 #ifndef NDEBUG
1643     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
1644 #endif
1645
1646 #if !PLATFORM(IOS)
1647     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1648 #endif
1649     [[NSNotificationCenter defaultCenter] removeObserver:self];
1650
1651     [self _closePluginDatabases];
1652 }
1653
1654 static bool fastDocumentTeardownEnabled()
1655 {
1656 #ifdef NDEBUG
1657     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1658 #else
1659     static bool initialized = false;
1660     static bool enabled = false;
1661     if (!initialized) {
1662         // This allows debug builds to default to not have fast teardown, so leak checking still works.
1663         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
1664         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1665         if (setting)
1666             enabled = ![setting boolValue];
1667         initialized = true;
1668     }
1669 #endif
1670     return enabled;
1671 }
1672
1673 // _close is here only for backward compatibility; clients and subclasses should use
1674 // public method -close instead.
1675 - (void)_close
1676 {
1677 #if PLATFORM(IOS)
1678     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
1679     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
1680
1681     [self _clearDelegates];
1682
1683     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1684     WebThreadRun(^{
1685 #endif            
1686
1687     if (!_private || _private->closed)
1688         return;
1689
1690     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
1691
1692     _private->closed = YES;
1693     [self _removeFromAllWebViewsSet];
1694
1695 #ifndef NDEBUG
1696     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1697 #endif
1698
1699     // To quit the apps fast we skip document teardown, except plugins
1700     // need to be destroyed and unloaded.
1701     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1702         [self _closeWithFastTeardown];
1703         return;
1704     }
1705
1706 #if ENABLE(VIDEO) && !PLATFORM(IOS)
1707     [self _exitVideoFullscreen];
1708 #endif
1709
1710 #if PLATFORM(IOS)
1711     _private->closing = YES;
1712 #endif
1713
1714     if (Frame* mainFrame = [self _mainCoreFrame])
1715         mainFrame->loader().detachFromParent();
1716
1717     [self setHostWindow:nil];
1718
1719 #if !PLATFORM(IOS)
1720     [self setDownloadDelegate:nil];
1721     [self setEditingDelegate:nil];
1722     [self setFrameLoadDelegate:nil];
1723     [self setPolicyDelegate:nil];
1724     [self setResourceLoadDelegate:nil];
1725     [self setScriptDebugDelegate:nil];
1726     [self setUIDelegate:nil];
1727
1728     [_private->inspector webViewClosed];
1729     [_private->actionMenuController webViewClosed];
1730 #endif
1731
1732 #if !PLATFORM(IOS)
1733     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1734     [self removeDragCaret];
1735 #endif
1736
1737     _private->group->removeWebView(self);
1738
1739     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
1740     // all the plug-ins in the page cache to break any retain cycles.
1741     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1742     Page* page = _private->page;
1743     _private->page = 0;
1744     delete page;
1745
1746 #if !PLATFORM(IOS)
1747     if (_private->hasSpellCheckerDocumentTag) {
1748         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1749         _private->hasSpellCheckerDocumentTag = NO;
1750     }
1751 #endif
1752
1753     if (_private->layerFlushController) {
1754         _private->layerFlushController->invalidate();
1755         _private->layerFlushController = nullptr;
1756     }
1757     
1758 #if USE(GLIB)
1759     [self _clearGlibLoopObserver];
1760 #endif
1761
1762     [[self _notificationProvider] unregisterWebView:self];
1763
1764 #if !PLATFORM(IOS)
1765     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1766 #endif
1767     [[NSNotificationCenter defaultCenter] removeObserver:self];
1768
1769     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1770
1771     WebPreferences *preferences = _private->preferences;
1772     _private->preferences = nil;
1773     [preferences didRemoveFromWebView];
1774     [preferences release];
1775
1776     [self _closePluginDatabases];
1777
1778 #ifndef NDEBUG
1779     // Need this to make leak messages accurate.
1780     if (applicationIsTerminating) {
1781         gcController().garbageCollectNow();
1782         [WebCache setDisabled:YES];
1783     }
1784 #endif
1785 #if PLATFORM(IOS)
1786     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1787     });
1788 #endif            
1789 }
1790
1791 // Indicates if the WebView is in the midst of a user gesture.
1792 - (BOOL)_isProcessingUserGesture
1793 {
1794     return ScriptController::processingUserGesture();
1795 }
1796
1797 + (NSString *)_MIMETypeForFile:(NSString *)path
1798 {
1799 #if !PLATFORM(IOS)
1800     NSString *extension = [path pathExtension];
1801 #endif
1802     NSString *MIMEType = nil;
1803
1804 #if !PLATFORM(IOS)
1805     // Get the MIME type from the extension.
1806     if ([extension length] != 0) {
1807         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
1808     }
1809 #endif
1810
1811     // If we can't get a known MIME type from the extension, sniff.
1812     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1813         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1814         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1815         [handle closeFile];
1816         if ([data length] != 0) {
1817             MIMEType = [data _webkit_guessedMIMEType];
1818         }
1819         if ([MIMEType length] == 0) {
1820             MIMEType = @"application/octet-stream";
1821         }
1822     }
1823
1824     return MIMEType;
1825 }
1826
1827 - (WebDownload *)_downloadURL:(NSURL *)URL
1828 {
1829     ASSERT(URL);
1830     
1831     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1832     WebDownload *download = [WebDownload _downloadWithRequest:request
1833                                                      delegate:_private->downloadDelegate
1834                                                     directory:nil];
1835     [request release];
1836     
1837     return download;
1838 }
1839
1840 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1841 {
1842     NSDictionary *features = [[NSDictionary alloc] init];
1843     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1844                                             createWebViewWithRequest:nil
1845                                                       windowFeatures:features];
1846     [features release];
1847     if (!newWindowWebView)
1848         return nil;
1849
1850     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1851     return newWindowWebView;
1852 }
1853
1854 - (WebInspector *)inspector
1855 {
1856     if (!_private->inspector)
1857         _private->inspector = [[WebInspector alloc] initWithWebView:self];
1858     return _private->inspector;
1859 }
1860
1861 #if ENABLE(REMOTE_INSPECTOR)
1862 + (void)_enableRemoteInspector
1863 {
1864     RemoteInspector::shared().start();
1865 }
1866
1867 + (void)_disableRemoteInspector
1868 {
1869     RemoteInspector::shared().stop();
1870 }
1871
1872 + (void)_disableAutoStartRemoteInspector
1873 {
1874     RemoteInspector::startDisabled();
1875 }
1876
1877 + (BOOL)_isRemoteInspectorEnabled
1878 {
1879     return RemoteInspector::shared().enabled();
1880 }
1881
1882 + (BOOL)_hasRemoteInspectorSession
1883 {
1884     return RemoteInspector::shared().hasActiveDebugSession();
1885 }
1886
1887 - (BOOL)allowsRemoteInspection
1888 {
1889     return _private->page->remoteInspectionAllowed();
1890 }
1891
1892 - (void)setAllowsRemoteInspection:(BOOL)allow
1893 {
1894     _private->page->setRemoteInspectionAllowed(allow);
1895 }
1896
1897 - (void)setShowingInspectorIndication:(BOOL)showing
1898 {
1899 #if PLATFORM(IOS)
1900     ASSERT(WebThreadIsLocked());
1901
1902     if (showing) {
1903         if (!_private->indicateLayer) {
1904             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
1905             [_private->indicateLayer setNeedsLayout];
1906             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
1907         }
1908     } else {
1909         [_private->indicateLayer removeFromSuperlayer];
1910         [_private->indicateLayer release];
1911         _private->indicateLayer = nil;
1912     }
1913 #else
1914     // Implemented in WebCore::InspectorOverlay.
1915 #endif
1916 }
1917
1918 #if PLATFORM(IOS)
1919 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
1920 {
1921     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
1922     RemoteInspector::shared().setParentProcessInformation(pid, auditData);
1923 }
1924 #endif // PLATFORM(IOS)
1925 #endif // ENABLE(REMOTE_INSPECTOR)
1926
1927 - (WebCore::Page*)page
1928 {
1929     return _private->page;
1930 }
1931
1932 #if !PLATFORM(IOS)
1933 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1934 {
1935     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
1936     NSArray *menuItems = defaultMenuItems;
1937
1938     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
1939     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
1940     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
1941     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
1942         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
1943         if (!menuItems)
1944             return nil;
1945     }
1946
1947     unsigned count = [menuItems count];
1948     if (!count)
1949         return nil;
1950
1951     NSMenu *menu = [[NSMenu alloc] init];
1952     for (unsigned i = 0; i < count; i++)
1953         [menu addItem:[menuItems objectAtIndex:i]];
1954
1955     return [menu autorelease];
1956 }
1957 #endif
1958
1959 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
1960 {
1961     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
1962     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
1963     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
1964     if (!dictionary)
1965         return;
1966     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
1967 }
1968
1969 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
1970 {
1971     if (!_private->page)
1972         return;
1973     
1974     if (!otherView->_private->page)
1975         return;
1976     
1977     // It turns out the right combination of behavior is done with the back/forward load
1978     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
1979     // in the back forward list, and go to the current one.
1980
1981     BackForwardClient* backForwardClient = _private->page->backForward().client();
1982     ASSERT(!backForwardClient->currentItem()); // destination list should be empty
1983
1984     BackForwardClient* otherBackForwardClient = otherView->_private->page->backForward().client();
1985     if (!otherBackForwardClient->currentItem())
1986         return; // empty back forward list, bail
1987     
1988     HistoryItem* newItemToGoTo = 0;
1989
1990     int lastItemIndex = otherBackForwardClient->forwardListCount();
1991     for (int i = -otherBackForwardClient->backListCount(); i <= lastItemIndex; ++i) {
1992         if (i == 0) {
1993             // If this item is showing , save away its current scroll and form state,
1994             // since that might have changed since loading and it is normally not saved
1995             // until we leave that page.
1996             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
1997         }
1998         RefPtr<HistoryItem> newItem = otherBackForwardClient->itemAtIndex(i)->copy();
1999         if (i == 0) 
2000             newItemToGoTo = newItem.get();
2001         backForwardClient->addItem(newItem.release());
2002     }
2003     
2004     ASSERT(newItemToGoTo);
2005     _private->page->goToItem(newItemToGoTo, FrameLoadType::IndexedBackForward);
2006 }
2007
2008 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2009 {
2010     _private->formDelegate = delegate;
2011 #if PLATFORM(IOS)
2012     [_private->formDelegateForwarder clearTarget];
2013     [_private->formDelegateForwarder release];
2014     _private->formDelegateForwarder = nil;
2015 #endif
2016 }
2017
2018 - (id<WebFormDelegate>)_formDelegate
2019 {
2020     return _private->formDelegate;
2021 }
2022
2023 #if PLATFORM(IOS)
2024 - (id)_formDelegateForwarder
2025 {
2026     if (_private->closing)
2027         return nil;
2028
2029     if (!_private->formDelegateForwarder)
2030         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2031     return _private->formDelegateForwarder;
2032 }
2033
2034 - (id)_formDelegateForSelector:(SEL)selector
2035 {
2036     id delegate = self->_private->formDelegate;
2037     if ([delegate respondsToSelector:selector])
2038         return delegate;
2039
2040     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2041     if ([delegate respondsToSelector:selector])
2042         return delegate;
2043
2044     return nil;
2045 }
2046 #endif
2047
2048 #if !PLATFORM(IOS)
2049 - (BOOL)_needsAdobeFrameReloadingQuirk
2050 {
2051     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
2052         || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
2053         || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
2054         || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
2055         || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
2056         || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
2057         || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
2058         || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
2059         || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
2060         || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
2061
2062     return needsQuirk;
2063 }
2064
2065 - (BOOL)_needsLinkElementTextCSSQuirk
2066 {
2067     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2068         && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
2069     return needsQuirk;
2070 }
2071
2072 - (BOOL)_needsIsLoadingInAPISenseQuirk
2073 {
2074     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
2075     
2076     return needsQuirk;
2077 }
2078
2079 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2080 {
2081     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !applicationIsSafari();
2082     return needsQuirks;
2083 }
2084
2085 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2086 {
2087     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);    
2088     return needsQuirk;
2089 }
2090
2091 static bool needsSelfRetainWhileLoadingQuirk()
2092 {
2093     static bool needsQuirk = applicationIsAperture();
2094     return needsQuirk;
2095 }
2096 #endif // !PLATFORM(IOS)
2097
2098 - (BOOL)_needsPreHTML5ParserQuirks
2099 {    
2100 #if !PLATFORM(IOS)
2101     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2102     // with the new HTML5 parser. If these applications were linked against a
2103     // version of WebKit prior to the introduction of the HTML5 parser, enable
2104     // parser quirks to maintain compatibility. For details, see 
2105     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2106     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2107     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2108         && (applicationIsAOLInstantMessenger() || applicationIsMicrosoftMyDay());
2109     
2110     // Mail.app must continue to display HTML email that contains quirky markup.
2111     static bool isAppleMail = applicationIsAppleMail();
2112
2113     return isApplicationNeedingParserQuirks
2114         || isAppleMail
2115 #if ENABLE(DASHBOARD_SUPPORT)
2116         // Pre-HTML5 parser quirks are required to remain compatible with many
2117         // Dashboard widgets. See <rdar://problem/8175982>.
2118         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2119 #endif
2120         || [[self preferences] usePreHTML5ParserQuirks];
2121 #else
2122     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER) && applicationIsDaijisenDictionary();
2123     return isApplicationNeedingParserQuirks || [[self preferences] usePreHTML5ParserQuirks];
2124 #endif
2125 }
2126
2127 - (void)_preferencesChangedNotification:(NSNotification *)notification
2128 {
2129 #if PLATFORM(IOS)
2130     // For WebViews that load synchronously, preference changes need to be propagated
2131     // down to WebCore synchronously so that loads in that WebView have the correct
2132     // up-to-date settings.
2133     if (!WebThreadIsLocked())
2134         WebThreadLock();
2135     if ([[self mainFrame] _loadsSynchronously]) {
2136 #endif
2137
2138     WebPreferences *preferences = (WebPreferences *)[notification object];
2139     [self _preferencesChanged:preferences];
2140
2141 #if PLATFORM(IOS)
2142     } else {
2143         WebThreadRun(^{
2144             // It is possible that the prefs object has already changed before the invocation could be called
2145             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2146             WebPreferences *preferences = (WebPreferences *)[notification object];
2147             if (preferences != [self preferences])
2148                 return;
2149             [self _preferencesChanged:preferences];
2150         });
2151     }
2152 #endif
2153 }
2154
2155 - (void)_preferencesChanged:(WebPreferences *)preferences
2156 {    
2157     ASSERT(preferences == [self preferences]);
2158     if (!_private->userAgentOverridden)
2159         _private->userAgent = String();
2160
2161     // Cache this value so we don't have to read NSUserDefaults on each page load
2162     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2163
2164     // Update corresponding WebCore Settings object.
2165     if (!_private->page)
2166         return;
2167
2168 #if PLATFORM(IOS)
2169     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2170     // didOneTimeInitialization is true so that we don't initialize databases
2171     // until the first WebView has been created. This is because database
2172     // initialization current requires disk access to populate the origins
2173     // quota map and we want to do this lazily by waiting until WebKit is
2174     // used to display web content in a WebView. The possible cases are:
2175     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2176     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2177     if (didOneTimeInitialization) {
2178         if ([preferences databasesEnabled])
2179             [WebDatabaseManager sharedWebDatabaseManager];
2180         
2181         if ([preferences storageTrackerEnabled])
2182             WebKitInitializeStorageIfNecessary();
2183     }
2184 #endif
2185     
2186     Settings& settings = _private->page->settings();
2187
2188     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2189     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2190     settings.setDefaultFontSize([preferences defaultFontSize]);
2191     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2192     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2193     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2194     settings.setFixedFontFamily([preferences fixedFontFamily]);
2195     settings.setScreenFontSubstitutionEnabled(
2196 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2197         [[NSUserDefaults standardUserDefaults] boolForKey:@"NSFontDefaultScreenFontSubstitutionEnabled"] ||
2198 #endif
2199         [preferences screenFontSubstitutionEnabled]
2200     );
2201     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2202     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2203     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2204     settings.setJavaEnabled([preferences isJavaEnabled]);
2205     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2206     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2207     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2208     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2209     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
2210     settings.setMinimumFontSize([preferences minimumFontSize]);
2211     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2212     settings.setPictographFontFamily([preferences pictographFontFamily]);
2213     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2214     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2215
2216     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2217     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2218     settings.setSerifFontFamily([preferences serifFontFamily]);
2219     settings.setStandardFontFamily([preferences standardFontFamily]);
2220     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2221     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2222 #if PLATFORM(IOS)
2223     settings.setShouldPrintBackgrounds(true);
2224 #else
2225     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2226 #endif
2227     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2228     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2229     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2230     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2231     settings.setUsesPageCache([self usesPageCache]);
2232     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2233     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2234
2235     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2236     settings.setJavaScriptExperimentsEnabled([preferences javaScriptExperimentsEnabled]);
2237     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2238     settings.setApplicationChromeMode([preferences applicationChromeModeEnabled]);
2239
2240     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2241     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2242     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2243     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2244     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2245     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2246     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2247     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2248     
2249     // FIXME: Enabling accelerated compositing when WebGL is enabled causes tests to fail on Leopard which expect HW compositing to be disabled.
2250     // Until we fix that, I will comment out the test (CFM)
2251     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2252     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2253     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);    
2254     settings.setShowDebugBorders([preferences showDebugBorders]);
2255     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2256     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2257     settings.setWebGLEnabled([preferences webGLEnabled]);
2258     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2259
2260     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2261     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2262     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2263     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2264     settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2265     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2266     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2267     RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled([preferences cssRegionsEnabled]);
2268     RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled([preferences cssCompositingEnabled]);
2269
2270     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2271     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2272     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2273     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2274     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2275
2276     settings.setMediaPlaybackRequiresUserGesture([preferences mediaPlaybackRequiresUserGesture]);
2277     settings.setMediaPlaybackAllowsInline([preferences mediaPlaybackAllowsInline]);
2278     settings.setAllowsAlternateFullscreen([preferences allowsAlternateFullscreen]);
2279     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2280     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2281     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2282     settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2283
2284     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2285
2286     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2287     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2288     settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2289
2290     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2291
2292     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2293     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2294
2295     switch ([preferences storageBlockingPolicy]) {
2296     case WebAllowAllStorage:
2297         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2298         break;
2299     case WebBlockThirdPartyStorage:
2300         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2301         break;
2302     case WebBlockAllStorage:
2303         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2304         break;
2305     }
2306
2307     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2308
2309     settings.setFixedPositionCreatesStackingContext(true);
2310 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2311     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2312 #endif
2313
2314 #if ENABLE(RUBBER_BANDING)
2315     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2316     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2317 #endif
2318
2319 #if PLATFORM(IOS)
2320     settings.setStandalone([preferences _standalone]);
2321     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2322     settings.setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
2323     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2324     settings.setLayoutInterval(std::chrono::milliseconds([preferences _layoutInterval]));
2325     settings.setMaxParseDuration([preferences _maxParseDuration]);
2326     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2327     settings.setMediaPlaybackAllowsAirPlay([preferences mediaPlaybackAllowsAirPlay]);
2328     settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2329     settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2330     settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2331     settings.setAVKitEnabled([preferences avKitEnabled]);
2332     settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2333     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2334
2335     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2336     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2337
2338     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2339     settings.setDelegatesPageScaling(true);
2340
2341 #if ENABLE(IOS_TEXT_AUTOSIZING)
2342     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2343 #endif
2344 #endif // PLATFORM(IOS)
2345
2346 #if PLATFORM(MAC)
2347     if ([preferences userStyleSheetEnabled]) {
2348         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2349         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2350             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2351         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2352     } else
2353         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2354
2355     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2356     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2357     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2358     settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2359     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2360     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2361     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2362     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2363     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2364     settings.setQTKitEnabled([preferences isQTKitEnabled]);
2365 #endif // PLATFORM(MAC)
2366
2367 #if ENABLE(SQL_DATABASE)
2368     DatabaseManager::manager().setIsAvailable([preferences databasesEnabled]);
2369 #endif
2370
2371 #if ENABLE(MEDIA_SOURCE)
2372     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2373 #endif
2374
2375 #if ENABLE(SERVICE_CONTROLS)
2376     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2377     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2378 #endif
2379
2380 #if ENABLE(VIDEO_TRACK)
2381     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2382     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2383     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2384 #endif
2385
2386 #if USE(AVFOUNDATION)
2387     settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2388 #endif
2389
2390 #if ENABLE(WEB_AUDIO)
2391     settings.setWebAudioEnabled([preferences webAudioEnabled]);
2392 #endif
2393
2394 #if ENABLE(FULLSCREEN_API)
2395     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2396 #endif
2397
2398 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2399     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2400 #endif
2401
2402     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2403
2404 #if ENABLE(GAMEPAD)
2405     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2406 #endif
2407
2408     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2409     if (timeout > 0)
2410         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2411
2412     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2413     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2414
2415     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2416     if (_private->zoomsTextOnly != zoomsTextOnly)
2417         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2418
2419 #if PLATFORM(IOS)
2420     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2421     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2422     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2423     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2424 #endif
2425
2426 #if ENABLE(ENCRYPTED_MEDIA_V2)
2427     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2428 #endif
2429 }
2430
2431 static inline IMP getMethod(id o, SEL s)
2432 {
2433     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2434 }
2435
2436 #if PLATFORM(IOS)
2437 - (id)_UIKitDelegateForwarder
2438 {
2439     if (_private->closing)
2440         return nil;
2441         
2442     if (!_private->UIKitDelegateForwarder)
2443         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2444     return _private->UIKitDelegateForwarder;
2445 }
2446 #endif
2447
2448 - (void)_cacheResourceLoadDelegateImplementations
2449 {
2450     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2451     id delegate = _private->resourceProgressDelegate;
2452
2453     if (!delegate) {
2454         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2455         return;
2456     }
2457
2458     cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
2459     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2460     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2461     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2462     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2463 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2464     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2465 #endif
2466
2467 #if PLATFORM(IOS)
2468     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2469     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2470     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2471     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2472     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2473     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2474     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2475     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2476     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2477 #endif
2478
2479     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2480     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2481     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2482     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2483     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
2484     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
2485     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
2486     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
2487 }
2488
2489 - (void)_cacheFrameLoadDelegateImplementations
2490 {
2491     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
2492     id delegate = _private->frameLoadDelegate;
2493
2494     if (!delegate) {
2495         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
2496         return;
2497     }
2498
2499     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
2500     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
2501     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
2502     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
2503     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
2504 #if JSC_OBJC_API_ENABLED
2505     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
2506 #endif
2507     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
2508     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
2509     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
2510     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
2511     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
2512     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
2513     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
2514     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
2515     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
2516     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
2517     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
2518     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
2519 #if ENABLE(ICONDATABASE)
2520     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
2521 #endif
2522     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
2523     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
2524     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
2525     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
2526     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
2527     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
2528     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
2529     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
2530     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
2531     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
2532 #if PLATFORM(IOS)
2533     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
2534 #endif
2535
2536     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
2537     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
2538     // for backwards compatibility.
2539     Page* page = core(self);
2540     if (page) {
2541         unsigned milestones = DidFirstLayout;
2542 #if PLATFORM(IOS)
2543         milestones |= DidFirstVisuallyNonEmptyLayout;
2544 #else
2545         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
2546             milestones |= DidFirstVisuallyNonEmptyLayout;
2547 #endif
2548         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
2549     }
2550 }
2551
2552 - (void)_cacheScriptDebugDelegateImplementations
2553 {
2554     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
2555     id delegate = _private->scriptDebugDelegate;
2556
2557     if (!delegate) {
2558         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
2559         return;
2560     }
2561
2562     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
2563     if (cache->didParseSourceFunc)
2564         cache->didParseSourceExpectsBaseLineNumber = YES;
2565     else {
2566         cache->didParseSourceExpectsBaseLineNumber = NO;
2567         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
2568     }
2569
2570     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
2571
2572     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
2573     if (cache->exceptionWasRaisedFunc)
2574         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
2575     else {
2576         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
2577         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
2578     }
2579 }
2580
2581 - (void)_cacheHistoryDelegateImplementations
2582 {
2583     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
2584     id delegate = _private->historyDelegate;
2585
2586     if (!delegate) {
2587         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
2588         return;
2589     }
2590
2591     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
2592     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
2593     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
2594     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
2595     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
2596     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
2597 }
2598
2599 - (id)_policyDelegateForwarder
2600 {
2601 #if PLATFORM(IOS)
2602     if (_private->closing)
2603         return nil;
2604 #endif
2605     if (!_private->policyDelegateForwarder)
2606         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
2607     return _private->policyDelegateForwarder;
2608 }
2609
2610 - (id)_UIDelegateForwarder
2611 {
2612 #if PLATFORM(IOS)
2613     if (_private->closing)
2614         return nil;
2615 #endif
2616     if (!_private->UIDelegateForwarder)
2617         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
2618     return _private->UIDelegateForwarder;
2619 }
2620
2621 #if PLATFORM(IOS)
2622 - (id)_UIDelegateForSelector:(SEL)selector
2623 {
2624     id delegate = self->_private->UIDelegate;
2625     if ([delegate respondsToSelector:selector])
2626         return delegate;
2627
2628     delegate = [WebDefaultUIDelegate sharedUIDelegate];
2629     if ([delegate respondsToSelector:selector])
2630         return delegate;
2631
2632     return nil;
2633 }
2634 #endif
2635
2636 - (id)_editingDelegateForwarder
2637 {
2638 #if PLATFORM(IOS)
2639     if (_private->closing)
2640         return nil;
2641 #endif    
2642     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
2643     // Not sure if that is a bug or not.
2644     if (!_private)
2645         return nil;
2646
2647     if (!_private->editingDelegateForwarder)
2648         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
2649     return _private->editingDelegateForwarder;
2650 }
2651
2652 - (void)_closeWindow
2653 {
2654     [[self _UIDelegateForwarder] webViewClose:self];
2655 }
2656
2657 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
2658 {
2659     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2660     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2661     
2662     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2663     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2664     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2665     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
2666 }
2667
2668 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
2669 {
2670     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
2671     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
2672
2673     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2674     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2675     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2676     if ([viewClass class] == [WebHTMLView class])
2677         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2678     
2679     // This is used to make _representationExistsForURLScheme faster.
2680     // Without this set, we'd have to create the MIME type each time.
2681     if (schemesWithRepresentationsSet == nil) {
2682         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
2683     }
2684     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
2685 }
2686
2687 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
2688 {
2689     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
2690 }
2691
2692 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
2693 {
2694     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
2695 }
2696
2697 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
2698 {
2699     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
2700     if (!request)
2701         return NO;
2702
2703     if ([NSURLConnection canHandleRequest:request])
2704         return YES;
2705
2706     NSString *scheme = [[request URL] scheme];
2707
2708     // Representations for URL schemes work at the top level.
2709     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
2710         return YES;
2711
2712     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
2713         return YES;
2714
2715     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
2716         return YES;
2717
2718     return NO;
2719 }
2720
2721 + (BOOL)_canHandleRequest:(NSURLRequest *)request
2722 {
2723     return [self _canHandleRequest:request forMainFrame:YES];
2724 }
2725
2726 + (NSString *)_decodeData:(NSData *)data
2727 {
2728     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
2729     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
2730 }
2731
2732 - (void)_pushPerformingProgrammaticFocus
2733 {
2734     _private->programmaticFocusCount++;
2735 }
2736
2737 - (void)_popPerformingProgrammaticFocus
2738 {
2739     _private->programmaticFocusCount--;
2740 }
2741
2742 - (BOOL)_isPerformingProgrammaticFocus
2743 {
2744     return _private->programmaticFocusCount != 0;
2745 }
2746
2747 #if !PLATFORM(IOS)
2748 - (void)_didChangeValueForKey: (NSString *)key
2749 {
2750     LOG (Bindings, "calling didChangeValueForKey: %@", key);
2751     [self didChangeValueForKey: key];
2752 }
2753
2754 - (void)_willChangeValueForKey: (NSString *)key
2755 {
2756     LOG (Bindings, "calling willChangeValueForKey: %@", key);
2757     [self willChangeValueForKey: key];
2758 }
2759
2760 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
2761     static NSSet *manualNotifyKeys = nil;
2762     if (!manualNotifyKeys)
2763         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2764             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
2765             nil];
2766     if ([manualNotifyKeys containsObject:key])
2767         return NO;
2768     return YES;
2769 }
2770
2771 - (NSArray *)_declaredKeys {
2772     static NSArray *declaredKeys = nil;
2773     if (!declaredKeys)
2774         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2775             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
2776     return declaredKeys;
2777 }
2778
2779 - (void)setObservationInfo:(void *)info
2780 {
2781     _private->observationInfo = info;
2782 }
2783
2784 - (void *)observationInfo
2785 {
2786     return _private->observationInfo;
2787 }
2788
2789 - (void)_willChangeBackForwardKeys
2790 {
2791     [self _willChangeValueForKey: _WebCanGoBackKey];
2792     [self _willChangeValueForKey: _WebCanGoForwardKey];
2793 }
2794
2795 - (void)_didChangeBackForwardKeys
2796 {
2797     [self _didChangeValueForKey: _WebCanGoBackKey];
2798     [self _didChangeValueForKey: _WebCanGoForwardKey];
2799 }
2800
2801 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
2802 {
2803     if (needsSelfRetainWhileLoadingQuirk())
2804         [self retain];
2805
2806     [self _willChangeBackForwardKeys];
2807     if (frame == [self mainFrame]){
2808         // Force an observer update by sending a will/did.
2809         [self _willChangeValueForKey: _WebIsLoadingKey];
2810         [self _didChangeValueForKey: _WebIsLoadingKey];
2811
2812         [self _willChangeValueForKey: _WebMainFrameURLKey];
2813     }
2814
2815     [NSApp setWindowsNeedUpdate:YES];
2816
2817 #if ENABLE(FULLSCREEN_API)
2818     Document* document = core([frame DOMDocument]);
2819     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
2820         SEL selector = @selector(webView:closeFullScreenWithListener:);
2821         if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2822             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
2823             CallUIDelegate(self, selector, listener);
2824             [listener release];
2825         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
2826             [_private->newFullscreenController close];
2827         }
2828     }
2829 #endif
2830 }
2831
2832 - (void)_checkDidPerformFirstNavigation
2833 {
2834     if (_private->_didPerformFirstNavigation)
2835         return;
2836
2837     Page* page = _private->page;
2838     if (!page)
2839         return;
2840
2841     auto& backForwardController = page->backForward();
2842
2843     if (!backForwardController.backItem())
2844         return;
2845
2846     _private->_didPerformFirstNavigation = YES;
2847
2848     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
2849         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
2850 }
2851
2852 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2853 {
2854     if (frame == [self mainFrame])
2855         [self _didChangeValueForKey: _WebMainFrameURLKey];
2856
2857     [self _checkDidPerformFirstNavigation];
2858
2859     [NSApp setWindowsNeedUpdate:YES];
2860 }
2861
2862 - (void)_didFinishLoadForFrame:(WebFrame *)frame
2863 {
2864     if (needsSelfRetainWhileLoadingQuirk())
2865         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2866         
2867     [self _didChangeBackForwardKeys];
2868     if (frame == [self mainFrame]){
2869         // Force an observer update by sending a will/did.
2870         [self _willChangeValueForKey: _WebIsLoadingKey];
2871         [self _didChangeValueForKey: _WebIsLoadingKey];
2872     }
2873     [NSApp setWindowsNeedUpdate:YES];
2874 }
2875
2876 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2877 {
2878     if (needsSelfRetainWhileLoadingQuirk())
2879         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2880
2881     [self _didChangeBackForwardKeys];
2882     if (frame == [self mainFrame]){
2883         // Force an observer update by sending a will/did.
2884         [self _willChangeValueForKey: _WebIsLoadingKey];
2885         [self _didChangeValueForKey: _WebIsLoadingKey];
2886     }
2887     [NSApp setWindowsNeedUpdate:YES];
2888 }
2889
2890 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2891 {
2892     if (needsSelfRetainWhileLoadingQuirk())
2893         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2894
2895     [self _didChangeBackForwardKeys];
2896     if (frame == [self mainFrame]){
2897         // Force an observer update by sending a will/did.
2898         [self _willChangeValueForKey: _WebIsLoadingKey];
2899         [self _didChangeValueForKey: _WebIsLoadingKey];
2900         
2901         [self _didChangeValueForKey: _WebMainFrameURLKey];
2902     }
2903     [NSApp setWindowsNeedUpdate:YES];
2904 }
2905
2906 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
2907 {
2908     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
2909     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
2910     NSCachedURLResponse *cachedResponse;
2911
2912     if (!_private->page)
2913         return nil;
2914
2915     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
2916         cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
2917     else
2918         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
2919
2920     return cachedResponse;
2921 }
2922
2923 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2924 {
2925     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
2926     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
2927     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
2928                         element:domElement
2929                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
2930                           title:[element objectForKey:WebElementImageAltStringKey] 
2931                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
2932                           types:types
2933                          source:nil];
2934 }
2935
2936 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2937 {
2938     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
2939                      andTitle:[element objectForKey:WebElementLinkLabelKey]
2940                         types:types];
2941 }
2942
2943 #if ENABLE(DRAG_SUPPORT)
2944 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
2945 {
2946     if (!_private->page)
2947         return;
2948     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
2949 }
2950 #endif
2951
2952 #else
2953
2954 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2955 {
2956     if (frame == [self mainFrame])
2957         _private->didDrawTiles = 0;
2958 }
2959
2960 #endif // PLATFORM(IOS)
2961
2962 #if ENABLE(DASHBOARD_SUPPORT)
2963
2964 #define DASHBOARD_CONTROL_LABEL @"control"
2965
2966 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
2967 {
2968     NSRect adjustedBounds = bounds;
2969     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
2970     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
2971     adjustedBounds.size = bounds.size;
2972
2973     NSRect adjustedClip;
2974     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
2975     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
2976     adjustedClip.size = clip.size;
2977
2978     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
2979         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
2980     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
2981     if (!scrollerRegions) {
2982         scrollerRegions = [[NSMutableArray alloc] init];
2983         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
2984         [scrollerRegions release];
2985     }
2986     [scrollerRegions addObject:region];
2987     [region release];
2988 }
2989
2990 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
2991 {    
2992     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
2993
2994     for (const auto& widget: frameView->children()) {
2995         if (is<FrameView>(*widget)) {
2996             [self _addScrollerDashboardRegionsForFrameView:downcast<FrameView>(widget.get()) dashboardRegions:regions];
2997             continue;
2998         }
2999
3000         if (!widget->isScrollbar())
3001             continue;
3002
3003         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3004         // it's not common to need this to be correct in Dashboard widgets.
3005         NSRect bounds = widget->frameRect();
3006         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3007     }
3008 }
3009
3010 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3011 {
3012     // Add scroller regions for NSScroller and WebCore scrollbars
3013     NSUInteger count = [views count];
3014     for (NSUInteger i = 0; i < count; i++) {
3015         NSView *view = [views objectAtIndex:i];
3016         
3017         if ([view isKindOfClass:[WebHTMLView class]]) {
3018             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3019                 if (FrameView* coreView = coreFrame->view())
3020                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3021             }
3022         } else if ([view isKindOfClass:[NSScroller class]]) {
3023             // AppKit places absent scrollers at -100,-100
3024             if ([view frame].origin.y < 0)
3025                 continue;
3026             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3027         }
3028         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3029     }
3030 }
3031
3032 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3033 {
3034     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3035 }
3036
3037 - (NSDictionary *)_dashboardRegions
3038 {
3039     // Only return regions from main frame.
3040     Frame* mainFrame = [self _mainCoreFrame];
3041     if (!mainFrame)
3042         return nil;
3043
3044     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3045     size_t size = regions.size();
3046
3047     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3048     for (size_t i = 0; i < size; i++) {
3049         const AnnotatedRegionValue& region = regions[i];
3050
3051         if (region.type == StyleDashboardRegion::None)
3052             continue;
3053
3054         NSString *label = region.label;
3055         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3056         if (region.type == StyleDashboardRegion::Circle)
3057             type = WebDashboardRegionTypeCircle;
3058         else if (region.type == StyleDashboardRegion::Rectangle)
3059             type = WebDashboardRegionTypeRectangle;
3060         NSMutableArray *regionValues = [webRegions objectForKey:label];
3061         if (!regionValues) {
3062             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3063             [webRegions setObject:regionValues forKey:label];
3064             [regionValues release];
3065         }
3066
3067         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3068         [regionValues addObject:webRegion];
3069         [webRegion release];
3070     }
3071
3072     [self _addScrollerDashboardRegions:webRegions];
3073
3074     return webRegions;
3075 }
3076
3077 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3078 {
3079     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3080     // specific support for the backward compatibility mode flag.
3081     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3082         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3083     
3084     switch (behavior) {
3085         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3086             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3087             break;
3088         }
3089         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3090             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3091             break;
3092         }
3093         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3094             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3095             break;
3096         }
3097         case WebDashboardBehaviorAllowWheelScrolling: {
3098             _private->dashboardBehaviorAllowWheelScrolling = flag;
3099             break;
3100         }
3101         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3102             if (_private->page)
3103                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3104 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3105             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3106 #endif
3107             break;
3108         }
3109     }
3110
3111     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3112     // compatibility mode. See <rdar://problem/8175982>.
3113     if (_private->page)
3114         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3115 }
3116
3117 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3118 {
3119     switch (behavior) {
3120         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3121             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3122         }
3123         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3124             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3125         }
3126         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3127             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3128         }
3129         case WebDashboardBehaviorAllowWheelScrolling: {
3130             return _private->dashboardBehaviorAllowWheelScrolling;
3131         }
3132         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3133             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3134         }
3135     }
3136     return NO;
3137 }
3138
3139 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3140
3141 + (void)_setShouldUseFontSmoothing:(BOOL)f
3142 {
3143     Font::setShouldUseSmoothing(f);
3144 }
3145
3146 + (BOOL)_shouldUseFontSmoothing
3147 {
3148     return Font::shouldUseSmoothing();
3149 }
3150
3151 #if !PLATFORM(IOS)
3152 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3153 {
3154     setUsesTestModeFocusRingColor(f);
3155 }
3156
3157 + (BOOL)_usesTestModeFocusRingColor
3158 {
3159     return usesTestModeFocusRingColor();
3160 }
3161 #endif
3162
3163 #if PLATFORM(IOS)
3164 - (void)_setUIKitDelegate:(id)delegate
3165 {
3166     _private->UIKitDelegate = delegate;
3167     [_private->UIKitDelegateForwarder clearTarget];
3168     [_private->UIKitDelegateForwarder release];
3169     _private->UIKitDelegateForwarder = nil;
3170 }
3171
3172 - (id)_UIKitDelegate
3173 {
3174     return _private->UIKitDelegate;
3175 }
3176
3177 - (void)setWebMailDelegate:(id)delegate
3178 {
3179     _private->WebMailDelegate = delegate;
3180 }
3181
3182 - (id)_webMailDelegate
3183 {
3184     return _private->WebMailDelegate;
3185 }
3186
3187 - (id <WebCaretChangeListener>)caretChangeListener
3188 {
3189     return _private->_caretChangeListener;
3190 }
3191
3192 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3193 {
3194     _private->_caretChangeListener = listener;
3195 }
3196
3197 - (NSSet *)caretChangeListeners
3198 {
3199     return _private->_caretChangeListeners;
3200 }
3201
3202 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3203 {
3204     if (_private->_caretChangeListeners == nil) {
3205         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3206     }
3207     
3208     [_private->_caretChangeListeners addObject:listener];
3209 }
3210
3211 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3212 {
3213     [_private->_caretChangeListeners removeObject:listener];
3214 }
3215
3216 - (void)removeAllCaretChangeListeners
3217 {
3218     [_private->_caretChangeListeners removeAllObjects];
3219 }
3220
3221 - (void)caretChanged
3222 {
3223     [_private->_caretChangeListener caretChanged];
3224     NSSet *copy = [_private->_caretChangeListeners copy];
3225     for (id <WebCaretChangeListener> listener in copy) {
3226         [listener caretChanged];
3227     }
3228     [copy release];
3229 }
3230
3231 - (void)_clearDelegates
3232 {
3233     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3234     
3235     [self _setFormDelegate:nil];
3236     [self _setUIKitDelegate:nil];
3237     [self setCaretChangeListener:nil];
3238     [self removeAllCaretChangeListeners];
3239     [self setWebMailDelegate:nil];
3240     
3241     [self setDownloadDelegate:nil];
3242     [self setEditingDelegate:nil]; 
3243     [self setFrameLoadDelegate:nil];
3244     [self setPolicyDelegate:nil];
3245     [self setResourceLoadDelegate:nil];
3246     [self setScriptDebugDelegate:nil];
3247     [self setUIDelegate:nil];     
3248 }
3249
3250 - (NSURL *)_displayURL
3251 {
3252     WebThreadLock();
3253     WebFrame *frame = [self mainFrame];
3254     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3255     WebDataSource *dataSource = [frame provisionalDataSource];
3256     if (!dataSource)
3257         dataSource = [frame dataSource];
3258     NSURL *unreachableURL = [dataSource unreachableURL];
3259     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3260     [[URL retain] autorelease];
3261     return URL;
3262 }
3263 #endif // PLATFORM(IOS)
3264
3265 #if !PLATFORM(IOS)
3266 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3267 {
3268     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3269     if (flag) {
3270         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3271     } else {
3272         [scrollview setVerticalScrollingModeLocked:NO];
3273         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3274     }
3275 }
3276
3277 - (BOOL)alwaysShowVerticalScroller
3278 {
3279     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3280     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3281 }
3282
3283 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3284 {
3285     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3286     if (flag) {
3287         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3288     } else {
3289         [scrollview setHorizontalScrollingModeLocked:NO];
3290         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3291     }
3292 }
3293
3294 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3295 {
3296     if (Frame* mainFrame = [self _mainCoreFrame])
3297         mainFrame->view()->setProhibitsScrolling(prohibits);
3298 }
3299
3300 - (BOOL)alwaysShowHorizontalScroller
3301 {
3302     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3303     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3304 }
3305 #endif // !PLATFORM(IOS)
3306
3307 - (void)_setUseFastImageScalingMode:(BOOL)flag
3308 {
3309     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3310         _private->page->setInLowQualityImageInterpolationMode(flag);
3311         [self setNeedsDisplay:YES];
3312     }
3313 }
3314
3315 - (BOOL)_inFastImageScalingMode
3316 {
3317     if (_private->page)
3318         return _private->page->inLowQualityImageInterpolationMode();
3319     return NO;
3320 }
3321
3322 - (BOOL)_cookieEnabled
3323 {
3324     if (_private->page)
3325         return _private->page->settings().cookieEnabled();
3326     return YES;
3327 }
3328
3329 - (void)_setCookieEnabled:(BOOL)enable
3330 {
3331     if (_private->page)
3332         _private->page->settings().setCookieEnabled(enable);
3333 }
3334
3335 #if !PLATFORM(IOS)
3336 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3337 {
3338     if (!_private->pluginDatabase)
3339         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3340         
3341     [_private->pluginDatabase setPlugInPaths:newPaths];
3342     [_private->pluginDatabase refresh];
3343 }
3344 #endif
3345
3346 #if PLATFORM(IOS)
3347 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3348 {
3349     // Ask plug-ins in this frame
3350     id <WebDocumentView> documentView = [[frame frameView] documentView];
3351     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3352         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3353             return YES;
3354     }
3355
3356     // Ask plug-ins in child frames
3357     NSArray *childFrames = [frame childFrames];
3358     unsigned childCount = [childFrames count];
3359     unsigned childIndex;
3360     for (childIndex = 0; childIndex < childCount; childIndex++) {
3361         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3362             return YES;
3363     }
3364     
3365     return NO;
3366 }
3367
3368 - (BOOL)_pluginsAreRunning
3369 {
3370     WebThreadLock();
3371     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3372 }
3373
3374 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3375 {
3376     // Send the message to plug-ins in this frame
3377     id <WebDocumentView> documentView = [[frame frameView] documentView];
3378     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3379         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3380
3381     // Send the message to plug-ins in child frames
3382     NSArray *childFrames = [frame childFrames];
3383     unsigned childCount = [childFrames count];
3384     unsigned childIndex;
3385     for (childIndex = 0; childIndex < childCount; childIndex++) {
3386         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3387     }
3388 }
3389
3390 - (void)_destroyAllPlugIns
3391 {
3392     WebThreadLock();
3393     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3394 }
3395
3396 - (void)_clearBackForwardCache
3397 {
3398     WebThreadRun(^{
3399         WebKit::MemoryMeasure measurer("[WebView _clearBackForwardCache]");
3400         BackForwardList* bfList = core([self backForwardList]);
3401         if (!bfList)
3402             return;
3403
3404         BOOL didClearBFCache = bfList->clearAllPageCaches();
3405         if (WebKit::MemoryMeasure::isLoggingEnabled())
3406             NSLog(@"[WebView _clearBackForwardCache] %@ empty cache\n", (didClearBFCache ? @"DID" : @"did NOT"));
3407     });
3408 }
3409
3410 - (void)_startAllPlugIns
3411 {
3412     WebThreadLock();
3413     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3414 }
3415
3416 - (void)_stopAllPlugIns
3417 {
3418     WebThreadLock();
3419     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3420 }
3421
3422 - (void)_stopAllPlugInsForPageCache
3423 {
3424     WebThreadLock();
3425     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3426 }
3427
3428 - (void)_restorePlugInsFromCache
3429 {
3430     WebThreadLock();
3431     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3432 }
3433
3434 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3435 {
3436     WebThreadLock();
3437
3438     Frame* mainCoreFrame = [self _mainCoreFrame];
3439     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3440         FrameView* coreView = frame ? frame->view() : 0;
3441         if (!coreView)
3442             continue;
3443
3444         // Get the GraphicsLayer for this widget.
3445         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3446         if (!layerForWidget)
3447             continue;
3448         
3449         if (layerForWidget->contentsLayerForMedia() != layer) {
3450             layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3451             // We need to make sure the layer hierachy change is applied immediately.
3452             if (mainCoreFrame->view())
3453                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3454             return YES;
3455         }
3456     }
3457
3458     return NO;
3459 }
3460
3461 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3462 {
3463     if (_private->page)
3464         _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3465 }
3466 #endif // PLATFORM(IOS)
3467
3468 - (void)_attachScriptDebuggerToAllFrames
3469 {
3470     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3471         [kit(frame) _attachScriptDebugger];
3472 }
3473
3474 - (void)_detachScriptDebuggerFromAllFrames
3475 {
3476     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3477         [kit(frame) _detachScriptDebugger];
3478 }
3479
3480 #if !PLATFORM(IOS)
3481 - (void)setBackgroundColor:(NSColor *)backgroundColor
3482 {
3483     if ([_private->backgroundColor isEqual:backgroundColor])
3484         return;
3485
3486     id old = _private->backgroundColor;
3487     _private->backgroundColor = [backgroundColor retain];
3488     [old release];
3489
3490     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3491 }
3492
3493 - (NSColor *)backgroundColor
3494 {
3495     return _private->backgroundColor;
3496 }
3497 #else
3498 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3499 {
3500    if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3501         return;
3502
3503     CFTypeRef old = _private->backgroundColor;
3504     CFRetain(backgroundColor);
3505     _private->backgroundColor = backgroundColor;
3506     CFRelease(old);
3507
3508     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3509 }
3510
3511 - (CGColorRef)backgroundColor
3512 {
3513     return _private->backgroundColor;
3514 }
3515 #endif
3516
3517 - (BOOL)defersCallbacks
3518 {
3519     if (!_private->page)
3520         return NO;
3521     return _private->page->defersLoading();
3522 }
3523
3524 - (void)setDefersCallbacks:(BOOL)defer
3525 {
3526     if (!_private->page)
3527         return;
3528     return _private->page->setDefersLoading(defer);
3529 }
3530
3531 #if TARGET_OS_IPHONE && USE(QUICK_LOOK)
3532 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
3533 {
3534     NSString *uti = qlPreviewConverterUTIForURL(url);
3535     if (!uti)
3536         return nil;
3537
3538     NSString *fileName = qlPreviewConverterFileNameForURL(url);
3539     if (!fileName)
3540         return nil;
3541
3542     return [NSDictionary dictionaryWithObjectsAndKeys: fileName, WebQuickLookFileNameKey, uti, WebQuickLookUTIKey, nil];
3543 }
3544 #endif
3545
3546 #if PLATFORM(IOS)
3547 - (BOOL)_isStopping
3548 {
3549     return _private->isStopping;
3550 }
3551
3552 - (BOOL)_isClosing
3553 {
3554     return _private->closing;
3555 }
3556
3557 + (NSArray *)_productivityDocumentMIMETypes
3558 {
3559 #if USE(QUICK_LOOK)
3560     return [QLPreviewGetSupportedMIMETypesSet() allObjects];
3561 #else
3562     return nil;
3563 #endif
3564 }
3565
3566 - (void)_setAllowsMessaging:(BOOL)aFlag
3567 {
3568     _private->allowsMessaging = aFlag;
3569 }
3570
3571 - (BOOL)_allowsMessaging
3572 {
3573     return _private->allowsMessaging;
3574 }
3575
3576 - (void)_setFixedLayoutSize:(CGSize)size
3577 {
3578     ASSERT(WebThreadIsLocked());
3579     _private->fixedLayoutSize = size;
3580     if (Frame* mainFrame = core([self mainFrame])) {
3581         IntSize newSize(size);
3582         mainFrame->view()->setFixedLayoutSize(newSize);
3583         mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
3584         [self setNeedsDisplay:YES];
3585     }
3586 }
3587
3588 - (CGSize)_fixedLayoutSize
3589 {
3590     return _private->fixedLayoutSize;
3591 }
3592
3593 - (void)_synchronizeCustomFixedPositionLayoutRect
3594 {
3595     ASSERT(WebThreadIsLocked());
3596
3597     IntRect newRect;
3598     {
3599         MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3600         if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
3601             return;
3602         newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
3603         _private->pendingFixedPositionLayoutRect = CGRectNull;
3604     }
3605
3606     if (Frame* mainFrame = core([self mainFrame]))
3607         mainFrame->view()->setCustomFixedPositionLayoutRect(newRect);
3608 }
3609
3610 - (void)_setCustomFixedPositionLayoutRectInWebThread:(CGRect)rect synchronize:(BOOL)synchronize
3611 {
3612     {
3613         MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3614         _private->pendingFixedPositionLayoutRect = rect;
3615     }
3616     if (!synchronize)
3617         return;
3618     WebThreadRun(^{
3619         [self _synchronizeCustomFixedPositionLayoutRect];
3620     });
3621 }
3622
3623 - (void)_setCustomFixedPositionLayoutRect:(CGRect)rect
3624 {
3625     ASSERT(WebThreadIsLocked());
3626     {
3627         MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3628         _private->pendingFixedPositionLayoutRect = rect;
3629     }
3630     [self _synchronizeCustomFixedPositionLayoutRect];
3631 }
3632
3633 - (BOOL)_fetchCustomFixedPositionLayoutRect:(NSRect*)rect
3634 {
3635     MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3636     if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
3637         return false;
3638
3639     *rect = _private->pendingFixedPositionLayoutRect;
3640     _private->pendingFixedPositionLayoutRect = CGRectNull;
3641     return true;
3642 }
3643
3644 - (void)_viewGeometryDidChange
3645 {
3646     ASSERT(WebThreadIsLocked());
3647     
3648     if (Frame* coreFrame = [self _mainCoreFrame])
3649         coreFrame->viewportOffsetChanged(Frame::IncrementalScrollOffset);
3650 }
3651
3652 - (void)_overflowScrollPositionChangedTo:(CGPoint)offset forNode:(DOMNode *)domNode isUserScroll:(BOOL)userScroll
3653 {
3654     // Find the frame
3655     Node* node = core(domNode);
3656     Frame* frame = node->document().frame();
3657     if (!frame)
3658         return;
3659
3660     frame->overflowScrollPositionChangedForNode(roundedIntPoint(offset), node, userScroll);
3661 }
3662
3663 + (void)_doNotStartObservingNetworkReachability
3664 {
3665     Settings::setShouldOptOutOfNetworkStateObservation(true);
3666 }
3667 #endif // PLATFORM(IOS)
3668
3669 #if ENABLE(TOUCH_EVENTS)
3670 - (NSArray *)_touchEventRegions
3671 {
3672     Frame* frame = [self _mainCoreFrame];
3673     if (!frame)
3674         return nil;
3675     
3676     Document* document = frame->document();
3677     if (!document)
3678         return nil;
3679
3680     Vector<IntRect> rects;
3681     document->getTouchRects(rects);
3682
3683     if (rects.size() == 0)
3684         return nil;
3685
3686     NSMutableArray *eventRegionArray = [[[NSMutableArray alloc] initWithCapacity:rects.size()] autorelease];
3687
3688     Vector<IntRect>::const_iterator end = rects.end();
3689     for (Vector<IntRect>::const_iterator it = rects.begin(); it != end; ++it) {
3690         const IntRect& rect = *it;
3691         if (rect.isEmpty())
3692             continue;
3693
3694         // Note that these rectangles are in the coordinate system of the document (inside the WebHTMLView), which is not
3695         // the same as the coordinate system of the WebView. If you want to do comparisons with locations in the WebView,
3696         // you must convert between the two using WAKView's convertRect:toView: selector. This will take care of scaling
3697         // and translations (which are relevant for right-to-left column layout).
3698
3699         // The event region wants this points in this order:
3700         //  p2------p3
3701         //  |       |
3702         //  p1------p4
3703         //
3704         WebEventRegion *eventRegion = [[WebEventRegion alloc] initWithPoints:FloatPoint(rect.x(), rect.maxY())
3705                                                                             :FloatPoint(rect.x(), rect.y())
3706                                                                             :FloatPoint(rect.maxX(), rect.y())
3707                                                                             :FloatPoint(rect.maxX(), rect.maxY())];
3708         if (eventRegion) {
3709             [eventRegionArray addObject:eventRegion];
3710             [eventRegion release];
3711         }
3712     }
3713
3714     return eventRegionArray;
3715 }
3716 #endif // ENABLE(TOUCH_EVENTS)
3717
3718 // For backwards compatibility with the WebBackForwardList API, we honor both
3719 // a per-WebView and a per-preferences setting for whether to use the page cache.
3720
3721 - (BOOL)usesPageCache
3722 {
3723     return _private->usesPageCache && [[self preferences] usesPageCache];
3724 }
3725
3726 - (void)setUsesPageCache:(BOOL)usesPageCache
3727 {
3728     _private->usesPageCache = usesPageCache;
3729
3730     // Update our own settings and post the public notification only
3731     [self _preferencesChanged:[self preferences]];
3732     [[self preferences] _postPreferencesChangedAPINotification];
3733 }
3734
3735 - (WebHistoryItem *)_globalHistoryItem
3736 {
3737     if (!_private)
3738         return nil;
3739
3740     return kit(_private->_globalHistoryItem.get());
3741 }
3742
3743 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
3744 {
3745     _private->_globalHistoryItem = historyItem;
3746 }
3747
3748 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
3749 {
3750     IntPoint rectStart(rect.origin.x, rect.origin.y);
3751     IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
3752     
3753     Frame* coreFrame = [self _mainCoreFrame];
3754     if (!coreFrame)
3755         return nil;
3756     
3757     VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
3758     
3759     return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
3760 }
3761
3762 #if ENABLE(DASHBOARD_SUPPORT)
3763 - (void)handleAuthenticationForResource:(id)identifier challenge:(NSURLAuthenticationChallenge *)challenge fromDataSource:(WebDataSource *)dataSource 
3764 {
3765     NSWindow *window = [self hostWindow] ? [self hostWindow] : [self window]; 
3766     [[WebPanelAuthenticationHandler sharedHandler] startAuthentication:challenge window:window]; 
3767
3768 #endif
3769
3770 #if !PLATFORM(IOS)
3771 - (void)_clearUndoRedoOperations
3772 {
3773     if (!_private->page)
3774         return;
3775     _private->page->clearUndoRedoOperations();
3776 }
3777 #endif
3778
3779 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
3780 {
3781     Frame* coreFrame = [self _mainCoreFrame];
3782     if (!coreFrame)
3783         return;
3784     coreFrame->editor().command(name).execute(value);
3785 }
3786
3787 - (void)_clearMainFrameName
3788 {
3789     _private->page->mainFrame().tree().clearName();
3790 }
3791
3792 - (void)setSelectTrailingWhitespaceEnabled:(BOOL)flag
3793 {
3794     if (_private->page->settings().selectTrailingWhitespaceEnabled() != flag) {
3795         _private->page->settings().setSelectTrailingWhitespaceEnabled(flag);
3796         [self setSmartInsertDeleteEnabled:!flag];
3797     }
3798 }
3799
3800 - (BOOL)isSelectTrailingWhitespaceEnabled
3801 {
3802     return _private->page->settings().selectTrailingWhitespaceEnabled();
3803 }
3804
3805 - (void)setMemoryCacheDelegateCallsEnabled:(BOOL)enabled
3806 {
3807     _private->page->setMemoryCacheClientCallsEnabled(enabled);
3808 }
3809
3810 - (BOOL)areMemoryCacheDelegateCallsEnabled
3811 {
3812     return _private->page->areMemoryCacheClientCallsEnabled();
3813 }
3814
3815 #if !PLATFORM(IOS)
3816 + (NSCursor *)_pointingHandCursor
3817 {
3818     return handCursor().platformCursor();
3819 }
3820 #endif
3821
3822 - (BOOL)_postsAcceleratedCompositingNotifications
3823 {
3824     return _private->postsAcceleratedCompositingNotifications;
3825 }
3826 - (void)_setPostsAcceleratedCompositingNotifications:(BOOL)flag
3827 {
3828     _private->postsAcceleratedCompositingNotifications = flag;
3829 }
3830
3831 - (BOOL)_isUsingAcceleratedCompositing
3832 {
3833     Frame* coreFrame = [self _mainCoreFrame];
3834     for (Frame* frame = coreFrame; frame; frame = frame->tree().traverseNext(coreFrame)) {
3835         NSView *documentView = [[kit(frame) frameView] documentView];
3836         if ([documentView isKindOfClass:[WebHTMLView class]] && [(WebHTMLView *)documentView _isUsingAcceleratedCompositing])
3837             return YES;
3838     }
3839
3840     return NO;
3841 }
3842
3843 - (void)_setBaseCTM:(CGAffineTransform)transform forContext:(CGContextRef)context
3844 {
3845     WKSetBaseCTM(context, transform);
3846 }
3847
3848 - (BOOL)interactiveFormValidationEnabled
3849 {
3850     return _private->interactiveFormValidationEnabled;
3851 }
3852
3853 - (void)setInteractiveFormValidationEnabled:(BOOL)enabled
3854 {
3855     _private->interactiveFormValidationEnabled = enabled;
3856 }
3857
3858 - (int)validationMessageTimerMagnification
3859 {
3860     return _private->validationMessageTimerMagnification;
3861 }
3862
3863 - (void)setValidationMessageTimerMagnification:(int)newValue
3864 {
3865     _private->validationMessageTimerMagnification = newValue;
3866 }
3867
3868 - (BOOL)_isSoftwareRenderable
3869 {
3870     Frame* coreFrame = [self _mainCoreFrame];
3871     for (Frame* frame = coreFrame; frame; frame = frame->tree().traverseNext(coreFrame)) {
3872         if (FrameView* view = frame->view()) {
3873             if (!view->isSoftwareRenderable())
3874                 return NO;
3875         }
3876     }
3877
3878     return YES;
3879 }
3880
3881 - (void)_setIncludesFlattenedCompositingLayersWhenDrawingToBitmap:(BOOL)flag
3882 {
3883     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = flag;
3884 }
3885
3886 - (BOOL)_includesFlattenedCompositingLayersWhenDrawingToBitmap
3887 {
3888     return _private->includesFlattenedCompositingLayersWhenDrawingToBitmap;
3889 }
3890
3891 - (void)setTracksRepaints:(BOOL)flag
3892 {
3893     Frame* coreFrame = [self _mainCoreFrame];
3894     if (FrameView* view = coreFrame->view())
3895         view->setTracksRepaints(flag);
3896 }
3897
3898 - (BOOL)isTrackingRepaints
3899 {
3900     Frame* coreFrame = [self _mainCoreFrame];
3901     if (FrameView* view = coreFrame->view())
3902         return view->isTrackingRepaints();
3903     
3904     return NO;
3905 }
3906
3907 - (void)resetTrackedRepaints
3908 {
3909     Frame* coreFrame = [self _mainCoreFrame];
3910     if (FrameView* view = coreFrame->view())
3911         view->resetTrackedRepaints();
3912 }
3913
3914 - (NSArray*)trackedRepaintRects
3915 {
3916     Frame* coreFrame = [self _mainCoreFrame];
3917     FrameView* view = coreFrame->view();
3918     if (!view || !view->isTrackingRepaints())
3919         return nil;
3920
3921     const Vector<FloatRect>& repaintRects = view->trackedRepaintRects();
3922     NSMutableArray* rectsArray = [[NSMutableArray alloc] initWithCapacity:repaintRects.size()];
3923     
3924     for (unsigned i = 0; i < repaintRects.size(); ++i)
3925         [rectsArray addObject:[NSValue valueWithRect:snappedIntRect(LayoutRect(repaintRects[i]))]];
3926
3927     return [rectsArray autorelease];
3928 }
3929
3930 #if !PLATFORM(IOS)
3931 - (NSPasteboard *)_insertionPasteboard
3932 {
3933     return _private ? _private->insertionPasteboard : nil;
3934 }
3935 #endif
3936
3937 + (void)_addOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
3938 {
3939     SecurityPolicy::addOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
3940 }
3941
3942 + (void)_removeOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
3943 {
3944     SecurityPolicy::removeOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(sourceOrigin), destinationProtocol, destinationHost, allowDestinationSubdomains);
3945 }
3946
3947 + (void)_resetOriginAccessWhitelists
3948 {
3949     SecurityPolicy::resetOriginAccessWhitelists();
3950 }
3951
3952 - (BOOL)_isViewVisible
3953 {
3954     if (![self window])
3955         return false;
3956
3957     if (![[self window] isVisible])
3958         return false;
3959
3960     if ([self isHiddenOrHasHiddenAncestor])
3961         return false;
3962
3963     return true;
3964 }
3965
3966 - (void)_updateVisibilityState
3967 {
3968     if (_private && _private->page)
3969         [self _setIsVisible:[self _isViewVisible]];
3970 }
3971
3972 - (void)_updateActiveState
3973 {
3974     if (_private && _private->page)
3975 #if PLATFORM(IOS)
3976         _private->page->focusController().setActive([[self window] isKeyWindow]);
3977 #else
3978         _private->page->focusController().setActive([[self window] _hasKeyAppearance]);
3979 #endif
3980 }
3981
3982 static Vector<String> toStringVector(NSArray* patterns)
3983 {
3984     Vector<String> patternsVector;
3985
3986     NSUInteger count = [patterns count];
3987     if (!count)
3988         return patternsVector;
3989
3990     for (NSUInteger i = 0; i < count; ++i) {
3991         id entry = [patterns objectAtIndex:i];
3992         if ([entry isKindOfClass:[NSString class]])
3993             patternsVector.append(String((NSString *)entry));
3994     }
3995     return patternsVector;
3996 }
3997
3998 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
3999                     whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4000                 injectionTime:(WebUserScriptInjectionTime)injectionTime
4001 {
4002     [WebView _addUserScriptToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectionTime:injectionTime injectedFrames:WebInjectInAllFrames];
4003 }
4004
4005 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4006                     whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4007                 injectionTime:(WebUserScriptInjectionTime)injectionTime
4008                injectedFrames:(WebUserContentInjectedFrames)injectedFrames
4009 {
4010     String group(groupName);
4011     if (group.isEmpty())
4012         return;
4013
4014     auto* viewGroup = WebViewGroup::get(group);
4015     if (!viewGroup)
4016         return;
4017
4018     if (!world)
4019         return;
4020
4021     auto userScript = std::make_unique<UserScript>(source, url, toStringVector(whitelist), toStringVector(blacklist), injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd, injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
4022     viewGroup->userContentController().addUserScript(*core(world), WTF::move(userScript));
4023 }
4024
4025 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4026                         whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4027 {
4028     [WebView _addUserStyleSheetToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectedFrames:WebInjectInAllFrames];
4029 }
4030
4031 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4032                         whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4033                    injectedFrames:(WebUserContentInjectedFrames)injectedFrames
4034 {
4035     String group(groupName);
4036     if (group.isEmpty())
4037         return;
4038
4039     auto* viewGroup = WebViewGroup::get(group);
4040     if (!viewGroup)
4041         return;
4042
4043     if (!world)
4044         return;
4045
4046     auto styleSheet = std::make_unique<UserStyleSheet>(source, url, toStringVector(whitelist), toStringVector(blacklist), injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly, UserStyleUserLevel);
4047     viewGroup->userContentController().addUserStyleSheet(*core(world), WTF::move(styleSheet), InjectInExistingDocuments);
4048 }
4049
4050 + (void)_removeUserScriptFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
4051 {
4052     String group(groupName);
4053     if (group.isEmpty())
4054         return;
4055
4056     auto* viewGroup = WebViewGroup::get(group);
4057     if (!viewGroup)
4058         return;
4059
4060     if (!world)
4061         return;
4062
4063     viewGroup->userContentController().removeUserScript(*core(world), url);
4064 }
4065
4066 + (void)_removeUserStyleSheetFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
4067 {
4068     String group(groupName);
4069     if (group.isEmpty())
4070         return;
4071
4072     auto* viewGroup = WebViewGroup::get(group);
4073     if (!viewGroup)
4074         return;
4075
4076     if (!world)
4077         return;
4078
4079     viewGroup->userContentController().removeUserStyleSheet(*core(world), url);
4080 }
4081
4082 + (void)_removeUserScriptsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
4083 {
4084     String group(groupName);
4085     if (group.isEmpty())
4086         return;
4087
4088     auto* viewGroup = WebViewGroup::get(group);
4089     if (!viewGroup)
4090         return;
4091
4092     if (!world)
4093         return;
4094
4095     viewGroup->userContentController().removeUserScripts(*core(world));
4096 }
4097
4098 + (void)_removeUserStyleSheetsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
4099 {
4100     String group(groupName);
4101     if (group.isEmpty())
4102         return;
4103
4104     auto* viewGroup = WebViewGroup::get(group);
4105     if (!viewGroup)
4106         return;
4107
4108     if (!world)
4109         return;
4110
4111     viewGroup->userContentController().removeUserStyleSheets(*core(world));
4112 }
4113
4114 + (void)_removeAllUserContentFromGroup:(NSString *)groupName
4115 {
4116     String group(groupName);
4117     if (group.isEmpty())
4118         return;
4119
4120     auto* viewGroup = WebViewGroup::get(group);
4121     if (!viewGroup)
4122         return;
4123
4124     viewGroup->userContentController().removeAllUserContent();
4125 }
4126
4127 - (BOOL)allowsNewCSSAnimationsWhileSuspended
4128 {
4129     Frame* frame = core([self mainFrame]);
4130     if (frame)
4131         return frame->animation().allowsNewAnimationsWhileSuspended();
4132
4133     return false;
4134 }
4135
4136 - (void)setAllowsNewCSSAnimationsWhileSuspended:(BOOL)allowed
4137 {
4138     Frame* frame = core([self mainFrame]);
4139     if (frame)
4140         frame->animation().setAllowsNewAnimationsWhileSuspended(allowed);
4141 }
4142
4143 - (BOOL)cssAnimationsSuspended
4144 {
4145     // should ask the page!
4146     Frame* frame = core([self mainFrame]);
4147     if (frame)
4148         return frame->animation().isSuspended();
4149
4150     return false;
4151 }
4152
4153 - (void)setCSSAnimationsSuspended:(BOOL)suspended
4154 {
4155     Frame* frame = core([self mainFrame]);
4156     if (suspended == frame->animation().isSuspended())
4157         return;
4158         
4159     if (suspended)
4160         frame->animation().suspendAnimations();
4161     else
4162         frame->animation().resumeAnimations();
4163 }
4164
4165 + (void)_setDomainRelaxationForbidden:(BOOL)forbidden forURLScheme:(NSString *)scheme
4166 {
4167     SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, scheme);
4168 }
4169
4170 + (void)_registerURLSchemeAsSecure:(NSString *)scheme
4171 {
4172     SchemeRegistry::registerURLSchemeAsSecure(scheme);
4173 }
4174
4175 + (void)_registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing:(NSString *)scheme
4176 {
4177     SchemeRegistry::registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing(scheme);
4178 }
4179
4180 + (void)_registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing:(NSString *)scheme
4181 {
4182     SchemeRegistry::registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing(scheme);
4183 }
4184
4185 - (void)_scaleWebView:(float)scale atOrigin:(NSPoint)origin
4186 {
4187     _private->page->setPageScaleFactor(scale, IntPoint(origin));
4188 }
4189
4190 - (float)_viewScaleFactor
4191 {
4192     return _private->page->pageScaleFactor();
4193 }
4194
4195 - (void)_setUseFixedLayout:(BOOL)fixed
4196 {
4197     Frame* coreFrame = [self _mainCoreFrame];
4198     if (!coreFrame)
4199         return;
4200
4201     FrameView* view = coreFrame->view();
4202     if (!view)
4203         return;
4204
4205     view->setUseFixedLayout(fixed);
4206     if (!fixed)
4207         view->setFixedLayoutSize(IntSize());
4208 }
4209
4210 #if !PLATFORM(IOS)
4211 - (void)_setFixedLayoutSize:(NSSize)size
4212 {
4213     Frame* coreFrame = [self _mainCoreFrame];
4214     if (!coreFrame)
4215         return;
4216     
4217     FrameView* view = coreFrame->view();
4218     if (!view)
4219         return;
4220     
4221     view->setFixedLayoutSize(IntSize(size));
4222     view->forceLayout();
4223 }
4224 #endif
4225
4226 - (BOOL)_useFixedLayout
4227 {
4228     Frame* coreFrame = [self _mainCoreFrame];
4229     if (!coreFrame)
4230         return NO;
4231     
4232     FrameView* view = coreFrame->view();
4233     if (!view)
4234         return NO;
4235     
4236     return view->useFixedLayout();
4237 }
4238
4239 #if !PLATFORM(IOS)
4240 - (NSSize)_fixedLayoutSize
4241 {
4242     Frame* coreFrame = [self _mainCoreFrame];
4243     if (!coreFrame)
4244         return IntSize();
4245     
4246     FrameView* view = coreFrame->view();
4247     if (!view)
4248         return IntSize();
4249
4250     return view->fixedLayoutSize();
4251 }
4252 #endif
4253
4254 - (void)_setPaginationMode:(WebPaginationMode)paginationMode
4255 {
4256     Page* page = core(self);
4257     if (!page)
4258         return;
4259
4260     Pagination pagination = page->pagination();
4261     switch (paginationMode) {
4262     case WebPaginationModeUnpaginated:
4263         pagination.mode = Pagination::Unpaginated;
4264         break;
4265     case WebPaginationModeLeftToRight:
4266         pagination.mode = Pagination::LeftToRightPaginated;
4267         break;
4268     case WebPaginationModeRightToLeft:
4269         pagination.mode = Pagination::RightToLeftPaginated;
4270         break;
4271     case WebPaginationModeTopToBottom:
4272         pagination.mode = Pagination::TopToBottomPaginated;
4273         break;
4274     case WebPaginationModeBottomToTop:
4275         pagination.mode = Pagination::BottomToTopPaginated;
4276         break;