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