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