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