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