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