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