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