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