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