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