[Win] Null pointer crash under WebView::scrollOffset.
[WebKit-https.git] / Source / WebKit / win / WebView.cpp
1 /*
2  * Copyright (C) 2006-2016 Apple, Inc.  All rights reserved.
3  * Copyright (C) 2009, 2010, 2011 Appcelerator, Inc. All rights reserved.
4  * Copyright (C) 2011 Brent Fulgham. All rights reserved.
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  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
26  */
27
28 #include "WebView.h"
29
30 #include "BackForwardController.h"
31 #include "COMVariantSetter.h"
32 #include "DOMCoreClasses.h"
33 #include "FullscreenVideoController.h"
34 #include "MarshallingHelpers.h"
35 #include "PluginDatabase.h"
36 #include "PluginView.h"
37 #include "SocketProvider.h"
38 #include "SoftLinking.h"
39 #include "SubframeLoader.h"
40 #include "TextIterator.h"
41 #include "WebApplicationCache.h"
42 #include "WebBackForwardList.h"
43 #include "WebChromeClient.h"
44 #include "WebContextMenuClient.h"
45 #include "WebCoreTextRenderer.h"
46 #include "WebDatabaseManager.h"
47 #include "WebDatabaseProvider.h"
48 #include "WebDocumentLoader.h"
49 #include "WebDownload.h"
50 #include "WebDragClient.h"
51 #include "WebEditorClient.h"
52 #include "WebElementPropertyBag.h"
53 #include "WebFrame.h"
54 #include "WebFrameLoaderClient.h"
55 #include "WebFrameNetworkingContext.h"
56 #include "WebGeolocationClient.h"
57 #include "WebGeolocationPosition.h"
58 #include "WebIconDatabase.h"
59 #include "WebInspector.h"
60 #include "WebInspectorClient.h"
61 #include "WebKit.h"
62 #include "WebKitDLL.h"
63 #include "WebKitLogging.h"
64 #include "WebKitStatisticsPrivate.h"
65 #include "WebKitSystemBits.h"
66 #include "WebKitVersion.h"
67 #include "WebMutableURLRequest.h"
68 #include "WebNotificationCenter.h"
69 #include "WebPlatformStrategies.h"
70 #include "WebPluginInfoProvider.h"
71 #include "WebPreferences.h"
72 #include "WebResourceLoadScheduler.h"
73 #include "WebScriptWorld.h"
74 #include "WebStorageNamespaceProvider.h"
75 #include "WebViewGroup.h"
76 #include "WebVisitedLinkStore.h"
77 #include "resource.h"
78 #include <JavaScriptCore/APICast.h>
79 #include <JavaScriptCore/Exception.h>
80 #include <JavaScriptCore/InitializeThreading.h>
81 #include <JavaScriptCore/JSCJSValue.h>
82 #include <JavaScriptCore/JSLock.h>
83 #include <WebCore/AXObjectCache.h>
84 #include <WebCore/ApplicationCacheStorage.h>
85 #include <WebCore/BString.h>
86 #include <WebCore/BackForwardController.h>
87 #include <WebCore/BackForwardList.h>
88 #include <WebCore/BitmapInfo.h>
89 #include <WebCore/Chrome.h>
90 #include <WebCore/ContextMenu.h>
91 #include <WebCore/ContextMenuController.h>
92 #include <WebCore/Cursor.h>
93 #include <WebCore/DatabaseManager.h>
94 #include <WebCore/Document.h>
95 #include <WebCore/DocumentMarkerController.h>
96 #include <WebCore/DragController.h>
97 #include <WebCore/DragData.h>
98 #include <WebCore/Editor.h>
99 #include <WebCore/EventHandler.h>
100 #include <WebCore/EventNames.h>
101 #include <WebCore/FileSystem.h>
102 #include <WebCore/FloatQuad.h>
103 #include <WebCore/FocusController.h>
104 #include <WebCore/Font.h>
105 #include <WebCore/FrameLoader.h>
106 #include <WebCore/FrameSelection.h>
107 #include <WebCore/FrameTree.h>
108 #include <WebCore/FrameView.h>
109 #include <WebCore/FrameWin.h>
110 #include <WebCore/FullScreenController.h>
111 #include <WebCore/GDIObjectCounter.h>
112 #include <WebCore/GDIUtilities.h>
113 #include <WebCore/GeolocationController.h>
114 #include <WebCore/GeolocationError.h>
115 #include <WebCore/GraphicsContext.h>
116 #include <WebCore/HTMLNames.h>
117 #include <WebCore/HTMLVideoElement.h>
118 #include <WebCore/HWndDC.h>
119 #include <WebCore/HistoryController.h>
120 #include <WebCore/HistoryItem.h>
121 #include <WebCore/HitTestRequest.h>
122 #include <WebCore/HitTestResult.h>
123 #include <WebCore/IntRect.h>
124 #include <WebCore/JSElement.h>
125 #include <WebCore/KeyboardEvent.h>
126 #include <WebCore/LogInitialization.h>
127 #include <WebCore/Logging.h>
128 #include <WebCore/MIMETypeRegistry.h>
129 #include <WebCore/MainFrame.h>
130 #include <WebCore/MemoryCache.h>
131 #include <WebCore/MemoryPressureHandler.h>
132 #include <WebCore/NotImplemented.h>
133 #include <WebCore/Page.h>
134 #include <WebCore/PageCache.h>
135 #include <WebCore/PageConfiguration.h>
136 #include <WebCore/PageGroup.h>
137 #include <WebCore/PathUtilities.h>
138 #include <WebCore/PlatformKeyboardEvent.h>
139 #include <WebCore/PlatformMouseEvent.h>
140 #include <WebCore/PlatformWheelEvent.h>
141 #include <WebCore/PluginData.h>
142 #include <WebCore/PopupMenu.h>
143 #include <WebCore/PopupMenuWin.h>
144 #include <WebCore/ProgressTracker.h>
145 #include <WebCore/RenderLayer.h>
146 #include <WebCore/RenderTheme.h>
147 #include <WebCore/RenderTreeAsText.h>
148 #include <WebCore/RenderView.h>
149 #include <WebCore/RenderWidget.h>
150 #include <WebCore/ResourceHandle.h>
151 #include <WebCore/ResourceHandleClient.h>
152 #include <WebCore/ResourceRequest.h>
153 #include <WebCore/RuntimeEnabledFeatures.h>
154 #include <WebCore/SchemeRegistry.h>
155 #include <WebCore/ScriptController.h>
156 #include <WebCore/Scrollbar.h>
157 #include <WebCore/ScrollbarTheme.h>
158 #include <WebCore/SecurityOrigin.h>
159 #include <WebCore/SecurityPolicy.h>
160 #include <WebCore/Settings.h>
161 #include <WebCore/SystemInfo.h>
162 #include <WebCore/UserContentController.h>
163 #include <WebCore/UserScript.h>
164 #include <WebCore/UserStyleSheet.h>
165 #include <WebCore/WindowMessageBroadcaster.h>
166 #include <WebCore/WindowsTouch.h>
167 #include <bindings/ScriptValue.h>
168 #include <wtf/MainThread.h>
169 #include <wtf/RAMSize.h>
170 #include <wtf/UniqueRef.h>
171
172 #if USE(CG)
173 #include <CoreGraphics/CGContext.h>
174 #endif
175
176 #if USE(CF)
177 #include <CoreFoundation/CoreFoundation.h>
178 #endif
179
180 #if USE(CFNETWORK)
181 #include <CFNetwork/CFURLCachePriv.h>
182 #include <CFNetwork/CFURLProtocolPriv.h>
183 #include <WebKitSystemInterface/WebKitSystemInterface.h>
184 #elif USE(CURL)
185 #include <WebCore/CurlCacheManager.h>
186 #endif
187
188 #if USE(CA)
189 #include <WebCore/CACFLayerTreeHost.h>
190 #include <WebCore/PlatformCALayer.h>
191 #elif USE(TEXTURE_MAPPER_GL)
192 #include "AcceleratedCompositingContext.h"
193 #endif
194
195 #if ENABLE(FULLSCREEN_API)
196 #include <WebCore/FullScreenController.h>
197 #endif
198
199 #include <ShlObj.h>
200 #include <comutil.h>
201 #include <dimm.h>
202 #include <oleacc.h>
203 #include <wchar.h>
204 #include <windowsx.h>
205 #include <winuser.h>
206 #include <wtf/HashSet.h>
207 #include <wtf/text/CString.h>
208 #include <wtf/text/StringConcatenate.h>
209 #include <wtf/win/GDIObject.h>
210
211 // Soft link functions for gestures and panning feedback
212 SOFT_LINK_LIBRARY(USER32);
213 SOFT_LINK_OPTIONAL(USER32, GetGestureInfo, BOOL, WINAPI, (HGESTUREINFO, PGESTUREINFO));
214 SOFT_LINK_OPTIONAL(USER32, SetGestureConfig, BOOL, WINAPI, (HWND, DWORD, UINT, PGESTURECONFIG, UINT));
215 SOFT_LINK_OPTIONAL(USER32, CloseGestureInfoHandle, BOOL, WINAPI, (HGESTUREINFO));
216 SOFT_LINK_LIBRARY(Uxtheme);
217 SOFT_LINK_OPTIONAL(Uxtheme, BeginPanningFeedback, BOOL, WINAPI, (HWND));
218 SOFT_LINK_OPTIONAL(Uxtheme, EndPanningFeedback, BOOL, WINAPI, (HWND, BOOL));
219 SOFT_LINK_OPTIONAL(Uxtheme, UpdatePanningFeedback, BOOL, WINAPI, (HWND, LONG, LONG, BOOL));
220
221 using namespace WebCore;
222 using namespace std;
223 using JSC::JSLock;
224
225 static HMODULE accessibilityLib;
226 static HashSet<WebView*>& pendingDeleteBackingStoreSet()
227 {
228     static NeverDestroyed<HashSet<WebView*>> pendingDeleteBackingStoreSet;
229     return pendingDeleteBackingStoreSet;
230 }
231
232 static CFStringRef WebKitLocalCacheDefaultsKey = CFSTR("WebKitLocalCache");
233
234 static String webKitVersionString();
235
236 WebView* kit(Page* page)
237 {
238     if (!page)
239         return 0;
240     
241     if (page->chrome().client().isEmptyChromeClient())
242         return 0;
243     
244     return static_cast<WebChromeClient&>(page->chrome().client()).webView();
245 }
246
247 static inline AtomicString toAtomicString(BSTR bstr)
248 {
249     return AtomicString(bstr, SysStringLen(bstr));
250 }
251
252 static inline String toString(BSTR bstr)
253 {
254     return String(bstr, SysStringLen(bstr));
255 }
256
257 static inline String toString(BString &bstr)
258 {
259     return String(bstr, SysStringLen(bstr));
260 }
261
262 static inline URL toURL(BSTR bstr)
263 {
264     return URL(URL(), toString(bstr));
265 }
266
267 static String localStorageDatabasePath(WebPreferences* preferences)
268 {
269     BString localStorageDatabasePath;
270     if (FAILED(preferences->localStorageDatabasePath(&localStorageDatabasePath)))
271         return String();
272
273     return toString(localStorageDatabasePath);
274 }
275
276 class PreferencesChangedOrRemovedObserver : public IWebNotificationObserver {
277 public:
278     static PreferencesChangedOrRemovedObserver* sharedInstance();
279
280 private:
281     PreferencesChangedOrRemovedObserver() {}
282     ~PreferencesChangedOrRemovedObserver() {}
283
284     virtual HRESULT STDMETHODCALLTYPE QueryInterface(_In_ REFIID, _Outptr_ void**) { return E_FAIL; }
285     virtual ULONG STDMETHODCALLTYPE AddRef() { return 0; }
286     virtual ULONG STDMETHODCALLTYPE Release() { return 0; }
287
288 public:
289     // IWebNotificationObserver
290     virtual HRESULT STDMETHODCALLTYPE onNotify( 
291         /* [in] */ IWebNotification* notification);
292
293 private:
294     HRESULT notifyPreferencesChanged(WebCacheModel);
295     HRESULT notifyPreferencesRemoved(WebCacheModel);
296 };
297
298 PreferencesChangedOrRemovedObserver* PreferencesChangedOrRemovedObserver::sharedInstance()
299 {
300     static PreferencesChangedOrRemovedObserver* shared = new PreferencesChangedOrRemovedObserver;
301     return shared;
302 }
303
304 HRESULT PreferencesChangedOrRemovedObserver::onNotify(IWebNotification* notification)
305 {
306     HRESULT hr = S_OK;
307
308     COMPtr<IUnknown> unkPrefs;
309     hr = notification->getObject(&unkPrefs);
310     if (FAILED(hr))
311         return hr;
312
313     COMPtr<IWebPreferences> preferences(Query, unkPrefs);
314     if (!preferences)
315         return E_NOINTERFACE;
316
317     WebCacheModel cacheModel;
318     hr = preferences->cacheModel(&cacheModel);
319     if (FAILED(hr))
320         return hr;
321
322     BString name;
323     hr = notification->name(&name);
324     if (FAILED(hr))
325         return hr;
326
327     if (wcscmp(name, WebPreferences::webPreferencesChangedNotification()) == 0)
328         return notifyPreferencesChanged(cacheModel);
329
330     if (wcscmp(name, WebPreferences::webPreferencesRemovedNotification()) == 0)
331         return notifyPreferencesRemoved(cacheModel);
332
333     ASSERT_NOT_REACHED();
334     return E_FAIL;
335 }
336
337 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesChanged(WebCacheModel cacheModel)
338 {
339     HRESULT hr = S_OK;
340
341     if (!WebView::didSetCacheModel() || cacheModel > WebView::cacheModel())
342         WebView::setCacheModel(cacheModel);
343     else if (cacheModel < WebView::cacheModel()) {
344         WebCacheModel sharedPreferencesCacheModel;
345         hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
346         if (FAILED(hr))
347             return hr;
348         WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
349     }
350
351     return hr;
352 }
353
354 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesRemoved(WebCacheModel cacheModel)
355 {
356     HRESULT hr = S_OK;
357
358     if (cacheModel == WebView::cacheModel()) {
359         WebCacheModel sharedPreferencesCacheModel;
360         hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
361         if (FAILED(hr))
362             return hr;
363         WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
364     }
365
366     return hr;
367 }
368
369
370 const LPCWSTR kWebViewWindowClassName = L"WebViewWindowClass";
371
372 const int WM_XP_THEMECHANGED = 0x031A;
373 const int WM_VISTA_MOUSEHWHEEL = 0x020E;
374 #ifndef WM_DPICHANGED
375 const int WM_DPICHANGED = 0x02E0;
376 #endif
377
378 static const int maxToolTipWidth = 250;
379
380 static const int delayBeforeDeletingBackingStoreMsec = 5000;
381
382 static ATOM registerWebView();
383
384 static void initializeStaticObservers();
385
386 static HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences*);
387
388 HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches);
389
390 static bool continuousSpellCheckingEnabled;
391 static bool grammarCheckingEnabled;
392
393 static bool s_didSetCacheModel;
394 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
395
396 enum {
397     UpdateActiveStateTimer = 1,
398     DeleteBackingStoreTimer = 2,
399 };
400
401 // WebView ----------------------------------------------------------------
402
403 bool WebView::s_allowSiteSpecificHacks = false;
404
405 WebView::WebView()
406 {
407     JSC::initializeThreading();
408     WTF::initializeMainThread();
409     RunLoop::initializeMainRunLoop();
410
411     m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
412
413     CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper,(void**)&m_dropTargetHelper);
414
415     initializeStaticObservers();
416
417     WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
418     BOOL enabled = FALSE;
419     if (SUCCEEDED(sharedPreferences->continuousSpellCheckingEnabled(&enabled)))
420         continuousSpellCheckingEnabled = !!enabled;
421     if (SUCCEEDED(sharedPreferences->grammarCheckingEnabled(&enabled)))
422         grammarCheckingEnabled = !!enabled;
423
424     m_webViewGroup = WebViewGroup::getOrCreate(String(), localStorageDatabasePath(sharedPreferences));
425     m_webViewGroup->addWebView(this);
426
427     WebViewCount++;
428     gClassCount++;
429     gClassNameCount().add("WebView");
430 }
431
432 WebView::~WebView()
433 {
434     deleteBackingStore();
435
436     // the tooltip window needs to be explicitly destroyed since it isn't a WS_CHILD
437     if (::IsWindow(m_toolTipHwnd))
438         ::DestroyWindow(m_toolTipHwnd);
439
440     ASSERT(!m_page);
441     ASSERT(!m_preferences);
442     ASSERT(!m_viewWindow);
443
444 #if USE(CA)
445     ASSERT(!m_layerTreeHost);
446 #endif
447
448     m_webViewGroup->removeWebView(this);
449
450     WebViewCount--;
451     gClassCount--;
452     gClassNameCount().remove("WebView");
453 }
454
455 WebView* WebView::createInstance()
456 {
457     WebView* instance = new WebView();
458     instance->AddRef();
459     return instance;
460 }
461
462 void initializeStaticObservers()
463 {
464     static bool initialized = false;
465     if (initialized)
466         return;
467     initialized = true;
468
469     IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
470     notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesChangedNotification(), 0);
471     notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesRemovedNotification(), 0);
472 }
473
474 static HashSet<WebView*>& allWebViewsSet()
475 {
476     static HashSet<WebView*> allWebViewsSet;
477     return allWebViewsSet;
478 }
479
480 void WebView::addToAllWebViewsSet()
481 {
482     allWebViewsSet().add(this);
483 }
484
485 void WebView::removeFromAllWebViewsSet()
486 {
487     allWebViewsSet().remove(this);
488 }
489
490 void WebView::setCacheModel(WebCacheModel cacheModel)
491 {
492     if (s_didSetCacheModel && cacheModel == s_cacheModel)
493         return;
494
495     String cacheDirectory;
496
497 #if USE(CFNETWORK)
498     RetainPtr<CFURLCacheRef> cfurlCache = adoptCF(CFURLCacheCopySharedURLCache());
499     RetainPtr<CFStringRef> cfurlCacheDirectory = adoptCF(wkCopyFoundationCacheDirectory(0));
500     if (!cfurlCacheDirectory) {
501         RetainPtr<CFPropertyListRef> preference = adoptCF(CFPreferencesCopyAppValue(WebKitLocalCacheDefaultsKey, kCFPreferencesCurrentApplication));
502         if (preference && (CFStringGetTypeID() == CFGetTypeID(preference.get())))
503             cfurlCacheDirectory = adoptCF(static_cast<CFStringRef>(preference.leakRef()));
504         else
505             cfurlCacheDirectory = WebCore::localUserSpecificStorageDirectory().createCFString();
506     }
507     cacheDirectory = String(cfurlCacheDirectory.get());
508     CFIndex cacheMemoryCapacity = 0;
509     CFIndex cacheDiskCapacity = 0;
510 #elif USE(CURL)
511     cacheDirectory = CurlCacheManager::getInstance().cacheDirectory();
512     long cacheMemoryCapacity = 0;
513     long cacheDiskCapacity = 0;
514 #endif
515
516     unsigned long long memSize = ramSize() / 1024 / 1024;
517
518     // As a fudge factor, use 1000 instead of 1024, in case the reported byte 
519     // count doesn't align exactly to a megabyte boundary.
520     unsigned long long diskFreeSize = WebVolumeFreeSize(cacheDirectory) / 1024 / 1000;
521
522     unsigned cacheTotalCapacity = 0;
523     unsigned cacheMinDeadCapacity = 0;
524     unsigned cacheMaxDeadCapacity = 0;
525     auto deadDecodedDataDeletionInterval = std::chrono::seconds { 0 };
526
527     unsigned pageCacheSize = 0;
528
529
530     switch (cacheModel) {
531     case WebCacheModelDocumentViewer: {
532         // Page cache capacity (in pages)
533         pageCacheSize = 0;
534
535         // Object cache capacities (in bytes)
536         if (memSize >= 2048)
537             cacheTotalCapacity = 96 * 1024 * 1024;
538         else if (memSize >= 1536)
539             cacheTotalCapacity = 64 * 1024 * 1024;
540         else if (memSize >= 1024)
541             cacheTotalCapacity = 32 * 1024 * 1024;
542         else if (memSize >= 512)
543             cacheTotalCapacity = 16 * 1024 * 1024; 
544
545         cacheMinDeadCapacity = 0;
546         cacheMaxDeadCapacity = 0;
547
548         // Memory cache capacity (in bytes)
549         cacheMemoryCapacity = 0;
550
551 #if USE(CFNETWORK)
552         // Foundation disk cache capacity (in bytes)
553         cacheDiskCapacity = CFURLCacheDiskCapacity(cfurlCache.get());
554 #endif
555         break;
556     }
557     case WebCacheModelDocumentBrowser: {
558         // Page cache capacity (in pages)
559         if (memSize >= 1024)
560             pageCacheSize = 3;
561         else if (memSize >= 512)
562             pageCacheSize = 2;
563         else if (memSize >= 256)
564             pageCacheSize = 1;
565         else
566             pageCacheSize = 0;
567
568         // Object cache capacities (in bytes)
569         if (memSize >= 2048)
570             cacheTotalCapacity = 96 * 1024 * 1024;
571         else if (memSize >= 1536)
572             cacheTotalCapacity = 64 * 1024 * 1024;
573         else if (memSize >= 1024)
574             cacheTotalCapacity = 32 * 1024 * 1024;
575         else if (memSize >= 512)
576             cacheTotalCapacity = 16 * 1024 * 1024; 
577
578         cacheMinDeadCapacity = cacheTotalCapacity / 8;
579         cacheMaxDeadCapacity = cacheTotalCapacity / 4;
580
581         // Memory cache capacity (in bytes)
582         if (memSize >= 2048)
583             cacheMemoryCapacity = 4 * 1024 * 1024;
584         else if (memSize >= 1024)
585             cacheMemoryCapacity = 2 * 1024 * 1024;
586         else if (memSize >= 512)
587             cacheMemoryCapacity = 1 * 1024 * 1024;
588         else
589             cacheMemoryCapacity =      512 * 1024; 
590
591         // Disk cache capacity (in bytes)
592         if (diskFreeSize >= 16384)
593             cacheDiskCapacity = 50 * 1024 * 1024;
594         else if (diskFreeSize >= 8192)
595             cacheDiskCapacity = 40 * 1024 * 1024;
596         else if (diskFreeSize >= 4096)
597             cacheDiskCapacity = 30 * 1024 * 1024;
598         else
599             cacheDiskCapacity = 20 * 1024 * 1024;
600
601         break;
602     }
603     case WebCacheModelPrimaryWebBrowser: {
604         // Page cache capacity (in pages)
605         // (Research indicates that value / page drops substantially after 3 pages.)
606         if (memSize >= 2048)
607             pageCacheSize = 5;
608         else if (memSize >= 1024)
609             pageCacheSize = 4;
610         else if (memSize >= 512)
611             pageCacheSize = 3;
612         else if (memSize >= 256)
613             pageCacheSize = 2;
614         else
615             pageCacheSize = 1;
616
617         // Object cache capacities (in bytes)
618         // (Testing indicates that value / MB depends heavily on content and
619         // browsing pattern. Even growth above 128MB can have substantial 
620         // value / MB for some content / browsing patterns.)
621         if (memSize >= 2048)
622             cacheTotalCapacity = 128 * 1024 * 1024;
623         else if (memSize >= 1536)
624             cacheTotalCapacity = 96 * 1024 * 1024;
625         else if (memSize >= 1024)
626             cacheTotalCapacity = 64 * 1024 * 1024;
627         else if (memSize >= 512)
628             cacheTotalCapacity = 32 * 1024 * 1024; 
629
630         cacheMinDeadCapacity = cacheTotalCapacity / 4;
631         cacheMaxDeadCapacity = cacheTotalCapacity / 2;
632
633         // This code is here to avoid a PLT regression. We can remove it if we
634         // can prove that the overall system gain would justify the regression.
635         cacheMaxDeadCapacity = max(24u, cacheMaxDeadCapacity);
636
637         deadDecodedDataDeletionInterval = std::chrono::seconds { 60 };
638
639         // Memory cache capacity (in bytes)
640         // (These values are small because WebCore does most caching itself.)
641         if (memSize >= 1024)
642             cacheMemoryCapacity = 4 * 1024 * 1024;
643         else if (memSize >= 512)
644             cacheMemoryCapacity = 2 * 1024 * 1024;
645         else if (memSize >= 256)
646             cacheMemoryCapacity = 1 * 1024 * 1024;
647         else
648             cacheMemoryCapacity =      512 * 1024; 
649
650         // Disk cache capacity (in bytes)
651         if (diskFreeSize >= 16384)
652             cacheDiskCapacity = 175 * 1024 * 1024;
653         else if (diskFreeSize >= 8192)
654             cacheDiskCapacity = 150 * 1024 * 1024;
655         else if (diskFreeSize >= 4096)
656             cacheDiskCapacity = 125 * 1024 * 1024;
657         else if (diskFreeSize >= 2048)
658             cacheDiskCapacity = 100 * 1024 * 1024;
659         else if (diskFreeSize >= 1024)
660             cacheDiskCapacity = 75 * 1024 * 1024;
661         else
662             cacheDiskCapacity = 50 * 1024 * 1024;
663
664         break;
665     }
666     default:
667         ASSERT_NOT_REACHED();
668     }
669
670     auto& memoryCache = MemoryCache::singleton();
671     memoryCache.setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
672     memoryCache.setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
673     PageCache::singleton().setMaxSize(pageCacheSize);
674
675 #if USE(CFNETWORK)
676     // Don't shrink a big disk cache, since that would cause churn.
677     cacheDiskCapacity = max(cacheDiskCapacity, CFURLCacheDiskCapacity(cfurlCache.get()));
678
679     CFURLCacheSetMemoryCapacity(cfurlCache.get(), cacheMemoryCapacity);
680     CFURLCacheSetDiskCapacity(cfurlCache.get(), cacheDiskCapacity);
681 #elif USE(CURL)
682     CurlCacheManager::getInstance().setStorageSizeLimit(cacheDiskCapacity);
683 #endif
684
685     s_didSetCacheModel = true;
686     s_cacheModel = cacheModel;
687     return;
688 }
689
690 WebCacheModel WebView::cacheModel()
691 {
692     return s_cacheModel;
693 }
694
695 bool WebView::didSetCacheModel()
696 {
697     return s_didSetCacheModel;
698 }
699
700 WebCacheModel WebView::maxCacheModelInAnyInstance()
701 {
702     WebCacheModel cacheModel = WebCacheModelDocumentViewer;
703
704     HashSet<WebView*>::iterator end = allWebViewsSet().end();
705     for (HashSet<WebView*>::iterator it = allWebViewsSet().begin(); it != end; ++it) {
706         COMPtr<IWebPreferences> pref;
707         if (FAILED((*it)->preferences(&pref)))
708             continue;
709         WebCacheModel prefCacheModel = WebCacheModelDocumentViewer;
710         if (FAILED(pref->cacheModel(&prefCacheModel)))
711             continue;
712
713         cacheModel = max(cacheModel, prefCacheModel);
714     }
715
716     return cacheModel;
717 }
718
719 HRESULT WebView::close()
720 {
721     if (m_didClose)
722         return S_OK;
723
724     m_didClose = true;
725
726     setAcceleratedCompositing(false);
727
728     WebNotificationCenter::defaultCenterInternal()->postNotificationName(_bstr_t(WebViewWillCloseNotification).GetBSTR(), static_cast<IWebView*>(this), 0);
729
730     if (m_uiDelegatePrivate)
731         m_uiDelegatePrivate->webViewClosing(this);
732
733     removeFromAllWebViewsSet();
734
735     if (m_page)
736         m_page->mainFrame().loader().detachFromParent();
737
738     if (m_mouseOutTracker) {
739         m_mouseOutTracker->dwFlags = TME_CANCEL;
740         ::TrackMouseEvent(m_mouseOutTracker.get());
741         m_mouseOutTracker.reset();
742     }
743     
744     revokeDragDrop();
745
746     if (m_viewWindow) {
747         // We can't check IsWindow(m_viewWindow) here, because that will return true even while
748         // we're already handling WM_DESTROY. So we check !isBeingDestroyed() instead.
749         if (!isBeingDestroyed())
750             DestroyWindow(m_viewWindow);
751         // Either we just destroyed m_viewWindow, or it's in the process of being destroyed. Either
752         // way, we clear it out to make sure we don't try to use it later.
753         m_viewWindow = 0;
754     }
755
756     setHostWindow(0);
757
758     setAccessibilityDelegate(0);
759     setDownloadDelegate(0);
760     setEditingDelegate(0);
761     setFrameLoadDelegate(0);
762     setFrameLoadDelegatePrivate(0);
763     setHistoryDelegate(0);
764     setPolicyDelegate(0);
765     setResourceLoadDelegate(0);
766     setUIDelegate(0);
767     setFormDelegate(0);
768
769     m_inspectorClient = nullptr;
770     if (m_webInspector)
771         m_webInspector->inspectedWebViewClosed();
772
773     delete m_page;
774     m_page = nullptr;
775
776     m_mainFrame = nullptr;
777
778     registerForIconNotification(false);
779     IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
780     notifyCenter->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
781
782     if (COMPtr<WebPreferences> preferences = m_preferences) {
783         BString identifier;
784         preferences->identifier(&identifier);
785
786         m_preferences = 0;
787         preferences->didRemoveFromWebView();
788         // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
789         preferences = 0;
790         if (identifier)
791             WebPreferences::removeReferenceForIdentifier(identifier);
792     }
793
794     deleteBackingStore();
795     return S_OK;
796 }
797
798 void WebView::repaint(const WebCore::IntRect& logicalWindowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
799 {
800     FloatRect windowRectFloat(logicalWindowRect);
801     windowRectFloat.scale(deviceScaleFactor());
802     IntRect windowRect(enclosingIntRect(windowRectFloat));
803
804     if (isAcceleratedCompositing()) {
805         // The contentChanged, immediate, and repaintContentOnly parameters are all based on a non-
806         // compositing painting/scrolling model.
807         addToDirtyRegion(logicalWindowRect);
808         return;
809     }
810
811     if (!repaintContentOnly) {
812         RECT rect = windowRect;
813         ::InvalidateRect(m_viewWindow, &rect, false);
814     }
815     if (contentChanged)
816         addToDirtyRegion(windowRect);
817     if (immediate) {
818         if (repaintContentOnly)
819             updateBackingStore(core(topLevelFrame())->view());
820         else
821             ::UpdateWindow(m_viewWindow);
822     }
823     m_needsDisplay = true;
824 }
825
826 void WebView::deleteBackingStore()
827 {
828     pendingDeleteBackingStoreSet().remove(this);
829
830     if (m_deleteBackingStoreTimerActive) {
831         KillTimer(m_viewWindow, DeleteBackingStoreTimer);
832         m_deleteBackingStoreTimerActive = false;
833     }
834     m_backingStoreBitmap = nullptr;
835     m_backingStoreDirtyRegion = nullptr;
836     m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
837 }
838
839 bool WebView::ensureBackingStore()
840 {
841     RECT windowRect;
842     ::GetClientRect(m_viewWindow, &windowRect);
843     LONG width = windowRect.right - windowRect.left;
844     LONG height = windowRect.bottom - windowRect.top;
845     if (width > 0 && height > 0 && (width != m_backingStoreSize.cx || height != m_backingStoreSize.cy)) {
846         deleteBackingStore();
847
848         m_backingStoreSize.cx = width;
849         m_backingStoreSize.cy = height;
850         BitmapInfo bitmapInfo = BitmapInfo::createBottomUp(IntSize(m_backingStoreSize));
851
852         void* pixels = NULL;
853         m_backingStoreBitmap = SharedGDIObject<HBITMAP>::create(adoptGDIObject(::CreateDIBSection(0, &bitmapInfo, DIB_RGB_COLORS, &pixels, 0, 0)));
854         return true;
855     }
856
857     return false;
858 }
859
860 void WebView::addToDirtyRegion(const IntRect& dirtyRect)
861 {
862     m_needsDisplay = true;
863
864     // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
865     // but it was being hit during our layout tests, and is being investigated in
866     // http://webkit.org/b/29350.
867
868     if (isAcceleratedCompositing()) {
869 #if USE(CA)
870         m_backingLayer->setNeedsDisplayInRect(dirtyRect);
871 #elif USE(TEXTURE_MAPPER_GL)
872         m_acceleratedCompositingContext->setNonCompositedContentsNeedDisplay(dirtyRect);
873 #endif
874         return;
875     }
876
877     auto newRegion = adoptGDIObject(::CreateRectRgn(dirtyRect.x(), dirtyRect.y(),
878         dirtyRect.maxX(), dirtyRect.maxY()));
879     addToDirtyRegion(WTFMove(newRegion));
880 }
881
882 void WebView::addToDirtyRegion(GDIObject<HRGN> newRegion)
883 {
884     m_needsDisplay = true;
885
886     ASSERT(!isAcceleratedCompositing());
887
888     LOCAL_GDI_COUNTER(0, __FUNCTION__);
889
890     if (m_backingStoreDirtyRegion) {
891         auto combinedRegion = adoptGDIObject(::CreateRectRgn(0, 0, 0, 0));
892         ::CombineRgn(combinedRegion.get(), m_backingStoreDirtyRegion->get(), newRegion.get(), RGN_OR);
893         m_backingStoreDirtyRegion = SharedGDIObject<HRGN>::create(WTFMove(combinedRegion));
894     } else
895         m_backingStoreDirtyRegion = SharedGDIObject<HRGN>::create(WTFMove(newRegion));
896
897     if (m_uiDelegatePrivate)
898         m_uiDelegatePrivate->webViewDidInvalidate(this);
899 }
900
901 void WebView::scrollBackingStore(FrameView* frameView, int logicalDx, int logicalDy, const IntRect& logicalScrollViewRect, const IntRect& logicalClipRect)
902 {
903     m_needsDisplay = true;
904
905     // Dimensions passed to us from WebCore are in logical units. We must convert to pixels:
906     float scaleFactor = deviceScaleFactor();
907     int dx = clampTo<int>(scaleFactor * logicalDx);
908     int dy = clampTo<int>(scaleFactor * logicalDy);
909     FloatRect scrollViewRectFloat(logicalScrollViewRect);
910     scrollViewRectFloat.scale(scaleFactor);
911     IntRect scrollViewRect(enclosingIntRect(scrollViewRectFloat));
912     FloatRect clipRect(logicalClipRect);
913     clipRect.scale(scaleFactor);
914
915     if (isAcceleratedCompositing()) {
916         // FIXME: We should be doing something smarter here, like moving tiles around and painting
917         // any newly-exposed tiles. <http://webkit.org/b/52714>
918 #if USE(CA)
919         m_backingLayer->setNeedsDisplayInRect(scrollViewRect);
920 #elif USE(TEXTURE_MAPPER_GL)
921         m_acceleratedCompositingContext->scrollNonCompositedContents(scrollViewRect, IntSize(dx, dy));
922 #endif
923         return;
924     }
925
926     LOCAL_GDI_COUNTER(0, __FUNCTION__);
927
928     // If there's no backing store we don't need to update it
929     if (!m_backingStoreBitmap) {
930         if (m_uiDelegatePrivate)
931             m_uiDelegatePrivate->webViewScrolled(this);
932
933         return;
934     }
935
936     // Make a region to hold the invalidated scroll area.
937     auto updateRegion = adoptGDIObject(::CreateRectRgn(0, 0, 0, 0));
938
939     // Collect our device context info and select the bitmap to scroll.
940     HWndDC windowDC(m_viewWindow);
941     auto bitmapDC = adoptGDIObject(::CreateCompatibleDC(windowDC));
942     HGDIOBJ oldBitmap = ::SelectObject(bitmapDC.get(), m_backingStoreBitmap->get());
943     if (!oldBitmap) {
944         // The ::SelectObject call will fail if m_backingStoreBitmap is already selected into a device context.
945         // This happens when this method is called indirectly from WebView::updateBackingStore during normal WM_PAINT handling.
946         // There is no point continuing, since we would just be scrolling a 1x1 bitmap which is selected into the device context by default.
947         // We can just scroll by repainting the scroll rectangle.
948         RECT scrollRect(scrollViewRect);
949         ::InvalidateRect(m_viewWindow, &scrollRect, FALSE);
950         return;
951     }
952
953     // Scroll the bitmap.
954     RECT scrollRectWin(scrollViewRect);
955     RECT clipRectWin(enclosingIntRect(clipRect));
956     ::ScrollDC(bitmapDC.get(), dx, dy, &scrollRectWin, &clipRectWin, updateRegion.get(), 0);
957     RECT regionBox;
958     ::GetRgnBox(updateRegion.get(), &regionBox);
959
960     // Flush.
961     GdiFlush();
962
963     // Add the dirty region to the backing store's dirty region.
964     addToDirtyRegion(WTFMove(updateRegion));
965
966     if (m_uiDelegatePrivate)
967         m_uiDelegatePrivate->webViewScrolled(this);
968
969     // Update the backing store.
970     updateBackingStore(frameView, bitmapDC.get(), false);
971
972     // Clean up.
973     ::SelectObject(bitmapDC.get(), oldBitmap);
974 }
975
976 void WebView::sizeChanged(const IntSize& newSize)
977 {
978     m_needsDisplay = true;
979
980     deleteBackingStore();
981
982     if (Frame* coreFrame = core(topLevelFrame())) {
983         IntSize logicalSize = newSize;
984         logicalSize.scale(1.0f / deviceScaleFactor());
985         coreFrame->view()->resize(logicalSize);
986     }
987
988 #if USE(CA)
989     if (m_layerTreeHost)
990         m_layerTreeHost->resize();
991
992     if (m_backingLayer) {
993         m_backingLayer->setSize(newSize);
994         m_backingLayer->setNeedsDisplay();
995     }
996 #elif USE(TEXTURE_MAPPER_GL)
997     if (m_acceleratedCompositingContext)
998         m_acceleratedCompositingContext->resizeRootLayer(newSize);
999 #endif
1000 }
1001
1002 bool WebView::dpiChanged(float, const WebCore::IntSize& newSize)
1003 {
1004     if (!IsProcessDPIAware())
1005         return false;
1006
1007     sizeChanged(newSize);
1008
1009     return true;
1010 }
1011
1012 // This emulates the Mac smarts for painting rects intelligently.  This is very
1013 // important for us, since we double buffer based off dirty rects.
1014 static void getUpdateRects(HRGN region, const IntRect& dirtyRect, Vector<IntRect>& rects)
1015 {
1016     ASSERT_ARG(region, region);
1017
1018     const int cRectThreshold = 10;
1019     const float cWastedSpaceThreshold = 0.75f;
1020
1021     rects.clear();
1022
1023     DWORD regionDataSize = GetRegionData(region, sizeof(RGNDATA), NULL);
1024     if (!regionDataSize) {
1025         rects.append(dirtyRect);
1026         return;
1027     }
1028
1029     Vector<unsigned char> buffer(regionDataSize);
1030     RGNDATA* regionData = reinterpret_cast<RGNDATA*>(buffer.data());
1031     GetRegionData(region, regionDataSize, regionData);
1032     if (regionData->rdh.nCount > cRectThreshold) {
1033         rects.append(dirtyRect);
1034         return;
1035     }
1036
1037     double singlePixels = 0.0;
1038     unsigned i;
1039     RECT* rect;
1040     for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
1041         singlePixels += (rect->right - rect->left) * (rect->bottom - rect->top);
1042
1043     double unionPixels = dirtyRect.width() * dirtyRect.height();
1044     double wastedSpace = 1.0 - (singlePixels / unionPixels);
1045     if (wastedSpace <= cWastedSpaceThreshold) {
1046         rects.append(dirtyRect);
1047         return;
1048     }
1049
1050     for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
1051         rects.append(*rect);
1052 }
1053
1054 void WebView::updateBackingStore(FrameView* frameView, HDC dc, bool backingStoreCompletelyDirty, WindowsToPaint windowsToPaint)
1055 {
1056     ASSERT(!isAcceleratedCompositing());
1057
1058     LOCAL_GDI_COUNTER(0, __FUNCTION__);
1059
1060     GDIObject<HDC> bitmapDCObject;
1061
1062     HDC bitmapDC = dc;
1063     HGDIOBJ oldBitmap = 0;
1064     if (!dc) {
1065         HWndDC windowDC(m_viewWindow);
1066         bitmapDCObject = adoptGDIObject(::CreateCompatibleDC(windowDC));
1067         bitmapDC = bitmapDCObject.get();
1068         oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->get());
1069     }
1070
1071     if (m_backingStoreBitmap && (m_backingStoreDirtyRegion || backingStoreCompletelyDirty)) {
1072         // Do a layout first so that everything we render to the backing store is always current.
1073         if (Frame* coreFrame = core(m_mainFrame))
1074             if (FrameView* view = coreFrame->view())
1075                 view->updateLayoutAndStyleIfNeededRecursive();
1076
1077         Vector<IntRect> paintRects;
1078         if (!backingStoreCompletelyDirty && m_backingStoreDirtyRegion) {
1079             RECT regionBox;
1080             ::GetRgnBox(m_backingStoreDirtyRegion->get(), &regionBox);
1081             getUpdateRects(m_backingStoreDirtyRegion->get(), regionBox, paintRects);
1082         } else {
1083             RECT clientRect;
1084             ::GetClientRect(m_viewWindow, &clientRect);
1085             paintRects.append(clientRect);
1086         }
1087
1088         for (unsigned i = 0; i < paintRects.size(); ++i)
1089             paintIntoBackingStore(frameView, bitmapDC, paintRects[i], windowsToPaint);
1090
1091         if (m_uiDelegatePrivate)
1092             m_uiDelegatePrivate->webViewPainted(this);
1093
1094         m_backingStoreDirtyRegion = nullptr;
1095     }
1096
1097     if (!dc)
1098         ::SelectObject(bitmapDC, oldBitmap);
1099
1100     GdiFlush();
1101
1102     m_needsDisplay = true;
1103 }
1104
1105 void WebView::performLayeredWindowUpdate()
1106 {
1107     // The backing store may have been destroyed if the window rect was set to zero height or zero width.
1108     if (!m_backingStoreBitmap)
1109         return;
1110
1111     HWndDC hdcScreen(m_viewWindow);
1112     auto hdcMem = adoptGDIObject(::CreateCompatibleDC(hdcScreen));
1113     HBITMAP hbmOld = static_cast<HBITMAP>(::SelectObject(hdcMem.get(), m_backingStoreBitmap->get()));
1114
1115     BITMAP bmpInfo;
1116     ::GetObject(m_backingStoreBitmap->get(), sizeof(bmpInfo), &bmpInfo);
1117     SIZE windowSize = { bmpInfo.bmWidth, bmpInfo.bmHeight };
1118
1119     BLENDFUNCTION blendFunction;
1120     blendFunction.BlendOp = AC_SRC_OVER;
1121     blendFunction.BlendFlags = 0;
1122     blendFunction.SourceConstantAlpha = 0xFF;
1123     blendFunction.AlphaFormat = AC_SRC_ALPHA;
1124
1125     POINT layerPos = { 0, 0 };
1126     ::UpdateLayeredWindow(m_viewWindow, hdcScreen, 0, &windowSize, hdcMem.get(), &layerPos, 0, &blendFunction, ULW_ALPHA);
1127
1128     ::SelectObject(hdcMem.get(), hbmOld);
1129
1130     m_needsDisplay = false;
1131 }
1132
1133 void WebView::paint(HDC dc, LPARAM options)
1134 {
1135     LOCAL_GDI_COUNTER(0, __FUNCTION__);
1136
1137     if (paintCompositedContentToHDC(dc)) {
1138         ::ValidateRect(m_viewWindow, nullptr);
1139         return;
1140     }
1141
1142     Frame* coreFrame = core(m_mainFrame);
1143     if (!coreFrame)
1144         return;
1145     FrameView* frameView = coreFrame->view();
1146
1147     RECT rcPaint;
1148     HDC hdc;
1149     GDIObject<HRGN> region;
1150     int regionType = NULLREGION;
1151     PAINTSTRUCT ps;
1152     WindowsToPaint windowsToPaint;
1153     if (!dc) {
1154         region = adoptGDIObject(::CreateRectRgn(0, 0, 0, 0));
1155         regionType = GetUpdateRgn(m_viewWindow, region.get(), false);
1156         hdc = BeginPaint(m_viewWindow, &ps);
1157         rcPaint = ps.rcPaint;
1158         // We're painting to the screen, and our child windows can handle
1159         // painting themselves to the screen.
1160         windowsToPaint = PaintWebViewOnly;
1161     } else {
1162         hdc = dc;
1163         ::GetClientRect(m_viewWindow, &rcPaint);
1164         if (options & PRF_ERASEBKGND)
1165             ::FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
1166         // Since we aren't painting to the screen, we want to paint all our
1167         // children into the HDC.
1168         windowsToPaint = PaintWebViewAndChildren;
1169     }
1170
1171     bool backingStoreCompletelyDirty = ensureBackingStore();
1172     if (!m_backingStoreBitmap) {
1173         if (!dc)
1174             EndPaint(m_viewWindow, &ps);
1175         return;
1176     }
1177
1178     m_paintCount++;
1179
1180     auto bitmapDC = adoptGDIObject(::CreateCompatibleDC(hdc));
1181     HGDIOBJ oldBitmap = ::SelectObject(bitmapDC.get(), m_backingStoreBitmap->get());
1182
1183     // Update our backing store if needed.
1184     updateBackingStore(frameView, bitmapDC.get(), backingStoreCompletelyDirty, windowsToPaint);
1185
1186     // Now we blit the updated backing store
1187     IntRect windowDirtyRect = rcPaint;
1188     
1189     // Apply the same heuristic for this update region too.
1190     Vector<IntRect> blitRects;
1191     if (region && regionType == COMPLEXREGION)
1192         getUpdateRects(region.get(), windowDirtyRect, blitRects);
1193     else
1194         blitRects.append(windowDirtyRect);
1195
1196     for (unsigned i = 0; i < blitRects.size(); ++i)
1197         paintIntoWindow(bitmapDC.get(), hdc, blitRects[i]);
1198
1199     ::SelectObject(bitmapDC.get(), oldBitmap);
1200
1201     if (!dc)
1202         EndPaint(m_viewWindow, &ps);
1203
1204     m_paintCount--;
1205
1206     if (active())
1207         cancelDeleteBackingStoreSoon();
1208     else
1209         deleteBackingStoreSoon();
1210 }
1211
1212 void WebView::paintIntoBackingStore(FrameView* frameView, HDC bitmapDC, const IntRect& dirtyRectPixels, WindowsToPaint windowsToPaint)
1213 {
1214     // FIXME: This function should never be called in accelerated compositing mode, and we should
1215     // assert as such. But currently it *is* sometimes called, so we can't assert yet. See
1216     // <http://webkit.org/b/58539>.
1217
1218     LOCAL_GDI_COUNTER(0, __FUNCTION__);
1219
1220     // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
1221     // but it was being hit during our layout tests, and is being investigated in
1222     // http://webkit.org/b/29350.
1223
1224     RECT rect = dirtyRectPixels;
1225
1226 #if FLASH_BACKING_STORE_REDRAW
1227     {
1228         HWndDC dc(m_viewWindow);
1229         auto yellowBrush = adoptGDIObject(::CreateSolidBrush(RGB(255, 255, 0)));
1230         FillRect(dc, &rect, yellowBrush.get());
1231         GdiFlush();
1232         Sleep(50);
1233         paintIntoWindow(bitmapDC, dc, dirtyRectPixels);
1234     }
1235 #endif
1236
1237     float scaleFactor = deviceScaleFactor();
1238     float inverseScaleFactor = 1.0f / scaleFactor;
1239
1240     FloatRect logicalDirtyRectFloat = dirtyRectPixels;
1241     logicalDirtyRectFloat.scale(inverseScaleFactor);    
1242     IntRect logicalDirtyRect(enclosingIntRect(logicalDirtyRectFloat));
1243
1244     GraphicsContext gc(bitmapDC, m_transparent);
1245     gc.setShouldIncludeChildWindows(windowsToPaint == PaintWebViewAndChildren);
1246     gc.save();
1247     if (m_transparent)
1248         gc.clearRect(logicalDirtyRect);
1249     else
1250         FillRect(bitmapDC, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
1251
1252     COMPtr<IWebUIDelegatePrivate2> uiPrivate(Query, m_uiDelegate);
1253     if (uiPrivate)
1254         uiPrivate->drawBackground(this, bitmapDC, &rect);
1255
1256     if (frameView && frameView->frame().contentRenderer()) {
1257         gc.save();
1258         gc.scale(FloatSize(scaleFactor, scaleFactor));
1259         gc.clip(logicalDirtyRect);
1260         frameView->paint(gc, logicalDirtyRect);
1261         gc.restore();
1262         if (m_shouldInvertColors)
1263             gc.fillRect(logicalDirtyRect, Color::white, CompositeDifference);
1264     }
1265     gc.restore();
1266 }
1267
1268 void WebView::paintIntoWindow(HDC bitmapDC, HDC windowDC, const IntRect& dirtyRectPixels)
1269 {
1270     // FIXME: This function should never be called in accelerated compositing mode, and we should
1271     // assert as such. But currently it *is* sometimes called, so we can't assert yet. See
1272     // <http://webkit.org/b/58539>.
1273
1274     LOCAL_GDI_COUNTER(0, __FUNCTION__);
1275 #if FLASH_WINDOW_REDRAW
1276     auto greenBrush = adoptGDIObject(::CreateSolidBrush(RGB(0, 255, 0)));
1277     RECT rect = dirtyRectPixels;
1278     FillRect(windowDC, &rect, greenBrush.get());
1279     GdiFlush();
1280     Sleep(50);
1281 #endif
1282
1283     // Blit the dirty rect from the backing store into the same position
1284     // in the destination DC.
1285     BitBlt(windowDC, dirtyRectPixels.x(), dirtyRectPixels.y(), dirtyRectPixels.width(), dirtyRectPixels.height(), bitmapDC,
1286         dirtyRectPixels.x(), dirtyRectPixels.y(), SRCCOPY);
1287
1288     m_needsDisplay = false;
1289 }
1290
1291 void WebView::frameRect(RECT* rect)
1292 {
1293     ::GetWindowRect(m_viewWindow, rect);
1294 }
1295
1296 class WindowCloseTimer final : public WebCore::SuspendableTimer {
1297 public:
1298     static WindowCloseTimer* create(WebView*);
1299
1300 private:
1301     WindowCloseTimer(ScriptExecutionContext&, WebView*);
1302
1303     // ActiveDOMObject API.
1304     void contextDestroyed() override;
1305     const char* activeDOMObjectName() const override { return "WindowCloseTimer"; }
1306
1307     // SuspendableTimer API.
1308     void fired() override;
1309
1310     WebView* m_webView;
1311 };
1312
1313 WindowCloseTimer* WindowCloseTimer::create(WebView* webView)
1314 {
1315     ASSERT_ARG(webView, webView);
1316     Frame* frame = core(webView->topLevelFrame());
1317     ASSERT(frame);
1318     if (!frame)
1319         return nullptr;
1320
1321     Document* document = frame->document();
1322     ASSERT(document);
1323     if (!document)
1324         return nullptr;
1325
1326     auto closeTimer = new WindowCloseTimer(*document, webView);
1327     closeTimer->suspendIfNeeded();
1328     return closeTimer;
1329 }
1330
1331 WindowCloseTimer::WindowCloseTimer(ScriptExecutionContext& context, WebView* webView)
1332     : SuspendableTimer(context)
1333     , m_webView(webView)
1334 {
1335     ASSERT_ARG(webView, webView);
1336 }
1337
1338 void WindowCloseTimer::contextDestroyed()
1339 {
1340     SuspendableTimer::contextDestroyed();
1341     delete this;
1342 }
1343
1344 void WindowCloseTimer::fired()
1345 {
1346     m_webView->closeWindowTimerFired();
1347 }
1348
1349 void WebView::closeWindowSoon()
1350 {
1351     if (m_closeWindowTimer)
1352         return;
1353
1354     m_closeWindowTimer = WindowCloseTimer::create(this);
1355     if (!m_closeWindowTimer)
1356         return;
1357     m_closeWindowTimer->startOneShot(0);
1358
1359     AddRef();
1360 }
1361
1362 void WebView::closeWindowTimerFired()
1363 {
1364     closeWindow();
1365     Release();
1366 }
1367
1368 void WebView::closeWindow()
1369 {
1370     if (m_hasSpellCheckerDocumentTag) {
1371         if (m_editingDelegate)
1372             m_editingDelegate->closeSpellDocument(this);
1373         m_hasSpellCheckerDocumentTag = false;
1374     }
1375
1376     COMPtr<IWebUIDelegate> ui;
1377     if (SUCCEEDED(uiDelegate(&ui)))
1378         ui->webViewClose(this);
1379 }
1380
1381 bool WebView::canHandleRequest(const WebCore::ResourceRequest& request)
1382 {
1383 #if USE(CFNETWORK)
1384     // On the Mac there's an about URL protocol implementation but Windows CFNetwork doesn't have that.
1385     if (request.url().protocolIs("about"))
1386         return true;
1387
1388     return CFURLProtocolCanHandleRequest(request.cfURLRequest(UpdateHTTPBody));
1389 #else
1390     return true;
1391 #endif
1392 }
1393
1394 String WebView::standardUserAgentWithApplicationName(const String& applicationName)
1395 {
1396     DEPRECATED_DEFINE_STATIC_LOCAL(String, osVersion, (windowsVersionForUAString()));
1397     DEPRECATED_DEFINE_STATIC_LOCAL(String, webKitVersion, (webKitVersionString()));
1398
1399     return makeString("Mozilla/5.0 (", osVersion, ") AppleWebKit/", webKitVersion, " (KHTML, like Gecko)", applicationName.isEmpty() ? "" : " ", applicationName);
1400 }
1401
1402 Page* WebView::page()
1403 {
1404     return m_page;
1405 }
1406
1407 static HMENU createContextMenuFromItems(const Vector<ContextMenuItem>& items)
1408 {
1409     HMENU menu = ::CreatePopupMenu();
1410
1411     for (auto& item : items) {
1412         UINT flags = 0;
1413
1414         flags |= item.enabled() ? MF_ENABLED : MF_DISABLED;
1415         flags |= item.checked() ? MF_CHECKED : MF_UNCHECKED;
1416
1417         switch (item.type()) {
1418         case ActionType:
1419         case CheckableActionType:
1420             ::AppendMenu(menu, flags | MF_STRING, item.action(), item.title().charactersWithNullTermination().data());
1421             break;
1422         case SeparatorType:
1423             ::AppendMenu(menu, flags | MF_SEPARATOR, item.action(), nullptr);
1424             break;
1425         case SubmenuType:
1426             ::AppendMenu(menu, flags | MF_POPUP, (UINT_PTR)createContextMenuFromItems(item.subMenuItems()), item.title().charactersWithNullTermination().data());
1427             break;
1428         }
1429     }
1430
1431     return menu;
1432 }
1433
1434 HMENU WebView::createContextMenu()
1435 {
1436     auto& contextMenuController = m_page->contextMenuController();
1437
1438     ContextMenu* coreMenu = contextMenuController.contextMenu();
1439     if (!coreMenu)
1440         return nullptr;
1441
1442     HMENU contextMenu = createContextMenuFromItems(coreMenu->items());
1443
1444     COMPtr<IWebUIDelegate> uiDelegate;
1445     if (SUCCEEDED(this->uiDelegate(&uiDelegate))) {
1446         ASSERT(uiDelegate);
1447
1448         COMPtr<WebElementPropertyBag> propertyBag;
1449         propertyBag.adoptRef(WebElementPropertyBag::createInstance(contextMenuController.hitTestResult()));
1450
1451         HMENU newMenu = nullptr;
1452         if (SUCCEEDED(uiDelegate->contextMenuItemsForElement(this, propertyBag.get(), contextMenu, &newMenu))) {
1453             // Make sure to delete the old menu if the delegate returned a new menu.
1454             if (newMenu != contextMenu) {
1455                 ::DestroyMenu(contextMenu);
1456                 contextMenu = newMenu;
1457             }
1458         }
1459     }
1460
1461     return contextMenu;
1462 }
1463
1464 bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam)
1465 {
1466     // Translate the screen coordinates into window coordinates
1467     POINT coords = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
1468     if (coords.x == -1 || coords.y == -1) {
1469         // The contextMenuController() holds onto the last context menu that was popped up on the
1470         // page until a new one is created. We need to clear this menu before propagating the event
1471         // through the DOM so that we can detect if we create a new menu for this event, since we
1472         // won't create a new menu if the DOM swallows the event and the defaultEventHandler does
1473         // not run.
1474         m_page->contextMenuController().clearContextMenu();
1475
1476         Frame& focusedFrame = m_page->focusController().focusedOrMainFrame();
1477         return focusedFrame.eventHandler().sendContextMenuEventForKey();
1478
1479     } else {
1480         if (!::ScreenToClient(m_viewWindow, &coords))
1481             return false;
1482     }
1483
1484     lParam = MAKELPARAM(coords.x, coords.y);
1485
1486     // Convert coordinates to logical pixels
1487     float scaleFactor = deviceScaleFactor();
1488     float inverseScaleFactor = 1.0f / scaleFactor;
1489     IntPoint logicalCoords(coords);
1490     logicalCoords.scale(inverseScaleFactor, inverseScaleFactor);
1491
1492     m_page->contextMenuController().clearContextMenu();
1493
1494     IntPoint documentPoint(m_page->mainFrame().view()->windowToContents(logicalCoords));
1495     HitTestResult result = m_page->mainFrame().eventHandler().hitTestResultAtPoint(documentPoint);
1496     Frame* targetFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document().frame() : &m_page->focusController().focusedOrMainFrame();
1497
1498     targetFrame->view()->setCursor(pointerCursor());
1499     PlatformMouseEvent mouseEvent(m_viewWindow, WM_RBUTTONUP, wParam, lParam);
1500     bool handledEvent = targetFrame->eventHandler().sendContextMenuEvent(mouseEvent);
1501     if (!handledEvent)
1502         return false;
1503
1504     ContextMenuController& contextMenuController = m_page->contextMenuController();
1505
1506     // Show the menu
1507     ContextMenu* coreMenu = contextMenuController.contextMenu();
1508     if (!coreMenu)
1509         return false;
1510
1511     Frame* frame = contextMenuController.hitTestResult().innerNodeFrame();
1512     if (!frame)
1513         return false;
1514
1515     FrameView* view = frame->view();
1516     if (!view)
1517         return false;
1518
1519     IntPoint logicalPoint = view->contentsToWindow(contextMenuController.hitTestResult().roundedPointInInnerNodeFrame());
1520     logicalPoint.scale(scaleFactor, scaleFactor);
1521
1522     // Translate the point to screen coordinates
1523     POINT point = logicalPoint;
1524     if (!::ClientToScreen(m_viewWindow, &point))
1525         return false;
1526
1527     if (m_currentContextMenu)
1528         ::DestroyMenu(m_currentContextMenu);
1529     m_currentContextMenu = createContextMenu();
1530
1531     MENUINFO menuInfo;
1532     menuInfo.cbSize = sizeof(menuInfo);
1533     menuInfo.fMask = MIM_STYLE;
1534     menuInfo.dwStyle = MNS_NOTIFYBYPOS;
1535     ::SetMenuInfo(m_currentContextMenu, &menuInfo);
1536
1537     BOOL hasCustomMenus = false;
1538     if (m_uiDelegate)
1539         m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1540
1541     if (hasCustomMenus)
1542         m_uiDelegate->trackCustomPopupMenu((IWebView*)this, m_currentContextMenu, &point);
1543     else {
1544         // Surprisingly, TPM_RIGHTBUTTON means that items are selectable with either the right OR left mouse button
1545         UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL | TPM_LEFTALIGN | TPM_HORPOSANIMATION;
1546         ::TrackPopupMenuEx(m_currentContextMenu, flags, point.x, point.y, m_viewWindow, 0);
1547     }
1548
1549     return true;
1550 }
1551
1552 bool WebView::onMeasureItem(WPARAM /*wParam*/, LPARAM lParam)
1553 {
1554     if (!m_uiDelegate)
1555         return false;
1556
1557     BOOL hasCustomMenus = false;
1558     m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1559     if (!hasCustomMenus)
1560         return false;
1561
1562     m_uiDelegate->measureCustomMenuItem((IWebView*)this, (void*)lParam);
1563     return true;
1564 }
1565
1566 bool WebView::onDrawItem(WPARAM /*wParam*/, LPARAM lParam)
1567 {
1568     if (!m_uiDelegate)
1569         return false;
1570
1571     BOOL hasCustomMenus = false;
1572     m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1573     if (!hasCustomMenus)
1574         return false;
1575
1576     m_uiDelegate->drawCustomMenuItem((IWebView*)this, (void*)lParam);
1577     return true;
1578 }
1579
1580 bool WebView::onInitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1581 {
1582     if (!m_uiDelegate)
1583         return false;
1584
1585     HMENU menu = (HMENU)wParam;
1586     if (!menu)
1587         return false;
1588
1589     BOOL hasCustomMenus = false;
1590     m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1591     if (!hasCustomMenus)
1592         return false;
1593
1594     m_uiDelegate->addCustomMenuDrawingData((IWebView*)this, menu);
1595     return true;
1596 }
1597
1598 bool WebView::onUninitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1599 {
1600     if (!m_uiDelegate)
1601         return false;
1602
1603     HMENU menu = (HMENU)wParam;
1604     if (!menu)
1605         return false;
1606
1607     BOOL hasCustomMenus = false;
1608     m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1609     if (!hasCustomMenus)
1610         return false;
1611
1612     m_uiDelegate->cleanUpCustomMenuDrawingData((IWebView*)this, menu);
1613     return true;
1614 }
1615
1616 void WebView::onMenuCommand(WPARAM wParam, LPARAM lParam)
1617 {
1618     HMENU hMenu = reinterpret_cast<HMENU>(lParam);
1619     unsigned index = static_cast<unsigned>(wParam);
1620
1621     MENUITEMINFO menuItemInfo = { 0 };
1622     menuItemInfo.cbSize = sizeof(menuItemInfo);
1623     menuItemInfo.fMask = MIIM_STRING;
1624     ::GetMenuItemInfo(hMenu, index, true, &menuItemInfo);
1625
1626     auto buffer = std::make_unique<WCHAR[]>(menuItemInfo.cch + 1);
1627     menuItemInfo.dwTypeData = buffer.get();
1628     menuItemInfo.cch++;
1629     menuItemInfo.fMask |= MIIM_ID;
1630
1631     ::GetMenuItemInfo(hMenu, index, true, &menuItemInfo);
1632
1633     ::DestroyMenu(m_currentContextMenu);
1634     m_currentContextMenu = nullptr;
1635
1636     String title(buffer.get(), menuItemInfo.cch);
1637     ContextMenuAction action = static_cast<ContextMenuAction>(menuItemInfo.wID);
1638
1639     if (action >= ContextMenuItemBaseApplicationTag) {
1640         if (m_uiDelegate) {
1641             COMPtr<WebElementPropertyBag> propertyBag;
1642             propertyBag.adoptRef(WebElementPropertyBag::createInstance(m_page->contextMenuController().hitTestResult()));
1643
1644             m_uiDelegate->contextMenuItemSelected(this, &menuItemInfo, propertyBag.get());
1645         }
1646         return;
1647     }
1648
1649     m_page->contextMenuController().contextMenuItemSelected(action, title);
1650 }
1651
1652 bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
1653 {
1654     static LONG globalClickCount;
1655     static IntPoint globalPrevPoint;
1656     static MouseButton globalPrevButton;
1657     static LONG globalPrevMouseDownTime;
1658
1659     if (message == WM_CANCELMODE) {
1660         m_page->mainFrame().eventHandler().lostMouseCapture();
1661         return true;
1662     }
1663
1664     // Create our event.
1665     // On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
1666     // of the event to be at (MINSHORT, MINSHORT).
1667     LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
1668     PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
1669
1670     setMouseActivated(false);
1671
1672     bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.position().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
1673                            abs(globalPrevPoint.y() - mouseEvent.position().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
1674     LONG messageTime = ::GetMessageTime();
1675
1676     bool handled = false;
1677
1678     if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
1679         // FIXME: I'm not sure if this is the "right" way to do this
1680         // but without this call, we never become focused since we don't allow
1681         // the default handling of mouse events.
1682         SetFocus(m_viewWindow);
1683
1684         // Always start capturing events when the mouse goes down in our HWND.
1685         ::SetCapture(m_viewWindow);
1686
1687         if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) && 
1688             insideThreshold &&
1689             mouseEvent.button() == globalPrevButton)
1690             globalClickCount++;
1691         else
1692             // Reset the click count.
1693             globalClickCount = 1;
1694         globalPrevMouseDownTime = messageTime;
1695         globalPrevButton = mouseEvent.button();
1696         globalPrevPoint = mouseEvent.position();
1697         
1698         mouseEvent.setClickCount(globalClickCount);
1699         handled = m_page->mainFrame().eventHandler().handleMousePressEvent(mouseEvent);
1700     } else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
1701         globalClickCount++;
1702         mouseEvent.setClickCount(globalClickCount);
1703         handled = m_page->mainFrame().eventHandler().handleMousePressEvent(mouseEvent);
1704     } else if (message == WM_LBUTTONUP || message == WM_MBUTTONUP || message == WM_RBUTTONUP) {
1705         // Record the global position and the button of the up.
1706         globalPrevButton = mouseEvent.button();
1707         globalPrevPoint = mouseEvent.position();
1708         mouseEvent.setClickCount(globalClickCount);
1709         m_page->mainFrame().eventHandler().handleMouseReleaseEvent(mouseEvent);
1710         ::ReleaseCapture();
1711     } else if (message == WM_MOUSELEAVE && m_mouseOutTracker) {
1712         // Once WM_MOUSELEAVE is fired windows clears this tracker
1713         // so there is no need to disable it ourselves.
1714         m_mouseOutTracker.reset();
1715         m_page->mainFrame().eventHandler().mouseMoved(mouseEvent);
1716         handled = true;
1717     } else if (message == WM_MOUSEMOVE) {
1718         if (!insideThreshold)
1719             globalClickCount = 0;
1720         mouseEvent.setClickCount(globalClickCount);
1721         handled = m_page->mainFrame().eventHandler().mouseMoved(mouseEvent);
1722         if (!m_mouseOutTracker) {
1723             m_mouseOutTracker = std::make_unique<TRACKMOUSEEVENT>();
1724             m_mouseOutTracker->cbSize = sizeof(TRACKMOUSEEVENT);
1725             m_mouseOutTracker->dwFlags = TME_LEAVE;
1726             m_mouseOutTracker->hwndTrack = m_viewWindow;
1727             ::TrackMouseEvent(m_mouseOutTracker.get());
1728         }
1729     }
1730     return handled;
1731 }
1732
1733 bool WebView::gestureNotify(WPARAM wParam, LPARAM lParam)
1734 {
1735     GESTURENOTIFYSTRUCT* gn = reinterpret_cast<GESTURENOTIFYSTRUCT*>(lParam);
1736
1737     Frame* coreFrame = core(m_mainFrame);
1738     if (!coreFrame)
1739         return false;
1740
1741     ScrollView* view = coreFrame->view();
1742     if (!view)
1743         return false;
1744
1745     // If we don't have this function, we shouldn't be receiving this message
1746     ASSERT(SetGestureConfigPtr());
1747
1748     bool hitScrollbar = false;
1749     POINT gestureBeginPoint = {gn->ptsLocation.x, gn->ptsLocation.y};
1750
1751     float scaleFactor = deviceScaleFactor();
1752     float inverseScaleFactor = 1.0f / scaleFactor;
1753     IntPoint logicalGestureBeginPoint(gestureBeginPoint);
1754     logicalGestureBeginPoint.scale(inverseScaleFactor, inverseScaleFactor);
1755
1756     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowUserAgentShadowContent);
1757     for (Frame* childFrame = &m_page->mainFrame(); childFrame; childFrame = EventHandler::subframeForTargetNode(m_gestureTargetNode.get())) {
1758         FrameView* frameView = childFrame->view();
1759         if (!frameView)
1760             break;
1761         RenderView* renderView = childFrame->document()->renderView();
1762         if (!renderView)
1763             break;
1764         RenderLayer* layer = renderView->layer();
1765         if (!layer)
1766             break;
1767
1768         HitTestResult result(frameView->screenToContents(logicalGestureBeginPoint));
1769         layer->hitTest(request, result);
1770         m_gestureTargetNode = result.innerNode();
1771
1772         if (!hitScrollbar)
1773             hitScrollbar = result.scrollbar();
1774     }
1775
1776     if (!hitScrollbar) {
1777         // The hit testing above won't detect if we've hit the main frame's vertical scrollbar. Check that manually now.
1778         RECT webViewRect;
1779         GetWindowRect(m_viewWindow, &webViewRect);
1780         hitScrollbar = (view->verticalScrollbar() && (gestureBeginPoint.x > (webViewRect.right - view->verticalScrollbar()->theme().scrollbarThickness()))) 
1781             || (view->horizontalScrollbar() && (gestureBeginPoint.y > (webViewRect.bottom - view->horizontalScrollbar()->theme().scrollbarThickness())));  
1782     }
1783
1784     bool canBeScrolled = false;
1785     if (m_gestureTargetNode) {
1786         for (RenderObject* renderer = m_gestureTargetNode->renderer(); renderer; renderer = renderer->parent()) {
1787             if (is<RenderBox>(*renderer) && downcast<RenderBox>(*renderer).canBeScrolledAndHasScrollableArea()) {
1788                 canBeScrolled = true;
1789                 break;
1790             }
1791         }
1792     } else {
1793         // We've hit the main document but not any of the document's content
1794         if (core(m_mainFrame)->view()->isScrollable())
1795             canBeScrolled = true;
1796     }
1797
1798     // We always allow two-fingered panning with inertia and a gutter (which limits movement to one
1799     // direction in most cases).
1800     DWORD dwPanWant = GC_PAN | GC_PAN_WITH_INERTIA | GC_PAN_WITH_GUTTER;
1801     DWORD dwPanBlock = 0;
1802
1803     if (hitScrollbar || !canBeScrolled) {
1804         // The part of the page under the gesture can't be scrolled, or the gesture is on a scrollbar.
1805         // Disallow single-fingered panning in this case so we'll fall back to the default
1806         // behavior (which allows the scrollbar thumb to be dragged, text selections to be made, etc.).
1807         dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_VERTICALLY | GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
1808     } else {
1809         // The part of the page the gesture is under can be scrolled, and we're not under a scrollbar.
1810         // Allow single-fingered vertical panning in this case, so the user will be able to pan the page
1811         // with one or two fingers.
1812         dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
1813
1814         // Disable single-fingered horizontal panning only if the target node is text.
1815         if (m_gestureTargetNode && m_gestureTargetNode->isTextNode())
1816             dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
1817         else
1818             dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
1819     }
1820
1821     GESTURECONFIG gc = { GID_PAN, dwPanWant, dwPanBlock };
1822     return SetGestureConfigPtr()(m_viewWindow, 0, 1, &gc, sizeof(GESTURECONFIG));
1823 }
1824
1825 bool WebView::gesture(WPARAM wParam, LPARAM lParam) 
1826 {
1827     // We want to bail out if we don't have either of these functions
1828     if (!GetGestureInfoPtr() || !CloseGestureInfoHandlePtr())
1829         return false;
1830
1831     HGESTUREINFO gestureHandle = reinterpret_cast<HGESTUREINFO>(lParam);
1832     
1833     GESTUREINFO gi = {0};
1834     gi.cbSize = sizeof(GESTUREINFO);
1835
1836     if (!GetGestureInfoPtr()(gestureHandle, reinterpret_cast<PGESTUREINFO>(&gi)))
1837         return false;
1838
1839     switch (gi.dwID) {
1840     case GID_BEGIN:
1841         m_lastPanX = gi.ptsLocation.x;
1842         m_lastPanY = gi.ptsLocation.y;
1843
1844         break;
1845     case GID_END:
1846         m_gestureTargetNode = nullptr;
1847         break;
1848     case GID_PAN: {
1849         if (gi.dwFlags & GF_BEGIN) {
1850             m_lastPanX = gi.ptsLocation.x;
1851             m_lastPanY = gi.ptsLocation.y;
1852         }
1853         // Where are the fingers currently?
1854         long currentX = gi.ptsLocation.x;
1855         long currentY = gi.ptsLocation.y;
1856         // How far did we pan in each direction?
1857         long deltaX = currentX - m_lastPanX;
1858         long deltaY = currentY - m_lastPanY;
1859         // Calculate the overpan for window bounce
1860         m_yOverpan -= m_lastPanY - currentY;
1861         m_xOverpan -= m_lastPanX - currentX;
1862         // Update our class variables with updated values
1863         m_lastPanX = currentX;
1864         m_lastPanY = currentY;
1865
1866         Frame* coreFrame = core(m_mainFrame);
1867         if (!coreFrame) {
1868             CloseGestureInfoHandlePtr()(gestureHandle);
1869             return false;
1870         }
1871
1872         ScrollableArea* scrolledArea = 0;
1873         float scaleFactor = deviceScaleFactor();
1874         IntSize logicalScrollDelta(-deltaX * scaleFactor, -deltaY * scaleFactor);
1875
1876         RenderLayer* scrollableLayer = nullptr;
1877         if (m_gestureTargetNode && m_gestureTargetNode->renderer() && m_gestureTargetNode->renderer()->enclosingLayer())
1878             scrollableLayer = m_gestureTargetNode->renderer()->enclosingLayer()->enclosingScrollableLayer();
1879
1880         if (!scrollableLayer) {
1881             // We might directly hit the document without hitting any nodes
1882             coreFrame->view()->scrollBy(logicalScrollDelta);
1883             scrolledArea = coreFrame->view();
1884         } else
1885             scrollableLayer->scrollByRecursively(logicalScrollDelta, WebCore::RenderLayer::ScrollOffsetClamped, &scrolledArea);
1886
1887         if (!(UpdatePanningFeedbackPtr() && BeginPanningFeedbackPtr() && EndPanningFeedbackPtr())) {
1888             CloseGestureInfoHandlePtr()(gestureHandle);
1889             return true;
1890         }
1891
1892         // Handle overpanning
1893         if (gi.dwFlags & GF_BEGIN) {
1894             BeginPanningFeedbackPtr()(m_viewWindow);
1895             m_yOverpan = 0;
1896             m_xOverpan = 0;
1897         } else if (gi.dwFlags & GF_END) {
1898             EndPanningFeedbackPtr()(m_viewWindow, true);
1899             m_yOverpan = 0;
1900             m_xOverpan = 0;
1901         }
1902
1903         if (!scrolledArea) {
1904             CloseGestureInfoHandlePtr()(gestureHandle);
1905             return true;
1906         }
1907
1908         Scrollbar* vertScrollbar = scrolledArea->verticalScrollbar();
1909
1910         int ypan = 0;
1911         int xpan = 0;
1912
1913         if (vertScrollbar && (!vertScrollbar->currentPos() || vertScrollbar->currentPos() >= vertScrollbar->maximum()))
1914             ypan = m_yOverpan;
1915
1916         Scrollbar* horiScrollbar = scrolledArea->horizontalScrollbar();
1917
1918         if (horiScrollbar && (!horiScrollbar->currentPos() || horiScrollbar->currentPos() >= horiScrollbar->maximum()))
1919             xpan = m_xOverpan;
1920
1921         UpdatePanningFeedbackPtr()(m_viewWindow, xpan, ypan, gi.dwFlags & GF_INERTIA);
1922
1923         CloseGestureInfoHandlePtr()(gestureHandle);
1924         return true;
1925     }
1926     default:
1927         break;
1928     }
1929
1930     // If we get to this point, the gesture has not been handled. We forward
1931     // the call to DefWindowProc by returning false, and we don't need to 
1932     // to call CloseGestureInfoHandle. 
1933     // http://msdn.microsoft.com/en-us/library/dd353228(VS.85).aspx
1934     return false;
1935 }
1936
1937 bool WebView::mouseWheel(WPARAM wParam, LPARAM lParam, bool isMouseHWheel)
1938 {
1939     // Ctrl+Mouse wheel doesn't ever go into WebCore.  It is used to
1940     // zoom instead (Mac zooms the whole Desktop, but Windows browsers trigger their
1941     // own local zoom modes for Ctrl+wheel).
1942     if (wParam & MK_CONTROL) {
1943         short delta = short(HIWORD(wParam));
1944         if (delta < 0)
1945             makeTextSmaller(0);
1946         else
1947             makeTextLarger(0);
1948         return true;
1949     }
1950     
1951     // FIXME: This doesn't fix https://bugs.webkit.org/show_bug.cgi?id=28217. This only fixes https://bugs.webkit.org/show_bug.cgi?id=28203.
1952     HWND focusedWindow = GetFocus();
1953     if (focusedWindow && focusedWindow != m_viewWindow) {
1954         // Our focus is on a different hwnd, see if it's a PopupMenu and if so, set the focus back on us (which will hide the popup).
1955         WCHAR className[256];
1956
1957         // Make sure truncation won't affect the comparison.
1958         ASSERT(WTF_ARRAY_LENGTH(className) > wcslen(PopupMenuWin::popupClassName()));
1959
1960         if (GetClassNameW(focusedWindow, className, WTF_ARRAY_LENGTH(className)) && !wcscmp(className, PopupMenuWin::popupClassName())) {
1961             // We don't let the WebView scroll here for two reasons - 1) To match Firefox behavior, 2) If we do scroll, we lose the
1962             // focus ring around the select menu.
1963             SetFocus(m_viewWindow);
1964             return true;
1965         }
1966     }
1967
1968     PlatformWheelEvent wheelEvent(m_viewWindow, wParam, lParam, isMouseHWheel);
1969     Frame* coreFrame = core(m_mainFrame);
1970     if (!coreFrame)
1971         return false;
1972
1973     return coreFrame->eventHandler().handleWheelEvent(wheelEvent);
1974 }
1975
1976 bool WebView::verticalScroll(WPARAM wParam, LPARAM /*lParam*/)
1977 {
1978     ScrollDirection direction;
1979     ScrollGranularity granularity;
1980     switch (LOWORD(wParam)) {
1981     case SB_LINEDOWN:
1982         granularity = ScrollByLine;
1983         direction = ScrollDown;
1984         break;
1985     case SB_LINEUP:
1986         granularity = ScrollByLine;
1987         direction = ScrollUp;
1988         break;
1989     case SB_PAGEDOWN:
1990         granularity = ScrollByDocument;
1991         direction = ScrollDown;
1992         break;
1993     case SB_PAGEUP:
1994         granularity = ScrollByDocument;
1995         direction = ScrollUp;
1996         break;
1997     default:
1998         return false;
1999         break;
2000     }
2001     
2002     Frame& frame = m_page->focusController().focusedOrMainFrame();
2003     return frame.eventHandler().scrollRecursively(direction, granularity);
2004 }
2005
2006 bool WebView::horizontalScroll(WPARAM wParam, LPARAM /*lParam*/)
2007 {
2008     ScrollDirection direction;
2009     ScrollGranularity granularity;
2010     switch (LOWORD(wParam)) {
2011     case SB_LINELEFT:
2012         granularity = ScrollByLine;
2013         direction = ScrollLeft;
2014         break;
2015     case SB_LINERIGHT:
2016         granularity = ScrollByLine;
2017         direction = ScrollRight;
2018         break;
2019     case SB_PAGELEFT:
2020         granularity = ScrollByDocument;
2021         direction = ScrollLeft;
2022         break;
2023     case SB_PAGERIGHT:
2024         granularity = ScrollByDocument;
2025         direction = ScrollRight;
2026         break;
2027     default:
2028         return false;
2029     }
2030
2031     Frame& frame = m_page->focusController().focusedOrMainFrame();
2032     return frame.eventHandler().scrollRecursively(direction, granularity);
2033 }
2034
2035
2036 bool WebView::execCommand(WPARAM wParam, LPARAM /*lParam*/)
2037 {
2038     Frame& frame = m_page->focusController().focusedOrMainFrame();
2039     switch (LOWORD(wParam)) {
2040         case SelectAll:
2041             return frame.editor().command("SelectAll").execute();
2042         case Undo:
2043             return frame.editor().command("Undo").execute();
2044         case Redo:
2045             return frame.editor().command("Redo").execute();
2046     }
2047     return false;
2048 }
2049
2050 bool WebView::keyUp(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
2051 {
2052     PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformEvent::KeyUp, systemKeyDown);
2053
2054     Frame& frame = m_page->focusController().focusedOrMainFrame();
2055     m_currentCharacterCode = 0;
2056
2057     return frame.eventHandler().keyEvent(keyEvent);
2058 }
2059
2060 static const unsigned CtrlKey = 1 << 0;
2061 static const unsigned AltKey = 1 << 1;
2062 static const unsigned ShiftKey = 1 << 2;
2063
2064
2065 struct KeyDownEntry {
2066     unsigned virtualKey;
2067     unsigned modifiers;
2068     const char* name;
2069 };
2070
2071 struct KeyPressEntry {
2072     unsigned charCode;
2073     unsigned modifiers;
2074     const char* name;
2075 };
2076
2077 static const KeyDownEntry keyDownEntries[] = {
2078     { VK_LEFT,   0,                  "MoveLeft"                                    },
2079     { VK_LEFT,   ShiftKey,           "MoveLeftAndModifySelection"                  },
2080     { VK_LEFT,   CtrlKey,            "MoveWordLeft"                                },
2081     { VK_LEFT,   CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection"              },
2082     { VK_RIGHT,  0,                  "MoveRight"                                   },
2083     { VK_RIGHT,  ShiftKey,           "MoveRightAndModifySelection"                 },
2084     { VK_RIGHT,  CtrlKey,            "MoveWordRight"                               },
2085     { VK_RIGHT,  CtrlKey | ShiftKey, "MoveWordRightAndModifySelection"             },
2086     { VK_UP,     0,                  "MoveUp"                                      },
2087     { VK_UP,     ShiftKey,           "MoveUpAndModifySelection"                    },
2088     { VK_PRIOR,  ShiftKey,           "MovePageUpAndModifySelection"                },
2089     { VK_DOWN,   0,                  "MoveDown"                                    },
2090     { VK_DOWN,   ShiftKey,           "MoveDownAndModifySelection"                  },
2091     { VK_NEXT,   ShiftKey,           "MovePageDownAndModifySelection"              },
2092     { VK_PRIOR,  0,                  "MovePageUp"                                  },
2093     { VK_NEXT,   0,                  "MovePageDown"                                },
2094     { VK_HOME,   0,                  "MoveToBeginningOfLine"                       },
2095     { VK_HOME,   ShiftKey,           "MoveToBeginningOfLineAndModifySelection"     },
2096     { VK_HOME,   CtrlKey,            "MoveToBeginningOfDocument"                   },
2097     { VK_HOME,   CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
2098
2099     { VK_END,    0,                  "MoveToEndOfLine"                             },
2100     { VK_END,    ShiftKey,           "MoveToEndOfLineAndModifySelection"           },
2101     { VK_END,    CtrlKey,            "MoveToEndOfDocument"                         },
2102     { VK_END,    CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection"       },
2103
2104     { VK_BACK,   0,                  "DeleteBackward"                              },
2105     { VK_BACK,   ShiftKey,           "DeleteBackward"                              },
2106     { VK_DELETE, 0,                  "DeleteForward"                               },
2107     { VK_BACK,   CtrlKey,            "DeleteWordBackward"                          },
2108     { VK_DELETE, CtrlKey,            "DeleteWordForward"                           },
2109     
2110     { 'B',       CtrlKey,            "ToggleBold"                                  },
2111     { 'I',       CtrlKey,            "ToggleItalic"                                },
2112
2113     { VK_ESCAPE, 0,                  "Cancel"                                      },
2114     { VK_OEM_PERIOD, CtrlKey,        "Cancel"                                      },
2115     { VK_TAB,    0,                  "InsertTab"                                   },
2116     { VK_TAB,    ShiftKey,           "InsertBacktab"                               },
2117     { VK_RETURN, 0,                  "InsertNewline"                               },
2118     { VK_RETURN, CtrlKey,            "InsertNewline"                               },
2119     { VK_RETURN, AltKey,             "InsertNewline"                               },
2120     { VK_RETURN, ShiftKey,           "InsertNewline"                               },
2121     { VK_RETURN, AltKey | ShiftKey,  "InsertNewline"                               },
2122
2123     // It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled
2124     // in the application or in WebKit. We chose WebKit.
2125     { 'C',       CtrlKey,            "Copy"                                        },
2126     { 'V',       CtrlKey,            "Paste"                                       },
2127     { 'X',       CtrlKey,            "Cut"                                         },
2128     { 'A',       CtrlKey,            "SelectAll"                                   },
2129     { VK_INSERT, CtrlKey,            "Copy"                                        },
2130     { VK_DELETE, ShiftKey,           "Cut"                                         },
2131     { VK_INSERT, ShiftKey,           "Paste"                                       },
2132     { 'Z',       CtrlKey,            "Undo"                                        },
2133     { 'Z',       CtrlKey | ShiftKey, "Redo"                                        },
2134 };
2135
2136 static const KeyPressEntry keyPressEntries[] = {
2137     { '\t',   0,                  "InsertTab"                                   },
2138     { '\t',   ShiftKey,           "InsertBacktab"                               },
2139     { '\r',   0,                  "InsertNewline"                               },
2140     { '\r',   CtrlKey,            "InsertNewline"                               },
2141     { '\r',   AltKey,             "InsertNewline"                               },
2142     { '\r',   ShiftKey,           "InsertNewline"                               },
2143     { '\r',   AltKey | ShiftKey,  "InsertNewline"                               },
2144 };
2145
2146 const char* WebView::interpretKeyEvent(const KeyboardEvent* evt)
2147 {
2148     ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
2149
2150     static HashMap<int, const char*>* keyDownCommandsMap = 0;
2151     static HashMap<int, const char*>* keyPressCommandsMap = 0;
2152
2153     if (!keyDownCommandsMap) {
2154         keyDownCommandsMap = new HashMap<int, const char*>;
2155         keyPressCommandsMap = new HashMap<int, const char*>;
2156
2157         for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyDownEntries); ++i)
2158             keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
2159
2160         for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyPressEntries); ++i)
2161             keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
2162     }
2163
2164     unsigned modifiers = 0;
2165     if (evt->shiftKey())
2166         modifiers |= ShiftKey;
2167     if (evt->altKey())
2168         modifiers |= AltKey;
2169     if (evt->ctrlKey())
2170         modifiers |= CtrlKey;
2171
2172     if (evt->type() == eventNames().keydownEvent) {
2173         int mapKey = modifiers << 16 | evt->keyCode();
2174         return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
2175     }
2176
2177     int mapKey = modifiers << 16 | evt->charCode();
2178     return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
2179 }
2180
2181 bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
2182 {
2183     Node* node = evt->target()->toNode();
2184     ASSERT(node);
2185     Frame* frame = node->document().frame();
2186     ASSERT(frame);
2187
2188     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2189     if (!keyEvent || keyEvent->isSystemKey())  // do not treat this as text input if it's a system key event
2190         return false;
2191
2192     Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
2193
2194     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2195         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2196         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2197         // (e.g. Tab that inserts a Tab character, or Enter).
2198         return !command.isTextInsertion() && command.execute(evt);
2199     }
2200
2201      if (command.execute(evt))
2202         return true;
2203
2204     // Don't insert null or control characters as they can result in unexpected behaviour
2205     if (evt->charCode() < ' ')
2206         return false;
2207
2208     return frame->editor().insertText(evt->keyEvent()->text(), evt);
2209 }
2210
2211 bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
2212 {
2213 #if ENABLE(FULLSCREEN_API)
2214     // Trap the ESC key when in full screen mode.
2215     if (virtualKeyCode == VK_ESCAPE && isFullScreen()) {
2216         m_fullscreenController->exitFullScreen();
2217         return false;
2218     }
2219 #endif
2220     Frame& frame = m_page->focusController().focusedOrMainFrame();
2221
2222     PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformEvent::RawKeyDown, systemKeyDown);
2223     bool handled = frame.eventHandler().keyEvent(keyEvent);
2224
2225     // These events cannot be canceled, and we have no default handling for them.
2226     // FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
2227     if (systemKeyDown && virtualKeyCode != VK_RETURN)
2228         return false;
2229
2230     if (handled) {
2231         // FIXME: remove WM_UNICHAR, too
2232         MSG msg;
2233         // WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
2234         if (!systemKeyDown)
2235             ::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
2236         return true;
2237     }
2238
2239     // We need to handle back/forward using either Ctrl+Left/Right Arrow keys.
2240     // FIXME: This logic should probably be in EventHandler::defaultArrowEventHandler().
2241     // FIXME: Should check that other modifiers aren't pressed.
2242     if (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey())
2243         return m_page->backForward().goForward();
2244     if (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey())
2245         return m_page->backForward().goBack();
2246
2247     // Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
2248     ScrollDirection direction;
2249     ScrollGranularity granularity;
2250     switch (virtualKeyCode) {
2251         case VK_LEFT:
2252             granularity = ScrollByLine;
2253             direction = ScrollLeft;
2254             break;
2255         case VK_RIGHT:
2256             granularity = ScrollByLine;
2257             direction = ScrollRight;
2258             break;
2259         case VK_UP:
2260             granularity = ScrollByLine;
2261             direction = ScrollUp;
2262             break;
2263         case VK_DOWN:
2264             granularity = ScrollByLine;
2265             direction = ScrollDown;
2266             break;
2267         case VK_HOME:
2268             granularity = ScrollByDocument;
2269             direction = ScrollUp;
2270             break;
2271         case VK_END:
2272             granularity = ScrollByDocument;
2273             direction = ScrollDown;
2274             break;
2275         case VK_PRIOR:
2276             granularity = ScrollByPage;
2277             direction = ScrollUp;
2278             break;
2279         case VK_NEXT:
2280             granularity = ScrollByPage;
2281             direction = ScrollDown;
2282             break;
2283         default:
2284             return false;
2285     }
2286
2287     return frame.eventHandler().scrollRecursively(direction, granularity);
2288 }
2289
2290 bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
2291 {
2292     Frame& frame = m_page->focusController().focusedOrMainFrame();
2293
2294     PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformEvent::Char, systemKeyDown);
2295     // IE does not dispatch keypress event for WM_SYSCHAR.
2296     if (systemKeyDown)
2297         return frame.eventHandler().handleAccessKey(keyEvent);
2298     return frame.eventHandler().keyEvent(keyEvent);
2299 }
2300
2301 void WebView::setIsBeingDestroyed()
2302 {
2303     m_isBeingDestroyed = true;
2304
2305     // Remove our this pointer from the window so we won't try to handle any more window messages.
2306     // See <http://webkit.org/b/55054>.
2307     ::SetWindowLongPtrW(m_viewWindow, 0, 0);
2308 }
2309
2310 void WebView::setShouldInvertColors(bool shouldInvertColors)
2311 {
2312     if (m_shouldInvertColors == shouldInvertColors)
2313         return;
2314
2315     m_shouldInvertColors = shouldInvertColors;
2316
2317 #if USE(CA)
2318     if (m_layerTreeHost)
2319         m_layerTreeHost->setShouldInvertColors(shouldInvertColors);
2320 #endif
2321
2322     RECT windowRect = {0};
2323     frameRect(&windowRect);
2324
2325     // repaint expects logical pixels, so rescale here.
2326     IntRect logicalRect(windowRect);
2327     logicalRect.scale(1.0f / deviceScaleFactor());
2328     repaint(logicalRect, true, true);
2329 }
2330
2331 bool WebView::registerWebViewWindowClass()
2332 {
2333     static bool haveRegisteredWindowClass = false;
2334     if (haveRegisteredWindowClass)
2335         return true;
2336
2337     haveRegisteredWindowClass = true;
2338
2339     WNDCLASSEX wcex;
2340
2341     wcex.cbSize = sizeof(WNDCLASSEX);
2342
2343     wcex.style          = CS_DBLCLKS;
2344     wcex.lpfnWndProc    = WebViewWndProc;
2345     wcex.cbClsExtra     = 0;
2346     wcex.cbWndExtra     = sizeof(WebView*);
2347     wcex.hInstance      = gInstance;
2348     wcex.hIcon          = 0;
2349     wcex.hCursor        = ::LoadCursor(0, IDC_ARROW);
2350     wcex.hbrBackground  = 0;
2351     wcex.lpszMenuName   = 0;
2352     wcex.lpszClassName  = kWebViewWindowClassName;
2353     wcex.hIconSm        = 0;
2354
2355     return !!RegisterClassEx(&wcex);
2356 }
2357
2358 static HWND findTopLevelParent(HWND window)
2359 {
2360     if (!window)
2361         return 0;
2362
2363     HWND current = window;
2364     for (HWND parent = GetParent(current); current; current = parent, parent = GetParent(parent))
2365         if (!parent || !(GetWindowLongPtr(current, GWL_STYLE) & (WS_POPUP | WS_CHILD)))
2366             return current;
2367     ASSERT_NOT_REACHED();
2368     return 0;
2369 }
2370
2371 LRESULT CALLBACK WebView::WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
2372 {
2373     LRESULT lResult = 0;
2374     LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
2375     WebView* webView = reinterpret_cast<WebView*>(longPtr);
2376     WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
2377     if (!mainFrameImpl)
2378         return DefWindowProc(hWnd, message, wParam, lParam);
2379
2380     // We shouldn't be trying to handle any window messages after WM_DESTROY.
2381     // See <http://webkit.org/b/55054>.
2382     ASSERT(!webView->isBeingDestroyed());
2383
2384     // hold a ref, since the WebView could go away in an event handler.
2385     COMPtr<WebView> protector(webView);
2386     ASSERT(webView);
2387
2388     // Windows Media Player has a modal message loop that will deliver messages
2389     // to us at inappropriate times and we will crash if we handle them when:
2390     // they are delivered. We repost paint messages so that we eventually get
2391     // a chance to paint once the modal loop has exited, but other messages
2392     // aren't safe to repost, so we just drop them.
2393     if (PluginView::isCallingPlugin()) {
2394         if (message == WM_PAINT)
2395             PostMessage(hWnd, message, wParam, lParam);
2396         return 0;
2397     }
2398
2399     bool handled = true;
2400
2401     switch (message) {
2402         case WM_PAINT: {
2403             webView->paint(0, 0);
2404             if (webView->usesLayeredWindow())
2405                 webView->performLayeredWindowUpdate();
2406             break;
2407         }
2408         case WM_ERASEBKGND:
2409             // Don't perform a background erase.
2410             handled = true;
2411             lResult = 1;
2412             break;
2413         case WM_PRINTCLIENT:
2414             webView->paint((HDC)wParam, lParam);
2415             break;
2416         case WM_DESTROY:
2417             webView->setIsBeingDestroyed();
2418             webView->close();
2419             break;
2420         case WM_GESTURENOTIFY:
2421             handled = webView->gestureNotify(wParam, lParam);
2422             break;
2423         case WM_GESTURE:
2424             handled = webView->gesture(wParam, lParam);
2425             break;
2426         case WM_MOUSEMOVE:
2427         case WM_LBUTTONDOWN:
2428         case WM_MBUTTONDOWN:
2429         case WM_RBUTTONDOWN:
2430         case WM_LBUTTONDBLCLK:
2431         case WM_MBUTTONDBLCLK:
2432         case WM_RBUTTONDBLCLK:
2433         case WM_LBUTTONUP:
2434         case WM_MBUTTONUP:
2435         case WM_RBUTTONUP:
2436         case WM_MOUSELEAVE:
2437         case WM_CANCELMODE:
2438             if (Frame* coreFrame = core(mainFrameImpl))
2439                 if (coreFrame->view()->didFirstLayout())
2440                     handled = webView->handleMouseEvent(message, wParam, lParam);
2441             break;
2442         case WM_MOUSEWHEEL:
2443         case WM_VISTA_MOUSEHWHEEL:
2444             if (Frame* coreFrame = core(mainFrameImpl))
2445                 if (coreFrame->view()->didFirstLayout())
2446                     handled = webView->mouseWheel(wParam, lParam, message == WM_VISTA_MOUSEHWHEEL);
2447             break;
2448         case WM_SYSKEYDOWN:
2449             handled = webView->keyDown(wParam, lParam, true);
2450             break;
2451         case WM_KEYDOWN:
2452             handled = webView->keyDown(wParam, lParam);
2453             break;
2454         case WM_SYSKEYUP:
2455             handled = webView->keyUp(wParam, lParam, true);
2456             break;
2457         case WM_KEYUP:
2458             handled = webView->keyUp(wParam, lParam);
2459             break;
2460         case WM_SYSCHAR:
2461             handled = webView->keyPress(wParam, lParam, true);
2462             break;
2463         case WM_CHAR:
2464             handled = webView->keyPress(wParam, lParam);
2465             break;
2466         // FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
2467         case WM_SIZE:
2468             if (lParam != 0)
2469                 webView->sizeChanged(IntSize(LOWORD(lParam), HIWORD(lParam)));
2470             break;
2471         case WM_DPICHANGED:
2472             webView->dpiChanged(LOWORD(wParam), IntSize(LOWORD(lParam), HIWORD(lParam)));
2473             break;
2474         case WM_SHOWWINDOW:
2475             lResult = DefWindowProc(hWnd, message, wParam, lParam);
2476             if (wParam == 0) {
2477                 // The window is being hidden (e.g., because we switched tabs).
2478                 // Null out our backing store.
2479                 webView->deleteBackingStore();
2480             }
2481             break;
2482         case WM_SETFOCUS: {
2483             COMPtr<IWebUIDelegate> uiDelegate;
2484             COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2485             if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2486                 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2487                 uiDelegatePrivate->webViewReceivedFocus(webView);
2488
2489             FocusController& focusController = webView->page()->focusController();
2490             if (Frame* frame = focusController.focusedFrame()) {
2491                 // Send focus events unless the previously focused window is a
2492                 // child of ours (for example a plugin).
2493                 if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
2494                     focusController.setFocused(true);
2495             } else
2496                 focusController.setFocused(true);
2497             break;
2498         }
2499         case WM_KILLFOCUS: {
2500             COMPtr<IWebUIDelegate> uiDelegate;
2501             COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2502             HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
2503             if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2504                 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2505                 uiDelegatePrivate->webViewLostFocus(webView, newFocusWnd);
2506
2507             FocusController& focusController = webView->page()->focusController();
2508             Frame& frame = focusController.focusedOrMainFrame();
2509             webView->resetIME(&frame);
2510             // Send blur events unless we're losing focus to a child of ours.
2511             if (!IsChild(hWnd, newFocusWnd))
2512                 focusController.setFocused(false);
2513
2514             // If we are pan-scrolling when we lose focus, stop the pan scrolling.
2515             frame.eventHandler().stopAutoscrollTimer();
2516
2517             break;
2518         }
2519         case WM_WINDOWPOSCHANGED:
2520             if (reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW)
2521                 webView->updateActiveStateSoon();
2522             handled = false;
2523             break;
2524         case WM_CUT:
2525             webView->cut(0);
2526             break;
2527         case WM_COPY:
2528             webView->copy(0);
2529             break;
2530         case WM_PASTE:
2531             webView->paste(0);
2532             break;
2533         case WM_CLEAR:
2534             webView->delete_(0);
2535             break;
2536         case WM_COMMAND:
2537             if (HIWORD(wParam))
2538                 handled = webView->execCommand(wParam, lParam);
2539             break;
2540         case WM_MENUCOMMAND:
2541             webView->onMenuCommand(wParam, lParam);
2542             break;
2543         case WM_CONTEXTMENU:
2544             handled = webView->handleContextMenuEvent(wParam, lParam);
2545             break;
2546         case WM_INITMENUPOPUP:
2547             handled = webView->onInitMenuPopup(wParam, lParam);
2548             break;
2549         case WM_MEASUREITEM:
2550             handled = webView->onMeasureItem(wParam, lParam);
2551             break;
2552         case WM_DRAWITEM:
2553             handled = webView->onDrawItem(wParam, lParam);
2554             break;
2555         case WM_UNINITMENUPOPUP:
2556             handled = webView->onUninitMenuPopup(wParam, lParam);
2557             break;
2558         case WM_XP_THEMECHANGED:
2559             if (Frame* coreFrame = core(mainFrameImpl)) {
2560                 webView->deleteBackingStore();
2561                 coreFrame->page()->theme().themeChanged();
2562                 ScrollbarTheme::theme().themeChanged();
2563                 RECT windowRect;
2564                 ::GetClientRect(hWnd, &windowRect);
2565                 ::InvalidateRect(hWnd, &windowRect, false);
2566 #if USE(CA)
2567                 if (webView->isAcceleratedCompositing())
2568                     webView->m_backingLayer->setNeedsDisplay();
2569 #endif
2570            }
2571             break;
2572         case WM_MOUSEACTIVATE:
2573             webView->setMouseActivated(true);
2574             handled = false;
2575             break;
2576         case WM_GETDLGCODE: {
2577             COMPtr<IWebUIDelegate> uiDelegate;
2578             COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2579             LONG_PTR dlgCode = 0;
2580             UINT keyCode = 0;
2581             if (lParam) {
2582                 LPMSG lpMsg = (LPMSG)lParam;
2583                 if (lpMsg->message == WM_KEYDOWN)
2584                     keyCode = (UINT) lpMsg->wParam;
2585             }
2586             if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2587                 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate
2588                 && SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
2589                 return dlgCode;
2590             handled = false;
2591             break;
2592         }
2593         case WM_GETOBJECT:
2594             handled = webView->onGetObject(wParam, lParam, lResult);
2595             break;
2596         case WM_IME_STARTCOMPOSITION:
2597             handled = webView->onIMEStartComposition();
2598             break;
2599         case WM_IME_REQUEST:
2600             lResult = webView->onIMERequest(wParam, lParam);
2601             break;
2602         case WM_IME_COMPOSITION:
2603             handled = webView->onIMEComposition(lParam);
2604             break;
2605         case WM_IME_ENDCOMPOSITION:
2606             handled = webView->onIMEEndComposition();
2607             break;
2608         case WM_IME_CHAR:
2609             handled = webView->onIMEChar(wParam, lParam);
2610             break;
2611         case WM_IME_NOTIFY:
2612             handled = webView->onIMENotify(wParam, lParam, &lResult);
2613             break;
2614         case WM_IME_SELECT:
2615             handled = webView->onIMESelect(wParam, lParam);
2616             break;
2617         case WM_IME_SETCONTEXT:
2618             handled = webView->onIMESetContext(wParam, lParam);
2619             break;
2620         case WM_TIMER:
2621             switch (wParam) {
2622                 case UpdateActiveStateTimer:
2623                     KillTimer(hWnd, UpdateActiveStateTimer);
2624                     webView->updateActiveState();
2625                     break;
2626                 case DeleteBackingStoreTimer:
2627                     webView->deleteBackingStore();
2628                     break;
2629             }
2630             break;
2631         case WM_SETCURSOR:
2632             handled = ::SetCursor(webView->m_lastSetCursor);
2633             break;
2634         case WM_VSCROLL:
2635             handled = webView->verticalScroll(wParam, lParam);
2636             break;
2637         case WM_HSCROLL:
2638             handled = webView->horizontalScroll(wParam, lParam);
2639             break;
2640         default:
2641             handled = false;
2642             break;
2643     }
2644
2645     webView->updateWindowIfNeeded(hWnd, message);
2646
2647     if (!handled)
2648         lResult = DefWindowProc(hWnd, message, wParam, lParam);
2649     
2650     // Let the client know whether we consider this message handled.
2651     return (message == WM_KEYDOWN || message == WM_SYSKEYDOWN || message == WM_KEYUP || message == WM_SYSKEYUP) ? !handled : lResult;
2652 }
2653
2654 void WebView::updateWindowIfNeeded(HWND hWnd, UINT message)
2655 {
2656     if (!needsDisplay())
2657         return;
2658
2659     // Care should be taken when updating the window from the window procedure.
2660     // Updating the window in response to e.g. WM_PARENTNOTIFY may cause reentrancy problems,
2661     // because WM_PARENTNOTIFY is sent synchronously to the parent window when e.g. DestroyWindow() is called.
2662
2663     switch (message) {
2664     case WM_PAINT:
2665     case WM_PARENTNOTIFY:
2666         return;
2667     }
2668
2669     ::UpdateWindow(hWnd);
2670 }
2671
2672 bool WebView::developerExtrasEnabled() const
2673 {
2674     if (m_preferences->developerExtrasDisabledByOverride())
2675         return false;
2676
2677 #ifdef NDEBUG
2678     BOOL enabled;
2679     return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
2680 #else
2681     return true;
2682 #endif
2683 }
2684
2685 static String webKitVersionString()
2686 {
2687 #if !USE(CAIRO)
2688     LPWSTR buildNumberStringPtr;
2689     if (::LoadStringW(gInstance, BUILD_NUMBER, reinterpret_cast<LPWSTR>(&buildNumberStringPtr), 0) && buildNumberStringPtr)
2690         return buildNumberStringPtr;
2691 #endif
2692     return String::format("%d.%d", WEBKIT_MAJOR_VERSION, WEBKIT_MINOR_VERSION);
2693 }
2694
2695 const String& WebView::userAgentForKURL(const URL&)
2696 {
2697     if (m_userAgentOverridden)
2698         return m_userAgentCustom;
2699
2700     if (!m_userAgentStandard.length())
2701         m_userAgentStandard = WebView::standardUserAgentWithApplicationName(m_applicationName);
2702     return m_userAgentStandard;
2703 }
2704
2705 // IUnknown -------------------------------------------------------------------
2706
2707 HRESULT WebView::QueryInterface(_In_ REFIID riid, _COM_Outptr_ void** ppvObject)
2708 {
2709     if (!ppvObject)
2710         return E_POINTER;
2711     *ppvObject = nullptr;
2712     if (IsEqualGUID(riid, CLSID_WebView))
2713         *ppvObject = this;
2714     else if (IsEqualGUID(riid, IID_IUnknown))
2715         *ppvObject = static_cast<IWebView*>(this);
2716     else if (IsEqualGUID(riid, IID_IWebView))
2717         *ppvObject = static_cast<IWebView*>(this);
2718     else if (IsEqualGUID(riid, IID_IWebViewPrivate))
2719         *ppvObject = static_cast<IWebViewPrivate*>(this);
2720     else if (IsEqualGUID(riid, IID_IWebViewPrivate2))
2721         *ppvObject = static_cast<IWebViewPrivate2*>(this);
2722     else if (IsEqualGUID(riid, IID_IWebViewPrivate3))
2723         *ppvObject = static_cast<IWebViewPrivate3*>(this);
2724     else if (IsEqualGUID(riid, IID_IWebIBActions))
2725         *ppvObject = static_cast<IWebIBActions*>(this);
2726     else if (IsEqualGUID(riid, IID_IWebViewCSS))
2727         *ppvObject = static_cast<IWebViewCSS*>(this);
2728     else if (IsEqualGUID(riid, IID_IWebViewEditing))
2729         *ppvObject = static_cast<IWebViewEditing*>(this);
2730     else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
2731         *ppvObject = static_cast<IWebViewUndoableEditing*>(this);
2732     else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
2733         *ppvObject = static_cast<IWebViewEditingActions*>(this);
2734     else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
2735         *ppvObject = static_cast<IWebNotificationObserver*>(this);
2736     else if (IsEqualGUID(riid, IID_IDropTarget))
2737         *ppvObject = static_cast<IDropTarget*>(this);
2738     else
2739         return E_NOINTERFACE;
2740
2741     AddRef();
2742     return S_OK;
2743 }
2744
2745 ULONG WebView::AddRef()
2746 {
2747     ASSERT(!m_deletionHasBegun);
2748     return ++m_refCount;
2749 }
2750
2751 ULONG WebView::Release()
2752 {
2753     ASSERT(!m_deletionHasBegun);
2754
2755     if (m_refCount == 1) {
2756         // Call close() now so that clients don't have to. (It's harmless to call close() multiple
2757         // times.) We do this here instead of in our destructor because close() can cause AddRef()
2758         // and Release() to be called, and if that happened in our destructor we would be destroyed
2759         // more than once.
2760         close();
2761     }
2762
2763     ULONG newRef = --m_refCount;
2764     if (!newRef) {
2765 #if !ASSERT_DISABLED
2766         m_deletionHasBegun = true;
2767 #endif
2768         delete(this);
2769     }
2770
2771     return newRef;
2772 }
2773
2774 // IWebView --------------------------------------------------------------------
2775
2776 HRESULT WebView::canShowMIMEType(_In_ BSTR mimeType, _Out_ BOOL* canShow)
2777 {
2778     if (!canShow)
2779         return E_POINTER;
2780
2781     *canShow = canShowMIMEType(toString(mimeType));
2782
2783     return S_OK;
2784 }
2785
2786 bool WebView::canShowMIMEType(const String& mimeType)
2787 {
2788     Frame* coreFrame = core(m_mainFrame);
2789     bool allowPlugins = coreFrame && coreFrame->loader().subframeLoader().allowPlugins();
2790
2791     bool canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeType)
2792         || MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType)
2793         || MIMETypeRegistry::isSupportedMediaMIMEType(mimeType);
2794
2795     if (!canShow && m_page) {
2796         canShow = (m_page->pluginData().supportsWebVisibleMimeType(mimeType, PluginData::AllPlugins) && allowPlugins)
2797             || m_page->pluginData().supportsWebVisibleMimeType(mimeType, PluginData::OnlyApplicationPlugins);
2798     }
2799
2800     if (!canShow)
2801         canShow = shouldUseEmbeddedView(mimeType);
2802
2803     return canShow;
2804 }
2805
2806 HRESULT WebView::canShowMIMETypeAsHTML(_In_ BSTR mimeType, _Out_ BOOL* canShow)
2807 {
2808     if (!canShow)
2809         return E_POINTER;
2810
2811     *canShow = canShowMIMETypeAsHTML(toString(mimeType));
2812
2813     return S_OK;
2814 }
2815
2816 bool WebView::canShowMIMETypeAsHTML(const String& /*mimeType*/)
2817 {
2818     // FIXME
2819     notImplemented();
2820     return true;
2821 }
2822
2823 HRESULT WebView::MIMETypesShownAsHTML(_COM_Outptr_opt_ IEnumVARIANT** enumVariant)
2824 {
2825     ASSERT_NOT_REACHED();
2826     if (!enumVariant)
2827         return E_POINTER;
2828     *enumVariant = nullptr;
2829     return E_NOTIMPL;
2830 }
2831
2832 HRESULT WebView::setMIMETypesShownAsHTML(__inout_ecount_full(cMimeTypes) BSTR* mimeTypes, int cMimeTypes)
2833 {
2834     ASSERT_NOT_REACHED();
2835     return E_NOTIMPL;
2836 }
2837
2838 HRESULT WebView::URLFromPasteboard(_In_opt_ IDataObject* /*pasteboard*/, _Deref_opt_out_ BSTR* /*url*/)
2839 {
2840     ASSERT_NOT_REACHED();
2841     return E_NOTIMPL;
2842 }
2843
2844 HRESULT WebView::URLTitleFromPasteboard(_In_opt_ IDataObject* /*pasteboard*/, _Deref_opt_out_ BSTR* /*urlTitle*/)
2845 {
2846     ASSERT_NOT_REACHED();
2847     return E_NOTIMPL;
2848 }
2849
2850 bool WebView::shouldInitializeTrackPointHack()
2851 {
2852     static bool shouldCreateScrollbars;
2853     static bool hasRunTrackPointCheck;
2854
2855     if (hasRunTrackPointCheck)
2856         return shouldCreateScrollbars;
2857
2858     hasRunTrackPointCheck = true;
2859     const WCHAR trackPointKeys[][50] = { L"Software\\Lenovo\\TrackPoint",
2860         L"Software\\Lenovo\\UltraNav",
2861         L"Software\\Alps\\Apoint\\TrackPoint",
2862         L"Software\\Synaptics\\SynTPEnh\\UltraNavUSB",
2863         L"Software\\Synaptics\\SynTPEnh\\UltraNavPS2" };
2864
2865     for (int i = 0; i < 5; ++i) {
2866         HKEY trackPointKey = nullptr;
2867         LSTATUS readKeyResult = ::RegOpenKeyExW(HKEY_CURRENT_USER, trackPointKeys[i], 0, KEY_READ, &trackPointKey);
2868         ::RegCloseKey(trackPointKey);
2869         if (readKeyResult == ERROR_SUCCESS) {
2870             shouldCreateScrollbars = true;
2871             return shouldCreateScrollbars;
2872         }
2873     }
2874
2875     return shouldCreateScrollbars;
2876 }
2877
2878 HRESULT WebView::initWithFrame(RECT frame, _In_ BSTR frameName, _In_ BSTR groupName)
2879 {
2880     HRESULT hr = S_OK;
2881
2882     if (m_viewWindow)
2883         return E_UNEXPECTED;
2884
2885     registerWebViewWindowClass();
2886
2887     m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
2888         frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow ? m_hostWindow : HWND_MESSAGE, 0, gInstance, 0);
2889     ASSERT(::IsWindow(m_viewWindow));
2890
2891     if (shouldInitializeTrackPointHack()) {
2892         // If we detected a registry key belonging to a TrackPoint driver, then create fake trackpoint
2893         // scrollbars, so the WebView will receive WM_VSCROLL and WM_HSCROLL messages. We create one
2894         // vertical scrollbar and one horizontal to allow for receiving both types of messages.
2895         ::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTHSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_HORZ, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
2896         ::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTVSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_VERT, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
2897     }
2898
2899     hr = registerDragDrop();
2900     if (FAILED(hr))
2901         return hr;
2902
2903     WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
2904     sharedPreferences->willAddToWebView();
2905     m_preferences = sharedPreferences;
2906
2907     static bool didOneTimeInitialization;
2908     if (!didOneTimeInitialization) {
2909 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
2910         initializeLogChannelsIfNecessary();
2911 #endif // !LOG_DISABLED || !RELEASE_LOG_DISABLED
2912
2913         // Initialize our platform strategies first before invoking the rest
2914         // of the initialization code which may depend on the strategies.
2915         WebPlatformStrategies::initialize();
2916
2917         WebKitInitializeWebDatabasesIfNecessary();
2918
2919         MemoryPressureHandler::singleton().install();
2920
2921         didOneTimeInitialization = true;
2922      }
2923
2924     BOOL useHighResolutionTimer;
2925     if (SUCCEEDED(m_preferences->shouldUseHighResolutionTimers(&useHighResolutionTimer)))
2926         Settings::setShouldUseHighResolutionTimers(useHighResolutionTimer);
2927
2928     m_inspectorClient = new WebInspectorClient(this);
2929
2930     PageConfiguration configuration(makeUniqueRef<WebEditorClient>(this), SocketProvider::create());
2931     configuration.chromeClient = new WebChromeClient(this);
2932     configuration.contextMenuClient = new WebContextMenuClient(this);
2933     configuration.dragClient = new WebDragClient(this);
2934     configuration.inspectorClient = m_inspectorClient;
2935     configuration.loaderClientForMainFrame = new WebFrameLoaderClient;
2936     configuration.applicationCacheStorage = &WebApplicationCache::storage();
2937     configuration.databaseProvider = &WebDatabaseProvider::singleton();
2938     configuration.storageNamespaceProvider = &m_webViewGroup->storageNamespaceProvider();
2939     configuration.progressTrackerClient = static_cast<WebFrameLoaderClient*>(configuration.loaderClientForMainFrame);
2940     configuration.userContentProvider = &m_webViewGroup->userContentController();
2941     configuration.visitedLinkStore = &m_webViewGroup->visitedLinkStore();
2942     configuration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
2943
2944     m_page = new Page(WTFMove(configuration));
2945     provideGeolocationTo(m_page, new WebGeolocationClient(this));
2946
2947     unsigned layoutMilestones = DidFirstLayout | DidFirstVisuallyNonEmptyLayout;
2948     m_page->addLayoutMilestones(static_cast<LayoutMilestones>(layoutMilestones));
2949
2950
2951     if (m_uiDelegate) {
2952         BString path;
2953         if (SUCCEEDED(m_uiDelegate->ftpDirectoryTemplatePath(this, &path)))
2954             m_page->settings().setFTPDirectoryTemplatePath(toString(path));
2955     }
2956
2957     WebFrame* webFrame = WebFrame::createInstance();
2958     webFrame->initWithWebView(this, m_page);
2959     static_cast<WebFrameLoaderClient&>(m_page->mainFrame().loader().client()).setWebFrame(webFrame);
2960     m_mainFrame = webFrame;
2961     webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
2962
2963     m_page->mainFrame().tree().setName(toString(frameName));
2964     m_page->mainFrame().init();
2965     setGroupName(groupName);
2966
2967     addToAllWebViewsSet();
2968
2969     #pragma warning(suppress: 4244)
2970     SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
2971     ShowWindow(m_viewWindow, SW_SHOW);
2972
2973     initializeToolTipWindow();
2974     windowAncestryDidChange();
2975
2976     IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
2977     notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2978     m_preferences->postPreferencesChangesNotification();
2979
2980     m_page->setDeviceScaleFactor(deviceScaleFactor());
2981
2982     setSmartInsertDeleteEnabled(TRUE);
2983     return hr;
2984 }
2985
2986 static bool initCommonControls()
2987 {
2988     static bool haveInitialized = false;
2989     if (haveInitialized)
2990         return true;
2991
2992     INITCOMMONCONTROLSEX init;
2993     init.dwSize = sizeof(init);
2994     init.dwICC = ICC_TREEVIEW_CLASSES;
2995     haveInitialized = !!::InitCommonControlsEx(&init);
2996     return haveInitialized;
2997 }
2998
2999 void WebView::initializeToolTipWindow()
3000 {
3001     if (!initCommonControls())
3002         return;
3003
3004     m_toolTipHwnd = CreateWindowEx(WS_EX_TRANSPARENT, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
3005                                    CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
3006                                    m_viewWindow, 0, 0, 0);
3007     if (!m_toolTipHwnd)
3008         return;
3009
3010     TOOLINFO info = {0};
3011     info.cbSize = sizeof(info);
3012     info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
3013     info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
3014
3015     ::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
3016     ::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, clampTo<int>(maxToolTipWidth * deviceScaleFactor()));
3017
3018     ::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
3019 }
3020
3021 void WebView::setToolTip(const String& toolTip)
3022 {
3023     if (!m_toolTipHwnd)
3024         return;
3025
3026     if (toolTip == m_toolTip)
3027         return;
3028
3029     m_toolTip = toolTip;
3030
3031     if (!m_toolTip.isEmpty()) {
3032         TOOLINFO info = {0};
3033         info.cbSize = sizeof(info);
3034         info.uFlags = TTF_IDISHWND;
3035         info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
3036         Vector<UChar> toolTipCharacters = m_toolTip.charactersWithNullTermination(); // Retain buffer long enough to make the SendMessage call
3037         info.lpszText = const_cast<UChar*>(toolTipCharacters.data());
3038         ::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
3039     }
3040
3041     ::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
3042 }
3043
3044 HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
3045 {
3046     COMPtr<IPropertyBag> propertyBag;
3047     HRESULT hr = notification->userInfo(&propertyBag);
3048     if (FAILED(hr))
3049         return hr;
3050     if (!propertyBag)
3051         return E_FAIL;
3052
3053     COMVariant iconUserInfoURL;
3054     hr = propertyBag->Read(WebIconDatabase::iconDatabaseNotificationUserInfoURLKey(), &iconUserInfoURL, nullptr);
3055     if (FAILED(hr))
3056         return hr;
3057
3058     if (iconUserInfoURL.variantType() != VT_BSTR)
3059         return E_FAIL;
3060
3061     String mainFrameURL;
3062     if (m_mainFrame)
3063         mainFrameURL = m_mainFrame->url().string();
3064
3065     if (!mainFrameURL.isEmpty() && mainFrameURL == toString(V_BSTR(&iconUserInfoURL)))
3066         dispatchDidReceiveIconFromWebFrame(m_mainFrame);
3067
3068     return hr;
3069 }
3070
3071 void WebView::registerForIconNotification(bool listen)
3072 {
3073     IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
3074     if (listen)
3075         nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
3076     else
3077         nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
3078 }
3079
3080 void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
3081 {
3082     registerForIconNotification(false);
3083
3084     if (m_frameLoadDelegate) {
3085         String str = frame->url().string();
3086
3087         IntSize sz(16, 16);
3088
3089         BitmapInfo bmInfo = BitmapInfo::create(sz);
3090
3091         HBITMAP hBitmap = nullptr;
3092
3093         Image* icon = iconDatabase().synchronousIconForPageURL(str, sz);
3094
3095         if (icon && icon->width()) {
3096             HWndDC dc(0);
3097             hBitmap = CreateDIBSection(dc, &bmInfo, DIB_RGB_COLORS, 0, 0, 0);
3098             icon->getHBITMAPOfSize(hBitmap, &sz);
3099         }
3100
3101         HRESULT hr = m_frameLoadDelegate->didReceiveIcon(this, hBitmap, frame);
3102         if ((hr == E_NOTIMPL) && hBitmap)
3103             DeleteObject(hBitmap);
3104     }
3105 }
3106
3107 HRESULT WebView::setAccessibilityDelegate(_In_opt_ IAccessibilityDelegate* d)
3108 {
3109     m_accessibilityDelegate = d;
3110     return S_OK;
3111 }
3112
3113 HRESULT WebView::accessibilityDelegate(_COM_Outptr_opt_ IAccessibilityDelegate** d)
3114 {
3115     if (!d)
3116         return E_POINTER;
3117     *d = nullptr;
3118     if (!m_accessibilityDelegate)
3119         return E_POINTER;
3120
3121     return m_accessibilityDelegate.copyRefTo(d);
3122 }
3123
3124 HRESULT WebView::setUIDelegate(_In_opt_ IWebUIDelegate* d)
3125 {
3126     m_uiDelegate = d;
3127
3128     if (m_uiDelegatePrivate)
3129         m_uiDelegatePrivate = 0;
3130
3131     if (d) {
3132         if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
3133             m_uiDelegatePrivate = 0;
3134     }
3135
3136     return S_OK;
3137 }
3138
3139 HRESULT WebView::uiDelegate(_COM_Outptr_opt_ IWebUIDelegate** d)
3140 {
3141     if (!d)
3142         return E_POINTER;
3143     *d = nullptr;
3144     if (!m_uiDelegate)
3145         return E_FAIL;
3146
3147     return m_uiDelegate.copyRefTo(d);
3148 }
3149
3150 HRESULT WebView::setResourceLoadDelegate(_In_opt_ IWebResourceLoadDelegate* d)
3151 {
3152     m_resourceLoadDelegate = d;
3153     return S_OK;
3154 }
3155
3156 HRESULT WebView::resourceLoadDelegate(_COM_Outptr_opt_ IWebResourceLoadDelegate** d)
3157 {
3158     if (!d)
3159         return E_POINTER;
3160     *d = nullptr;
3161     if (!m_resourceLoadDelegate)
3162         return E_FAIL;
3163
3164     return m_resourceLoadDelegate.copyRefTo(d);
3165 }
3166
3167 HRESULT WebView::setDownloadDelegate(_In_opt_ IWebDownloadDelegate* d)
3168 {
3169     m_downloadDelegate = d;
3170     return S_OK;
3171 }
3172
3173 HRESULT WebView::downloadDelegate(_COM_Outptr_opt_ IWebDownloadDelegate** d)
3174 {
3175     if (!d)
3176         return E_POINTER;
3177     *d = nullptr;
3178     if (!m_downloadDelegate)
3179         return E_FAIL;
3180
3181     return m_downloadDelegate.copyRefTo(d);
3182 }
3183
3184 HRESULT WebView::setFrameLoadDelegate(_In_opt_ IWebFrameLoadDelegate* d)
3185 {
3186     m_frameLoadDelegate = d;
3187     return S_OK;
3188 }
3189
3190 HRESULT WebView::frameLoadDelegate(_COM_Outptr_opt_ IWebFrameLoadDelegate** d)
3191 {
3192     if (!d)
3193         return E_POINTER;
3194     *d = nullptr;
3195     if (!m_frameLoadDelegate)
3196         return E_FAIL;
3197
3198     return m_frameLoadDelegate.copyRefTo(d);
3199 }
3200
3201 HRESULT WebView::setPolicyDelegate(_In_opt_ IWebPolicyDelegate* d)
3202 {
3203     m_policyDelegate = d;
3204     return S_OK;
3205 }
3206
3207 HRESULT WebView::policyDelegate(_COM_Outptr_opt_ IWebPolicyDelegate** d)
3208 {
3209     if (!d)
3210         return E_POINTER;
3211     *d = nullptr;
3212     if (!m_policyDelegate)
3213         return E_FAIL;
3214
3215     return m_policyDelegate.copyRefTo(d);
3216 }
3217
3218 HRESULT WebView::mainFrame(_COM_Outptr_opt_ IWebFrame** frame)
3219 {
3220     if (!frame) {
3221         ASSERT_NOT_REACHED();
3222         return E_POINTER;
3223     }
3224
3225     *frame = m_mainFrame;
3226     if (!m_mainFrame)
3227         return E_UNEXPECTED;
3228
3229     m_mainFrame->AddRef();
3230     return S_OK;
3231 }
3232
3233 HRESULT WebView::focusedFrame(_COM_Outptr_opt_ IWebFrame** frame)
3234 {
3235     if (!frame) {
3236         ASSERT_NOT_REACHED();
3237         return E_POINTER;
3238     }
3239
3240     *frame = nullptr;
3241     Frame* f = m_page->focusController().focusedFrame();
3242     if (!f)
3243         return E_FAIL;
3244
3245     WebFrame* webFrame = kit(f);
3246     if (!webFrame)
3247         return E_UNEXPECTED;
3248
3249     return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
3250 }
3251
3252 HRESULT WebView::backForwardList(_COM_Outptr_opt_ IWebBackForwardList** list)
3253 {
3254     if (!list) {
3255         ASSERT_NOT_REACHED();
3256         return E_POINTER;
3257     }
3258     *list = nullptr;
3259     if (!m_useBackForwardList)
3260         return E_FAIL;
3261  
3262     *list = WebBackForwardList::createInstance(static_cast<WebCore::BackForwardList*>(m_page->backForward().client()));
3263
3264     return S_OK;
3265 }
3266
3267 HRESULT WebView::setMaintainsBackForwardList(BOOL flag)
3268 {
3269     m_useBackForwardList = !!flag;
3270     return S_OK;
3271 }
3272
3273 HRESULT WebView::goBack(_Out_ BOOL* succeeded)
3274 {
3275     if (!succeeded)
3276         return E_POINTER;
3277
3278     *succeeded = m_page->backForward().goBack();
3279     return S_OK;
3280 }
3281
3282 HRESULT WebView::goForward(_Out_ BOOL* succeeded)
3283 {
3284     if (!succeeded)
3285         return E_POINTER;
3286
3287     *succeeded = m_page->backForward().goForward();
3288     return S_OK;
3289 }
3290
3291 HRESULT WebView::goToBackForwardItem(_In_opt_ IWebHistoryItem* item, _Out_ BOOL* succeeded)
3292 {
3293     if (!item)
3294         return E_FAIL;
3295
3296     if (!succeeded)
3297         return E_POINTER;
3298
3299     *succeeded = FALSE;
3300
3301     COMPtr<WebHistoryItem> webHistoryItem;
3302     HRESULT hr = item->QueryInterface(&webHistoryItem);
3303     if (FAILED(hr))
3304         return hr;
3305
3306     m_page->goToItem(*webHistoryItem->historyItem(), FrameLoadType::IndexedBackForward);
3307     *succeeded = TRUE;
3308
3309     return S_OK;
3310 }
3311
3312 HRESULT WebView::setTextSizeMultiplier(float multiplier)
3313 {
3314     if (!m_mainFrame)
3315         return E_UNEXPECTED;
3316     setZoomMultiplier(multiplier, true);
3317     return S_OK;
3318 }
3319
3320 HRESULT WebView::setPageSizeMultiplier(float multiplier)
3321 {
3322     if (!m_mainFrame)
3323         return E_UNEXPECTED;
3324     setZoomMultiplier(multiplier, false);
3325     return S_OK;
3326 }
3327
3328 void WebView::setZoomMultiplier(float multiplier, bool isTextOnly)
3329 {
3330     m_zoomMultiplier = multiplier;
3331     m_zoomsTextOnly = isTextOnly;
3332
3333     if (Frame* coreFrame = core(m_mainFrame)) {
3334         if (m_zoomsTextOnly)
3335             coreFrame->setPageAndTextZoomFactors(1, multiplier);
3336         else
3337             coreFrame->setPageAndTextZoomFactors(multiplier, 1);
3338     }
3339 }
3340
3341 HRESULT WebView::textSizeMultiplier(_Out_ float* multiplier)
3342 {
3343     if (!multiplier)
3344         return E_POINTER;
3345
3346     *multiplier = zoomMultiplier(true);
3347     return S_OK;
3348 }
3349
3350 HRESULT WebView::pageSizeMultiplier(_Out_ float* multiplier)
3351 {
3352     if (!multiplier)
3353         return E_POINTER;
3354
3355     *multiplier = zoomMultiplier(false);
3356     return S_OK;
3357 }
3358
3359 float WebView::zoomMultiplier(bool isTextOnly)
3360 {
3361     if (isTextOnly != m_zoomsTextOnly)
3362         return 1.0f;
3363     return m_zoomMultiplier;
3364 }
3365
3366 HRESULT WebView::setApplicationNameForUserAgent(_In_ BSTR applicationName)
3367 {
3368     m_applicationName = toString(applicationName);
3369     m_userAgentStandard = String();
3370     return S_OK;
3371 }
3372
3373 HRESULT WebView::applicationNameForUserAgent(_Deref_opt_out_ BSTR* applicationName)
3374 {
3375     if (!applicationName)
3376         return E_POINTER;
3377
3378     *applicationName = BString(m_applicationName).release();
3379     if (!*applicationName && m_applicationName.length())
3380         return E_OUTOFMEMORY;
3381     return S_OK;
3382 }
3383
3384 HRESULT WebView::setCustomUserAgent(_In_ BSTR userAgentString)
3385 {
3386     m_userAgentOverridden = userAgentString;
3387     m_userAgentCustom = toString(userAgentString);
3388     return S_OK;
3389 }
3390
3391 HRESULT WebView::customUserAgent(_Deref_opt_out_ BSTR* userAgentString)
3392 {
3393     if (!userAgentString)
3394         return E_POINTER;
3395
3396     *userAgentString = nullptr;
3397     if (!m_userAgentOverridden)
3398         return S_OK;
3399     *userAgentString = BString(m_userAgentCustom).release();
3400     if (!*userAgentString && m_userAgentCustom.length())
3401         return E_OUTOFMEMORY;
3402     return S_OK;
3403 }
3404
3405 HRESULT WebView::userAgentForURL(_In_ BSTR url, _Deref_opt_out_ BSTR* userAgent)
3406 {
3407     if (!userAgent)
3408         return E_POINTER;
3409
3410     String userAgentString = userAgentForKURL(MarshallingHelpers::BSTRToKURL(url));
3411     *userAgent = BString(userAgentString).release();
3412     if (!*userAgent && userAgentString.length())
3413         return E_OUTOFMEMORY;
3414     return S_OK;
3415 }
3416
3417 HRESULT WebView::supportsTextEncoding(_Out_ BOOL* supports)
3418 {
3419     if (!supports)
3420         return E_POINTER;
3421
3422     *supports = TRUE;
3423     return S_OK;
3424 }
3425
3426 HRESULT WebView::setCustomTextEncodingName(_In_ BSTR encodingName)
3427 {
3428     if (!m_mainFrame)
3429         return E_UNEXPECTED;
3430
3431     HRESULT hr;
3432     BString oldEncoding;
3433     hr = customTextEncodingName(&oldEncoding);
3434     if (FAILED(hr))
3435         return hr;
3436
3437     if (oldEncoding != encodingName && (!oldEncoding || !encodingName || wcscmp(oldEncoding, encodingName))) {
3438         if (Frame* coreFrame = core(m_mainFrame))
3439             coreFrame->loader().reloadWithOverrideEncoding(toString(encodingName));
3440     }
3441
3442     return S_OK;
3443 }
3444
3445 HRESULT WebView::customTextEncodingName(_Deref_opt_out_ BSTR* encodingName)
3446 {
3447     if (!encodingName)
3448         return E_POINTER;
3449
3450     HRESULT hr = S_OK;
3451     COMPtr<IWebDataSource> dataSource;
3452     COMPtr<WebDataSource> dataSourceImpl;
3453     *encodingName = nullptr;
3454
3455     if (!m_mainFrame)
3456         return E_UNEXPECTED;
3457
3458     if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
3459         hr = m_mainFrame->dataSource(&dataSource);
3460         if (FAILED(hr) || !dataSource)
3461             return hr;
3462     }
3463
3464     hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
3465     if (FAILED(hr))
3466         return hr;
3467
3468     BString str = dataSourceImpl->documentLoader()->overrideEncoding();
3469     if (FAILED(hr))
3470         return hr;
3471
3472     if (!*encodingName)
3473         *encodingName = BString(m_overrideEncoding).release();
3474
3475     if (!*encodingName && m_overrideEncoding.length())
3476         return E_OUTOFMEMORY;
3477
3478     return S_OK;
3479 }
3480
3481 HRESULT WebView::setMediaStyle(_In_ BSTR /*media*/)
3482 {
3483     ASSERT_NOT_REACHED();
3484     return E_NOTIMPL;
3485 }
3486
3487 HRESULT WebView::mediaStyle(_Deref_opt_out_ BSTR* /*media*/)
3488 {
3489     ASSERT_NOT_REACHED();
3490     return E_NOTIMPL;
3491 }
3492
3493 HRESULT WebView::stringByEvaluatingJavaScriptFromString(_In_ BSTR script, // assumes input does not have "JavaScript" at the begining.
3494     _Deref_opt_out_ BSTR* result)
3495 {
3496     if (!result) {
3497         ASSERT_NOT_REACHED();
3498         return E_POINTER;
3499     }
3500
3501     *result = nullptr;
3502
3503     Frame* coreFrame = core(m_mainFrame);
3504     if (!coreFrame)
3505         return E_UNEXPECTED;
3506
3507     auto scriptExecutionResult = coreFrame->script().executeScript(WTF::String(script), true);
3508     if (!scriptExecutionResult)
3509         return E_FAIL;
3510     else if (scriptExecutionResult.isString()) {
3511         JSC::ExecState* exec = coreFrame->script().globalObject(mainThreadNormalWorld())->globalExec();
3512         JSC::JSLockHolder lock(exec);
3513         *result = BString(scriptExecutionResult.getString(exec));
3514     }
3515
3516     return S_OK;
3517 }
3518
3519 HRESULT WebView::windowScriptObject(_COM_Outptr_opt_ IWebScriptObject** webScriptObject)
3520 {
3521     ASSERT_NOT_REACHED();
3522     if (!webScriptObject)
3523         return E_POINTER;
3524     *webScriptObject = nullptr;
3525     return E_NOTIMPL;
3526 }
3527
3528 HRESULT WebView::setPreferences(_In_opt_ IWebPreferences* prefs)
3529 {
3530     if (!prefs)
3531         prefs = WebPreferences::sharedStandardPreferences();
3532
3533     if (m_preferences == prefs)
3534         return S_OK;
3535
3536     COMPtr<WebPreferences> webPrefs(Query, prefs);
3537     if (!webPrefs)
3538         return E_NOINTERFACE;
3539     webPrefs->willAddToWebView();
3540
3541     COMPtr<WebPreferences> oldPrefs = m_preferences;
3542
3543     IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
3544     nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3545
3546     BString identifier;
3547     oldPrefs->identifier(&identifier);
3548     oldPrefs->didRemoveFromWebView();
3549     oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
3550
3551     m_preferences = webPrefs;
3552
3553     if (identifier)
3554         WebPreferences::removeReferenceForIdentifier(identifier);
3555
3556     nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3557
3558     m_preferences->postPreferencesChangesNotification();
3559
3560     return S_OK;
3561 }
3562
3563 HRESULT WebView::preferences(_COM_Outptr_opt_ IWebPreferences** prefs)
3564 {
3565     if (!prefs)
3566         return E_POINTER;
3567     *prefs = m_preferences.get();
3568     if (m_preferences)
3569         m_preferences->AddRef();
3570     return S_OK;
3571 }
3572
3573 HRESULT WebView::setPreferencesIdentifier(_In_ BSTR /*anIdentifier*/)
3574 {
3575     ASSERT_NOT_REACHED();
3576     return E_NOTIMPL;
3577 }
3578
3579 HRESULT WebView::preferencesIdentifier(_Deref_opt_out_ BSTR* /*anIdentifier*/)
3580 {
3581     ASSERT_NOT_REACHED();
3582     return E_NOTIMPL;
3583 }
3584
3585 static void systemParameterChanged(WPARAM parameter)
3586 {
3587 #if USE(CG)
3588     if (parameter == SPI_SETFONTSMOOTHING || parameter == SPI_SETFONTSMOOTHINGTYPE || parameter == SPI_SETFONTSMOOTHINGCONTRAST || parameter == SPI_SETFONTSMOOTHINGORIENTATION)
3589         wkSystemFontSmoothingChanged();
3590 #endif
3591 }
3592
3593 void WebView::windowReceivedMessage(HWND, UINT message, WPARAM wParam, LPARAM)
3594 {
3595     switch (message) {
3596     case WM_NCACTIVATE:
3597         updateActiveStateSoon();
3598         if (!wParam)
3599             deleteBackingStoreSoon();
3600         break;
3601     case WM_SETTINGCHANGE:
3602         systemParameterChanged(wParam);
3603         break;
3604     }
3605 }
3606
3607 void WebView::updateActiveStateSoon() const
3608 {
3609     // This function is called while processing the WM_NCACTIVATE message.
3610     // While processing WM_NCACTIVATE when we are being deactivated, GetActiveWindow() will
3611     // still return our window. If we were to call updateActiveState() in that case, we would
3612     // wrongly think that we are still the active window. To work around this, we update our
3613     // active state after a 0-delay timer fires, at which point GetActiveWindow() will return
3614     // the newly-activated window.
3615
3616     SetTimer(m_viewWindow, UpdateActiveStateTimer, 0, 0);
3617 }
3618
3619 void WebView::deleteBackingStoreSoon()
3620 {
3621     if (pendingDeleteBackingStoreSet().size() > 2) {
3622         Vector<WebView*> views;
3623         HashSet<WebView*>::iterator end = pendingDeleteBackingStoreSet().end();
3624         for (HashSet<WebView*>::iterator it = pendingDeleteBackingStoreSet().begin(); it != end; ++it)
3625             views.append(*it);
3626         for (int i = 0; i < views.size(); ++i)
3627             views[i]->deleteBackingStore();
3628         ASSERT(pendingDeleteBackingStoreSet().isEmpty());
3629     }
3630
3631     pendingDeleteBackingStoreSet().add(this);
3632     m_deleteBackingStoreTimerActive = true;
3633     SetTimer(m_viewWindow, DeleteBackingStoreTimer, delayBeforeDeletingBackingStoreMsec, 0);
3634 }
3635
3636 void WebView::cancelDeleteBackingStoreSoon()
3637 {
3638     if (!m_deleteBackingStoreTimerActive)
3639         return;
3640     pendingDeleteBackingStoreSet().remove(this);
3641     m_deleteBackingStoreTimerActive = false;
3642     KillTimer(m_viewWindow, DeleteBackingStoreTimer);
3643 }
3644
3645 HRESULT WebView::setHostWindow(_In_ HWND window)
3646 {
3647     if (m_viewWindow) {
3648         if (window)
3649             SetParent(m_viewWindow, window);
3650         else if (!isBeingDestroyed()) {
3651             // Turn the WebView into a message-only window so it will no longer be a child of the
3652             // old host window and will be hidden from screen. We only do this when
3653             // isBeingDestroyed() is false because doing this while handling WM_DESTROY can leave
3654             // m_viewWindow in a weird state (see <http://webkit.org/b/29337>).
3655             SetParent(m_viewWindow, HWND_MESSAGE);
3656         }
3657     }
3658
3659     m_hostWindow = window;
3660
3661     windowAncestryDidChange();
3662
3663     if (m_page)
3664         m_page->setDeviceScaleFactor(deviceScaleFactor());
3665
3666     return S_OK;
3667 }
3668
3669 HRESULT WebView::hostWindow(_Deref_opt_out_ HWND* window)
3670 {
3671     if (!window)
3672         return E_POINTER;
3673
3674     *window = m_hostWindow;
3675     return S_OK;
3676 }
3677
3678
3679 static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
3680 {
3681     return forward
3682         ? curr->tree().traverseNextWithWrap(wrapFlag)
3683         : curr->tree().traversePreviousWithWrap(wrapFlag);
3684 }
3685
3686 HRESULT WebView::searchFor(_In_ BSTR str, BOOL forward, BOOL caseFlag, BOOL wrapFlag, _Out_ BOOL* found)
3687 {
3688     if (!found)
3689         return E_INVALIDARG;
3690     
3691     if (!m_page)
3692         return E_FAIL;
3693
3694     if (!str || !SysStringLen(str))
3695         return E_INVALIDARG;
3696
3697     FindOptions options = (caseFlag ? 0 : CaseInsensitive) | (forward ? 0 : Backwards) | (wrapFlag ? WrapAround : 0);
3698     *found = m_page->findString(toString(str), options);
3699     return S_OK;
3700 }
3701
3702 bool WebView::active()
3703 {
3704     HWND activeWindow = GetActiveWindow();
3705     if (usesLayeredWindow() && activeWindow == m_viewWindow)
3706         return true;
3707
3708     return (activeWindow && m_topLevelParent == findTopLevelParent(activeWindow));
3709 }
3710
3711 void WebView::updateActiveState()
3712 {
3713     if (m_page)
3714         m_page->focusController().setActive(active());
3715 }
3716
3717 HRESULT WebView::updateFocusedAndActiveState()
3718 {
3719     updateActiveState();
3720
3721     bool active = m_page->focusController().isActive();
3722     Frame& mainFrame = m_page->mainFrame();
3723     Frame& focusedFrame = m_page->focusController().focusedOrMainFrame();
3724     mainFrame.selection().setFocused(active && &mainFrame == &focusedFrame);
3725
3726     return S_OK;
3727 }
3728
3729 HRESULT WebView::executeCoreCommandByName(_In_ BSTR name, _In_ BSTR value)
3730 {
3731     if (!m_page)
3732         return E_FAIL;
3733
3734     m_page->focusController().focusedOrMainFrame().editor().command(toString(name)).execute(toString(value));
3735
3736     return S_OK;
3737 }
3738
3739 HRESULT WebView::clearMainFrameName()
3740 {
3741     if (!m_page)
3742         return E_FAIL;
3743
3744     m_page->mainFrame().tree().clearName();
3745
3746     return S_OK;
3747 }
3748
3749 HRESULT WebView::markAllMatchesForText(_In_ BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, _Out_ UINT* matches)
3750 {
3751     if (!matches)
3752         return E_INVALIDARG;
3753
3754     if (!m_page)
3755         return E_FAIL;
3756
3757     if (!str || !SysStringLen(str))
3758         return E_INVALIDARG;
3759
3760     *matches = m_page->markAllMatchesForText(toString(str), caseSensitive ? TextCaseSensitive : TextCaseInsensitive, highlight, limit);
3761     return S_OK;
3762 }
3763
3764 HRESULT WebView::unmarkAllTextMatches()
3765 {
3766     if (!m_page)
3767         return E_FAIL;
3768
3769     m_page->unmarkAllTextMatches();
3770     return S_OK;
3771 }
3772
3773 HRESULT WebView::rectsForTextMatches(_COM_Outptr_opt_ IEnumTextMatches** pmatches)
3774 {
3775     if (!pmatches)
3776         return E_POINTER;
3777     *pmatches = nullptr;
3778     if (!m_page)
3779         return E_FAIL;
3780
3781     Vector<IntRect> allRects;
3782     WebCore::Frame* frame = &m_page->mainFrame();
3783     do {
3784         if (Document* document = frame->document()) {
3785             IntRect visibleRect = frame->view()->visibleContentRect();
3786             Vector<FloatRect> frameRects = document->markers().renderedRectsForMarkers(DocumentMarker::TextMatch);
3787             IntPoint frameOffset = -frame->view()->scrollPosition();
3788             frameOffset = frame->view()->convertToContainingWindow(frameOffset);
3789
3790             Vector<FloatRect>::iterator end = frameRects.end();
3791             for (Vector<FloatRect>::iterator it = frameRects.begin(); it < end; it++) {
3792                 it->intersect(visibleRect);
3793                 it->move(frameOffset.x(), frameOffset.y());
3794                 allRects.append(enclosingIntRect(*it));
3795             }
3796         }
3797         frame = incrementFrame(frame, true, false);
3798     } while (frame);
3799
3800     return createMatchEnumerator(&allRects, pmatches);
3801 }
3802
3803 HRESULT WebView::generateSelectionImage(BOOL forceWhiteText, _Deref_opt_out_ HBITMAP* hBitmap)
3804 {
3805     if (!hBitmap)
3806         return E_POINTER;
3807
3808     if (!m_page)
3809         return E_FAIL;
3810
3811     *hBitmap = nullptr;
3812
3813     WebCore::Frame& frame = m_page->focusController().focusedOrMainFrame();
3814
3815     auto bitmap = imageFromSelection(&frame, forceWhiteText ? TRUE : FALSE);
3816     *hBitmap = bitmap.leak();
3817
3818     return S_OK;
3819 }
3820
3821 HRESULT WebView::selectionRect(_Inout_ RECT* rc)
3822 {
3823     if (!rc)
3824         return E_POINTER;
3825
3826     if (!m_page)
3827         return E_FAIL;
3828
3829     WebCore::Frame& frame = m_page->focusController().focusedOrMainFrame();
3830
3831     IntRect ir = enclosingIntRect(frame.selection().selectionBounds());
3832     ir = frame.view()->convertToContainingWindow(ir);
3833     ir.moveBy(-frame.view()->scrollPosition());
3834
3835     float scaleFactor = deviceScaleFactor();
3836     rc->left = ir.x() * scaleFactor;
3837     rc->top = ir.y() * scaleFactor;
3838     rc->bottom = rc->top + ir.height() * scaleFactor;
3839     rc->right = rc->left + ir.width() * scaleFactor;
3840
3841     return S_OK;
3842 }
3843
3844 HRESULT WebView::registerViewClass(_In_opt_ IWebDocumentView*, _In_opt_ IWebDocumentRepresentation*, _In_ BSTR /*forMIMEType*/)
3845 {
3846     ASSERT_NOT_REACHED();
3847     return E_NOTIMPL;
3848 }
3849
3850 HRESULT WebView::setGroupName(_In_ BSTR groupName)
3851 {
3852     if (m_webViewGroup)
3853         m_webViewGroup->removeWebView(this);
3854
3855     m_webViewGroup = WebViewGroup::getOrCreate(groupName, localStorageDatabasePath(m_preferences.get()));
3856     m_webViewGroup->addWebView(this);
3857
3858     if (!m_page)
3859         return S_OK;
3860
3861     m_page->setUserContentProvider(m_webViewGroup->userContentController());
3862     m_page->setVisitedLinkStore(m_webViewGroup->visitedLinkStore());
3863     m_page->setGroupName(toString(groupName));
3864     return S_OK;
3865 }
3866     
3867 HRESULT WebView::groupName(_Deref_opt_out_ BSTR* groupName)
3868 {
3869     if (!groupName)
3870         return E_POINTER;
3871
3872     *groupName = nullptr;
3873     if (!m_page)
3874         return S_OK;
3875     String groupNameString = m_page->groupName();
3876     *groupName = BString(groupNameString).release();
3877     if (!*groupName && groupNameString.length())
3878         return E_OUTOFMEMORY;
3879     return S_OK;
3880 }
3881     
3882 HRESULT WebView::estimatedProgress(_Out_ double* estimatedProgress)
3883 {
3884     if (!estimatedProgress)
3885         return E_POINTER;
3886     *estimatedProgress = m_page->progress().estimatedProgress();
3887     return S_OK;
3888 }
3889     
3890 HRESULT WebView::isLoading(_Out_ BOOL* isLoading)
3891 {
3892     COMPtr<IWebDataSource> dataSource;
3893     COMPtr<IWebDataSource> provisionalDataSource;
3894
3895     if (!isLoading)
3896         return E_POINTER;
3897
3898     *isLoading = FALSE;
3899
3900     if (!m_mainFrame)
3901         return E_UNEXPECTED;
3902
3903     if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
3904         dataSource->isLoading(isLoading);
3905
3906     if (*isLoading)
3907         return S_OK;
3908
3909     if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
3910         provisionalDataSource->isLoading(isLoading);
3911     return S_OK;
3912 }
3913     
3914 HRESULT WebView::elementAtPoint(_In_ LPPOINT point, _COM_Outptr_opt_ IPropertyBag** elementDictionary)
3915 {
3916     if (!elementDictionary || !point) {
3917         ASSERT_NOT_REACHED();
3918         return E_POINTER;
3919     }
3920
3921     *elementDictionary = nullptr;
3922
3923     Frame* frame = core(m_mainFrame);
3924     if (!frame)
3925         return E_UNEXPECTED;
3926
3927     IntPoint webCorePoint = IntPoint(point->x, point->y);
3928     float inverseScaleFactor = 1.0f / deviceScaleFactor();
3929     webCorePoint.scale(inverseScaleFactor, inverseScaleFactor);
3930     HitTestResult result = HitTestResult(webCorePoint);
3931     if (frame->contentRenderer())
3932         result = frame->eventHandler().hitTestResultAtPoint(webCorePoint);
3933     *elementDictionary = WebElementPropertyBag::createInstance(result);
3934     return S_OK;
3935 }
3936     
3937 HRESULT WebView::pasteboardTypesForSelection(_COM_Outptr_opt_ IEnumVARIANT** enumVariant)
3938 {
3939     ASSERT_NOT_REACHED();
3940     if (!enumVariant)
3941         return E_POINTER;
3942     *enumVariant = nullptr;
3943     return E_NOTIMPL;
3944 }
3945     
3946 HRESULT WebView::writeSelectionWithPasteboardTypes(__inout_ecount_full(cTypes) BSTR* types, int cTypes, _In_opt_ IDataObject* /*pasteboard*/)
3947 {
3948     ASSERT_NOT_REACHED();
3949     return E_NOTIMPL;
3950 }
3951     
3952 HRESULT WebView::pasteboardTypesForElement(_In_opt_ IPropertyBag* /*elementDictionary*/, _COM_Outptr_opt_ IEnumVARIANT** enumVariant)
3953 {
3954     ASSERT_NOT_REACHED();
3955     if (!enumVariant)
3956         return E_POINTER;
3957     *enumVariant = nullptr;
3958     return E_NOTIMPL;
3959 }
3960     
3961 HRESULT WebView::writeElement(_In_opt_ IPropertyBag* /*elementDictionary*/, __inout_ecount_full(cWithPasteboardTypes) BSTR* withPasteboardTypes, int cWithPasteboardTypes, _In_opt_ IDataObject* /*pasteboard*/)
3962 {
3963     ASSERT_NOT_REACHED();
3964     return E_NOTIMPL;
3965 }
3966     
3967 HRESULT WebView::selectedText(_Deref_opt_out_ BSTR* text)
3968 {
3969     if (!text) {
3970         ASSERT_NOT_REACHED();
3971         return E_POINTER;
3972     }
3973
3974     *text = nullptr;
3975
3976     Frame* focusedFrame = m_page ? &m_page->focusController().focusedOrMainFrame() : 0;
3977     if (!focusedFrame)
3978         return E_FAIL;
3979
3980     String frameSelectedText = focusedFrame->editor().selectedText();
3981     *text = BString(frameSelectedText).release();
3982     if (!*text && frameSelectedText.length())
3983         return E_OUTOFMEMORY;
3984     return S_OK;
3985 }
3986
3987 HRESULT WebView::centerSelectionInVisibleArea(_In_opt_ IUnknown* /* sender */)
3988 {
3989     Frame* coreFrame = core(m_mainFrame);
3990     if (!coreFrame)
3991         return E_UNEXPECTED;
3992
3993     coreFrame->selection().revealSelection(SelectionRevealMode::Reveal, ScrollAlignment::alignCenterAlways);
3994     return S_OK;
3995 }
3996
3997
3998 HRESULT WebView::moveDragCaretToPoint(_In_ LPPOINT /*point*/)
3999 {
4000     ASSERT_NOT_REACHED();
4001     return E_NOTIMPL;
4002 }
4003     
4004 HRESULT WebView::removeDragCaret()
4005 {
4006     ASSERT_NOT_REACHED();
4007     return E_NOTIMPL;
4008 }
4009     
4010 HRESULT WebView::setDrawsBackground(BOOL /*drawsBackground*/)
4011 {
4012     ASSERT_NOT_REACHED();
4013     return E_NOTIMPL;
4014 }
4015     
4016 HRESULT WebView::drawsBackground(_Out_ BOOL* /*drawsBackground*/)
4017 {
4018     ASSERT_NOT_REACHED();
4019     return E_NOTIMPL;
4020 }
4021     
4022 HRESULT WebView::setMainFrameURL(_In_ BSTR /*urlString*/)
4023 {
4024     ASSERT_NOT_REACHED();
4025     return E_NOTIMPL;
4026 }
4027     
4028 HRESULT WebView::mainFrameURL(_Deref_opt_out_ BSTR* urlString)
4029 {
4030     if (!urlString)
4031         return E_POINTER;
4032
4033     if (!m_mainFrame)
4034         return E_UNEXPECTED;
4035
4036     COMPtr<IWebDataSource> dataSource;
4037
4038     if (FAILED(m_mainFrame->provisionalDataSource(&dataSource))) {
4039         if (FAILED(m_mainFrame->dataSource(&dataSource)))
4040             return E_FAIL;
4041     }
4042
4043     if (!dataSource) {
4044         *urlString = nullptr;
4045         return S_OK;
4046     }
4047     
4048     COMPtr<IWebMutableURLRequest> request;
4049     if (FAILED(dataSource->request(&request)) || !request)
4050         return E_FAIL;
4051
4052     if (FAILED(request->URL(urlString)))
4053         return E_FAIL;
4054
4055     return S_OK;
4056 }
4057     
4058 HRESULT WebView::mainFrameDocument(_COM_Outptr_opt_ IDOMDocument** document)
4059 {
4060     if (!document)
4061         return E_POINTER;
4062
4063     *document = nullptr;
4064
4065     if (!m_mainFrame)
4066         return E_UNEXPECTED;
4067     return m_mainFrame->DOMDocument(document);
4068 }
4069     
4070 HRESULT WebView::mainFrameTitle(_Deref_opt_out_ BSTR* /*title*/)
4071 {
4072     ASSERT_NOT_REACHED();
4073     return E_NOTIMPL;
4074 }
4075     
4076 HRESULT WebView::mainFrameIcon(_Deref_opt_out_ HBITMAP* /*hBitmap*/)
4077 {
4078     ASSERT_NOT_REACHED();
4079     return E_NOTIMPL;
4080 }
4081
4082 HRESULT WebView::registerURLSchemeAsLocal(_In_ BSTR scheme)
4083 {
4084     if (!scheme)
4085         return E_POINTER;
4086
4087     SchemeRegistry::registerURLSchemeAsLocal(toString(scheme));
4088
4089     return S_OK;
4090 }
4091
4092 // IWebIBActions ---------------------------------------------------------------
4093
4094 HRESULT WebView::takeStringURLFrom(_In_opt_ IUnknown* /*sender*/)
4095 {
4096     ASSERT_NOT_REACHED();
4097     return E_NOTIMPL;
4098 }
4099     
4100 HRESULT WebView::stopLoading(_In_opt_ IUnknown* /*sender*/)
4101 {
4102     if (!m_mainFrame)
4103         return E_UNEXPECTED;
4104
4105     return m_mainFrame->stopLoading();
4106 }
4107     
4108 HRESULT WebView::reload(_In_opt_ IUnknown* /*sender*/)
4109 {
4110     if (!m_mainFrame)
4111         return E_UNEXPECTED;
4112
4113     return m_mainFrame->reload();
4114 }
4115     
4116 HRESULT WebView::canGoBack(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4117 {
4118     if (!result)
4119         return E_POINTER;
4120
4121     *result = !!(m_page->backForward().backItem() && !m_page->defersLoading());
4122     return S_OK;
4123 }
4124     
4125 HRESULT WebView::goBack(_In_opt_ IUnknown* /*sender*/)
4126 {
4127     ASSERT_NOT_REACHED();
4128     return E_NOTIMPL;
4129 }
4130     
4131 HRESULT WebView::canGoForward(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4132 {
4133     if (!result)
4134         return E_POINTER;
4135     
4136     *result = !!(m_page->backForward().forwardItem() && !m_page->defersLoading());
4137     return S_OK;
4138 }
4139     
4140 HRESULT WebView::goForward(_In_opt_ IUnknown* /*sender*/)
4141 {
4142     ASSERT_NOT_REACHED();
4143     return E_NOTIMPL;
4144 }
4145
4146 // FIXME: This code should move into WebCore so it can be shared by all the WebKits.
4147 #define MinimumZoomMultiplier   0.5f
4148 #define MaximumZoomMultiplier   3.0f
4149 #define ZoomMultiplierRatio     1.2f
4150
4151 HRESULT WebView::canMakeTextLarger(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4152 {
4153     if (!result)
4154         return E_POINTER;
4155
4156     bool canGrowMore = canZoomIn(m_zoomsTextOnly);
4157     *result = canGrowMore ? TRUE : FALSE;
4158     return S_OK;
4159 }
4160
4161 HRESULT WebView::canZoomPageIn(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4162 {
4163     if (!result)
4164         return E_POINTER;
4165
4166     bool canGrowMore = canZoomIn(false);
4167     *result = canGrowMore ? TRUE : FALSE;
4168     return S_OK;
4169 }
4170
4171 bool WebView::canZoomIn(bool isTextOnly)
4172 {
4173     return zoomMultiplier(isTextOnly) * ZoomMultiplierRatio < MaximumZoomMultiplier;
4174 }
4175     
4176 HRESULT WebView::makeTextLarger(_In_opt_ IUnknown* /*sender*/)
4177 {
4178     return zoomIn(m_zoomsTextOnly);
4179 }
4180
4181 HRESULT WebView::zoomPageIn(_In_opt_ IUnknown* /*sender*/)
4182 {
4183     return zoomIn(false);
4184 }
4185
4186 HRESULT WebView::zoomIn(bool isTextOnly)
4187 {
4188     if (!canZoomIn(isTextOnly))
4189         return E_FAIL;
4190     setZoomMultiplier(zoomMultiplier(isTextOnly) * ZoomMultiplierRatio, isTextOnly);
4191     return S_OK;
4192 }
4193
4194 HRESULT WebView::canMakeTextSmaller(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4195 {
4196     if (!result)
4197         return E_POINTER;
4198
4199     bool canShrinkMore = canZoomOut(m_zoomsTextOnly);
4200     *result = canShrinkMore ? TRUE : FALSE;
4201     return S_OK;
4202 }
4203
4204 HRESULT WebView::canZoomPageOut(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4205 {
4206     if (!result)
4207         return E_POINTER;
4208
4209     bool canShrinkMore = canZoomOut(false);
4210     *result = canShrinkMore ? TRUE : FALSE;
4211     return S_OK;
4212 }
4213
4214 bool WebView::canZoomOut(bool isTextOnly)
4215 {
4216     return zoomMultiplier(isTextOnly) / ZoomMultiplierRatio > MinimumZoomMultiplier;
4217 }
4218
4219 HRESULT WebView::makeTextSmaller(_In_opt_ IUnknown* /*sender*/)
4220 {
4221     return zoomOut(m_zoomsTextOnly);
4222 }
4223
4224 HRESULT WebView::zoomPageOut(_In_opt_ IUnknown* /*sender*/)
4225 {
4226     return zoomOut(false);
4227 }
4228
4229 HRESULT WebView::zoomOut(bool isTextOnly)
4230 {
4231     if (!canZoomOut(isTextOnly))
4232         return E_FAIL;
4233     setZoomMultiplier(zoomMultiplier(isTextOnly) / ZoomMultiplierRatio, isTextOnly);
4234     return S_OK;
4235 }
4236
4237 HRESULT WebView::canMakeTextStandardSize(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4238 {
4239     if (!result)
4240         return E_POINTER;
4241
4242     // Since we always reset text zoom and page zoom together, this should continue to return an answer about text zoom even if its not enabled.
4243     bool notAlreadyStandard = canResetZoom(true);
4244     *result = notAlreadyStandard ? TRUE : FALSE;
4245     return S_OK;
4246 }
4247
4248 HRESULT WebView::canResetPageZoom(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4249 {
4250     if (!result)
4251         return E_POINTER;
4252
4253     bool notAlreadyStandard = canResetZoom(false);
4254     *result = notAlreadyStandard ? TRUE : FALSE;
4255     return S_OK;
4256 }
4257
4258 bool WebView::canResetZoom(bool isTextOnly)
4259 {
4260     return zoomMultiplier(isTextOnly) != 1.0f;
4261 }
4262
4263 HRESULT WebView::makeTextStandardSize(_In_opt_ IUnknown* /*sender*/)
4264 {
4265     return resetZoom(true);
4266 }
4267
4268 HRESULT WebView::resetPageZoom(_In_opt_ IUnknown* /*sender*/)
4269 {
4270     return resetZoom(false);
4271 }
4272
4273 HRESULT WebView::resetZoom(bool isTextOnly)
4274 {
4275     if (!canResetZoom(isTextOnly))
4276         return E_FAIL;
4277     setZoomMultiplier(1.0f, isTextOnly);
4278     return S_OK;
4279 }
4280
4281 HRESULT WebView::toggleContinuousSpellChecking(_In_opt_ IUnknown* /*sender*/)
4282 {
4283     HRESULT hr;
4284     BOOL enabled;
4285     if (FAILED(hr = isContinuousSpellCheckingEnabled(&enabled)))
4286         return hr;
4287     return setContinuousSpellCheckingEnabled(enabled ? FALSE : TRUE);
4288 }
4289
4290 HRESULT WebView::toggleSmartInsertDelete(_In_opt_ IUnknown* /*sender*/)
4291 {
4292     BOOL enabled = FALSE;
4293     HRESULT hr = smartInsertDeleteEnabled(&enabled);
4294     if (FAILED(hr))
4295         return hr;
4296
4297     return setSmartInsertDeleteEnabled(enabled ? FALSE : TRUE);
4298 }
4299
4300 HRESULT WebView::toggleGrammarChecking(_In_opt_ IUnknown* /*sender*/)
4301 {