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