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