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