REGRESSION(r167770): Cannot login in Evernote Safari extension
[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
2302 #if PLATFORM(IOS)
2303     settings.setStandalone([preferences _standalone]);
2304     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2305     settings.setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
2306     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2307     settings.setLayoutInterval(std::chrono::milliseconds([preferences _layoutInterval]));
2308     settings.setMaxParseDuration([preferences _maxParseDuration]);
2309     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2310     settings.setMediaPlaybackAllowsAirPlay([preferences mediaPlaybackAllowsAirPlay]);
2311     settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2312     settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2313     settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2314     settings.setAVKitEnabled([preferences avKitEnabled]);
2315     settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2316     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2317
2318     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2319     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2320
2321     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2322     settings.setDelegatesPageScaling(true);
2323
2324 #if ENABLE(IOS_TEXT_AUTOSIZING)
2325     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2326 #endif
2327
2328     settings.setAllowNavigationToInvalidURL(!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_NAVIGATION_URL_VALIDATION));
2329 #endif // PLATFORM(IOS)
2330
2331 #if PLATFORM(MAC)
2332     if ([preferences userStyleSheetEnabled]) {
2333         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2334         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2335             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2336         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2337     } else
2338         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2339
2340     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2341     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2342     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2343     settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2344     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2345     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2346     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2347     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2348     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2349     settings.setQTKitEnabled([preferences isQTKitEnabled]);
2350
2351     // FIXME: Should we enable this following <rdar://problem/15290404>?
2352     settings.setMultithreadedWebGLEnabled([preferences multithreadedWebGLEnabled]);
2353 #endif // PLATFORM(MAC)
2354
2355 #if ENABLE(SQL_DATABASE)
2356     DatabaseManager::manager().setIsAvailable([preferences databasesEnabled]);
2357 #endif
2358
2359 #if ENABLE(MEDIA_SOURCE)
2360     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2361 #endif
2362
2363 #if ENABLE(SERVICE_CONTROLS)
2364     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2365 #endif
2366
2367 #if ENABLE(VIDEO_TRACK)
2368     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2369     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2370     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2371 #endif
2372
2373 #if USE(AVFOUNDATION)
2374     settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2375 #endif
2376
2377 #if ENABLE(WEB_AUDIO)
2378     settings.setWebAudioEnabled([preferences webAudioEnabled]);
2379 #endif
2380
2381 #if ENABLE(FULLSCREEN_API)
2382     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2383 #endif
2384
2385 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2386     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2387 #endif
2388
2389     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2390
2391 #if ENABLE(GAMEPAD)
2392     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2393 #endif
2394
2395     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2396     if (timeout > 0)
2397         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2398
2399     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2400     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2401
2402     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2403     if (_private->zoomsTextOnly != zoomsTextOnly)
2404         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2405
2406 #if ENABLE(DISK_IMAGE_CACHE) && PLATFORM(IOS)
2407     DiskImageCache& diskImageCache = WebCore::diskImageCache();
2408     diskImageCache.setEnabled([preferences diskImageCacheEnabled]);
2409     diskImageCache.setMinimumImageSize([preferences diskImageCacheMinimumImageSize]);
2410     diskImageCache.setMaximumCacheSize([preferences diskImageCacheMaximumCacheSize]);
2411 #endif
2412
2413 #if PLATFORM(IOS)
2414     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2415     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2416     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2417     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2418 #endif
2419 }
2420
2421 static inline IMP getMethod(id o, SEL s)
2422 {
2423     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2424 }
2425
2426 #if PLATFORM(IOS)
2427 - (id)_UIKitDelegateForwarder
2428 {
2429     if (_private->closing)
2430         return nil;
2431         
2432     if (!_private->UIKitDelegateForwarder)
2433         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2434     return _private->UIKitDelegateForwarder;
2435 }
2436 #endif
2437
2438 - (void)_cacheResourceLoadDelegateImplementations
2439 {
2440     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2441     id delegate = _private->resourceProgressDelegate;
2442
2443     if (!delegate) {
2444         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2445         return;
2446     }
2447
2448     cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
2449     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2450     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2451     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2452     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2453 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2454     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2455 #endif
2456
2457 #if PLATFORM(IOS)
2458     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2459     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2460     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2461     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2462     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2463     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2464     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2465     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2466     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2467 #endif
2468
2469     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2470     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2471     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2472     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2473     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
2474     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
2475     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
2476     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
2477 }
2478
2479 - (void)_cacheFrameLoadDelegateImplementations
2480 {
2481     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
2482     id delegate = _private->frameLoadDelegate;
2483
2484     if (!delegate) {
2485         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
2486         return;
2487     }
2488
2489     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
2490     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
2491     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
2492     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
2493     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
2494 #if JSC_OBJC_API_ENABLED
2495     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
2496 #endif
2497     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
2498     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
2499     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
2500     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
2501     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
2502     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
2503     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
2504     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
2505     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
2506     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
2507     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
2508     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
2509 #if ENABLE(ICONDATABASE)
2510     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
2511 #endif
2512     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
2513     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
2514     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
2515     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
2516     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
2517     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
2518     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
2519     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
2520     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
2521     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
2522 #if PLATFORM(IOS)
2523     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
2524 #endif
2525
2526     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
2527     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
2528     // for backwards compatibility.
2529     Page* page = core(self);
2530     if (page) {
2531         unsigned milestones = DidFirstLayout;
2532 #if PLATFORM(IOS)
2533         milestones |= DidFirstVisuallyNonEmptyLayout;
2534 #else
2535         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
2536             milestones |= DidFirstVisuallyNonEmptyLayout;
2537 #endif
2538         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
2539     }
2540 }
2541
2542 - (void)_cacheScriptDebugDelegateImplementations
2543 {
2544     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
2545     id delegate = _private->scriptDebugDelegate;
2546
2547     if (!delegate) {
2548         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
2549         return;
2550     }
2551
2552     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
2553     if (cache->didParseSourceFunc)
2554         cache->didParseSourceExpectsBaseLineNumber = YES;
2555     else {
2556         cache->didParseSourceExpectsBaseLineNumber = NO;
2557         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
2558     }
2559
2560     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
2561
2562     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
2563     if (cache->exceptionWasRaisedFunc)
2564         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
2565     else {
2566         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
2567         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
2568     }
2569 }
2570
2571 - (void)_cacheHistoryDelegateImplementations
2572 {
2573     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
2574     id delegate = _private->historyDelegate;
2575
2576     if (!delegate) {
2577         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
2578         return;
2579     }
2580
2581     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
2582     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
2583     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
2584     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
2585     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
2586     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
2587 }
2588
2589 - (id)_policyDelegateForwarder
2590 {
2591 #if PLATFORM(IOS)
2592     if (_private->closing)
2593         return nil;
2594 #endif
2595     if (!_private->policyDelegateForwarder)
2596         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
2597     return _private->policyDelegateForwarder;
2598 }
2599
2600 - (id)_UIDelegateForwarder
2601 {
2602 #if PLATFORM(IOS)
2603     if (_private->closing)
2604         return nil;
2605 #endif
2606     if (!_private->UIDelegateForwarder)
2607         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
2608     return _private->UIDelegateForwarder;
2609 }
2610
2611 #if PLATFORM(IOS)
2612 - (id)_UIDelegateForSelector:(SEL)selector
2613 {
2614     id delegate = self->_private->UIDelegate;
2615     if ([delegate respondsToSelector:selector])
2616         return delegate;
2617
2618     delegate = [WebDefaultUIDelegate sharedUIDelegate];
2619     if ([delegate respondsToSelector:selector])
2620         return delegate;
2621
2622     return nil;
2623 }
2624 #endif
2625
2626 - (id)_editingDelegateForwarder
2627 {
2628 #if PLATFORM(IOS)
2629     if (_private->closing)
2630         return nil;
2631 #endif    
2632     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
2633     // Not sure if that is a bug or not.
2634     if (!_private)
2635         return nil;
2636
2637     if (!_private->editingDelegateForwarder)
2638         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
2639     return _private->editingDelegateForwarder;
2640 }
2641
2642 - (void)_closeWindow
2643 {
2644     [[self _UIDelegateForwarder] webViewClose:self];
2645 }
2646
2647 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
2648 {
2649     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2650     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2651     
2652     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2653     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2654     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2655     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
2656 }
2657
2658 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
2659 {
2660     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
2661     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
2662
2663     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2664     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2665     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2666     if ([viewClass class] == [WebHTMLView class])
2667         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2668     
2669     // This is used to make _representationExistsForURLScheme faster.
2670     // Without this set, we'd have to create the MIME type each time.
2671     if (schemesWithRepresentationsSet == nil) {
2672         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
2673     }
2674     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
2675 }
2676
2677 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
2678 {
2679     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
2680 }
2681
2682 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
2683 {
2684     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
2685 }
2686
2687 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
2688 {
2689     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
2690     if (!request)
2691         return NO;
2692
2693     if ([NSURLConnection canHandleRequest:request])
2694         return YES;
2695
2696     NSString *scheme = [[request URL] scheme];
2697
2698     // Representations for URL schemes work at the top level.
2699     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
2700         return YES;
2701
2702     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
2703         return YES;
2704
2705     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
2706         return YES;
2707
2708     return NO;
2709 }
2710
2711 + (BOOL)_canHandleRequest:(NSURLRequest *)request
2712 {
2713     return [self _canHandleRequest:request forMainFrame:YES];
2714 }
2715
2716 + (NSString *)_decodeData:(NSData *)data
2717 {
2718     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
2719     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
2720 }
2721
2722 - (void)_pushPerformingProgrammaticFocus
2723 {
2724     _private->programmaticFocusCount++;
2725 }
2726
2727 - (void)_popPerformingProgrammaticFocus
2728 {
2729     _private->programmaticFocusCount--;
2730 }
2731
2732 - (BOOL)_isPerformingProgrammaticFocus
2733 {
2734     return _private->programmaticFocusCount != 0;
2735 }
2736
2737 #if !PLATFORM(IOS)
2738 - (void)_didChangeValueForKey: (NSString *)key
2739 {
2740     LOG (Bindings, "calling didChangeValueForKey: %@", key);
2741     [self didChangeValueForKey: key];
2742 }
2743
2744 - (void)_willChangeValueForKey: (NSString *)key
2745 {
2746     LOG (Bindings, "calling willChangeValueForKey: %@", key);
2747     [self willChangeValueForKey: key];
2748 }
2749
2750 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
2751     static NSSet *manualNotifyKeys = nil;
2752     if (!manualNotifyKeys)
2753         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2754             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
2755             nil];
2756     if ([manualNotifyKeys containsObject:key])
2757         return NO;
2758     return YES;
2759 }
2760
2761 - (NSArray *)_declaredKeys {
2762     static NSArray *declaredKeys = nil;
2763     if (!declaredKeys)
2764         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2765             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
2766     return declaredKeys;
2767 }
2768
2769 - (void)setObservationInfo:(void *)info
2770 {
2771     _private->observationInfo = info;
2772 }
2773
2774 - (void *)observationInfo
2775 {
2776     return _private->observationInfo;
2777 }
2778
2779 - (void)_willChangeBackForwardKeys
2780 {
2781     [self _willChangeValueForKey: _WebCanGoBackKey];
2782     [self _willChangeValueForKey: _WebCanGoForwardKey];
2783 }
2784
2785 - (void)_didChangeBackForwardKeys
2786 {
2787     [self _didChangeValueForKey: _WebCanGoBackKey];
2788     [self _didChangeValueForKey: _WebCanGoForwardKey];
2789 }
2790
2791 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
2792 {
2793     if (needsSelfRetainWhileLoadingQuirk())
2794         [self retain];
2795
2796     [self _willChangeBackForwardKeys];
2797     if (frame == [self mainFrame]){
2798         // Force an observer update by sending a will/did.
2799         [self _willChangeValueForKey: _WebIsLoadingKey];
2800         [self _didChangeValueForKey: _WebIsLoadingKey];
2801
2802         [self _willChangeValueForKey: _WebMainFrameURLKey];
2803     }
2804
2805     [NSApp setWindowsNeedUpdate:YES];
2806
2807 #if ENABLE(FULLSCREEN_API)
2808     Document* document = core([frame DOMDocument]);
2809     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
2810         SEL selector = @selector(webView:closeFullScreenWithListener:);
2811         if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2812             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
2813             CallUIDelegate(self, selector, listener);
2814             [listener release];
2815         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
2816             [_private->newFullscreenController close];
2817         }
2818     }
2819 #endif
2820 }
2821
2822 - (void)_checkDidPerformFirstNavigation
2823 {
2824     if (_private->_didPerformFirstNavigation)
2825         return;
2826
2827     Page* page = _private->page;
2828     if (!page)
2829         return;
2830
2831     auto& backForwardController = page->backForward();
2832
2833     if (!backForwardController.backItem())
2834         return;
2835
2836     _private->_didPerformFirstNavigation = YES;
2837
2838     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
2839         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
2840 }
2841
2842 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2843 {
2844     if (frame == [self mainFrame])
2845         [self _didChangeValueForKey: _WebMainFrameURLKey];
2846
2847     [self _checkDidPerformFirstNavigation];
2848
2849     [NSApp setWindowsNeedUpdate:YES];
2850 }
2851
2852 - (void)_didFinishLoadForFrame:(WebFrame *)frame
2853 {
2854     if (needsSelfRetainWhileLoadingQuirk())
2855         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2856         
2857     [self _didChangeBackForwardKeys];
2858     if (frame == [self mainFrame]){
2859         // Force an observer update by sending a will/did.
2860         [self _willChangeValueForKey: _WebIsLoadingKey];
2861         [self _didChangeValueForKey: _WebIsLoadingKey];
2862     }
2863     [NSApp setWindowsNeedUpdate:YES];
2864 }
2865
2866 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2867 {
2868     if (needsSelfRetainWhileLoadingQuirk())
2869         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2870
2871     [self _didChangeBackForwardKeys];
2872     if (frame == [self mainFrame]){
2873         // Force an observer update by sending a will/did.
2874         [self _willChangeValueForKey: _WebIsLoadingKey];
2875         [self _didChangeValueForKey: _WebIsLoadingKey];
2876     }
2877     [NSApp setWindowsNeedUpdate:YES];
2878 }
2879
2880 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2881 {
2882     if (needsSelfRetainWhileLoadingQuirk())
2883         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2884
2885     [self _didChangeBackForwardKeys];
2886     if (frame == [self mainFrame]){
2887         // Force an observer update by sending a will/did.
2888         [self _willChangeValueForKey: _WebIsLoadingKey];
2889         [self _didChangeValueForKey: _WebIsLoadingKey];
2890         
2891         [self _didChangeValueForKey: _WebMainFrameURLKey];
2892     }
2893     [NSApp setWindowsNeedUpdate:YES];
2894 }
2895
2896 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
2897 {
2898     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
2899     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
2900     NSCachedURLResponse *cachedResponse;
2901
2902     if (!_private->page)
2903         return nil;
2904
2905     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
2906         cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
2907     else
2908         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
2909
2910     return cachedResponse;
2911 }
2912
2913 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2914 {
2915     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
2916     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
2917     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
2918                         element:domElement
2919                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
2920                           title:[element objectForKey:WebElementImageAltStringKey] 
2921                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
2922                           types:types
2923                          source:nil];
2924 }
2925
2926 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2927 {
2928     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
2929                      andTitle:[element objectForKey:WebElementLinkLabelKey]
2930                         types:types];
2931 }
2932
2933 #if ENABLE(DRAG_SUPPORT)
2934 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
2935 {
2936     if (!_private->page)
2937         return;
2938     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
2939 }
2940 #endif
2941
2942 #else
2943
2944 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2945 {
2946     if (frame == [self mainFrame])
2947         _private->didDrawTiles = 0;
2948 }
2949
2950 #endif // PLATFORM(IOS)
2951
2952 #if ENABLE(DASHBOARD_SUPPORT)
2953
2954 #define DASHBOARD_CONTROL_LABEL @"control"
2955
2956 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
2957 {
2958     NSRect adjustedBounds = bounds;
2959     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
2960     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
2961     adjustedBounds.size = bounds.size;
2962
2963     NSRect adjustedClip;
2964     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
2965     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
2966     adjustedClip.size = clip.size;
2967
2968     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
2969         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
2970     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
2971     if (!scrollerRegions) {
2972         scrollerRegions = [[NSMutableArray alloc] init];
2973         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
2974         [scrollerRegions release];
2975     }
2976     [scrollerRegions addObject:region];
2977     [region release];
2978 }
2979
2980 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
2981 {    
2982     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
2983
2984     for (const auto& widget: frameView->children()) {
2985         if (widget->isFrameView()) {
2986             [self _addScrollerDashboardRegionsForFrameView:toFrameView(widget.get()) dashboardRegions:regions];
2987             continue;
2988         }
2989
2990         if (!widget->isScrollbar())
2991             continue;
2992
2993         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
2994         // it's not common to need this to be correct in Dashboard widgets.
2995         NSRect bounds = widget->frameRect();
2996         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
2997     }
2998 }
2999
3000 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3001 {
3002     // Add scroller regions for NSScroller and WebCore scrollbars
3003     NSUInteger count = [views count];
3004     for (NSUInteger i = 0; i < count; i++) {
3005         NSView *view = [views objectAtIndex:i];
3006         
3007         if ([view isKindOfClass:[WebHTMLView class]]) {
3008             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3009                 if (FrameView* coreView = coreFrame->view())
3010                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3011             }
3012         } else if ([view isKindOfClass:[NSScroller class]]) {
3013             // AppKit places absent scrollers at -100,-100
3014             if ([view frame].origin.y < 0)
3015                 continue;
3016             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3017         }
3018         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3019     }
3020 }
3021
3022 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3023 {
3024     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3025 }
3026
3027 - (NSDictionary *)_dashboardRegions
3028 {
3029     // Only return regions from main frame.
3030     Frame* mainFrame = [self _mainCoreFrame];
3031     if (!mainFrame)
3032         return nil;
3033
3034     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3035     size_t size = regions.size();
3036
3037     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3038     for (size_t i = 0; i < size; i++) {
3039         const AnnotatedRegionValue& region = regions[i];
3040
3041         if (region.type == StyleDashboardRegion::None)
3042             continue;
3043
3044         NSString *label = region.label;
3045         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3046         if (region.type == StyleDashboardRegion::Circle)
3047             type = WebDashboardRegionTypeCircle;
3048         else if (region.type == StyleDashboardRegion::Rectangle)
3049             type = WebDashboardRegionTypeRectangle;
3050         NSMutableArray *regionValues = [webRegions objectForKey:label];
3051         if (!regionValues) {
3052             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3053             [webRegions setObject:regionValues forKey:label];
3054             [regionValues release];
3055         }
3056
3057         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:pixelSnappedIntRect(region.bounds) clip:pixelSnappedIntRect(region.clip) type:type];
3058         [regionValues addObject:webRegion];
3059         [webRegion release];
3060     }
3061
3062     [self _addScrollerDashboardRegions:webRegions];
3063
3064     return webRegions;
3065 }
3066
3067 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3068 {
3069     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3070     // specific support for the backward compatibility mode flag.
3071     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3072         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3073     
3074     switch (behavior) {
3075         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3076             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3077             break;
3078         }
3079         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3080             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3081             break;
3082         }
3083         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3084             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3085             break;
3086         }
3087         case WebDashboardBehaviorAllowWheelScrolling: {
3088             _private->dashboardBehaviorAllowWheelScrolling = flag;
3089             break;
3090         }
3091         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3092             if (_private->page)
3093                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3094 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3095             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3096 #endif
3097             break;
3098         }
3099     }
3100
3101     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3102     // compatibility mode. See <rdar://problem/8175982>.
3103     if (_private->page)
3104         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3105 }
3106
3107 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3108 {
3109     switch (behavior) {
3110         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3111             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3112         }
3113         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3114             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3115         }
3116         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3117             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3118         }
3119         case WebDashboardBehaviorAllowWheelScrolling: {
3120             return _private->dashboardBehaviorAllowWheelScrolling;
3121         }
3122         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3123             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3124         }
3125     }
3126     return NO;
3127 }
3128
3129 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3130
3131 + (void)_setShouldUseFontSmoothing:(BOOL)f
3132 {
3133     Font::setShouldUseSmoothing(f);
3134 }
3135
3136 + (BOOL)_shouldUseFontSmoothing
3137 {
3138     return Font::shouldUseSmoothing();
3139 }
3140
3141 #if !PLATFORM(IOS)
3142 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3143 {
3144     setUsesTestModeFocusRingColor(f);
3145 }
3146
3147 + (BOOL)_usesTestModeFocusRingColor
3148 {
3149     return usesTestModeFocusRingColor();
3150 }
3151 #endif
3152
3153 #if PLATFORM(IOS)
3154 - (void)_setUIKitDelegate:(id)delegate
3155 {
3156     _private->UIKitDelegate = delegate;
3157     [_private->UIKitDelegateForwarder clearTarget];
3158     [_private->UIKitDelegateForwarder release];
3159     _private->UIKitDelegateForwarder = nil;
3160 }
3161
3162 - (id)_UIKitDelegate
3163 {
3164     return _private->UIKitDelegate;
3165 }
3166
3167 - (void)setWebMailDelegate:(id)delegate
3168 {
3169     _private->WebMailDelegate = delegate;
3170 }
3171
3172 - (id)_webMailDelegate
3173 {
3174     return _private->WebMailDelegate;
3175 }
3176
3177 - (id <WebCaretChangeListener>)caretChangeListener
3178 {
3179     return _private->_caretChangeListener;
3180 }
3181
3182 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3183 {
3184     _private->_caretChangeListener = listener;
3185 }
3186
3187 - (NSSet *)caretChangeListeners
3188 {
3189     return _private->_caretChangeListeners;
3190 }
3191
3192 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3193 {
3194     if (_private->_caretChangeListeners == nil) {
3195         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3196     }
3197     
3198     [_private->_caretChangeListeners addObject:listener];
3199 }
3200
3201 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3202 {
3203     [_private->_caretChangeListeners removeObject:listener];
3204 }
3205
3206 - (void)removeAllCaretChangeListeners
3207 {
3208     [_private->_caretChangeListeners removeAllObjects];
3209 }
3210
3211 - (void)caretChanged
3212 {
3213     [_private->_caretChangeListener caretChanged];
3214     NSSet *copy = [_private->_caretChangeListeners copy];
3215     for (id <WebCaretChangeListener> listener in copy) {
3216         [listener caretChanged];
3217     }
3218     [copy release];
3219 }
3220
3221 - (void)_clearDelegates
3222 {
3223     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3224     
3225     [self _setFormDelegate:nil];
3226     [self _setUIKitDelegate:nil];
3227     [self setCaretChangeListener:nil];
3228     [self removeAllCaretChangeListeners];
3229     [self setWebMailDelegate:nil];
3230     
3231     [self setDownloadDelegate:nil];
3232     [self setEditingDelegate:nil]; 
3233     [self setFrameLoadDelegate:nil];
3234     [self setPolicyDelegate:nil];
3235     [self setResourceLoadDelegate:nil];
3236     [self setScriptDebugDelegate:nil];
3237     [self setUIDelegate:nil];     
3238 }
3239
3240 - (NSURL *)_displayURL
3241 {
3242     WebThreadLock();
3243     WebFrame *frame = [self mainFrame];
3244     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3245     WebDataSource *dataSource = [frame provisionalDataSource];
3246     if (!dataSource)
3247         dataSource = [frame dataSource];
3248     NSURL *unreachableURL = [dataSource unreachableURL];
3249     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3250     [[URL retain] autorelease];
3251     return URL;
3252 }
3253 #endif // PLATFORM(IOS)
3254
3255 #if !PLATFORM(IOS)
3256 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3257 {
3258     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3259     if (flag) {
3260         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3261     } else {
3262         [scrollview setVerticalScrollingModeLocked:NO];
3263         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3264     }
3265 }
3266
3267 - (BOOL)alwaysShowVerticalScroller
3268 {
3269     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3270     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3271 }
3272
3273 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3274 {
3275     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3276     if (flag) {
3277         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3278     } else {
3279         [scrollview setHorizontalScrollingModeLocked:NO];
3280         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3281     }
3282 }
3283
3284 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3285 {
3286     if (Frame* mainFrame = [self _mainCoreFrame])
3287         mainFrame->view()->setProhibitsScrolling(prohibits);
3288 }
3289
3290 - (BOOL)alwaysShowHorizontalScroller
3291 {
3292     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3293     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3294 }
3295 #endif // !PLATFORM(IOS)
3296
3297 - (void)_setUseFastImageScalingMode:(BOOL)flag
3298 {
3299     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3300         _private->page->setInLowQualityImageInterpolationMode(flag);
3301         [self setNeedsDisplay:YES];
3302     }
3303 }
3304
3305 - (BOOL)_inFastImageScalingMode
3306 {
3307     if (_private->page)
3308         return _private->page->inLowQualityImageInterpolationMode();
3309     return NO;
3310 }
3311
3312 - (BOOL)_cookieEnabled
3313 {
3314     if (_private->page)
3315         return _private->page->settings().cookieEnabled();
3316     return YES;
3317 }
3318
3319 - (void)_setCookieEnabled:(BOOL)enable
3320 {
3321     if (_private->page)
3322         _private->page->settings().setCookieEnabled(enable);
3323 }
3324
3325 #if !PLATFORM(IOS)
3326 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3327 {
3328     if (!_private->pluginDatabase)
3329         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3330         
3331     [_private->pluginDatabase setPlugInPaths:newPaths];
3332     [_private->pluginDatabase refresh];
3333 }
3334 #endif
3335
3336 #if PLATFORM(IOS)
3337 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3338 {
3339     // Ask plug-ins in this frame
3340     id <WebDocumentView> documentView = [[frame frameView] documentView];
3341     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3342         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3343             return YES;
3344     }
3345
3346     // Ask plug-ins in child frames
3347     NSArray *childFrames = [frame childFrames];
3348     unsigned childCount = [childFrames count];
3349     unsigned childIndex;
3350     for (childIndex = 0; childIndex < childCount; childIndex++) {
3351         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3352             return YES;
3353     }
3354     
3355     return NO;
3356 }
3357
3358 - (BOOL)_pluginsAreRunning
3359 {
3360     WebThreadLock();
3361     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3362 }
3363
3364 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3365 {
3366     // Send the message to plug-ins in this frame
3367     id <WebDocumentView> documentView = [[frame frameView] documentView];
3368     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3369         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3370
3371     // Send the message to plug-ins in child frames
3372     NSArray *childFrames = [frame childFrames];
3373     unsigned childCount = [childFrames count];
3374     unsigned childIndex;
3375     for (childIndex = 0; childIndex < childCount; childIndex++) {
3376         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3377     }
3378 }
3379
3380 - (void)_destroyAllPlugIns
3381 {
3382     WebThreadLock();
3383     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3384 }
3385
3386 - (void)_clearBackForwardCache
3387 {
3388     WebThreadRun(^{
3389         WebKit::MemoryMeasure measurer("[WebView _clearBackForwardCache]");
3390         BackForwardList* bfList = core([self backForwardList]);
3391         if (!bfList)
3392             return;
3393
3394         BOOL didClearBFCache = bfList->clearAllPageCaches();
3395         if (WebKit::MemoryMeasure::isLoggingEnabled())
3396             NSLog(@"[WebView _clearBackForwardCache] %@ empty cache\n", (didClearBFCache ? @"DID" : @"did NOT"));
3397     });
3398 }
3399
3400 - (void)_startAllPlugIns
3401 {
3402     WebThreadLock();
3403     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3404 }
3405
3406 - (void)_stopAllPlugIns
3407 {
3408     WebThreadLock();
3409     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3410 }
3411
3412 - (void)_stopAllPlugInsForPageCache
3413 {
3414     WebThreadLock();
3415     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3416 }
3417
3418 - (void)_restorePlugInsFromCache
3419 {
3420     WebThreadLock();
3421     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3422 }
3423
3424 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3425 {
3426     WebThreadLock();
3427
3428     Frame* mainCoreFrame = [self _mainCoreFrame];
3429     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3430         FrameView* coreView = frame ? frame->view() : 0;
3431         if (!coreView)
3432             continue;
3433
3434         // Get the GraphicsLayer for this widget.
3435         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3436         if (!layerForWidget)
3437             continue;
3438         
3439         if (layerForWidget->contentsLayerForMedia() != layer) {
3440             layerForWidget->setContentsToMedia(layer);
3441             // We need to make sure the layer hierachy change is applied immediately.
3442             if (mainCoreFrame->view())
3443                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3444             return YES;
3445         }
3446     }
3447
3448     return NO;
3449 }
3450
3451 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3452 {
3453     if (_private->page)
3454         _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3455 }
3456 #endif // PLATFORM(IOS)
3457
3458 - (void)_attachScriptDebuggerToAllFrames
3459 {
3460     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3461         [kit(frame) _attachScriptDebugger];
3462 }
3463
3464 - (void)_detachScriptDebuggerFromAllFrames
3465 {
3466     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3467         [kit(frame) _detachScriptDebugger];
3468 }
3469
3470 #if !PLATFORM(IOS)
3471 - (void)setBackgroundColor:(NSColor *)backgroundColor
3472 {
3473     if ([_private->backgroundColor isEqual:backgroundColor])
3474         return;
3475
3476     id old = _private->backgroundColor;
3477     _private->backgroundColor = [backgroundColor retain];
3478     [old release];
3479
3480     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3481 }
3482
3483 - (NSColor *)backgroundColor
3484 {
3485     return _private->backgroundColor;
3486 }
3487 #else
3488 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3489 {
3490    if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3491         return;
3492
3493     CFTypeRef old = _private->backgroundColor;
3494     CFRetain(backgroundColor);
3495     _private->backgroundColor = backgroundColor;
3496     CFRelease(old);
3497
3498     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3499 }
3500
3501 - (CGColorRef)backgroundColor
3502 {
3503     return _private->backgroundColor;
3504 }
3505 #endif
3506
3507 - (BOOL)defersCallbacks
3508 {
3509     if (!_private->page)
3510         return NO;
3511     return _private->page->defersLoading();
3512 }
3513
3514 - (void)setDefersCallbacks:(BOOL)defer
3515 {
3516     if (!_private->page)
3517         return;
3518     return _private->page->setDefersLoading(defer);
3519 }
3520
3521 #if TARGET_OS_IPHONE && USE(QUICK_LOOK)
3522 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
3523 {
3524     NSString *uti = qlPreviewConverterUTIForURL(url);
3525     if (!uti)
3526         return nil;
3527
3528     NSString *fileName = qlPreviewConverterFileNameForURL(url);
3529     if (!fileName)
3530         return nil;
3531
3532     return [NSDictionary dictionaryWithObjectsAndKeys: fileName, WebQuickLookFileNameKey, uti, WebQuickLookUTIKey, nil];
3533 }
3534 #endif
3535
3536 #if PLATFORM(IOS)
3537 - (BOOL)_isStopping
3538 {
3539     return _private->isStopping;
3540 }
3541
3542 - (BOOL)_isClosing
3543 {
3544     return _private->closing;
3545 }
3546
3547 + (NSArray *)_productivityDocumentMIMETypes
3548 {
3549 #if USE(QUICK_LOOK)
3550     return [QLPreviewGetSupportedMIMETypesSet() allObjects];
3551 #else
3552     return nil;
3553 #endif
3554 }
3555
3556 - (void)_setAllowsMessaging:(BOOL)aFlag
3557 {
3558     _private->allowsMessaging = aFlag;
3559 }
3560
3561 - (BOOL)_allowsMessaging
3562 {
3563     return _private->allowsMessaging;
3564 }
3565
3566 - (void)_setFixedLayoutSize:(CGSize)size
3567 {
3568     ASSERT(WebThreadIsLocked());
3569     _private->fixedLayoutSize = size;
3570     if (Frame* mainFrame = core([self mainFrame])) {
3571         IntSize newSize(size);
3572         mainFrame->view()->setFixedLayoutSize(newSize);
3573         mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
3574         [self setNeedsDisplay:YES];
3575     }
3576 }
3577
3578 - (CGSize)_fixedLayoutSize
3579 {
3580     return _private->fixedLayoutSize;
3581 }
3582
3583 - (void)_synchronizeCustomFixedPositionLayoutRect
3584 {
3585     ASSERT(WebThreadIsLocked());
3586
3587     IntRect newRect;
3588     {
3589         MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3590         if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
3591             return;
3592         newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
3593         _private->pendingFixedPositionLayoutRect = CGRectNull;
3594     }
3595
3596     if (Frame* mainFrame = core([self mainFrame]))
3597         mainFrame->view()->setCustomFixedPositionLayoutRect(newRect);
3598 }
3599
3600 - (void)_setCustomFixedPositionLayoutRectInWebThread:(CGRect)rect synchronize:(BOOL)synchronize
3601 {
3602     {
3603         MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3604         _private->pendingFixedPositionLayoutRect = rect;
3605     }
3606     if (!synchronize)
3607         return;
3608     WebThreadRun(^{
3609         [self _synchronizeCustomFixedPositionLayoutRect];
3610     });
3611 }
3612
3613 - (void)_setCustomFixedPositionLayoutRect:(CGRect)rect
3614 {
3615     ASSERT(WebThreadIsLocked());
3616     {
3617         MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3618         _private->pendingFixedPositionLayoutRect = rect;
3619     }
3620     [self _synchronizeCustomFixedPositionLayoutRect];
3621 }
3622