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