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