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