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