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