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