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