Handle custom menu items in WebKit instead of WebCore on Windows
[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 "ResourceLoadScheduler.h"
38 #include "SoftLinking.h"
39 #include "SubframeLoader.h"
40 #include "TextIterator.h"
41 #include "WebBackForwardList.h"
42 #include "WebChromeClient.h"
43 #include "WebContextMenuClient.h"
44 #include "WebCoreTextRenderer.h"
45 #include "WebDatabaseManager.h"
46 #include "WebDatabaseProvider.h"
47 #include "WebDocumentLoader.h"
48 #include "WebDownload.h"
49 #include "WebDragClient.h"
50 #include "WebEditorClient.h"
51 #include "WebElementPropertyBag.h"
52 #include "WebFrame.h"
53 #include "WebFrameLoaderClient.h"
54 #include "WebFrameNetworkingContext.h"
55 #include "WebGeolocationClient.h"
56 #include "WebGeolocationPosition.h"
57 #include "WebIconDatabase.h"
58 #include "WebInspector.h"
59 #include "WebInspectorClient.h"
60 #include "WebKit.h"
61 #include "WebKitDLL.h"
62 #include "WebKitLogging.h"
63 #include "WebKitStatisticsPrivate.h"
64 #include "WebKitSystemBits.h"
65 #include "WebKitVersion.h"
66 #include "WebMutableURLRequest.h"
67 #include "WebNotificationCenter.h"
68 #include "WebPlatformStrategies.h"
69 #include "WebPreferences.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     ContextMenuItem item(ActionType, action, title, true, false);
1639     m_page->contextMenuController().contextMenuItemSelected(&item);
1640 }
1641
1642 bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
1643 {
1644     static LONG globalClickCount;
1645     static IntPoint globalPrevPoint;
1646     static MouseButton globalPrevButton;
1647     static LONG globalPrevMouseDownTime;
1648
1649     if (message == WM_CANCELMODE) {
1650         m_page->mainFrame().eventHandler().lostMouseCapture();
1651         return true;
1652     }
1653
1654     // Create our event.
1655     // On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
1656     // of the event to be at (MINSHORT, MINSHORT).
1657     LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
1658     PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
1659
1660     setMouseActivated(false);
1661
1662     bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.position().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
1663                            abs(globalPrevPoint.y() - mouseEvent.position().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
1664     LONG messageTime = ::GetMessageTime();
1665
1666     bool handled = false;
1667
1668     if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
1669         // FIXME: I'm not sure if this is the "right" way to do this
1670         // but without this call, we never become focused since we don't allow
1671         // the default handling of mouse events.
1672         SetFocus(m_viewWindow);
1673
1674         // Always start capturing events when the mouse goes down in our HWND.
1675         ::SetCapture(m_viewWindow);
1676
1677         if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) && 
1678             insideThreshold &&
1679             mouseEvent.button() == globalPrevButton)
1680             globalClickCount++;
1681         else
1682             // Reset the click count.
1683             globalClickCount = 1;
1684         globalPrevMouseDownTime = messageTime;
1685         globalPrevButton = mouseEvent.button();
1686         globalPrevPoint = mouseEvent.position();
1687         
1688         mouseEvent.setClickCount(globalClickCount);
1689         handled = m_page->mainFrame().eventHandler().handleMousePressEvent(mouseEvent);
1690     } else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
1691         globalClickCount++;
1692         mouseEvent.setClickCount(globalClickCount);
1693         handled = m_page->mainFrame().eventHandler().handleMousePressEvent(mouseEvent);
1694     } else if (message == WM_LBUTTONUP || message == WM_MBUTTONUP || message == WM_RBUTTONUP) {
1695         // Record the global position and the button of the up.
1696         globalPrevButton = mouseEvent.button();
1697         globalPrevPoint = mouseEvent.position();
1698         mouseEvent.setClickCount(globalClickCount);
1699         m_page->mainFrame().eventHandler().handleMouseReleaseEvent(mouseEvent);
1700         ::ReleaseCapture();
1701     } else if (message == WM_MOUSELEAVE && m_mouseOutTracker) {
1702         // Once WM_MOUSELEAVE is fired windows clears this tracker
1703         // so there is no need to disable it ourselves.
1704         m_mouseOutTracker.reset();
1705         m_page->mainFrame().eventHandler().mouseMoved(mouseEvent);
1706         handled = true;
1707     } else if (message == WM_MOUSEMOVE) {
1708         if (!insideThreshold)
1709             globalClickCount = 0;
1710         mouseEvent.setClickCount(globalClickCount);
1711         handled = m_page->mainFrame().eventHandler().mouseMoved(mouseEvent);
1712         if (!m_mouseOutTracker) {
1713             m_mouseOutTracker = std::make_unique<TRACKMOUSEEVENT>();
1714             m_mouseOutTracker->cbSize = sizeof(TRACKMOUSEEVENT);
1715             m_mouseOutTracker->dwFlags = TME_LEAVE;
1716             m_mouseOutTracker->hwndTrack = m_viewWindow;
1717             ::TrackMouseEvent(m_mouseOutTracker.get());
1718         }
1719     }
1720     return handled;
1721 }
1722
1723 bool WebView::gestureNotify(WPARAM wParam, LPARAM lParam)
1724 {
1725     GESTURENOTIFYSTRUCT* gn = reinterpret_cast<GESTURENOTIFYSTRUCT*>(lParam);
1726
1727     Frame* coreFrame = core(m_mainFrame);
1728     if (!coreFrame)
1729         return false;
1730
1731     ScrollView* view = coreFrame->view();
1732     if (!view)
1733         return false;
1734
1735     // If we don't have this function, we shouldn't be receiving this message
1736     ASSERT(SetGestureConfigPtr());
1737
1738     bool hitScrollbar = false;
1739     POINT gestureBeginPoint = {gn->ptsLocation.x, gn->ptsLocation.y};
1740
1741     float scaleFactor = deviceScaleFactor();
1742     float inverseScaleFactor = 1.0f / scaleFactor;
1743     IntPoint logicalGestureBeginPoint(gestureBeginPoint);
1744     logicalGestureBeginPoint.scale(inverseScaleFactor, inverseScaleFactor);
1745
1746     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
1747     for (Frame* childFrame = &m_page->mainFrame(); childFrame; childFrame = EventHandler::subframeForTargetNode(m_gestureTargetNode.get())) {
1748         FrameView* frameView = childFrame->view();
1749         if (!frameView)
1750             break;
1751         RenderView* renderView = childFrame->document()->renderView();
1752         if (!renderView)
1753             break;
1754         RenderLayer* layer = renderView->layer();
1755         if (!layer)
1756             break;
1757
1758         HitTestResult result(frameView->screenToContents(logicalGestureBeginPoint));
1759         layer->hitTest(request, result);
1760         m_gestureTargetNode = result.innerNode();
1761
1762         if (!hitScrollbar)
1763             hitScrollbar = result.scrollbar();
1764     }
1765
1766     if (!hitScrollbar) {
1767         // The hit testing above won't detect if we've hit the main frame's vertical scrollbar. Check that manually now.
1768         RECT webViewRect;
1769         GetWindowRect(m_viewWindow, &webViewRect);
1770         hitScrollbar = (view->verticalScrollbar() && (gestureBeginPoint.x > (webViewRect.right - view->verticalScrollbar()->theme().scrollbarThickness()))) 
1771             || (view->horizontalScrollbar() && (gestureBeginPoint.y > (webViewRect.bottom - view->horizontalScrollbar()->theme().scrollbarThickness())));  
1772     }
1773
1774     bool canBeScrolled = false;
1775     if (m_gestureTargetNode) {
1776         for (RenderObject* renderer = m_gestureTargetNode->renderer(); renderer; renderer = renderer->parent()) {
1777             if (is<RenderBox>(*renderer) && downcast<RenderBox>(*renderer).canBeScrolledAndHasScrollableArea()) {
1778                 canBeScrolled = true;
1779                 break;
1780             }
1781         }
1782     } else {
1783         // We've hit the main document but not any of the document's content
1784         if (core(m_mainFrame)->view()->isScrollable())
1785             canBeScrolled = true;
1786     }
1787
1788     // We always allow two-fingered panning with inertia and a gutter (which limits movement to one
1789     // direction in most cases).
1790     DWORD dwPanWant = GC_PAN | GC_PAN_WITH_INERTIA | GC_PAN_WITH_GUTTER;
1791     DWORD dwPanBlock = 0;
1792
1793     if (hitScrollbar || !canBeScrolled) {
1794         // The part of the page under the gesture can't be scrolled, or the gesture is on a scrollbar.
1795         // Disallow single-fingered panning in this case so we'll fall back to the default
1796         // behavior (which allows the scrollbar thumb to be dragged, text selections to be made, etc.).
1797         dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_VERTICALLY | GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
1798     } else {
1799         // The part of the page the gesture is under can be scrolled, and we're not under a scrollbar.
1800         // Allow single-fingered vertical panning in this case, so the user will be able to pan the page
1801         // with one or two fingers.
1802         dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
1803
1804         // Disable single-fingered horizontal panning only if the target node is text.
1805         if (m_gestureTargetNode && m_gestureTargetNode->isTextNode())
1806             dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
1807         else
1808             dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
1809     }
1810
1811     GESTURECONFIG gc = { GID_PAN, dwPanWant, dwPanBlock };
1812     return SetGestureConfigPtr()(m_viewWindow, 0, 1, &gc, sizeof(GESTURECONFIG));
1813 }
1814
1815 bool WebView::gesture(WPARAM wParam, LPARAM lParam) 
1816 {
1817     // We want to bail out if we don't have either of these functions
1818     if (!GetGestureInfoPtr() || !CloseGestureInfoHandlePtr())
1819         return false;
1820
1821     HGESTUREINFO gestureHandle = reinterpret_cast<HGESTUREINFO>(lParam);
1822     
1823     GESTUREINFO gi = {0};
1824     gi.cbSize = sizeof(GESTUREINFO);
1825
1826     if (!GetGestureInfoPtr()(gestureHandle, reinterpret_cast<PGESTUREINFO>(&gi)))
1827         return false;
1828
1829     switch (gi.dwID) {
1830     case GID_BEGIN:
1831         m_lastPanX = gi.ptsLocation.x;
1832         m_lastPanY = gi.ptsLocation.y;
1833
1834         break;
1835     case GID_END:
1836         m_gestureTargetNode = nullptr;
1837         break;
1838     case GID_PAN: {
1839         if (gi.dwFlags & GF_BEGIN) {
1840             m_lastPanX = gi.ptsLocation.x;
1841             m_lastPanY = gi.ptsLocation.y;
1842         }
1843         // Where are the fingers currently?
1844         long currentX = gi.ptsLocation.x;
1845         long currentY = gi.ptsLocation.y;
1846         // How far did we pan in each direction?
1847         long deltaX = currentX - m_lastPanX;
1848         long deltaY = currentY - m_lastPanY;
1849         // Calculate the overpan for window bounce
1850         m_yOverpan -= m_lastPanY - currentY;
1851         m_xOverpan -= m_lastPanX - currentX;
1852         // Update our class variables with updated values
1853         m_lastPanX = currentX;
1854         m_lastPanY = currentY;
1855
1856         Frame* coreFrame = core(m_mainFrame);
1857         if (!coreFrame) {
1858             CloseGestureInfoHandlePtr()(gestureHandle);
1859             return false;
1860         }
1861
1862         ScrollableArea* scrolledArea = 0;
1863         float scaleFactor = deviceScaleFactor();
1864         IntSize logicalScrollDelta(-deltaX * scaleFactor, -deltaY * scaleFactor);
1865
1866         if (!m_gestureTargetNode || !m_gestureTargetNode->renderer()) {
1867             // We might directly hit the document without hitting any nodes
1868             coreFrame->view()->scrollBy(logicalScrollDelta);
1869             scrolledArea = coreFrame->view();
1870         } else
1871             m_gestureTargetNode->renderer()->enclosingLayer()->enclosingScrollableLayer()->scrollByRecursively(logicalScrollDelta, WebCore::RenderLayer::ScrollOffsetClamped, &scrolledArea);
1872
1873         if (!(UpdatePanningFeedbackPtr() && BeginPanningFeedbackPtr() && EndPanningFeedbackPtr())) {
1874             CloseGestureInfoHandlePtr()(gestureHandle);
1875             return true;
1876         }
1877
1878         // Handle overpanning
1879         if (gi.dwFlags & GF_BEGIN) {
1880             BeginPanningFeedbackPtr()(m_viewWindow);
1881             m_yOverpan = 0;
1882             m_xOverpan = 0;
1883         } else if (gi.dwFlags & GF_END) {
1884             EndPanningFeedbackPtr()(m_viewWindow, true);
1885             m_yOverpan = 0;
1886             m_xOverpan = 0;
1887         }
1888
1889         if (!scrolledArea) {
1890             CloseGestureInfoHandlePtr()(gestureHandle);
1891             return true;
1892         }
1893
1894         Scrollbar* vertScrollbar = scrolledArea->verticalScrollbar();
1895
1896         int ypan = 0;
1897         int xpan = 0;
1898
1899         if (vertScrollbar && (!vertScrollbar->currentPos() || vertScrollbar->currentPos() >= vertScrollbar->maximum()))
1900             ypan = m_yOverpan;
1901
1902         Scrollbar* horiScrollbar = scrolledArea->horizontalScrollbar();
1903
1904         if (horiScrollbar && (!horiScrollbar->currentPos() || horiScrollbar->currentPos() >= horiScrollbar->maximum()))
1905             xpan = m_xOverpan;
1906
1907         UpdatePanningFeedbackPtr()(m_viewWindow, xpan, ypan, gi.dwFlags & GF_INERTIA);
1908
1909         CloseGestureInfoHandlePtr()(gestureHandle);
1910         return true;
1911     }
1912     default:
1913         break;
1914     }
1915
1916     // If we get to this point, the gesture has not been handled. We forward
1917     // the call to DefWindowProc by returning false, and we don't need to 
1918     // to call CloseGestureInfoHandle. 
1919     // http://msdn.microsoft.com/en-us/library/dd353228(VS.85).aspx
1920     return false;
1921 }
1922
1923 bool WebView::mouseWheel(WPARAM wParam, LPARAM lParam, bool isMouseHWheel)
1924 {
1925     // Ctrl+Mouse wheel doesn't ever go into WebCore.  It is used to
1926     // zoom instead (Mac zooms the whole Desktop, but Windows browsers trigger their
1927     // own local zoom modes for Ctrl+wheel).
1928     if (wParam & MK_CONTROL) {
1929         short delta = short(HIWORD(wParam));
1930         if (delta < 0)
1931             makeTextSmaller(0);
1932         else
1933             makeTextLarger(0);
1934         return true;
1935     }
1936     
1937     // 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.
1938     HWND focusedWindow = GetFocus();
1939     if (focusedWindow && focusedWindow != m_viewWindow) {
1940         // 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).
1941         WCHAR className[256];
1942
1943         // Make sure truncation won't affect the comparison.
1944         ASSERT(WTF_ARRAY_LENGTH(className) > wcslen(PopupMenuWin::popupClassName()));
1945
1946         if (GetClassNameW(focusedWindow, className, WTF_ARRAY_LENGTH(className)) && !wcscmp(className, PopupMenuWin::popupClassName())) {
1947             // We don't let the WebView scroll here for two reasons - 1) To match Firefox behavior, 2) If we do scroll, we lose the
1948             // focus ring around the select menu.
1949             SetFocus(m_viewWindow);
1950             return true;
1951         }
1952     }
1953
1954     PlatformWheelEvent wheelEvent(m_viewWindow, wParam, lParam, isMouseHWheel);
1955     Frame* coreFrame = core(m_mainFrame);
1956     if (!coreFrame)
1957         return false;
1958
1959     return coreFrame->eventHandler().handleWheelEvent(wheelEvent);
1960 }
1961
1962 bool WebView::verticalScroll(WPARAM wParam, LPARAM /*lParam*/)
1963 {
1964     ScrollDirection direction;
1965     ScrollGranularity granularity;
1966     switch (LOWORD(wParam)) {
1967     case SB_LINEDOWN:
1968         granularity = ScrollByLine;
1969         direction = ScrollDown;
1970         break;
1971     case SB_LINEUP:
1972         granularity = ScrollByLine;
1973         direction = ScrollUp;
1974         break;
1975     case SB_PAGEDOWN:
1976         granularity = ScrollByDocument;
1977         direction = ScrollDown;
1978         break;
1979     case SB_PAGEUP:
1980         granularity = ScrollByDocument;
1981         direction = ScrollUp;
1982         break;
1983     default:
1984         return false;
1985         break;
1986     }
1987     
1988     Frame& frame = m_page->focusController().focusedOrMainFrame();
1989     return frame.eventHandler().scrollRecursively(direction, granularity);
1990 }
1991
1992 bool WebView::horizontalScroll(WPARAM wParam, LPARAM /*lParam*/)
1993 {
1994     ScrollDirection direction;
1995     ScrollGranularity granularity;
1996     switch (LOWORD(wParam)) {
1997     case SB_LINELEFT:
1998         granularity = ScrollByLine;
1999         direction = ScrollLeft;
2000         break;
2001     case SB_LINERIGHT:
2002         granularity = ScrollByLine;
2003         direction = ScrollRight;
2004         break;
2005     case SB_PAGELEFT:
2006         granularity = ScrollByDocument;
2007         direction = ScrollLeft;
2008         break;
2009     case SB_PAGERIGHT:
2010         granularity = ScrollByDocument;
2011         direction = ScrollRight;
2012         break;
2013     default:
2014         return false;
2015     }
2016
2017     Frame& frame = m_page->focusController().focusedOrMainFrame();
2018     return frame.eventHandler().scrollRecursively(direction, granularity);
2019 }
2020
2021
2022 bool WebView::execCommand(WPARAM wParam, LPARAM /*lParam*/)
2023 {
2024     Frame& frame = m_page->focusController().focusedOrMainFrame();
2025     switch (LOWORD(wParam)) {
2026         case SelectAll:
2027             return frame.editor().command("SelectAll").execute();
2028         case Undo:
2029             return frame.editor().command("Undo").execute();
2030         case Redo:
2031             return frame.editor().command("Redo").execute();
2032     }
2033     return false;
2034 }
2035
2036 bool WebView::keyUp(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
2037 {
2038     PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformEvent::KeyUp, systemKeyDown);
2039
2040     Frame& frame = m_page->focusController().focusedOrMainFrame();
2041     m_currentCharacterCode = 0;
2042
2043     return frame.eventHandler().keyEvent(keyEvent);
2044 }
2045
2046 static const unsigned CtrlKey = 1 << 0;
2047 static const unsigned AltKey = 1 << 1;
2048 static const unsigned ShiftKey = 1 << 2;
2049
2050
2051 struct KeyDownEntry {
2052     unsigned virtualKey;
2053     unsigned modifiers;
2054     const char* name;
2055 };
2056
2057 struct KeyPressEntry {
2058     unsigned charCode;
2059     unsigned modifiers;
2060     const char* name;
2061 };
2062
2063 static const KeyDownEntry keyDownEntries[] = {
2064     { VK_LEFT,   0,                  "MoveLeft"                                    },
2065     { VK_LEFT,   ShiftKey,           "MoveLeftAndModifySelection"                  },
2066     { VK_LEFT,   CtrlKey,            "MoveWordLeft"                                },
2067     { VK_LEFT,   CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection"              },
2068     { VK_RIGHT,  0,                  "MoveRight"                                   },
2069     { VK_RIGHT,  ShiftKey,           "MoveRightAndModifySelection"                 },
2070     { VK_RIGHT,  CtrlKey,            "MoveWordRight"                               },
2071     { VK_RIGHT,  CtrlKey | ShiftKey, "MoveWordRightAndModifySelection"             },
2072     { VK_UP,     0,                  "MoveUp"                                      },
2073     { VK_UP,     ShiftKey,           "MoveUpAndModifySelection"                    },
2074     { VK_PRIOR,  ShiftKey,           "MovePageUpAndModifySelection"                },
2075     { VK_DOWN,   0,                  "MoveDown"                                    },
2076     { VK_DOWN,   ShiftKey,           "MoveDownAndModifySelection"                  },
2077     { VK_NEXT,   ShiftKey,           "MovePageDownAndModifySelection"              },
2078     { VK_PRIOR,  0,                  "MovePageUp"                                  },
2079     { VK_NEXT,   0,                  "MovePageDown"                                },
2080     { VK_HOME,   0,                  "MoveToBeginningOfLine"                       },
2081     { VK_HOME,   ShiftKey,           "MoveToBeginningOfLineAndModifySelection"     },
2082     { VK_HOME,   CtrlKey,            "MoveToBeginningOfDocument"                   },
2083     { VK_HOME,   CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
2084
2085     { VK_END,    0,                  "MoveToEndOfLine"                             },
2086     { VK_END,    ShiftKey,           "MoveToEndOfLineAndModifySelection"           },
2087     { VK_END,    CtrlKey,            "MoveToEndOfDocument"                         },
2088     { VK_END,    CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection"       },
2089
2090     { VK_BACK,   0,                  "DeleteBackward"                              },
2091     { VK_BACK,   ShiftKey,           "DeleteBackward"                              },
2092     { VK_DELETE, 0,                  "DeleteForward"                               },
2093     { VK_BACK,   CtrlKey,            "DeleteWordBackward"                          },
2094     { VK_DELETE, CtrlKey,            "DeleteWordForward"                           },
2095     
2096     { 'B',       CtrlKey,            "ToggleBold"                                  },
2097     { 'I',       CtrlKey,            "ToggleItalic"                                },
2098
2099     { VK_ESCAPE, 0,                  "Cancel"                                      },
2100     { VK_OEM_PERIOD, CtrlKey,        "Cancel"                                      },
2101     { VK_TAB,    0,                  "InsertTab"                                   },
2102     { VK_TAB,    ShiftKey,           "InsertBacktab"                               },
2103     { VK_RETURN, 0,                  "InsertNewline"                               },
2104     { VK_RETURN, CtrlKey,            "InsertNewline"                               },
2105     { VK_RETURN, AltKey,             "InsertNewline"                               },
2106     { VK_RETURN, ShiftKey,           "InsertNewline"                               },
2107     { VK_RETURN, AltKey | ShiftKey,  "InsertNewline"                               },
2108
2109     // It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled
2110     // in the application or in WebKit. We chose WebKit.
2111     { 'C',       CtrlKey,            "Copy"                                        },
2112     { 'V',       CtrlKey,            "Paste"                                       },
2113     { 'X',       CtrlKey,            "Cut"                                         },
2114     { 'A',       CtrlKey,            "SelectAll"                                   },
2115     { VK_INSERT, CtrlKey,            "Copy"                                        },
2116     { VK_DELETE, ShiftKey,           "Cut"                                         },
2117     { VK_INSERT, ShiftKey,           "Paste"                                       },
2118     { 'Z',       CtrlKey,            "Undo"                                        },
2119     { 'Z',       CtrlKey | ShiftKey, "Redo"                                        },
2120 };
2121
2122 static const KeyPressEntry keyPressEntries[] = {
2123     { '\t',   0,                  "InsertTab"                                   },
2124     { '\t',   ShiftKey,           "InsertBacktab"                               },
2125     { '\r',   0,                  "InsertNewline"                               },
2126     { '\r',   CtrlKey,            "InsertNewline"                               },
2127     { '\r',   AltKey,             "InsertNewline"                               },
2128     { '\r',   ShiftKey,           "InsertNewline"                               },
2129     { '\r',   AltKey | ShiftKey,  "InsertNewline"                               },
2130 };
2131
2132 const char* WebView::interpretKeyEvent(const KeyboardEvent* evt)
2133 {
2134     ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
2135
2136     static HashMap<int, const char*>* keyDownCommandsMap = 0;
2137     static HashMap<int, const char*>* keyPressCommandsMap = 0;
2138
2139     if (!keyDownCommandsMap) {
2140         keyDownCommandsMap = new HashMap<int, const char*>;
2141         keyPressCommandsMap = new HashMap<int, const char*>;
2142
2143         for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyDownEntries); ++i)
2144             keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
2145
2146         for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyPressEntries); ++i)
2147             keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
2148     }
2149
2150     unsigned modifiers = 0;
2151     if (evt->shiftKey())
2152         modifiers |= ShiftKey;
2153     if (evt->altKey())
2154         modifiers |= AltKey;
2155     if (evt->ctrlKey())
2156         modifiers |= CtrlKey;
2157
2158     if (evt->type() == eventNames().keydownEvent) {
2159         int mapKey = modifiers << 16 | evt->keyCode();
2160         return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
2161     }
2162
2163     int mapKey = modifiers << 16 | evt->charCode();
2164     return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
2165 }
2166
2167 bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
2168 {
2169     Node* node = evt->target()->toNode();
2170     ASSERT(node);
2171     Frame* frame = node->document().frame();
2172     ASSERT(frame);
2173
2174     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2175     if (!keyEvent || keyEvent->isSystemKey())  // do not treat this as text input if it's a system key event
2176         return false;
2177
2178     Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
2179
2180     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2181         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2182         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2183         // (e.g. Tab that inserts a Tab character, or Enter).
2184         return !command.isTextInsertion() && command.execute(evt);
2185     }
2186
2187      if (command.execute(evt))
2188         return true;
2189
2190     // Don't insert null or control characters as they can result in unexpected behaviour
2191     if (evt->charCode() < ' ')
2192         return false;
2193
2194     return frame->editor().insertText(evt->keyEvent()->text(), evt);
2195 }
2196
2197 bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
2198 {
2199 #if ENABLE(FULLSCREEN_API)
2200     // Trap the ESC key when in full screen mode.
2201     if (virtualKeyCode == VK_ESCAPE && isFullScreen()) {
2202         m_fullscreenController->exitFullScreen();
2203         return false;
2204     }
2205 #endif
2206     Frame& frame = m_page->focusController().focusedOrMainFrame();
2207
2208     PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformEvent::RawKeyDown, systemKeyDown);
2209     bool handled = frame.eventHandler().keyEvent(keyEvent);
2210
2211     // These events cannot be canceled, and we have no default handling for them.
2212     // FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
2213     if (systemKeyDown && virtualKeyCode != VK_RETURN)
2214         return false;
2215
2216     if (handled) {
2217         // FIXME: remove WM_UNICHAR, too
2218         MSG msg;
2219         // WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
2220         if (!systemKeyDown)
2221             ::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
2222         return true;
2223     }
2224
2225     // We need to handle back/forward using either Ctrl+Left/Right Arrow keys.
2226     // FIXME: This logic should probably be in EventHandler::defaultArrowEventHandler().
2227     // FIXME: Should check that other modifiers aren't pressed.
2228     if (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey())
2229         return m_page->backForward().goForward();
2230     if (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey())
2231         return m_page->backForward().goBack();
2232
2233     // Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
2234     ScrollDirection direction;
2235     ScrollGranularity granularity;
2236     switch (virtualKeyCode) {
2237         case VK_LEFT:
2238             granularity = ScrollByLine;
2239             direction = ScrollLeft;
2240             break;
2241         case VK_RIGHT:
2242             granularity = ScrollByLine;
2243             direction = ScrollRight;
2244             break;
2245         case VK_UP:
2246             granularity = ScrollByLine;
2247             direction = ScrollUp;
2248             break;
2249         case VK_DOWN:
2250             granularity = ScrollByLine;
2251             direction = ScrollDown;
2252             break;
2253         case VK_HOME:
2254             granularity = ScrollByDocument;
2255             direction = ScrollUp;
2256             break;
2257         case VK_END:
2258             granularity = ScrollByDocument;
2259             direction = ScrollDown;
2260             break;
2261         case VK_PRIOR:
2262             granularity = ScrollByPage;
2263             direction = ScrollUp;
2264             break;
2265         case VK_NEXT:
2266             granularity = ScrollByPage;
2267             direction = ScrollDown;
2268             break;
2269         default:
2270             return false;
2271     }
2272
2273     return frame.eventHandler().scrollRecursively(direction, granularity);
2274 }
2275
2276 bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
2277 {
2278     Frame& frame = m_page->focusController().focusedOrMainFrame();
2279
2280     PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformEvent::Char, systemKeyDown);
2281     // IE does not dispatch keypress event for WM_SYSCHAR.
2282     if (systemKeyDown)
2283         return frame.eventHandler().handleAccessKey(keyEvent);
2284     return frame.eventHandler().keyEvent(keyEvent);
2285 }
2286
2287 void WebView::setIsBeingDestroyed()
2288 {
2289     m_isBeingDestroyed = true;
2290
2291     // Remove our this pointer from the window so we won't try to handle any more window messages.
2292     // See <http://webkit.org/b/55054>.
2293     ::SetWindowLongPtrW(m_viewWindow, 0, 0);
2294 }
2295
2296 void WebView::setShouldInvertColors(bool shouldInvertColors)
2297 {
2298     if (m_shouldInvertColors == shouldInvertColors)
2299         return;
2300
2301     m_shouldInvertColors = shouldInvertColors;
2302
2303 #if USE(CA)
2304     if (m_layerTreeHost)
2305         m_layerTreeHost->setShouldInvertColors(shouldInvertColors);
2306 #endif
2307
2308     RECT windowRect = {0};
2309     frameRect(&windowRect);
2310
2311     // repaint expects logical pixels, so rescale here.
2312     IntRect logicalRect(windowRect);
2313     logicalRect.scale(1.0f / deviceScaleFactor());
2314     repaint(logicalRect, true, true);
2315 }
2316
2317 bool WebView::registerWebViewWindowClass()
2318 {
2319     static bool haveRegisteredWindowClass = false;
2320     if (haveRegisteredWindowClass)
2321         return true;
2322
2323     haveRegisteredWindowClass = true;
2324
2325     WNDCLASSEX wcex;
2326
2327     wcex.cbSize = sizeof(WNDCLASSEX);
2328
2329     wcex.style          = CS_DBLCLKS;
2330     wcex.lpfnWndProc    = WebViewWndProc;
2331     wcex.cbClsExtra     = 0;
2332     wcex.cbWndExtra     = sizeof(WebView*);
2333     wcex.hInstance      = gInstance;
2334     wcex.hIcon          = 0;
2335     wcex.hCursor        = ::LoadCursor(0, IDC_ARROW);
2336     wcex.hbrBackground  = 0;
2337     wcex.lpszMenuName   = 0;
2338     wcex.lpszClassName  = kWebViewWindowClassName;
2339     wcex.hIconSm        = 0;
2340
2341     return !!RegisterClassEx(&wcex);
2342 }
2343
2344 static HWND findTopLevelParent(HWND window)
2345 {
2346     if (!window)
2347         return 0;
2348
2349     HWND current = window;
2350     for (HWND parent = GetParent(current); current; current = parent, parent = GetParent(parent))
2351         if (!parent || !(GetWindowLongPtr(current, GWL_STYLE) & (WS_POPUP | WS_CHILD)))
2352             return current;
2353     ASSERT_NOT_REACHED();
2354     return 0;
2355 }
2356
2357 LRESULT CALLBACK WebView::WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
2358 {
2359     LRESULT lResult = 0;
2360     LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
2361     WebView* webView = reinterpret_cast<WebView*>(longPtr);
2362     WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
2363     if (!mainFrameImpl)
2364         return DefWindowProc(hWnd, message, wParam, lParam);
2365
2366     // We shouldn't be trying to handle any window messages after WM_DESTROY.
2367     // See <http://webkit.org/b/55054>.
2368     ASSERT(!webView->isBeingDestroyed());
2369
2370     // hold a ref, since the WebView could go away in an event handler.
2371     COMPtr<WebView> protector(webView);
2372     ASSERT(webView);
2373
2374     // Windows Media Player has a modal message loop that will deliver messages
2375     // to us at inappropriate times and we will crash if we handle them when:
2376     // they are delivered. We repost paint messages so that we eventually get
2377     // a chance to paint once the modal loop has exited, but other messages
2378     // aren't safe to repost, so we just drop them.
2379     if (PluginView::isCallingPlugin()) {
2380         if (message == WM_PAINT)
2381             PostMessage(hWnd, message, wParam, lParam);
2382         return 0;
2383     }
2384
2385     bool handled = true;
2386
2387     switch (message) {
2388         case WM_PAINT: {
2389             webView->paint(0, 0);
2390             if (webView->usesLayeredWindow())
2391                 webView->performLayeredWindowUpdate();
2392             break;
2393         }
2394         case WM_ERASEBKGND:
2395             // Don't perform a background erase.
2396             handled = true;
2397             lResult = 1;
2398             break;
2399         case WM_PRINTCLIENT:
2400             webView->paint((HDC)wParam, lParam);
2401             break;
2402         case WM_DESTROY:
2403             webView->setIsBeingDestroyed();
2404             webView->close();
2405             break;
2406         case WM_GESTURENOTIFY:
2407             handled = webView->gestureNotify(wParam, lParam);
2408             break;
2409         case WM_GESTURE:
2410             handled = webView->gesture(wParam, lParam);
2411             break;
2412         case WM_MOUSEMOVE:
2413         case WM_LBUTTONDOWN:
2414         case WM_MBUTTONDOWN:
2415         case WM_RBUTTONDOWN:
2416         case WM_LBUTTONDBLCLK:
2417         case WM_MBUTTONDBLCLK:
2418         case WM_RBUTTONDBLCLK:
2419         case WM_LBUTTONUP:
2420         case WM_MBUTTONUP:
2421         case WM_RBUTTONUP:
2422         case WM_MOUSELEAVE:
2423         case WM_CANCELMODE:
2424             if (Frame* coreFrame = core(mainFrameImpl))
2425                 if (coreFrame->view()->didFirstLayout())
2426                     handled = webView->handleMouseEvent(message, wParam, lParam);
2427             break;
2428         case WM_MOUSEWHEEL:
2429         case WM_VISTA_MOUSEHWHEEL:
2430             if (Frame* coreFrame = core(mainFrameImpl))
2431                 if (coreFrame->view()->didFirstLayout())
2432                     handled = webView->mouseWheel(wParam, lParam, message == WM_VISTA_MOUSEHWHEEL);
2433             break;
2434         case WM_SYSKEYDOWN:
2435             handled = webView->keyDown(wParam, lParam, true);
2436             break;
2437         case WM_KEYDOWN:
2438             handled = webView->keyDown(wParam, lParam);
2439             break;
2440         case WM_SYSKEYUP:
2441             handled = webView->keyUp(wParam, lParam, true);
2442             break;
2443         case WM_KEYUP:
2444             handled = webView->keyUp(wParam, lParam);
2445             break;
2446         case WM_SYSCHAR:
2447             handled = webView->keyPress(wParam, lParam, true);
2448             break;
2449         case WM_CHAR:
2450             handled = webView->keyPress(wParam, lParam);
2451             break;
2452         // FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
2453         case WM_SIZE:
2454             if (lParam != 0)
2455                 webView->sizeChanged(IntSize(LOWORD(lParam), HIWORD(lParam)));
2456             break;
2457         case WM_DPICHANGED:
2458             webView->dpiChanged(LOWORD(wParam), IntSize(LOWORD(lParam), HIWORD(lParam)));
2459             break;
2460         case WM_SHOWWINDOW:
2461             lResult = DefWindowProc(hWnd, message, wParam, lParam);
2462             if (wParam == 0) {
2463                 // The window is being hidden (e.g., because we switched tabs).
2464                 // Null out our backing store.
2465                 webView->deleteBackingStore();
2466             }
2467             break;
2468         case WM_SETFOCUS: {
2469             COMPtr<IWebUIDelegate> uiDelegate;
2470             COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2471             if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2472                 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2473                 uiDelegatePrivate->webViewReceivedFocus(webView);
2474
2475             FocusController& focusController = webView->page()->focusController();
2476             if (Frame* frame = focusController.focusedFrame()) {
2477                 // Send focus events unless the previously focused window is a
2478                 // child of ours (for example a plugin).
2479                 if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
2480                     focusController.setFocused(true);
2481             } else
2482                 focusController.setFocused(true);
2483             break;
2484         }
2485         case WM_KILLFOCUS: {
2486             COMPtr<IWebUIDelegate> uiDelegate;
2487             COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2488             HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
2489             if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2490                 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2491                 uiDelegatePrivate->webViewLostFocus(webView, newFocusWnd);
2492
2493             FocusController& focusController = webView->page()->focusController();
2494             Frame& frame = focusController.focusedOrMainFrame();
2495             webView->resetIME(&frame);
2496             // Send blur events unless we're losing focus to a child of ours.
2497             if (!IsChild(hWnd, newFocusWnd))
2498                 focusController.setFocused(false);
2499
2500             // If we are pan-scrolling when we lose focus, stop the pan scrolling.
2501             frame.eventHandler().stopAutoscrollTimer();
2502
2503             break;
2504         }
2505         case WM_WINDOWPOSCHANGED:
2506             if (reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW)
2507                 webView->updateActiveStateSoon();
2508             handled = false;
2509             break;
2510         case WM_CUT:
2511             webView->cut(0);
2512             break;
2513         case WM_COPY:
2514             webView->copy(0);
2515             break;
2516         case WM_PASTE:
2517             webView->paste(0);
2518             break;
2519         case WM_CLEAR:
2520             webView->delete_(0);
2521             break;
2522         case WM_COMMAND:
2523             if (HIWORD(wParam))
2524                 handled = webView->execCommand(wParam, lParam);
2525             break;
2526         case WM_MENUCOMMAND:
2527             webView->onMenuCommand(wParam, lParam);
2528             break;
2529         case WM_CONTEXTMENU:
2530             handled = webView->handleContextMenuEvent(wParam, lParam);
2531             break;
2532         case WM_INITMENUPOPUP:
2533             handled = webView->onInitMenuPopup(wParam, lParam);
2534             break;
2535         case WM_MEASUREITEM:
2536             handled = webView->onMeasureItem(wParam, lParam);
2537             break;
2538         case WM_DRAWITEM:
2539             handled = webView->onDrawItem(wParam, lParam);
2540             break;
2541         case WM_UNINITMENUPOPUP:
2542             handled = webView->onUninitMenuPopup(wParam, lParam);
2543             break;
2544         case WM_XP_THEMECHANGED:
2545             if (Frame* coreFrame = core(mainFrameImpl)) {
2546                 webView->deleteBackingStore();
2547                 coreFrame->page()->theme().themeChanged();
2548                 ScrollbarTheme::theme().themeChanged();
2549                 RECT windowRect;
2550                 ::GetClientRect(hWnd, &windowRect);
2551                 ::InvalidateRect(hWnd, &windowRect, false);
2552 #if USE(CA)
2553                 if (webView->isAcceleratedCompositing())
2554                     webView->m_backingLayer->setNeedsDisplay();
2555 #endif
2556            }
2557             break;
2558         case WM_MOUSEACTIVATE:
2559             webView->setMouseActivated(true);
2560             handled = false;
2561             break;
2562         case WM_GETDLGCODE: {
2563             COMPtr<IWebUIDelegate> uiDelegate;
2564             COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2565             LONG_PTR dlgCode = 0;
2566             UINT keyCode = 0;
2567             if (lParam) {
2568                 LPMSG lpMsg = (LPMSG)lParam;
2569                 if (lpMsg->message == WM_KEYDOWN)
2570                     keyCode = (UINT) lpMsg->wParam;
2571             }
2572             if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2573                 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate
2574                 && SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
2575                 return dlgCode;
2576             handled = false;
2577             break;
2578         }
2579         case WM_GETOBJECT:
2580             handled = webView->onGetObject(wParam, lParam, lResult);
2581             break;
2582         case WM_IME_STARTCOMPOSITION:
2583             handled = webView->onIMEStartComposition();
2584             break;
2585         case WM_IME_REQUEST:
2586             lResult = webView->onIMERequest(wParam, lParam);
2587             break;
2588         case WM_IME_COMPOSITION:
2589             handled = webView->onIMEComposition(lParam);
2590             break;
2591         case WM_IME_ENDCOMPOSITION:
2592             handled = webView->onIMEEndComposition();
2593             break;
2594         case WM_IME_CHAR:
2595             handled = webView->onIMEChar(wParam, lParam);
2596             break;
2597         case WM_IME_NOTIFY:
2598             handled = webView->onIMENotify(wParam, lParam, &lResult);
2599             break;
2600         case WM_IME_SELECT:
2601             handled = webView->onIMESelect(wParam, lParam);
2602             break;
2603         case WM_IME_SETCONTEXT:
2604             handled = webView->onIMESetContext(wParam, lParam);
2605             break;
2606         case WM_TIMER:
2607             switch (wParam) {
2608                 case UpdateActiveStateTimer:
2609                     KillTimer(hWnd, UpdateActiveStateTimer);
2610                     webView->updateActiveState();
2611                     break;
2612                 case DeleteBackingStoreTimer:
2613                     webView->deleteBackingStore();
2614                     break;
2615             }
2616             break;
2617         case WM_SETCURSOR:
2618             handled = ::SetCursor(webView->m_lastSetCursor);
2619             break;
2620         case WM_VSCROLL:
2621             handled = webView->verticalScroll(wParam, lParam);
2622             break;
2623         case WM_HSCROLL:
2624             handled = webView->horizontalScroll(wParam, lParam);
2625             break;
2626         default:
2627             handled = false;
2628             break;
2629     }
2630
2631     webView->updateWindowIfNeeded(hWnd, message);
2632
2633     if (!handled)
2634         lResult = DefWindowProc(hWnd, message, wParam, lParam);
2635     
2636     // Let the client know whether we consider this message handled.
2637     return (message == WM_KEYDOWN || message == WM_SYSKEYDOWN || message == WM_KEYUP || message == WM_SYSKEYUP) ? !handled : lResult;
2638 }
2639
2640 void WebView::updateWindowIfNeeded(HWND hWnd, UINT message)
2641 {
2642     if (!needsDisplay())
2643         return;
2644
2645     // Care should be taken when updating the window from the window procedure.
2646     // Updating the window in response to e.g. WM_PARENTNOTIFY may cause reentrancy problems,
2647     // because WM_PARENTNOTIFY is sent synchronously to the parent window when e.g. DestroyWindow() is called.
2648
2649     switch (message) {
2650     case WM_PAINT:
2651     case WM_PARENTNOTIFY:
2652         return;
2653     }
2654
2655     ::UpdateWindow(hWnd);
2656 }
2657
2658 bool WebView::developerExtrasEnabled() const
2659 {
2660     if (m_preferences->developerExtrasDisabledByOverride())
2661         return false;
2662
2663 #ifdef NDEBUG
2664     BOOL enabled;
2665     return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
2666 #else
2667     return true;
2668 #endif
2669 }
2670
2671 static String webKitVersionString()
2672 {
2673 #if !USE(CAIRO)
2674     LPWSTR buildNumberStringPtr;
2675     if (::LoadStringW(gInstance, BUILD_NUMBER, reinterpret_cast<LPWSTR>(&buildNumberStringPtr), 0) && buildNumberStringPtr)
2676         return buildNumberStringPtr;
2677 #endif
2678     return String::format("%d.%d", WEBKIT_MAJOR_VERSION, WEBKIT_MINOR_VERSION);
2679 }
2680
2681 const String& WebView::userAgentForKURL(const URL&)
2682 {
2683     if (m_userAgentOverridden)
2684         return m_userAgentCustom;
2685
2686     if (!m_userAgentStandard.length())
2687         m_userAgentStandard = WebView::standardUserAgentWithApplicationName(m_applicationName);
2688     return m_userAgentStandard;
2689 }
2690
2691 // IUnknown -------------------------------------------------------------------
2692
2693 HRESULT WebView::QueryInterface(_In_ REFIID riid, _COM_Outptr_ void** ppvObject)
2694 {
2695     if (!ppvObject)
2696         return E_POINTER;
2697     *ppvObject = nullptr;
2698     if (IsEqualGUID(riid, CLSID_WebView))
2699         *ppvObject = this;
2700     else if (IsEqualGUID(riid, IID_IUnknown))
2701         *ppvObject = static_cast<IWebView*>(this);
2702     else if (IsEqualGUID(riid, IID_IWebView))
2703         *ppvObject = static_cast<IWebView*>(this);
2704     else if (IsEqualGUID(riid, IID_IWebViewPrivate))
2705         *ppvObject = static_cast<IWebViewPrivate*>(this);
2706     else if (IsEqualGUID(riid, IID_IWebViewPrivate2))
2707         *ppvObject = static_cast<IWebViewPrivate2*>(this);
2708     else if (IsEqualGUID(riid, IID_IWebViewPrivate3))
2709         *ppvObject = static_cast<IWebViewPrivate3*>(this);
2710     else if (IsEqualGUID(riid, IID_IWebIBActions))
2711         *ppvObject = static_cast<IWebIBActions*>(this);
2712     else if (IsEqualGUID(riid, IID_IWebViewCSS))
2713         *ppvObject = static_cast<IWebViewCSS*>(this);
2714     else if (IsEqualGUID(riid, IID_IWebViewEditing))
2715         *ppvObject = static_cast<IWebViewEditing*>(this);
2716     else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
2717         *ppvObject = static_cast<IWebViewUndoableEditing*>(this);
2718     else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
2719         *ppvObject = static_cast<IWebViewEditingActions*>(this);
2720     else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
2721         *ppvObject = static_cast<IWebNotificationObserver*>(this);
2722     else if (IsEqualGUID(riid, IID_IDropTarget))
2723         *ppvObject = static_cast<IDropTarget*>(this);
2724     else
2725         return E_NOINTERFACE;
2726
2727     AddRef();
2728     return S_OK;
2729 }
2730
2731 ULONG WebView::AddRef()
2732 {
2733     ASSERT(!m_deletionHasBegun);
2734     return ++m_refCount;
2735 }
2736
2737 ULONG WebView::Release()
2738 {
2739     ASSERT(!m_deletionHasBegun);
2740
2741     if (m_refCount == 1) {
2742         // Call close() now so that clients don't have to. (It's harmless to call close() multiple
2743         // times.) We do this here instead of in our destructor because close() can cause AddRef()
2744         // and Release() to be called, and if that happened in our destructor we would be destroyed
2745         // more than once.
2746         close();
2747     }
2748
2749     ULONG newRef = --m_refCount;
2750     if (!newRef) {
2751 #if !ASSERT_DISABLED
2752         m_deletionHasBegun = true;
2753 #endif
2754         delete(this);
2755     }
2756
2757     return newRef;
2758 }
2759
2760 // IWebView --------------------------------------------------------------------
2761
2762 HRESULT WebView::canShowMIMEType(_In_ BSTR mimeType, _Out_ BOOL* canShow)
2763 {
2764     if (!canShow)
2765         return E_POINTER;
2766
2767     *canShow = canShowMIMEType(toString(mimeType));
2768
2769     return S_OK;
2770 }
2771
2772 bool WebView::canShowMIMEType(const String& mimeType)
2773 {
2774     Frame* coreFrame = core(m_mainFrame);
2775     bool allowPlugins = coreFrame && coreFrame->loader().subframeLoader().allowPlugins();
2776
2777     bool canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeType)
2778         || MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType)
2779         || MIMETypeRegistry::isSupportedMediaMIMEType(mimeType);
2780
2781     if (!canShow && m_page) {
2782         canShow = (m_page->pluginData().supportsWebVisibleMimeType(mimeType, PluginData::AllPlugins) && allowPlugins)
2783             || m_page->pluginData().supportsWebVisibleMimeType(mimeType, PluginData::OnlyApplicationPlugins);
2784     }
2785
2786     if (!canShow)
2787         canShow = shouldUseEmbeddedView(mimeType);
2788
2789     return canShow;
2790 }
2791
2792 HRESULT WebView::canShowMIMETypeAsHTML(_In_ BSTR mimeType, _Out_ BOOL* canShow)
2793 {
2794     if (!canShow)
2795         return E_POINTER;
2796
2797     *canShow = canShowMIMETypeAsHTML(toString(mimeType));
2798
2799     return S_OK;
2800 }
2801
2802 bool WebView::canShowMIMETypeAsHTML(const String& /*mimeType*/)
2803 {
2804     // FIXME
2805     notImplemented();
2806     return true;
2807 }
2808
2809 HRESULT WebView::MIMETypesShownAsHTML(_COM_Outptr_opt_ IEnumVARIANT** enumVariant)
2810 {
2811     ASSERT_NOT_REACHED();
2812     if (!enumVariant)
2813         return E_POINTER;
2814     *enumVariant = nullptr;
2815     return E_NOTIMPL;
2816 }
2817
2818 HRESULT WebView::setMIMETypesShownAsHTML(__inout_ecount_full(cMimeTypes) BSTR* mimeTypes, int cMimeTypes)
2819 {
2820     ASSERT_NOT_REACHED();
2821     return E_NOTIMPL;
2822 }
2823
2824 HRESULT WebView::URLFromPasteboard(_In_opt_ IDataObject* /*pasteboard*/, _Deref_opt_out_ BSTR* /*url*/)
2825 {
2826     ASSERT_NOT_REACHED();
2827     return E_NOTIMPL;
2828 }
2829
2830 HRESULT WebView::URLTitleFromPasteboard(_In_opt_ IDataObject* /*pasteboard*/, _Deref_opt_out_ BSTR* /*urlTitle*/)
2831 {
2832     ASSERT_NOT_REACHED();
2833     return E_NOTIMPL;
2834 }
2835
2836 static void WebKitSetApplicationCachePathIfNecessary()
2837 {
2838     static bool initialized = false;
2839     if (initialized)
2840         return;
2841
2842     String path = localUserSpecificStorageDirectory();
2843
2844 #if USE(CF)
2845     RetainPtr<CFPropertyListRef> cacheDirectoryPreference = adoptCF(CFPreferencesCopyAppValue(WebKitLocalCacheDefaultsKey, kCFPreferencesCurrentApplication));
2846     if (cacheDirectoryPreference && (CFStringGetTypeID() == CFGetTypeID(cacheDirectoryPreference.get())))
2847         path = static_cast<CFStringRef>(cacheDirectoryPreference.get());
2848 #endif
2849
2850     if (!path.isNull())
2851         ApplicationCacheStorage::singleton().setCacheDirectory(path);
2852
2853     initialized = true;
2854 }
2855
2856 bool WebView::shouldInitializeTrackPointHack()
2857 {
2858     static bool shouldCreateScrollbars;
2859     static bool hasRunTrackPointCheck;
2860
2861     if (hasRunTrackPointCheck)
2862         return shouldCreateScrollbars;
2863
2864     hasRunTrackPointCheck = true;
2865     const WCHAR trackPointKeys[][50] = { L"Software\\Lenovo\\TrackPoint",
2866         L"Software\\Lenovo\\UltraNav",
2867         L"Software\\Alps\\Apoint\\TrackPoint",
2868         L"Software\\Synaptics\\SynTPEnh\\UltraNavUSB",
2869         L"Software\\Synaptics\\SynTPEnh\\UltraNavPS2" };
2870
2871     for (int i = 0; i < 5; ++i) {
2872         HKEY trackPointKey = nullptr;
2873         LSTATUS readKeyResult = ::RegOpenKeyExW(HKEY_CURRENT_USER, trackPointKeys[i], 0, KEY_READ, &trackPointKey);
2874         ::RegCloseKey(trackPointKey);
2875         if (readKeyResult == ERROR_SUCCESS) {
2876             shouldCreateScrollbars = true;
2877             return shouldCreateScrollbars;
2878         }
2879     }
2880
2881     return shouldCreateScrollbars;
2882 }
2883
2884 HRESULT WebView::initWithFrame(RECT frame, _In_ BSTR frameName, _In_ BSTR groupName)
2885 {
2886     HRESULT hr = S_OK;
2887
2888     if (m_viewWindow)
2889         return E_UNEXPECTED;
2890
2891     registerWebViewWindowClass();
2892
2893     m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
2894         frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow ? m_hostWindow : HWND_MESSAGE, 0, gInstance, 0);
2895     ASSERT(::IsWindow(m_viewWindow));
2896
2897     if (shouldInitializeTrackPointHack()) {
2898         // If we detected a registry key belonging to a TrackPoint driver, then create fake trackpoint
2899         // scrollbars, so the WebView will receive WM_VSCROLL and WM_HSCROLL messages. We create one
2900         // vertical scrollbar and one horizontal to allow for receiving both types of messages.
2901         ::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTHSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_HORZ, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
2902         ::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTVSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_VERT, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
2903     }
2904
2905     hr = registerDragDrop();
2906     if (FAILED(hr))
2907         return hr;
2908
2909     WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
2910     sharedPreferences->willAddToWebView();
2911     m_preferences = sharedPreferences;
2912
2913     static bool didOneTimeInitialization;
2914     if (!didOneTimeInitialization) {
2915 #if !LOG_DISABLED
2916         initializeLoggingChannelsIfNecessary();
2917 #endif // !LOG_DISABLED
2918
2919         // Initialize our platform strategies first before invoking the rest
2920         // of the initialization code which may depend on the strategies.
2921         WebPlatformStrategies::initialize();
2922
2923         WebKitInitializeWebDatabasesIfNecessary();
2924         WebKitSetApplicationCachePathIfNecessary();
2925
2926         MemoryPressureHandler::singleton().install();
2927
2928         didOneTimeInitialization = true;
2929      }
2930
2931     BOOL useHighResolutionTimer;
2932     if (SUCCEEDED(m_preferences->shouldUseHighResolutionTimers(&useHighResolutionTimer)))
2933         Settings::setShouldUseHighResolutionTimers(useHighResolutionTimer);
2934
2935     m_inspectorClient = new WebInspectorClient(this);
2936
2937     PageConfiguration configuration;
2938     configuration.chromeClient = new WebChromeClient(this);
2939     configuration.contextMenuClient = new WebContextMenuClient(this);
2940     configuration.editorClient = new WebEditorClient(this);
2941     configuration.dragClient = new WebDragClient(this);
2942     configuration.inspectorClient = m_inspectorClient;
2943     configuration.loaderClientForMainFrame = new WebFrameLoaderClient;
2944     configuration.databaseProvider = &WebDatabaseProvider::singleton();
2945     configuration.storageNamespaceProvider = &m_webViewGroup->storageNamespaceProvider();
2946     configuration.progressTrackerClient = static_cast<WebFrameLoaderClient*>(configuration.loaderClientForMainFrame);
2947     configuration.userContentController = &m_webViewGroup->userContentController();
2948     configuration.visitedLinkStore = &m_webViewGroup->visitedLinkStore();
2949
2950     m_page = new Page(configuration);
2951     provideGeolocationTo(m_page, new WebGeolocationClient(this));
2952
2953     unsigned layoutMilestones = DidFirstLayout | DidFirstVisuallyNonEmptyLayout;
2954     m_page->addLayoutMilestones(static_cast<LayoutMilestones>(layoutMilestones));
2955
2956
2957     if (m_uiDelegate) {
2958         BString path;
2959         if (SUCCEEDED(m_uiDelegate->ftpDirectoryTemplatePath(this, &path)))
2960             m_page->settings().setFTPDirectoryTemplatePath(toString(path));
2961     }
2962
2963     WebFrame* webFrame = WebFrame::createInstance();
2964     webFrame->initWithWebView(this, m_page);
2965     static_cast<WebFrameLoaderClient&>(m_page->mainFrame().loader().client()).setWebFrame(webFrame);
2966     m_mainFrame = webFrame;
2967     webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
2968
2969     m_page->mainFrame().tree().setName(toString(frameName));
2970     m_page->mainFrame().init();
2971     setGroupName(groupName);
2972
2973     addToAllWebViewsSet();
2974
2975     #pragma warning(suppress: 4244)
2976     SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
2977     ShowWindow(m_viewWindow, SW_SHOW);
2978
2979     initializeToolTipWindow();
2980     windowAncestryDidChange();
2981
2982     IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
2983     notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2984     m_preferences->postPreferencesChangesNotification();
2985
2986     m_page->setDeviceScaleFactor(deviceScaleFactor());
2987
2988     setSmartInsertDeleteEnabled(TRUE);
2989     return hr;
2990 }
2991
2992 static bool initCommonControls()
2993 {
2994     static bool haveInitialized = false;
2995     if (haveInitialized)
2996         return true;
2997
2998     INITCOMMONCONTROLSEX init;
2999     init.dwSize = sizeof(init);
3000     init.dwICC = ICC_TREEVIEW_CLASSES;
3001     haveInitialized = !!::InitCommonControlsEx(&init);
3002     return haveInitialized;
3003 }
3004
3005 void WebView::initializeToolTipWindow()
3006 {
3007     if (!initCommonControls())
3008         return;
3009
3010     m_toolTipHwnd = CreateWindowEx(WS_EX_TRANSPARENT, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
3011                                    CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
3012                                    m_viewWindow, 0, 0, 0);
3013     if (!m_toolTipHwnd)
3014         return;
3015
3016     TOOLINFO info = {0};
3017     info.cbSize = sizeof(info);
3018     info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
3019     info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
3020
3021     ::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
3022     ::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, clampTo<int>(maxToolTipWidth * deviceScaleFactor()));
3023
3024     ::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
3025 }
3026
3027 void WebView::setToolTip(const String& toolTip)
3028 {
3029     if (!m_toolTipHwnd)
3030         return;
3031
3032     if (toolTip == m_toolTip)
3033         return;
3034
3035     m_toolTip = toolTip;
3036
3037     if (!m_toolTip.isEmpty()) {
3038         TOOLINFO info = {0};
3039         info.cbSize = sizeof(info);
3040         info.uFlags = TTF_IDISHWND;
3041         info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
3042         Vector<UChar> toolTipCharacters = m_toolTip.charactersWithNullTermination(); // Retain buffer long enough to make the SendMessage call
3043         info.lpszText = const_cast<UChar*>(toolTipCharacters.data());
3044         ::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
3045     }
3046
3047     ::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
3048 }
3049
3050 HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
3051 {
3052     COMPtr<IPropertyBag> propertyBag;
3053     HRESULT hr = notification->userInfo(&propertyBag);
3054     if (FAILED(hr))
3055         return hr;
3056     if (!propertyBag)
3057         return E_FAIL;
3058
3059     COMVariant iconUserInfoURL;
3060     hr = propertyBag->Read(WebIconDatabase::iconDatabaseNotificationUserInfoURLKey(), &iconUserInfoURL, nullptr);
3061     if (FAILED(hr))
3062         return hr;
3063
3064     if (iconUserInfoURL.variantType() != VT_BSTR)
3065         return E_FAIL;
3066
3067     String mainFrameURL;
3068     if (m_mainFrame)
3069         mainFrameURL = m_mainFrame->url().string();
3070
3071     if (!mainFrameURL.isEmpty() && mainFrameURL == toString(V_BSTR(&iconUserInfoURL)))
3072         dispatchDidReceiveIconFromWebFrame(m_mainFrame);
3073
3074     return hr;
3075 }
3076
3077 void WebView::registerForIconNotification(bool listen)
3078 {
3079     IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
3080     if (listen)
3081         nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
3082     else
3083         nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
3084 }
3085
3086 void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
3087 {
3088     registerForIconNotification(false);
3089
3090     if (m_frameLoadDelegate) {
3091         String str = frame->url().string();
3092
3093         IntSize sz(16, 16);
3094
3095         BitmapInfo bmInfo = BitmapInfo::create(sz);
3096
3097         HBITMAP hBitmap = nullptr;
3098
3099         Image* icon = iconDatabase().synchronousIconForPageURL(str, sz);
3100
3101         if (icon && icon->width()) {
3102             HWndDC dc(0);
3103             hBitmap = CreateDIBSection(dc, &bmInfo, DIB_RGB_COLORS, 0, 0, 0);
3104             icon->getHBITMAPOfSize(hBitmap, &sz);
3105         }
3106
3107         HRESULT hr = m_frameLoadDelegate->didReceiveIcon(this, hBitmap, frame);
3108         if ((hr == E_NOTIMPL) && hBitmap)
3109             DeleteObject(hBitmap);
3110     }
3111 }
3112
3113 HRESULT WebView::setAccessibilityDelegate(_In_opt_ IAccessibilityDelegate* d)
3114 {
3115     m_accessibilityDelegate = d;
3116     return S_OK;
3117 }
3118
3119 HRESULT WebView::accessibilityDelegate(_COM_Outptr_opt_ IAccessibilityDelegate** d)
3120 {
3121     if (!d)
3122         return E_POINTER;
3123     *d = nullptr;
3124     if (!m_accessibilityDelegate)
3125         return E_POINTER;
3126
3127     return m_accessibilityDelegate.copyRefTo(d);
3128 }
3129
3130 HRESULT WebView::setUIDelegate(_In_opt_ IWebUIDelegate* d)
3131 {
3132     m_uiDelegate = d;
3133
3134     if (m_uiDelegatePrivate)
3135         m_uiDelegatePrivate = 0;
3136
3137     if (d) {
3138         if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
3139             m_uiDelegatePrivate = 0;
3140     }
3141
3142     return S_OK;
3143 }
3144
3145 HRESULT WebView::uiDelegate(_COM_Outptr_opt_ IWebUIDelegate** d)
3146 {
3147     if (!d)
3148         return E_POINTER;
3149     *d = nullptr;
3150     if (!m_uiDelegate)
3151         return E_FAIL;
3152
3153     return m_uiDelegate.copyRefTo(d);
3154 }
3155
3156 HRESULT WebView::setResourceLoadDelegate(_In_opt_ IWebResourceLoadDelegate* d)
3157 {
3158     m_resourceLoadDelegate = d;
3159     return S_OK;
3160 }
3161
3162 HRESULT WebView::resourceLoadDelegate(_COM_Outptr_opt_ IWebResourceLoadDelegate** d)
3163 {
3164     if (!d)
3165         return E_POINTER;
3166     *d = nullptr;
3167     if (!m_resourceLoadDelegate)
3168         return E_FAIL;
3169
3170     return m_resourceLoadDelegate.copyRefTo(d);
3171 }
3172
3173 HRESULT WebView::setDownloadDelegate(_In_opt_ IWebDownloadDelegate* d)
3174 {
3175     m_downloadDelegate = d;
3176     return S_OK;
3177 }
3178
3179 HRESULT WebView::downloadDelegate(_COM_Outptr_opt_ IWebDownloadDelegate** d)
3180 {
3181     if (!d)
3182         return E_POINTER;
3183     *d = nullptr;
3184     if (!m_downloadDelegate)
3185         return E_FAIL;
3186
3187     return m_downloadDelegate.copyRefTo(d);
3188 }
3189
3190 HRESULT WebView::setFrameLoadDelegate(_In_opt_ IWebFrameLoadDelegate* d)
3191 {
3192     m_frameLoadDelegate = d;
3193     return S_OK;
3194 }
3195
3196 HRESULT WebView::frameLoadDelegate(_COM_Outptr_opt_ IWebFrameLoadDelegate** d)
3197 {
3198     if (!d)
3199         return E_POINTER;
3200     *d = nullptr;
3201     if (!m_frameLoadDelegate)
3202         return E_FAIL;
3203
3204     return m_frameLoadDelegate.copyRefTo(d);
3205 }
3206
3207 HRESULT WebView::setPolicyDelegate(_In_opt_ IWebPolicyDelegate* d)
3208 {
3209     m_policyDelegate = d;
3210     return S_OK;
3211 }
3212
3213 HRESULT WebView::policyDelegate(_COM_Outptr_opt_ IWebPolicyDelegate** d)
3214 {
3215     if (!d)
3216         return E_POINTER;
3217     *d = nullptr;
3218     if (!m_policyDelegate)
3219         return E_FAIL;
3220
3221     return m_policyDelegate.copyRefTo(d);
3222 }
3223
3224 HRESULT WebView::mainFrame(_COM_Outptr_opt_ IWebFrame** frame)
3225 {
3226     if (!frame) {
3227         ASSERT_NOT_REACHED();
3228         return E_POINTER;
3229     }
3230
3231     *frame = m_mainFrame;
3232     if (!m_mainFrame)
3233         return E_UNEXPECTED;
3234
3235     m_mainFrame->AddRef();
3236     return S_OK;
3237 }
3238
3239 HRESULT WebView::focusedFrame(_COM_Outptr_opt_ IWebFrame** frame)
3240 {
3241     if (!frame) {
3242         ASSERT_NOT_REACHED();
3243         return E_POINTER;
3244     }
3245
3246     *frame = nullptr;
3247     Frame* f = m_page->focusController().focusedFrame();
3248     if (!f)
3249         return E_FAIL;
3250
3251     WebFrame* webFrame = kit(f);
3252     if (!webFrame)
3253         return E_UNEXPECTED;
3254
3255     return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
3256 }
3257
3258 HRESULT WebView::backForwardList(_COM_Outptr_opt_ IWebBackForwardList** list)
3259 {
3260     if (!list) {
3261         ASSERT_NOT_REACHED();
3262         return E_POINTER;
3263     }
3264     *list = nullptr;
3265     if (!m_useBackForwardList)
3266         return E_FAIL;
3267  
3268     *list = WebBackForwardList::createInstance(static_cast<WebCore::BackForwardList*>(m_page->backForward().client()));
3269
3270     return S_OK;
3271 }
3272
3273 HRESULT WebView::setMaintainsBackForwardList(BOOL flag)
3274 {
3275     m_useBackForwardList = !!flag;
3276     return S_OK;
3277 }
3278
3279 HRESULT WebView::goBack(_Out_ BOOL* succeeded)
3280 {
3281     if (!succeeded)
3282         return E_POINTER;
3283
3284     *succeeded = m_page->backForward().goBack();
3285     return S_OK;
3286 }
3287
3288 HRESULT WebView::goForward(_Out_ BOOL* succeeded)
3289 {
3290     if (!succeeded)
3291         return E_POINTER;
3292
3293     *succeeded = m_page->backForward().goForward();
3294     return S_OK;
3295 }
3296
3297 HRESULT WebView::goToBackForwardItem(_In_opt_ IWebHistoryItem* item, _Out_ BOOL* succeeded)
3298 {
3299     if (!item)
3300         return E_FAIL;
3301
3302     if (!succeeded)
3303         return E_POINTER;
3304
3305     *succeeded = FALSE;
3306
3307     COMPtr<WebHistoryItem> webHistoryItem;
3308     HRESULT hr = item->QueryInterface(&webHistoryItem);
3309     if (FAILED(hr))
3310         return hr;
3311
3312     m_page->goToItem(*webHistoryItem->historyItem(), FrameLoadType::IndexedBackForward);
3313     *succeeded = TRUE;
3314
3315     return S_OK;
3316 }
3317
3318 HRESULT WebView::setTextSizeMultiplier(float multiplier)
3319 {
3320     if (!m_mainFrame)
3321         return E_UNEXPECTED;
3322     setZoomMultiplier(multiplier, true);
3323     return S_OK;
3324 }
3325
3326 HRESULT WebView::setPageSizeMultiplier(float multiplier)
3327 {
3328     if (!m_mainFrame)
3329         return E_UNEXPECTED;
3330     setZoomMultiplier(multiplier, false);
3331     return S_OK;
3332 }
3333
3334 void WebView::setZoomMultiplier(float multiplier, bool isTextOnly)
3335 {
3336     m_zoomMultiplier = multiplier;
3337     m_zoomsTextOnly = isTextOnly;
3338
3339     if (Frame* coreFrame = core(m_mainFrame)) {
3340         if (m_zoomsTextOnly)
3341             coreFrame->setPageAndTextZoomFactors(1, multiplier);
3342         else
3343             coreFrame->setPageAndTextZoomFactors(multiplier, 1);
3344     }
3345 }
3346
3347 HRESULT WebView::textSizeMultiplier(_Out_ float* multiplier)
3348 {
3349     if (!multiplier)
3350         return E_POINTER;
3351
3352     *multiplier = zoomMultiplier(true);
3353     return S_OK;
3354 }
3355
3356 HRESULT WebView::pageSizeMultiplier(_Out_ float* multiplier)
3357 {
3358     if (!multiplier)
3359         return E_POINTER;
3360
3361     *multiplier = zoomMultiplier(false);
3362     return S_OK;
3363 }
3364
3365 float WebView::zoomMultiplier(bool isTextOnly)
3366 {
3367     if (isTextOnly != m_zoomsTextOnly)
3368         return 1.0f;
3369     return m_zoomMultiplier;
3370 }
3371
3372 HRESULT WebView::setApplicationNameForUserAgent(_In_ BSTR applicationName)
3373 {
3374     m_applicationName = toString(applicationName);
3375     m_userAgentStandard = String();
3376     return S_OK;
3377 }
3378
3379 HRESULT WebView::applicationNameForUserAgent(_Deref_opt_out_ BSTR* applicationName)
3380 {
3381     if (!applicationName)
3382         return E_POINTER;
3383
3384     *applicationName = BString(m_applicationName).release();
3385     if (!*applicationName && m_applicationName.length())
3386         return E_OUTOFMEMORY;
3387     return S_OK;
3388 }
3389
3390 HRESULT WebView::setCustomUserAgent(_In_ BSTR userAgentString)
3391 {
3392     m_userAgentOverridden = userAgentString;
3393     m_userAgentCustom = toString(userAgentString);
3394     return S_OK;
3395 }
3396
3397 HRESULT WebView::customUserAgent(_Deref_opt_out_ BSTR* userAgentString)
3398 {
3399     if (!userAgentString)
3400         return E_POINTER;
3401
3402     *userAgentString = nullptr;
3403     if (!m_userAgentOverridden)
3404         return S_OK;
3405     *userAgentString = BString(m_userAgentCustom).release();
3406     if (!*userAgentString && m_userAgentCustom.length())
3407         return E_OUTOFMEMORY;
3408     return S_OK;
3409 }
3410
3411 HRESULT WebView::userAgentForURL(_In_ BSTR url, _Deref_opt_out_ BSTR* userAgent)
3412 {
3413     if (!userAgent)
3414         return E_POINTER;
3415
3416     String userAgentString = userAgentForKURL(MarshallingHelpers::BSTRToKURL(url));
3417     *userAgent = BString(userAgentString).release();
3418     if (!*userAgent && userAgentString.length())
3419         return E_OUTOFMEMORY;
3420     return S_OK;
3421 }
3422
3423 HRESULT WebView::supportsTextEncoding(_Out_ BOOL* supports)
3424 {
3425     if (!supports)
3426         return E_POINTER;
3427
3428     *supports = TRUE;
3429     return S_OK;
3430 }
3431
3432 HRESULT WebView::setCustomTextEncodingName(_In_ BSTR encodingName)
3433 {
3434     if (!m_mainFrame)
3435         return E_UNEXPECTED;
3436
3437     HRESULT hr;
3438     BString oldEncoding;
3439     hr = customTextEncodingName(&oldEncoding);
3440     if (FAILED(hr))
3441         return hr;
3442
3443     if (oldEncoding != encodingName && (!oldEncoding || !encodingName || wcscmp(oldEncoding, encodingName))) {
3444         if (Frame* coreFrame = core(m_mainFrame))
3445             coreFrame->loader().reloadWithOverrideEncoding(toString(encodingName));
3446     }
3447
3448     return S_OK;
3449 }
3450
3451 HRESULT WebView::customTextEncodingName(_Deref_opt_out_ BSTR* encodingName)
3452 {
3453     if (!encodingName)
3454         return E_POINTER;
3455
3456     HRESULT hr = S_OK;
3457     COMPtr<IWebDataSource> dataSource;
3458     COMPtr<WebDataSource> dataSourceImpl;
3459     *encodingName = nullptr;
3460
3461     if (!m_mainFrame)
3462         return E_UNEXPECTED;
3463
3464     if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
3465         hr = m_mainFrame->dataSource(&dataSource);
3466         if (FAILED(hr) || !dataSource)
3467             return hr;
3468     }
3469
3470     hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
3471     if (FAILED(hr))
3472         return hr;
3473
3474     BString str = dataSourceImpl->documentLoader()->overrideEncoding();
3475     if (FAILED(hr))
3476         return hr;
3477
3478     if (!*encodingName)
3479         *encodingName = BString(m_overrideEncoding).release();
3480
3481     if (!*encodingName && m_overrideEncoding.length())
3482         return E_OUTOFMEMORY;
3483
3484     return S_OK;
3485 }
3486
3487 HRESULT WebView::setMediaStyle(_In_ BSTR /*media*/)
3488 {
3489     ASSERT_NOT_REACHED();
3490     return E_NOTIMPL;
3491 }
3492
3493 HRESULT WebView::mediaStyle(_Deref_opt_out_ BSTR* /*media*/)
3494 {
3495     ASSERT_NOT_REACHED();
3496     return E_NOTIMPL;
3497 }
3498
3499 HRESULT WebView::stringByEvaluatingJavaScriptFromString(_In_ BSTR script, // assumes input does not have "JavaScript" at the begining.
3500     _Deref_opt_out_ BSTR* result)
3501 {
3502     if (!result) {
3503         ASSERT_NOT_REACHED();
3504         return E_POINTER;
3505     }
3506
3507     *result = nullptr;
3508
3509     Frame* coreFrame = core(m_mainFrame);
3510     if (!coreFrame)
3511         return E_UNEXPECTED;
3512
3513     JSC::JSValue scriptExecutionResult = coreFrame->script().executeScript(WTF::String(script), true).jsValue();
3514     if (!scriptExecutionResult)
3515         return E_FAIL;
3516     else if (scriptExecutionResult.isString()) {
3517         JSC::ExecState* exec = coreFrame->script().globalObject(mainThreadNormalWorld())->globalExec();
3518         JSC::JSLockHolder lock(exec);
3519         *result = BString(scriptExecutionResult.getString(exec));
3520     }
3521
3522     return S_OK;
3523 }
3524
3525 HRESULT WebView::windowScriptObject(_COM_Outptr_opt_ IWebScriptObject** webScriptObject)
3526 {
3527     ASSERT_NOT_REACHED();
3528     if (!webScriptObject)
3529         return E_POINTER;
3530     *webScriptObject = nullptr;
3531     return E_NOTIMPL;
3532 }
3533
3534 HRESULT WebView::setPreferences(_In_opt_ IWebPreferences* prefs)
3535 {
3536     if (!prefs)
3537         prefs = WebPreferences::sharedStandardPreferences();
3538
3539     if (m_preferences == prefs)
3540         return S_OK;
3541
3542     COMPtr<WebPreferences> webPrefs(Query, prefs);
3543     if (!webPrefs)
3544         return E_NOINTERFACE;
3545     webPrefs->willAddToWebView();
3546
3547     COMPtr<WebPreferences> oldPrefs = m_preferences;
3548
3549     IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
3550     nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3551
3552     BString identifier;
3553     oldPrefs->identifier(&identifier);
3554     oldPrefs->didRemoveFromWebView();
3555     oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
3556
3557     m_preferences = webPrefs;
3558
3559     if (identifier)
3560         WebPreferences::removeReferenceForIdentifier(identifier);
3561
3562     nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3563
3564     m_preferences->postPreferencesChangesNotification();
3565
3566     return S_OK;
3567 }
3568
3569 HRESULT WebView::preferences(_COM_Outptr_opt_ IWebPreferences** prefs)
3570 {
3571     if (!prefs)
3572         return E_POINTER;
3573     *prefs = m_preferences.get();
3574     if (m_preferences)
3575         m_preferences->AddRef();
3576     return S_OK;
3577 }
3578
3579 HRESULT WebView::setPreferencesIdentifier(_In_ BSTR /*anIdentifier*/)
3580 {
3581     ASSERT_NOT_REACHED();
3582     return E_NOTIMPL;
3583 }
3584
3585 HRESULT WebView::preferencesIdentifier(_Deref_opt_out_ BSTR* /*anIdentifier*/)
3586 {
3587     ASSERT_NOT_REACHED();
3588     return E_NOTIMPL;
3589 }
3590
3591 static void systemParameterChanged(WPARAM parameter)
3592 {
3593 #if USE(CG)
3594     if (parameter == SPI_SETFONTSMOOTHING || parameter == SPI_SETFONTSMOOTHINGTYPE || parameter == SPI_SETFONTSMOOTHINGCONTRAST || parameter == SPI_SETFONTSMOOTHINGORIENTATION)
3595         wkSystemFontSmoothingChanged();
3596 #endif
3597 }
3598
3599 void WebView::windowReceivedMessage(HWND, UINT message, WPARAM wParam, LPARAM)
3600 {
3601     switch (message) {
3602     case WM_NCACTIVATE:
3603         updateActiveStateSoon();
3604         if (!wParam)
3605             deleteBackingStoreSoon();
3606         break;
3607     case WM_SETTINGCHANGE:
3608         systemParameterChanged(wParam);
3609         break;
3610     }
3611 }
3612
3613 void WebView::updateActiveStateSoon() const
3614 {
3615     // This function is called while processing the WM_NCACTIVATE message.
3616     // While processing WM_NCACTIVATE when we are being deactivated, GetActiveWindow() will
3617     // still return our window. If we were to call updateActiveState() in that case, we would
3618     // wrongly think that we are still the active window. To work around this, we update our
3619     // active state after a 0-delay timer fires, at which point GetActiveWindow() will return
3620     // the newly-activated window.
3621
3622     SetTimer(m_viewWindow, UpdateActiveStateTimer, 0, 0);
3623 }
3624
3625 void WebView::deleteBackingStoreSoon()
3626 {
3627     if (pendingDeleteBackingStoreSet().size() > 2) {
3628         Vector<WebView*> views;
3629         HashSet<WebView*>::iterator end = pendingDeleteBackingStoreSet().end();
3630         for (HashSet<WebView*>::iterator it = pendingDeleteBackingStoreSet().begin(); it != end; ++it)
3631             views.append(*it);
3632         for (int i = 0; i < views.size(); ++i)
3633             views[i]->deleteBackingStore();
3634         ASSERT(pendingDeleteBackingStoreSet().isEmpty());
3635     }
3636
3637     pendingDeleteBackingStoreSet().add(this);
3638     m_deleteBackingStoreTimerActive = true;
3639     SetTimer(m_viewWindow, DeleteBackingStoreTimer, delayBeforeDeletingBackingStoreMsec, 0);
3640 }
3641
3642 void WebView::cancelDeleteBackingStoreSoon()
3643 {
3644     if (!m_deleteBackingStoreTimerActive)
3645         return;
3646     pendingDeleteBackingStoreSet().remove(this);
3647     m_deleteBackingStoreTimerActive = false;
3648     KillTimer(m_viewWindow, DeleteBackingStoreTimer);
3649 }
3650
3651 HRESULT WebView::setHostWindow(_In_ HWND window)
3652 {
3653     if (m_viewWindow) {
3654         if (window)
3655             SetParent(m_viewWindow, window);
3656         else if (!isBeingDestroyed()) {
3657             // Turn the WebView into a message-only window so it will no longer be a child of the
3658             // old host window and will be hidden from screen. We only do this when
3659             // isBeingDestroyed() is false because doing this while handling WM_DESTROY can leave
3660             // m_viewWindow in a weird state (see <http://webkit.org/b/29337>).
3661             SetParent(m_viewWindow, HWND_MESSAGE);
3662         }
3663     }
3664
3665     m_hostWindow = window;
3666
3667     windowAncestryDidChange();
3668
3669     if (m_page)
3670         m_page->setDeviceScaleFactor(deviceScaleFactor());
3671
3672     return S_OK;
3673 }
3674
3675 HRESULT WebView::hostWindow(_Deref_opt_out_ HWND* window)
3676 {
3677     if (!window)
3678         return E_POINTER;
3679
3680     *window = m_hostWindow;
3681     return S_OK;
3682 }
3683
3684
3685 static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
3686 {
3687     return forward
3688         ? curr->tree().traverseNextWithWrap(wrapFlag)
3689         : curr->tree().traversePreviousWithWrap(wrapFlag);
3690 }
3691
3692 HRESULT WebView::searchFor(_In_ BSTR str, BOOL forward, BOOL caseFlag, BOOL wrapFlag, _Out_ BOOL* found)
3693 {
3694     if (!found)
3695         return E_INVALIDARG;
3696     
3697     if (!m_page)
3698         return E_FAIL;
3699
3700     if (!str || !SysStringLen(str))
3701         return E_INVALIDARG;
3702
3703     FindOptions options = (caseFlag ? 0 : CaseInsensitive) | (forward ? 0 : Backwards) | (wrapFlag ? WrapAround : 0);
3704     *found = m_page->findString(toString(str), options);
3705     return S_OK;
3706 }
3707
3708 bool WebView::active()
3709 {
3710     HWND activeWindow = GetActiveWindow();
3711     if (usesLayeredWindow() && activeWindow == m_viewWindow)
3712         return true;
3713
3714     return (activeWindow && m_topLevelParent == findTopLevelParent(activeWindow));
3715 }
3716
3717 void WebView::updateActiveState()
3718 {
3719     if (m_page)
3720         m_page->focusController().setActive(active());
3721 }
3722
3723 HRESULT WebView::updateFocusedAndActiveState()
3724 {
3725     updateActiveState();
3726
3727     bool active = m_page->focusController().isActive();
3728     Frame& mainFrame = m_page->mainFrame();
3729     Frame& focusedFrame = m_page->focusController().focusedOrMainFrame();
3730     mainFrame.selection().setFocused(active && &mainFrame == &focusedFrame);
3731
3732     return S_OK;
3733 }
3734
3735 HRESULT WebView::executeCoreCommandByName(_In_ BSTR name, _In_ BSTR value)
3736 {
3737     if (!m_page)
3738         return E_FAIL;
3739
3740     m_page->focusController().focusedOrMainFrame().editor().command(toString(name)).execute(toString(value));
3741
3742     return S_OK;
3743 }
3744
3745 HRESULT WebView::clearMainFrameName()
3746 {
3747     if (!m_page)
3748         return E_FAIL;
3749
3750     m_page->mainFrame().tree().clearName();
3751
3752     return S_OK;
3753 }
3754
3755 HRESULT WebView::markAllMatchesForText(_In_ BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, _Out_ UINT* matches)
3756 {
3757     if (!matches)
3758         return E_INVALIDARG;
3759
3760     if (!m_page)
3761         return E_FAIL;
3762
3763     if (!str || !SysStringLen(str))
3764         return E_INVALIDARG;
3765
3766     *matches = m_page->markAllMatchesForText(toString(str), caseSensitive ? TextCaseSensitive : TextCaseInsensitive, highlight, limit);
3767     return S_OK;
3768 }
3769
3770 HRESULT WebView::unmarkAllTextMatches()
3771 {
3772     if (!m_page)
3773         return E_FAIL;
3774
3775     m_page->unmarkAllTextMatches();
3776     return S_OK;
3777 }
3778
3779 HRESULT WebView::rectsForTextMatches(_COM_Outptr_opt_ IEnumTextMatches** pmatches)
3780 {
3781     if (!pmatches)
3782         return E_POINTER;
3783     *pmatches = nullptr;
3784     if (!m_page)
3785         return E_FAIL;
3786
3787     Vector<IntRect> allRects;
3788     WebCore::Frame* frame = &m_page->mainFrame();
3789     do {
3790         if (Document* document = frame->document()) {
3791             IntRect visibleRect = frame->view()->visibleContentRect();
3792             Vector<FloatRect> frameRects = document->markers().renderedRectsForMarkers(DocumentMarker::TextMatch);
3793             IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
3794             frameOffset = frame->view()->convertToContainingWindow(frameOffset);
3795
3796             Vector<FloatRect>::iterator end = frameRects.end();
3797             for (Vector<FloatRect>::iterator it = frameRects.begin(); it < end; it++) {
3798                 it->intersect(visibleRect);
3799                 it->move(frameOffset.x(), frameOffset.y());
3800                 allRects.append(enclosingIntRect(*it));
3801             }
3802         }
3803         frame = incrementFrame(frame, true, false);
3804     } while (frame);
3805
3806     return createMatchEnumerator(&allRects, pmatches);
3807 }
3808
3809 HRESULT WebView::generateSelectionImage(BOOL forceWhiteText, _Deref_opt_out_ HBITMAP* hBitmap)
3810 {
3811     if (!hBitmap)
3812         return E_POINTER;
3813
3814     if (!m_page)
3815         return E_FAIL;
3816
3817     *hBitmap = nullptr;
3818
3819     WebCore::Frame& frame = m_page->focusController().focusedOrMainFrame();
3820
3821     auto bitmap = imageFromSelection(&frame, forceWhiteText ? TRUE : FALSE);
3822     *hBitmap = bitmap.leak();
3823
3824     return S_OK;
3825 }
3826
3827 HRESULT WebView::selectionRect(_Inout_ RECT* rc)
3828 {
3829     if (!rc)
3830         return E_POINTER;
3831
3832     if (!m_page)
3833         return E_FAIL;
3834
3835     WebCore::Frame& frame = m_page->focusController().focusedOrMainFrame();
3836
3837     IntRect ir = enclosingIntRect(frame.selection().selectionBounds());
3838     ir = frame.view()->convertToContainingWindow(ir);
3839     ir.move(-frame.view()->scrollOffset().width(), -frame.view()->scrollOffset().height());
3840
3841     float scaleFactor = deviceScaleFactor();
3842     rc->left = ir.x() * scaleFactor;
3843     rc->top = ir.y() * scaleFactor;
3844     rc->bottom = rc->top + ir.height() * scaleFactor;
3845     rc->right = rc->left + ir.width() * scaleFactor;
3846
3847     return S_OK;
3848 }
3849
3850 HRESULT WebView::registerViewClass(_In_opt_ IWebDocumentView*, _In_opt_ IWebDocumentRepresentation*, _In_ BSTR /*forMIMEType*/)
3851 {
3852     ASSERT_NOT_REACHED();
3853     return E_NOTIMPL;
3854 }
3855
3856 HRESULT WebView::setGroupName(_In_ BSTR groupName)
3857 {
3858     if (m_webViewGroup)
3859         m_webViewGroup->removeWebView(this);
3860
3861     m_webViewGroup = WebViewGroup::getOrCreate(groupName, localStorageDatabasePath(m_preferences.get()));
3862     m_webViewGroup->addWebView(this);
3863
3864     if (!m_page)
3865         return S_OK;
3866
3867     m_page->setUserContentController(&m_webViewGroup->userContentController());
3868     m_page->setVisitedLinkStore(m_webViewGroup->visitedLinkStore());
3869     m_page->setGroupName(toString(groupName));
3870     return S_OK;
3871 }
3872     
3873 HRESULT WebView::groupName(_Deref_opt_out_ BSTR* groupName)
3874 {
3875     if (!groupName)
3876         return E_POINTER;
3877
3878     *groupName = nullptr;
3879     if (!m_page)
3880         return S_OK;
3881     String groupNameString = m_page->groupName();
3882     *groupName = BString(groupNameString).release();
3883     if (!*groupName && groupNameString.length())
3884         return E_OUTOFMEMORY;
3885     return S_OK;
3886 }
3887     
3888 HRESULT WebView::estimatedProgress(_Out_ double* estimatedProgress)
3889 {
3890     if (!estimatedProgress)
3891         return E_POINTER;
3892     *estimatedProgress = m_page->progress().estimatedProgress();
3893     return S_OK;
3894 }
3895     
3896 HRESULT WebView::isLoading(_Out_ BOOL* isLoading)
3897 {
3898     COMPtr<IWebDataSource> dataSource;
3899     COMPtr<IWebDataSource> provisionalDataSource;
3900
3901     if (!isLoading)
3902         return E_POINTER;
3903
3904     *isLoading = FALSE;
3905
3906     if (!m_mainFrame)
3907         return E_UNEXPECTED;
3908
3909     if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
3910         dataSource->isLoading(isLoading);
3911
3912     if (*isLoading)
3913         return S_OK;
3914
3915     if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
3916         provisionalDataSource->isLoading(isLoading);
3917     return S_OK;
3918 }
3919     
3920 HRESULT WebView::elementAtPoint(_In_ LPPOINT point, _COM_Outptr_opt_ IPropertyBag** elementDictionary)
3921 {
3922     if (!elementDictionary || !point) {
3923         ASSERT_NOT_REACHED();
3924         return E_POINTER;
3925     }
3926
3927     *elementDictionary = nullptr;
3928
3929     Frame* frame = core(m_mainFrame);
3930     if (!frame)
3931         return E_UNEXPECTED;
3932
3933     IntPoint webCorePoint = IntPoint(point->x, point->y);
3934     float inverseScaleFactor = 1.0f / deviceScaleFactor();
3935     webCorePoint.scale(inverseScaleFactor, inverseScaleFactor);
3936     HitTestResult result = HitTestResult(webCorePoint);
3937     if (frame->contentRenderer())
3938         result = frame->eventHandler().hitTestResultAtPoint(webCorePoint);
3939     *elementDictionary = WebElementPropertyBag::createInstance(result);
3940     return S_OK;
3941 }
3942     
3943 HRESULT WebView::pasteboardTypesForSelection(_COM_Outptr_opt_ IEnumVARIANT** enumVariant)
3944 {
3945     ASSERT_NOT_REACHED();
3946     if (!enumVariant)
3947         return E_POINTER;
3948     *enumVariant = nullptr;
3949     return E_NOTIMPL;
3950 }
3951     
3952 HRESULT WebView::writeSelectionWithPasteboardTypes(__inout_ecount_full(cTypes) BSTR* types, int cTypes, _In_opt_ IDataObject* /*pasteboard*/)
3953 {
3954     ASSERT_NOT_REACHED();
3955     return E_NOTIMPL;
3956 }
3957     
3958 HRESULT WebView::pasteboardTypesForElement(_In_opt_ IPropertyBag* /*elementDictionary*/, _COM_Outptr_opt_ IEnumVARIANT** enumVariant)
3959 {
3960     ASSERT_NOT_REACHED();
3961     if (!enumVariant)
3962         return E_POINTER;
3963     *enumVariant = nullptr;
3964     return E_NOTIMPL;
3965 }
3966     
3967 HRESULT WebView::writeElement(_In_opt_ IPropertyBag* /*elementDictionary*/, __inout_ecount_full(cWithPasteboardTypes) BSTR* withPasteboardTypes, int cWithPasteboardTypes, _In_opt_ IDataObject* /*pasteboard*/)
3968 {
3969     ASSERT_NOT_REACHED();
3970     return E_NOTIMPL;
3971 }
3972     
3973 HRESULT WebView::selectedText(_Deref_opt_out_ BSTR* text)
3974 {
3975     if (!text) {
3976         ASSERT_NOT_REACHED();
3977         return E_POINTER;
3978     }
3979
3980     *text = nullptr;
3981
3982     Frame* focusedFrame = m_page ? &m_page->focusController().focusedOrMainFrame() : 0;
3983     if (!focusedFrame)
3984         return E_FAIL;
3985
3986     String frameSelectedText = focusedFrame->editor().selectedText();
3987     *text = BString(frameSelectedText).release();
3988     if (!*text && frameSelectedText.length())
3989         return E_OUTOFMEMORY;
3990     return S_OK;
3991 }
3992
3993 HRESULT WebView::centerSelectionInVisibleArea(_In_opt_ IUnknown* /* sender */)
3994 {
3995     Frame* coreFrame = core(m_mainFrame);
3996     if (!coreFrame)
3997         return E_UNEXPECTED;
3998
3999     coreFrame->selection().revealSelection(ScrollAlignment::alignCenterAlways);
4000     return S_OK;
4001 }
4002
4003
4004 HRESULT WebView::moveDragCaretToPoint(_In_ LPPOINT /*point*/)
4005 {
4006     ASSERT_NOT_REACHED();
4007     return E_NOTIMPL;
4008 }
4009     
4010 HRESULT WebView::removeDragCaret()
4011 {
4012     ASSERT_NOT_REACHED();
4013     return E_NOTIMPL;
4014 }
4015     
4016 HRESULT WebView::setDrawsBackground(BOOL /*drawsBackground*/)
4017 {
4018     ASSERT_NOT_REACHED();
4019     return E_NOTIMPL;
4020 }
4021     
4022 HRESULT WebView::drawsBackground(_Out_ BOOL* /*drawsBackground*/)
4023 {
4024     ASSERT_NOT_REACHED();
4025     return E_NOTIMPL;
4026 }
4027     
4028 HRESULT WebView::setMainFrameURL(_In_ BSTR /*urlString*/)
4029 {
4030     ASSERT_NOT_REACHED();
4031     return E_NOTIMPL;
4032 }
4033     
4034 HRESULT WebView::mainFrameURL(_Deref_opt_out_ BSTR* urlString)
4035 {
4036     if (!urlString)
4037         return E_POINTER;
4038
4039     if (!m_mainFrame)
4040         return E_UNEXPECTED;
4041
4042     COMPtr<IWebDataSource> dataSource;
4043
4044     if (FAILED(m_mainFrame->provisionalDataSource(&dataSource))) {
4045         if (FAILED(m_mainFrame->dataSource(&dataSource)))
4046             return E_FAIL;
4047     }
4048
4049     if (!dataSource) {
4050         *urlString = nullptr;
4051         return S_OK;
4052     }
4053     
4054     COMPtr<IWebMutableURLRequest> request;
4055     if (FAILED(dataSource->request(&request)) || !request)
4056         return E_FAIL;
4057
4058     if (FAILED(request->URL(urlString)))
4059         return E_FAIL;
4060
4061     return S_OK;
4062 }
4063     
4064 HRESULT WebView::mainFrameDocument(_COM_Outptr_opt_ IDOMDocument** document)
4065 {
4066     if (!document)
4067         return E_POINTER;
4068
4069     *document = nullptr;
4070
4071     if (!m_mainFrame)
4072         return E_UNEXPECTED;
4073     return m_mainFrame->DOMDocument(document);
4074 }
4075     
4076 HRESULT WebView::mainFrameTitle(_Deref_opt_out_ BSTR* /*title*/)
4077 {
4078     ASSERT_NOT_REACHED();
4079     return E_NOTIMPL;
4080 }
4081     
4082 HRESULT WebView::mainFrameIcon(_Deref_opt_out_ HBITMAP* /*hBitmap*/)
4083 {
4084     ASSERT_NOT_REACHED();
4085     return E_NOTIMPL;
4086 }
4087
4088 HRESULT WebView::registerURLSchemeAsLocal(_In_ BSTR scheme)
4089 {
4090     if (!scheme)
4091         return E_POINTER;
4092
4093     SchemeRegistry::registerURLSchemeAsLocal(toString(scheme));
4094
4095     return S_OK;
4096 }
4097
4098 // IWebIBActions ---------------------------------------------------------------
4099
4100 HRESULT WebView::takeStringURLFrom(_In_opt_ IUnknown* /*sender*/)
4101 {
4102     ASSERT_NOT_REACHED();
4103     return E_NOTIMPL;
4104 }
4105     
4106 HRESULT WebView::stopLoading(_In_opt_ IUnknown* /*sender*/)
4107 {
4108     if (!m_mainFrame)
4109         return E_UNEXPECTED;
4110
4111     return m_mainFrame->stopLoading();
4112 }
4113     
4114 HRESULT WebView::reload(_In_opt_ IUnknown* /*sender*/)
4115 {
4116     if (!m_mainFrame)
4117         return E_UNEXPECTED;
4118
4119     return m_mainFrame->reload();
4120 }
4121     
4122 HRESULT WebView::canGoBack(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4123 {
4124     if (!result)
4125         return E_POINTER;
4126
4127     *result = !!(m_page->backForward().backItem() && !m_page->defersLoading());
4128     return S_OK;
4129 }
4130     
4131 HRESULT WebView::goBack(_In_opt_ IUnknown* /*sender*/)
4132 {
4133     ASSERT_NOT_REACHED();
4134     return E_NOTIMPL;
4135 }
4136     
4137 HRESULT WebView::canGoForward(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4138 {
4139     if (!result)
4140         return E_POINTER;
4141     
4142     *result = !!(m_page->backForward().forwardItem() && !m_page->defersLoading());
4143     return S_OK;
4144 }
4145     
4146 HRESULT WebView::goForward(_In_opt_ IUnknown* /*sender*/)
4147 {
4148     ASSERT_NOT_REACHED();
4149     return E_NOTIMPL;
4150 }
4151
4152 // FIXME: This code should move into WebCore so it can be shared by all the WebKits.
4153 #define MinimumZoomMultiplier   0.5f
4154 #define MaximumZoomMultiplier   3.0f
4155 #define ZoomMultiplierRatio     1.2f
4156
4157 HRESULT WebView::canMakeTextLarger(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4158 {
4159     if (!result)
4160         return E_POINTER;
4161
4162     bool canGrowMore = canZoomIn(m_zoomsTextOnly);
4163     *result = canGrowMore ? TRUE : FALSE;
4164     return S_OK;
4165 }
4166
4167 HRESULT WebView::canZoomPageIn(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4168 {
4169     if (!result)
4170         return E_POINTER;
4171
4172     bool canGrowMore = canZoomIn(false);
4173     *result = canGrowMore ? TRUE : FALSE;
4174     return S_OK;
4175 }
4176
4177 bool WebView::canZoomIn(bool isTextOnly)
4178 {
4179     return zoomMultiplier(isTextOnly) * ZoomMultiplierRatio < MaximumZoomMultiplier;
4180 }
4181     
4182 HRESULT WebView::makeTextLarger(_In_opt_ IUnknown* /*sender*/)
4183 {
4184     return zoomIn(m_zoomsTextOnly);
4185 }
4186
4187 HRESULT WebView::zoomPageIn(_In_opt_ IUnknown* /*sender*/)
4188 {
4189     return zoomIn(false);
4190 }
4191
4192 HRESULT WebView::zoomIn(bool isTextOnly)
4193 {
4194     if (!canZoomIn(isTextOnly))
4195         return E_FAIL;
4196     setZoomMultiplier(zoomMultiplier(isTextOnly) * ZoomMultiplierRatio, isTextOnly);
4197     return S_OK;
4198 }
4199
4200 HRESULT WebView::canMakeTextSmaller(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4201 {
4202     if (!result)
4203         return E_POINTER;
4204
4205     bool canShrinkMore = canZoomOut(m_zoomsTextOnly);
4206     *result = canShrinkMore ? TRUE : FALSE;
4207     return S_OK;
4208 }
4209
4210 HRESULT WebView::canZoomPageOut(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4211 {
4212     if (!result)
4213         return E_POINTER;
4214
4215     bool canShrinkMore = canZoomOut(false);
4216     *result = canShrinkMore ? TRUE : FALSE;
4217     return S_OK;
4218 }
4219
4220 bool WebView::canZoomOut(bool isTextOnly)
4221 {
4222     return zoomMultiplier(isTextOnly) / ZoomMultiplierRatio > MinimumZoomMultiplier;
4223 }
4224
4225 HRESULT WebView::makeTextSmaller(_In_opt_ IUnknown* /*sender*/)
4226 {
4227     return zoomOut(m_zoomsTextOnly);
4228 }
4229
4230 HRESULT WebView::zoomPageOut(_In_opt_ IUnknown* /*sender*/)
4231 {
4232     return zoomOut(false);
4233 }
4234
4235 HRESULT WebView::zoomOut(bool isTextOnly)
4236 {
4237     if (!canZoomOut(isTextOnly))
4238         return E_FAIL;
4239     setZoomMultiplier(zoomMultiplier(isTextOnly) / ZoomMultiplierRatio, isTextOnly);
4240     return S_OK;
4241 }
4242
4243 HRESULT WebView::canMakeTextStandardSize(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4244 {
4245     if (!result)
4246         return E_POINTER;
4247
4248     // 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.
4249     bool notAlreadyStandard = canResetZoom(true);
4250     *result = notAlreadyStandard ? TRUE : FALSE;
4251     return S_OK;
4252 }
4253
4254 HRESULT WebView::canResetPageZoom(_In_opt_ IUnknown* /*sender*/, _Out_ BOOL* result)
4255 {
4256     if (!result)
4257         return E_POINTER;
4258
4259     bool notAlreadyStandard = canResetZoom(false);
4260     *result = notAlreadyStandard ? TRUE : FALSE;
4261     return S_OK;
4262 }
4263
4264 bool WebView::canResetZoom(bool isTextOnly)
4265 {
4266     return zoomMultiplier(isTextOnly) != 1.0f;
4267 }
4268
4269 HRESULT WebView::makeTextStandardSize(_In_opt_ IUnknown* /*sender*/)
4270 {
4271     return resetZoom(true);
4272 }
4273
4274 HRESULT WebView::resetPageZoom(_In_opt_ IUnknown* /*sender*/)
4275 {
4276     return resetZoom(false);
4277 }
4278
4279 HRESULT WebView::resetZoom(bool isTextOnly)
4280 {
4281     if (!canResetZoom(isTextOnly))
4282         return E_FAIL;
4283     setZoomMultiplier(1.0f, isTextOnly);
4284     return S_OK;
4285 }
4286
4287 HRESULT WebView::toggleContinuousSpellChecking(_In_opt_ IUnknown* /*sender*/)
4288 {
4289     HRESULT hr;
4290     BOOL enabled;
4291     if (FAILED(hr = isContinuousSpellCheckingEnabled(&enabled)))
4292         return hr;
4293     return setContinuousSpellCheckingEnabled(enabled ? FALSE : TRUE);
4294 }
4295
4296 HRESULT WebView::toggleSmartInsertDelete(_In_opt_ IUnknown* /*sender*/)
4297 {
4298     BOOL enabled = FALSE;
4299     HRESULT hr = smartInsertDeleteEnabled(&enabled);
4300     if (FAILED(hr))
4301         return hr;
4302
4303     return setSmartInsertDeleteEnabled(enabled ? FALSE : TRUE);
4304 }