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