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