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