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