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