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