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