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