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