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