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