[WinCairo][Curl] Download request has incorrect user agent string.
[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     pageClients.progressTrackerClient = static_cast<WebFrameLoaderClient*>(pageClients.loaderClientForMainFrame);
2776
2777     m_page = new Page(pageClients);
2778     provideGeolocationTo(m_page, new WebGeolocationClient(this));
2779
2780     unsigned layoutMilestones = DidFirstLayout | DidFirstVisuallyNonEmptyLayout;
2781     m_page->addLayoutMilestones(static_cast<LayoutMilestones>(layoutMilestones));
2782
2783     BString localStoragePath;
2784     if (SUCCEEDED(m_preferences->localStorageDatabasePath(&localStoragePath)))
2785         m_page->settings().setLocalStorageDatabasePath(toString(localStoragePath));
2786
2787     if (m_uiDelegate) {
2788         BString path;
2789         if (SUCCEEDED(m_uiDelegate->ftpDirectoryTemplatePath(this, &path)))
2790             m_page->settings().setFTPDirectoryTemplatePath(toString(path));
2791     }
2792
2793     WebFrame* webFrame = WebFrame::createInstance();
2794     webFrame->initWithWebView(this, m_page);
2795     static_cast<WebFrameLoaderClient&>(m_page->mainFrame().loader().client()).setWebFrame(webFrame);
2796     m_mainFrame = webFrame;
2797     webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
2798
2799     m_page->mainFrame().tree().setName(toString(frameName));
2800     m_page->mainFrame().init();
2801     setGroupName(groupName);
2802
2803     addToAllWebViewsSet();
2804
2805     #pragma warning(suppress: 4244)
2806     SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
2807     ShowWindow(m_viewWindow, SW_SHOW);
2808
2809     initializeToolTipWindow();
2810     windowAncestryDidChange();
2811
2812     IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
2813     notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2814     m_preferences->postPreferencesChangesNotification();
2815
2816     setSmartInsertDeleteEnabled(TRUE);
2817     return hr;
2818 }
2819
2820 static bool initCommonControls()
2821 {
2822     static bool haveInitialized = false;
2823     if (haveInitialized)
2824         return true;
2825
2826     INITCOMMONCONTROLSEX init;
2827     init.dwSize = sizeof(init);
2828     init.dwICC = ICC_TREEVIEW_CLASSES;
2829     haveInitialized = !!::InitCommonControlsEx(&init);
2830     return haveInitialized;
2831 }
2832
2833 void WebView::initializeToolTipWindow()
2834 {
2835     if (!initCommonControls())
2836         return;
2837
2838     m_toolTipHwnd = CreateWindowEx(WS_EX_TRANSPARENT, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
2839                                    CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
2840                                    m_viewWindow, 0, 0, 0);
2841     if (!m_toolTipHwnd)
2842         return;
2843
2844     TOOLINFO info = {0};
2845     info.cbSize = sizeof(info);
2846     info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
2847     info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2848
2849     ::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
2850     ::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, maxToolTipWidth);
2851
2852     ::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
2853 }
2854
2855 void WebView::setToolTip(const String& toolTip)
2856 {
2857     if (!m_toolTipHwnd)
2858         return;
2859
2860     if (toolTip == m_toolTip)
2861         return;
2862
2863     m_toolTip = toolTip;
2864
2865     if (!m_toolTip.isEmpty()) {
2866         TOOLINFO info = {0};
2867         info.cbSize = sizeof(info);
2868         info.uFlags = TTF_IDISHWND;
2869         info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2870         Vector<UChar> toolTipCharacters = m_toolTip.charactersWithNullTermination(); // Retain buffer long enough to make the SendMessage call
2871         info.lpszText = const_cast<UChar*>(toolTipCharacters.data());
2872         ::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
2873     }
2874
2875     ::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
2876 }
2877
2878 HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
2879 {
2880     COMPtr<IPropertyBag> propertyBag;
2881     HRESULT hr = notification->userInfo(&propertyBag);
2882     if (FAILED(hr))
2883         return hr;
2884     if (!propertyBag)
2885         return E_FAIL;
2886
2887     COMVariant iconUserInfoURL;
2888     hr = propertyBag->Read(WebIconDatabase::iconDatabaseNotificationUserInfoURLKey(), &iconUserInfoURL, 0);
2889     if (FAILED(hr))
2890         return hr;
2891
2892     if (iconUserInfoURL.variantType() != VT_BSTR)
2893         return E_FAIL;
2894
2895     String mainFrameURL;
2896     if (m_mainFrame)
2897         mainFrameURL = m_mainFrame->url().string();
2898
2899     if (!mainFrameURL.isEmpty() && mainFrameURL == toString(V_BSTR(&iconUserInfoURL)))
2900         dispatchDidReceiveIconFromWebFrame(m_mainFrame);
2901
2902     return hr;
2903 }
2904
2905 void WebView::registerForIconNotification(bool listen)
2906 {
2907     IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2908     if (listen)
2909         nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2910     else
2911         nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2912 }
2913
2914 void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
2915 {
2916     registerForIconNotification(false);
2917
2918     if (m_frameLoadDelegate) {
2919         String str = frame->url().string();
2920
2921         IntSize sz(16, 16);
2922
2923         BitmapInfo bmInfo = BitmapInfo::create(sz);
2924
2925         HBITMAP hBitmap = 0;
2926
2927         Image* icon = iconDatabase().synchronousIconForPageURL(str, sz);
2928
2929         if (icon && icon->width()) {
2930             HWndDC dc(0);
2931             hBitmap = CreateDIBSection(dc, &bmInfo, DIB_RGB_COLORS, 0, 0, 0);
2932             icon->getHBITMAPOfSize(hBitmap, &sz);
2933         }
2934
2935         HRESULT hr = m_frameLoadDelegate->didReceiveIcon(this, (OLE_HANDLE)hBitmap, frame);
2936         if (hr == E_NOTIMPL)
2937             DeleteObject(hBitmap);
2938     }
2939 }
2940
2941 HRESULT WebView::setAccessibilityDelegate(
2942     /* [in] */ IAccessibilityDelegate* d)
2943 {
2944     m_accessibilityDelegate = d;
2945     return S_OK;
2946 }
2947
2948 HRESULT WebView::accessibilityDelegate(
2949     /* [out][retval] */ IAccessibilityDelegate** d)
2950 {
2951     if (!m_accessibilityDelegate)
2952         return E_POINTER;
2953
2954     return m_accessibilityDelegate.copyRefTo(d);
2955 }
2956
2957 HRESULT STDMETHODCALLTYPE WebView::setUIDelegate( 
2958     /* [in] */ IWebUIDelegate* d)
2959 {
2960     m_uiDelegate = d;
2961
2962     if (m_uiDelegatePrivate)
2963         m_uiDelegatePrivate = 0;
2964
2965     if (d) {
2966         if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
2967             m_uiDelegatePrivate = 0;
2968     }
2969
2970     return S_OK;
2971 }
2972
2973 HRESULT STDMETHODCALLTYPE WebView::uiDelegate( 
2974     /* [out][retval] */ IWebUIDelegate** d)
2975 {
2976     if (!m_uiDelegate)
2977         return E_FAIL;
2978
2979     return m_uiDelegate.copyRefTo(d);
2980 }
2981
2982 HRESULT STDMETHODCALLTYPE WebView::setResourceLoadDelegate( 
2983     /* [in] */ IWebResourceLoadDelegate* d)
2984 {
2985     m_resourceLoadDelegate = d;
2986     return S_OK;
2987 }
2988
2989 HRESULT STDMETHODCALLTYPE WebView::resourceLoadDelegate( 
2990     /* [out][retval] */ IWebResourceLoadDelegate** d)
2991 {
2992     if (!m_resourceLoadDelegate)
2993         return E_FAIL;
2994
2995     return m_resourceLoadDelegate.copyRefTo(d);
2996 }
2997
2998 HRESULT STDMETHODCALLTYPE WebView::setDownloadDelegate( 
2999     /* [in] */ IWebDownloadDelegate* d)
3000 {
3001     m_downloadDelegate = d;
3002     return S_OK;
3003 }
3004
3005 HRESULT STDMETHODCALLTYPE WebView::downloadDelegate( 
3006     /* [out][retval] */ IWebDownloadDelegate** d)
3007 {
3008     if (!m_downloadDelegate)
3009         return E_FAIL;
3010
3011     return m_downloadDelegate.copyRefTo(d);
3012 }
3013
3014 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegate( 
3015     /* [in] */ IWebFrameLoadDelegate* d)
3016 {
3017     m_frameLoadDelegate = d;
3018     return S_OK;
3019 }
3020
3021 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegate( 
3022     /* [out][retval] */ IWebFrameLoadDelegate** d)
3023 {
3024     if (!m_frameLoadDelegate)
3025         return E_FAIL;
3026
3027     return m_frameLoadDelegate.copyRefTo(d);
3028 }
3029
3030 HRESULT STDMETHODCALLTYPE WebView::setPolicyDelegate( 
3031     /* [in] */ IWebPolicyDelegate* d)
3032 {
3033     m_policyDelegate = d;
3034     return S_OK;
3035 }
3036
3037 HRESULT STDMETHODCALLTYPE WebView::policyDelegate( 
3038     /* [out][retval] */ IWebPolicyDelegate** d)
3039 {
3040     if (!m_policyDelegate)
3041         return E_FAIL;
3042     return m_policyDelegate.copyRefTo(d);
3043 }
3044
3045 HRESULT STDMETHODCALLTYPE WebView::mainFrame( 
3046     /* [out][retval] */ IWebFrame** frame)
3047 {
3048     if (!frame) {
3049         ASSERT_NOT_REACHED();
3050         return E_POINTER;
3051     }
3052
3053     *frame = m_mainFrame;
3054     if (!m_mainFrame)
3055         return E_FAIL;
3056
3057     m_mainFrame->AddRef();
3058     return S_OK;
3059 }
3060
3061 HRESULT STDMETHODCALLTYPE WebView::focusedFrame( 
3062     /* [out][retval] */ IWebFrame** frame)
3063 {
3064     if (!frame) {
3065         ASSERT_NOT_REACHED();
3066         return E_POINTER;
3067     }
3068
3069     *frame = 0;
3070     Frame* f = m_page->focusController().focusedFrame();
3071     if (!f)
3072         return E_FAIL;
3073
3074     WebFrame* webFrame = kit(f);
3075     if (!webFrame)
3076         return E_FAIL;
3077
3078     return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
3079 }
3080
3081 HRESULT STDMETHODCALLTYPE WebView::backForwardList( 
3082     /* [out][retval] */ IWebBackForwardList** list)
3083 {
3084     if (!m_useBackForwardList)
3085         return E_FAIL;
3086  
3087     *list = WebBackForwardList::createInstance(static_cast<WebCore::BackForwardList*>(m_page->backForwardClient()));
3088
3089     return S_OK;
3090 }
3091
3092 HRESULT STDMETHODCALLTYPE WebView::setMaintainsBackForwardList( 
3093     /* [in] */ BOOL flag)
3094 {
3095     m_useBackForwardList = !!flag;
3096     return S_OK;
3097 }
3098
3099 HRESULT STDMETHODCALLTYPE WebView::goBack( 
3100     /* [retval][out] */ BOOL* succeeded)
3101 {
3102     *succeeded = m_page->goBack();
3103     return S_OK;
3104 }
3105
3106 HRESULT STDMETHODCALLTYPE WebView::goForward( 
3107     /* [retval][out] */ BOOL* succeeded)
3108 {
3109     *succeeded = m_page->goForward();
3110     return S_OK;
3111 }
3112
3113 HRESULT STDMETHODCALLTYPE WebView::goToBackForwardItem( 
3114     /* [in] */ IWebHistoryItem* item,
3115     /* [retval][out] */ BOOL* succeeded)
3116 {
3117     *succeeded = FALSE;
3118
3119     COMPtr<WebHistoryItem> webHistoryItem;
3120     HRESULT hr = item->QueryInterface(&webHistoryItem);
3121     if (FAILED(hr))
3122         return hr;
3123
3124     m_page->goToItem(webHistoryItem->historyItem(), FrameLoadTypeIndexedBackForward);
3125     *succeeded = TRUE;
3126
3127     return S_OK;
3128 }
3129
3130 HRESULT STDMETHODCALLTYPE WebView::setTextSizeMultiplier( 
3131     /* [in] */ float multiplier)
3132 {
3133     if (!m_mainFrame)
3134         return E_FAIL;
3135     setZoomMultiplier(multiplier, true);
3136     return S_OK;
3137 }
3138
3139 HRESULT STDMETHODCALLTYPE WebView::setPageSizeMultiplier( 
3140     /* [in] */ float multiplier)
3141 {
3142     if (!m_mainFrame)
3143         return E_FAIL;
3144     setZoomMultiplier(multiplier, false);
3145     return S_OK;
3146 }
3147
3148 void WebView::setZoomMultiplier(float multiplier, bool isTextOnly)
3149 {
3150     m_zoomMultiplier = multiplier;
3151     m_zoomsTextOnly = isTextOnly;
3152
3153     if (Frame* coreFrame = core(m_mainFrame)) {
3154         if (m_zoomsTextOnly)
3155             coreFrame->setPageAndTextZoomFactors(1, multiplier);
3156         else
3157             coreFrame->setPageAndTextZoomFactors(multiplier, 1);
3158     }
3159 }
3160
3161 HRESULT STDMETHODCALLTYPE WebView::textSizeMultiplier( 
3162     /* [retval][out] */ float* multiplier)
3163 {
3164     *multiplier = zoomMultiplier(true);
3165     return S_OK;
3166 }
3167
3168 HRESULT STDMETHODCALLTYPE WebView::pageSizeMultiplier( 
3169     /* [retval][out] */ float* multiplier)
3170 {
3171     *multiplier = zoomMultiplier(false);
3172     return S_OK;
3173 }
3174
3175 float WebView::zoomMultiplier(bool isTextOnly)
3176 {
3177     if (isTextOnly != m_zoomsTextOnly)
3178         return 1.0f;
3179     return m_zoomMultiplier;
3180 }
3181
3182 HRESULT STDMETHODCALLTYPE WebView::setApplicationNameForUserAgent( 
3183     /* [in] */ BSTR applicationName)
3184 {
3185     m_applicationName = toString(applicationName);
3186     m_userAgentStandard = String();
3187     return S_OK;
3188 }
3189
3190 HRESULT STDMETHODCALLTYPE WebView::applicationNameForUserAgent( 
3191     /* [retval][out] */ BSTR* applicationName)
3192 {
3193     *applicationName = SysAllocStringLen(m_applicationName.characters(), m_applicationName.length());
3194     if (!*applicationName && m_applicationName.length())
3195         return E_OUTOFMEMORY;
3196     return S_OK;
3197 }
3198
3199 HRESULT STDMETHODCALLTYPE WebView::setCustomUserAgent( 
3200     /* [in] */ BSTR userAgentString)
3201 {
3202     m_userAgentOverridden = userAgentString;
3203     m_userAgentCustom = toString(userAgentString);
3204     return S_OK;
3205 }
3206
3207 HRESULT STDMETHODCALLTYPE WebView::customUserAgent( 
3208     /* [retval][out] */ BSTR* userAgentString)
3209 {
3210     *userAgentString = 0;
3211     if (!m_userAgentOverridden)
3212         return S_OK;
3213     *userAgentString = SysAllocStringLen(m_userAgentCustom.characters(), m_userAgentCustom.length());
3214     if (!*userAgentString && m_userAgentCustom.length())
3215         return E_OUTOFMEMORY;
3216     return S_OK;
3217 }
3218
3219 HRESULT STDMETHODCALLTYPE WebView::userAgentForURL( 
3220     /* [in] */ BSTR url,
3221     /* [retval][out] */ BSTR* userAgent)
3222 {
3223     String userAgentString = userAgentForKURL(MarshallingHelpers::BSTRToKURL(url));
3224     *userAgent = BString(userAgentString).release();
3225     if (!*userAgent && userAgentString.length())
3226         return E_OUTOFMEMORY;
3227     return S_OK;
3228 }
3229
3230 HRESULT STDMETHODCALLTYPE WebView::supportsTextEncoding( 
3231     /* [retval][out] */ BOOL* supports)
3232 {
3233     *supports = TRUE;
3234     return S_OK;
3235 }
3236
3237 HRESULT STDMETHODCALLTYPE WebView::setCustomTextEncodingName( 
3238     /* [in] */ BSTR encodingName)
3239 {
3240     if (!m_mainFrame)
3241         return E_FAIL;
3242
3243     HRESULT hr;
3244     BString oldEncoding;
3245     hr = customTextEncodingName(&oldEncoding);
3246     if (FAILED(hr))
3247         return hr;
3248
3249     if (oldEncoding != encodingName && (!oldEncoding || !encodingName || wcscmp(oldEncoding, encodingName))) {
3250         if (Frame* coreFrame = core(m_mainFrame))
3251             coreFrame->loader().reloadWithOverrideEncoding(toString(encodingName));
3252     }
3253
3254     return S_OK;
3255 }
3256
3257 HRESULT STDMETHODCALLTYPE WebView::customTextEncodingName( 
3258     /* [retval][out] */ BSTR* encodingName)
3259 {
3260     HRESULT hr = S_OK;
3261     COMPtr<IWebDataSource> dataSource;
3262     COMPtr<WebDataSource> dataSourceImpl;
3263     *encodingName = 0;
3264
3265     if (!m_mainFrame)
3266         return E_FAIL;
3267
3268     if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
3269         hr = m_mainFrame->dataSource(&dataSource);
3270         if (FAILED(hr) || !dataSource)
3271             return hr;
3272     }
3273
3274     hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
3275     if (FAILED(hr))
3276         return hr;
3277
3278     BString str = dataSourceImpl->documentLoader()->overrideEncoding();
3279     if (FAILED(hr))
3280         return hr;
3281
3282     if (!*encodingName)
3283         *encodingName = BString(m_overrideEncoding).release();
3284
3285     if (!*encodingName && m_overrideEncoding.length())
3286         return E_OUTOFMEMORY;
3287
3288     return S_OK;
3289 }
3290
3291 HRESULT STDMETHODCALLTYPE WebView::setMediaStyle( 
3292     /* [in] */ BSTR /*media*/)
3293 {
3294     ASSERT_NOT_REACHED();
3295     return E_NOTIMPL;
3296 }
3297
3298 HRESULT STDMETHODCALLTYPE WebView::mediaStyle( 
3299     /* [retval][out] */ BSTR* /*media*/)
3300 {
3301     ASSERT_NOT_REACHED();
3302     return E_NOTIMPL;
3303 }
3304
3305 HRESULT STDMETHODCALLTYPE WebView::stringByEvaluatingJavaScriptFromString( 
3306     /* [in] */ BSTR script, // assumes input does not have "JavaScript" at the begining.
3307     /* [retval][out] */ BSTR* result)
3308 {
3309     if (!result) {
3310         ASSERT_NOT_REACHED();
3311         return E_POINTER;
3312     }
3313
3314     *result = 0;
3315
3316     Frame* coreFrame = core(m_mainFrame);
3317     if (!coreFrame)
3318         return E_FAIL;
3319
3320     JSC::JSValue scriptExecutionResult = coreFrame->script().executeScript(WTF::String(script), true).jsValue();
3321     if (!scriptExecutionResult)
3322         return E_FAIL;
3323     else if (scriptExecutionResult.isString()) {
3324         JSC::ExecState* exec = coreFrame->script().globalObject(mainThreadNormalWorld())->globalExec();
3325         JSC::JSLockHolder lock(exec);
3326         *result = BString(scriptExecutionResult.getString(exec));
3327     }
3328
3329     return S_OK;
3330 }
3331
3332 HRESULT STDMETHODCALLTYPE WebView::windowScriptObject( 
3333     /* [retval][out] */ IWebScriptObject** /*webScriptObject*/)
3334 {
3335     ASSERT_NOT_REACHED();
3336     return E_NOTIMPL;
3337 }
3338
3339 HRESULT STDMETHODCALLTYPE WebView::setPreferences( 
3340     /* [in] */ IWebPreferences* prefs)
3341 {
3342     if (!prefs)
3343         prefs = WebPreferences::sharedStandardPreferences();
3344
3345     if (m_preferences == prefs)
3346         return S_OK;
3347
3348     COMPtr<WebPreferences> webPrefs(Query, prefs);
3349     if (!webPrefs)
3350         return E_NOINTERFACE;
3351     webPrefs->willAddToWebView();
3352
3353     COMPtr<WebPreferences> oldPrefs = m_preferences;
3354
3355     IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
3356     nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3357
3358     BString identifier;
3359     oldPrefs->identifier(&identifier);
3360     oldPrefs->didRemoveFromWebView();
3361     oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
3362
3363     m_preferences = webPrefs;
3364
3365     if (identifier)
3366         WebPreferences::removeReferenceForIdentifier(identifier);
3367
3368     nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3369
3370     m_preferences->postPreferencesChangesNotification();
3371
3372     return S_OK;
3373 }
3374
3375 HRESULT STDMETHODCALLTYPE WebView::preferences( 
3376     /* [retval][out] */ IWebPreferences** prefs)
3377 {
3378     if (!prefs)
3379         return E_POINTER;
3380     *prefs = m_preferences.get();
3381     if (m_preferences)
3382         m_preferences->AddRef();
3383     return S_OK;
3384 }
3385
3386 HRESULT STDMETHODCALLTYPE WebView::setPreferencesIdentifier( 
3387     /* [in] */ BSTR /*anIdentifier*/)
3388 {
3389     ASSERT_NOT_REACHED();
3390     return E_NOTIMPL;
3391 }
3392
3393 HRESULT STDMETHODCALLTYPE WebView::preferencesIdentifier( 
3394     /* [retval][out] */ BSTR* /*anIdentifier*/)
3395 {
3396     ASSERT_NOT_REACHED();
3397     return E_NOTIMPL;
3398 }
3399
3400 static void systemParameterChanged(WPARAM parameter)
3401 {
3402 #if USE(CG)
3403     if (parameter == SPI_SETFONTSMOOTHING || parameter == SPI_SETFONTSMOOTHINGTYPE || parameter == SPI_SETFONTSMOOTHINGCONTRAST || parameter == SPI_SETFONTSMOOTHINGORIENTATION)
3404         wkSystemFontSmoothingChanged();
3405 #endif
3406 }
3407
3408 void WebView::windowReceivedMessage(HWND, UINT message, WPARAM wParam, LPARAM)
3409 {
3410     switch (message) {
3411     case WM_NCACTIVATE:
3412         updateActiveStateSoon();
3413         if (!wParam)
3414             deleteBackingStoreSoon();
3415         break;
3416     case WM_SETTINGCHANGE:
3417         systemParameterChanged(wParam);
3418         break;
3419     }
3420 }
3421
3422 void WebView::updateActiveStateSoon() const
3423 {
3424     // This function is called while processing the WM_NCACTIVATE message.
3425     // While processing WM_NCACTIVATE when we are being deactivated, GetActiveWindow() will
3426     // still return our window. If we were to call updateActiveState() in that case, we would
3427     // wrongly think that we are still the active window. To work around this, we update our
3428     // active state after a 0-delay timer fires, at which point GetActiveWindow() will return
3429     // the newly-activated window.
3430
3431     SetTimer(m_viewWindow, UpdateActiveStateTimer, 0, 0);
3432 }
3433
3434 void WebView::deleteBackingStoreSoon()
3435 {
3436     if (pendingDeleteBackingStoreSet.size() > 2) {
3437         Vector<WebView*> views;
3438         HashSet<WebView*>::iterator end = pendingDeleteBackingStoreSet.end();
3439         for (HashSet<WebView*>::iterator it = pendingDeleteBackingStoreSet.begin(); it != end; ++it)
3440             views.append(*it);
3441         for (int i = 0; i < views.size(); ++i)
3442             views[i]->deleteBackingStore();
3443         ASSERT(pendingDeleteBackingStoreSet.isEmpty());
3444     }
3445
3446     pendingDeleteBackingStoreSet.add(this);
3447     m_deleteBackingStoreTimerActive = true;
3448     SetTimer(m_viewWindow, DeleteBackingStoreTimer, delayBeforeDeletingBackingStoreMsec, 0);
3449 }
3450
3451 void WebView::cancelDeleteBackingStoreSoon()
3452 {
3453     if (!m_deleteBackingStoreTimerActive)
3454         return;
3455     pendingDeleteBackingStoreSet.remove(this);
3456     m_deleteBackingStoreTimerActive = false;
3457     KillTimer(m_viewWindow, DeleteBackingStoreTimer);
3458 }
3459
3460 HRESULT STDMETHODCALLTYPE WebView::setHostWindow( 
3461     /* [in] */ OLE_HANDLE oleWindow)
3462 {
3463     HWND window = (HWND)(ULONG64)oleWindow;
3464     if (m_viewWindow) {
3465         if (window)
3466             SetParent(m_viewWindow, window);
3467         else if (!isBeingDestroyed()) {
3468             // Turn the WebView into a message-only window so it will no longer be a child of the
3469             // old host window and will be hidden from screen. We only do this when
3470             // isBeingDestroyed() is false because doing this while handling WM_DESTROY can leave
3471             // m_viewWindow in a weird state (see <http://webkit.org/b/29337>).
3472             SetParent(m_viewWindow, HWND_MESSAGE);
3473         }
3474     }
3475
3476     m_hostWindow = window;
3477
3478     windowAncestryDidChange();
3479
3480     return S_OK;
3481 }
3482
3483 HRESULT STDMETHODCALLTYPE WebView::hostWindow( 
3484     /* [retval][out] */ OLE_HANDLE* window)
3485 {
3486     *window = (OLE_HANDLE)(ULONG64)m_hostWindow;
3487     return S_OK;
3488 }
3489
3490
3491 static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
3492 {
3493     return forward
3494         ? curr->tree().traverseNextWithWrap(wrapFlag)
3495         : curr->tree().traversePreviousWithWrap(wrapFlag);
3496 }
3497
3498 HRESULT STDMETHODCALLTYPE WebView::searchFor( 
3499     /* [in] */ BSTR str,
3500     /* [in] */ BOOL forward,
3501     /* [in] */ BOOL caseFlag,
3502     /* [in] */ BOOL wrapFlag,
3503     /* [retval][out] */ BOOL* found)
3504 {
3505     if (!found)
3506         return E_INVALIDARG;
3507     
3508     if (!m_page)
3509         return E_UNEXPECTED;
3510
3511     if (!str || !SysStringLen(str))
3512         return E_INVALIDARG;
3513
3514     FindOptions options = (caseFlag ? 0 : CaseInsensitive) | (forward ? 0 : Backwards) | (wrapFlag ? WrapAround : 0);
3515     *found = m_page->findString(toString(str), options);
3516     return S_OK;
3517 }
3518
3519 bool WebView::active()
3520 {
3521     HWND activeWindow = GetActiveWindow();
3522     if (usesLayeredWindow() && activeWindow == m_viewWindow)
3523         return true;
3524
3525     return (activeWindow && m_topLevelParent == findTopLevelParent(activeWindow));
3526 }
3527
3528 void WebView::updateActiveState()
3529 {
3530     m_page->focusController().setActive(active());
3531 }
3532
3533 HRESULT STDMETHODCALLTYPE WebView::updateFocusedAndActiveState()
3534 {
3535     updateActiveState();
3536
3537     bool active = m_page->focusController().isActive();
3538     Frame& mainFrame = m_page->mainFrame();
3539     Frame& focusedFrame = m_page->focusController().focusedOrMainFrame();
3540     mainFrame.selection().setFocused(active && &mainFrame == &focusedFrame);
3541
3542     return S_OK;
3543 }
3544
3545 HRESULT STDMETHODCALLTYPE WebView::executeCoreCommandByName(BSTR name, BSTR value)
3546 {
3547     m_page->focusController().focusedOrMainFrame().editor().command(toString(name)).execute(toString(value));
3548
3549     return S_OK;
3550 }
3551
3552 HRESULT STDMETHODCALLTYPE WebView::clearMainFrameName()
3553 {
3554     m_page->mainFrame().tree().clearName();
3555
3556     return S_OK;
3557 }
3558
3559 HRESULT STDMETHODCALLTYPE WebView::markAllMatchesForText(
3560     BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, UINT* matches)
3561 {
3562     if (!matches)
3563         return E_INVALIDARG;
3564
3565     if (!m_page)
3566         return E_UNEXPECTED;
3567
3568     if (!str || !SysStringLen(str))
3569         return E_INVALIDARG;
3570
3571     *matches = m_page->markAllMatchesForText(toString(str), caseSensitive ? TextCaseSensitive : TextCaseInsensitive, highlight, limit);
3572     return S_OK;
3573 }
3574
3575 HRESULT STDMETHODCALLTYPE WebView::unmarkAllTextMatches()
3576 {
3577     if (!m_page)
3578         return E_UNEXPECTED;
3579
3580     m_page->unmarkAllTextMatches();
3581     return S_OK;
3582 }
3583
3584 HRESULT STDMETHODCALLTYPE WebView::rectsForTextMatches(
3585     IEnumTextMatches** pmatches)
3586 {
3587     Vector<IntRect> allRects;
3588     WebCore::Frame* frame = &m_page->mainFrame();
3589     do {
3590         if (Document* document = frame->document()) {
3591             IntRect visibleRect = frame->view()->visibleContentRect();
3592             Vector<IntRect> frameRects = document->markers().renderedRectsForMarkers(DocumentMarker::TextMatch);
3593             IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
3594             frameOffset = frame->view()->convertToContainingWindow(frameOffset);
3595
3596             Vector<IntRect>::iterator end = frameRects.end();
3597             for (Vector<IntRect>::iterator it = frameRects.begin(); it < end; it++) {
3598                 it->intersect(visibleRect);
3599                 it->move(frameOffset.x(), frameOffset.y());
3600                 allRects.append(*it);
3601             }
3602         }
3603         frame = incrementFrame(frame, true, false);
3604     } while (frame);
3605
3606     return createMatchEnumerator(&allRects, pmatches);
3607 }
3608
3609 HRESULT STDMETHODCALLTYPE WebView::generateSelectionImage(BOOL forceWhiteText, OLE_HANDLE* hBitmap)
3610 {
3611     *hBitmap = 0;
3612
3613     WebCore::Frame& frame = m_page->focusController().focusedOrMainFrame();
3614
3615     auto bitmap = imageFromSelection(&frame, forceWhiteText ? TRUE : FALSE);
3616     *hBitmap = static_cast<OLE_HANDLE>(reinterpret_cast<ULONG64>(bitmap.leak()));
3617
3618     return S_OK;
3619 }
3620
3621 HRESULT STDMETHODCALLTYPE WebView::selectionRect(RECT* rc)
3622 {
3623     WebCore::Frame& frame = m_page->focusController().focusedOrMainFrame();
3624
3625     IntRect ir = enclosingIntRect(frame.selection().bounds());
3626     ir = frame.view()->convertToContainingWindow(ir);
3627     ir.move(-frame.view()->scrollOffset().width(), -frame.view()->scrollOffset().height());
3628     rc->left = ir.x();
3629     rc->top = ir.y();
3630     rc->bottom = rc->top + ir.height();
3631     rc->right = rc->left + ir.width();
3632
3633     return S_OK;
3634 }
3635
3636 HRESULT STDMETHODCALLTYPE WebView::registerViewClass( 
3637     /* [in] */ IWebDocumentView* /*view*/,
3638     /* [in] */ IWebDocumentRepresentation* /*representation*/,
3639     /* [in] */ BSTR /*forMIMEType*/)
3640 {
3641     ASSERT_NOT_REACHED();
3642     return E_NOTIMPL;
3643 }
3644
3645 HRESULT STDMETHODCALLTYPE WebView::setGroupName( 
3646         /* [in] */ BSTR groupName)
3647 {
3648     if (!m_page)
3649         return S_OK;
3650     m_page->setGroupName(toString(groupName));
3651     return S_OK;
3652 }
3653     
3654 HRESULT STDMETHODCALLTYPE WebView::groupName( 
3655         /* [retval][out] */ BSTR* groupName)
3656 {
3657     *groupName = 0;
3658     if (!m_page)
3659         return S_OK;
3660     String groupNameString = m_page->groupName();
3661     *groupName = SysAllocStringLen(groupNameString.characters(), groupNameString.length());
3662     if (!*groupName && groupNameString.length())
3663         return E_OUTOFMEMORY;
3664     return S_OK;
3665 }
3666     
3667 HRESULT STDMETHODCALLTYPE WebView::estimatedProgress( 
3668         /* [retval][out] */ double* estimatedProgress)
3669 {
3670     *estimatedProgress = m_page->progress().estimatedProgress();
3671     return S_OK;
3672 }
3673     
3674 HRESULT STDMETHODCALLTYPE WebView::isLoading( 
3675         /* [retval][out] */ BOOL* isLoading)
3676 {
3677     COMPtr<IWebDataSource> dataSource;
3678     COMPtr<IWebDataSource> provisionalDataSource;
3679
3680     if (!isLoading)
3681         return E_POINTER;
3682
3683     *isLoading = FALSE;
3684
3685     if (!m_mainFrame)
3686         return E_FAIL;
3687
3688     if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
3689         dataSource->isLoading(isLoading);
3690
3691     if (*isLoading)
3692         return S_OK;
3693
3694     if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
3695         provisionalDataSource->isLoading(isLoading);
3696     return S_OK;
3697 }
3698     
3699 HRESULT STDMETHODCALLTYPE WebView::elementAtPoint( 
3700         /* [in] */ LPPOINT point,
3701         /* [retval][out] */ IPropertyBag** elementDictionary)
3702 {
3703     if (!elementDictionary) {
3704         ASSERT_NOT_REACHED();
3705         return E_POINTER;
3706     }
3707
3708     *elementDictionary = 0;
3709
3710     Frame* frame = core(m_mainFrame);
3711     if (!frame)
3712         return E_FAIL;
3713
3714     IntPoint webCorePoint = IntPoint(point->x, point->y);
3715     HitTestResult result = HitTestResult(webCorePoint);
3716     if (frame->contentRenderer())
3717         result = frame->eventHandler().hitTestResultAtPoint(webCorePoint);
3718     *elementDictionary = WebElementPropertyBag::createInstance(result);
3719     return S_OK;
3720 }
3721     
3722 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForSelection( 
3723     /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3724 {
3725     ASSERT_NOT_REACHED();
3726     return E_NOTIMPL;
3727 }
3728     
3729 HRESULT STDMETHODCALLTYPE WebView::writeSelectionWithPasteboardTypes( 
3730         /* [size_is][in] */ BSTR* /*types*/,
3731         /* [in] */ int /*cTypes*/,
3732         /* [in] */ IDataObject* /*pasteboard*/)
3733 {
3734     ASSERT_NOT_REACHED();
3735     return E_NOTIMPL;
3736 }
3737     
3738 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForElement( 
3739     /* [in] */ IPropertyBag* /*elementDictionary*/,
3740     /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3741 {
3742     ASSERT_NOT_REACHED();
3743     return E_NOTIMPL;
3744 }
3745     
3746 HRESULT STDMETHODCALLTYPE WebView::writeElement( 
3747         /* [in] */ IPropertyBag* /*elementDictionary*/,
3748         /* [size_is][in] */ BSTR* /*withPasteboardTypes*/,
3749         /* [in] */ int /*cWithPasteboardTypes*/,
3750         /* [in] */ IDataObject* /*pasteboard*/)
3751 {
3752     ASSERT_NOT_REACHED();
3753     return E_NOTIMPL;
3754 }
3755     
3756 HRESULT STDMETHODCALLTYPE WebView::selectedText(
3757         /* [out, retval] */ BSTR* text)
3758 {
3759     if (!text) {
3760         ASSERT_NOT_REACHED();
3761         return E_POINTER;
3762     }
3763
3764     *text = 0;
3765
3766     Frame* focusedFrame = m_page ? &m_page->focusController().focusedOrMainFrame() : 0;
3767     if (!focusedFrame)
3768         return E_FAIL;
3769
3770     String frameSelectedText = focusedFrame->editor().selectedText();
3771     *text = SysAllocStringLen(frameSelectedText.characters(), frameSelectedText.length());
3772     if (!*text && frameSelectedText.length())
3773         return E_OUTOFMEMORY;
3774     return S_OK;
3775 }
3776
3777 HRESULT STDMETHODCALLTYPE WebView::centerSelectionInVisibleArea(
3778         /* [in] */ IUnknown* /* sender */)
3779 {
3780     Frame* coreFrame = core(m_mainFrame);
3781     if (!coreFrame)
3782         return E_FAIL;
3783
3784     coreFrame->selection().revealSelection(ScrollAlignment::alignCenterAlways);
3785     return S_OK;
3786 }
3787
3788
3789 HRESULT STDMETHODCALLTYPE WebView::moveDragCaretToPoint( 
3790         /* [in] */ LPPOINT /*point*/)
3791 {
3792     ASSERT_NOT_REACHED();
3793     return E_NOTIMPL;
3794 }
3795     
3796 HRESULT STDMETHODCALLTYPE WebView::removeDragCaret( void)
3797 {
3798     ASSERT_NOT_REACHED();
3799     return E_NOTIMPL;
3800 }
3801     
3802 HRESULT STDMETHODCALLTYPE WebView::setDrawsBackground( 
3803         /* [in] */ BOOL /*drawsBackground*/)
3804 {
3805     ASSERT_NOT_REACHED();
3806     return E_NOTIMPL;
3807 }
3808     
3809 HRESULT STDMETHODCALLTYPE WebView::drawsBackground( 
3810         /* [retval][out] */ BOOL* /*drawsBackground*/)
3811 {
3812     ASSERT_NOT_REACHED();
3813     return E_NOTIMPL;
3814 }
3815     
3816 HRESULT STDMETHODCALLTYPE WebView::setMainFrameURL( 
3817         /* [in] */ BSTR /*urlString*/)
3818 {
3819     ASSERT_NOT_REACHED();
3820     return E_NOTIMPL;
3821 }
3822     
3823 HRESULT STDMETHODCALLTYPE WebView::mainFrameURL( 
3824         /* [retval][out] */ BSTR* urlString)
3825 {
3826     if (!urlString)
3827         return E_POINTER;
3828
3829     if (!m_mainFrame)
3830         return E_FAIL;
3831
3832     COMPtr<IWebDataSource> dataSource;
3833
3834     if (FAILED(m_mainFrame->provisionalDataSource(&dataSource))) {
3835         if (FAILED(m_mainFrame->dataSource(&dataSource)))
3836             return E_FAIL;
3837     }
3838
3839     if (!dataSource) {
3840         *urlString = 0;
3841         return S_OK;
3842     }
3843     
3844     COMPtr<IWebMutableURLRequest> request;
3845     if (FAILED(dataSource->request(&request)) || !request)
3846         return E_FAIL;
3847
3848     if (FAILED(request->URL(urlString)))
3849         return E_FAIL;
3850
3851     return S_OK;
3852 }
3853     
3854 HRESULT STDMETHODCALLTYPE WebView::mainFrameDocument( 
3855         /* [retval][out] */ IDOMDocument** document)
3856 {
3857     if (document)
3858         *document = 0;
3859     if (!m_mainFrame)
3860         return E_FAIL;
3861     return m_mainFrame->DOMDocument(document);
3862 }
3863     
3864 HRESULT STDMETHODCALLTYPE WebView::mainFrameTitle( 
3865         /* [retval][out] */ BSTR* /*title*/)
3866 {
3867     ASSERT_NOT_REACHED();
3868     return E_NOTIMPL;
3869 }
3870     
3871 HRESULT STDMETHODCALLTYPE WebView::mainFrameIcon( 
3872         /* [retval][out] */ OLE_HANDLE* /*hBitmap*/)
3873 {
3874     ASSERT_NOT_REACHED();
3875     return E_NOTIMPL;
3876 }
3877
3878 HRESULT STDMETHODCALLTYPE WebView::registerURLSchemeAsLocal( 
3879         /* [in] */ BSTR scheme)
3880 {
3881     if (!scheme)
3882         return E_POINTER;
3883
3884     SchemeRegistry::registerURLSchemeAsLocal(toString(scheme));
3885
3886     return S_OK;
3887 }
3888
3889 // IWebIBActions ---------------------------------------------------------------
3890
3891 HRESULT STDMETHODCALLTYPE WebView::takeStringURLFrom( 
3892         /* [in] */ IUnknown* /*sender*/)
3893 {
3894     ASSERT_NOT_REACHED();
3895     return E_NOTIMPL;
3896 }
3897     
3898 HRESULT STDMETHODCALLTYPE WebView::stopLoading( 
3899         /* [in] */ IUnknown* /*sender*/)
3900 {
3901     if (!m_mainFrame)
3902         return E_FAIL;
3903
3904     return m_mainFrame->stopLoading();
3905 }
3906     
3907 HRESULT STDMETHODCALLTYPE WebView::reload( 
3908         /* [in] */ IUnknown* /*sender*/)
3909 {
3910     if (!m_mainFrame)
3911         return E_FAIL;
3912
3913     return m_mainFrame->reload();
3914 }
3915     
3916 HRESULT STDMETHODCALLTYPE WebView::canGoBack( 
3917         /* [in] */ IUnknown* /*sender*/,
3918         /* [retval][out] */ BOOL* result)
3919 {
3920     *result = !!(m_page->backForwardClient()->backItem() && !m_page->defersLoading());
3921     return S_OK;
3922 }
3923     
3924 HRESULT STDMETHODCALLTYPE WebView::goBack( 
3925         /* [in] */ IUnknown* /*sender*/)
3926 {
3927     ASSERT_NOT_REACHED();
3928     return E_NOTIMPL;
3929 }
3930     
3931 HRESULT STDMETHODCALLTYPE WebView::canGoForward( 
3932         /* [in] */ IUnknown* /*sender*/,
3933         /* [retval][out] */ BOOL* result)
3934 {
3935     *result = !!(m_page->backForwardClient()->forwardItem() && !m_page->defersLoading());
3936     return S_OK;
3937 }
3938     
3939 HRESULT STDMETHODCALLTYPE WebView::goForward( 
3940         /* [in] */ IUnknown* /*sender*/)
3941 {
3942     ASSERT_NOT_REACHED();
3943     return E_NOTIMPL;
3944 }
3945
3946 // FIXME: This code should move into WebCore so it can be shared by all the WebKits.
3947 #define MinimumZoomMultiplier   0.5f
3948 #define MaximumZoomMultiplier   3.0f
3949 #define ZoomMultiplierRatio     1.2f
3950
3951 HRESULT STDMETHODCALLTYPE WebView::canMakeTextLarger( 
3952         /* [in] */ IUnknown* /*sender*/,
3953         /* [retval][out] */ BOOL* result)
3954 {
3955     bool canGrowMore = canZoomIn(m_zoomsTextOnly);
3956     *result = canGrowMore ? TRUE : FALSE;
3957     return S_OK;
3958 }
3959
3960 HRESULT STDMETHODCALLTYPE WebView::canZoomPageIn( 
3961         /* [in] */ IUnknown* /*sender*/,
3962         /* [retval][out] */ BOOL* result)
3963 {
3964     bool canGrowMore = canZoomIn(false);
3965     *result = canGrowMore ? TRUE : FALSE;
3966     return S_OK;
3967 }
3968
3969 bool WebView::canZoomIn(bool isTextOnly)
3970 {
3971     return zoomMultiplier(isTextOnly) * ZoomMultiplierRatio < MaximumZoomMultiplier;
3972 }
3973     
3974 HRESULT STDMETHODCALLTYPE WebView::makeTextLarger( 
3975         /* [in] */ IUnknown* /*sender*/)
3976 {
3977     return zoomIn(m_zoomsTextOnly);
3978 }
3979
3980 HRESULT STDMETHODCALLTYPE WebView::zoomPageIn( 
3981         /* [in] */ IUnknown* /*sender*/)
3982 {
3983     return zoomIn(false);
3984 }
3985
3986 HRESULT WebView::zoomIn(bool isTextOnly)
3987 {
3988     if (!canZoomIn(isTextOnly))
3989         return E_FAIL;
3990     setZoomMultiplier(zoomMultiplier(isTextOnly) * ZoomMultiplierRatio, isTextOnly);
3991     return S_OK;
3992 }
3993
3994 HRESULT STDMETHODCALLTYPE WebView::canMakeTextSmaller( 
3995         /* [in] */ IUnknown* /*sender*/,
3996         /* [retval][out] */ BOOL* result)
3997 {
3998     bool canShrinkMore = canZoomOut(m_zoomsTextOnly);
3999     *result = canShrinkMore ? TRUE : FALSE;
4000     return S_OK;
4001 }
4002
4003 HRESULT STDMETHODCALLTYPE WebView::canZoomPageOut( 
4004         /* [in] */ IUnknown* /*sender*/,
4005         /* [retval][out] */ BOOL* result)
4006 {
4007     bool canShrinkMore = canZoomOut(false);
4008     *result = canShrinkMore ? TRUE : FALSE;
4009     return S_OK;
4010 }
4011
4012 bool WebView::canZoomOut(bool isTextOnly)
4013 {
4014     return zoomMultiplier(isTextOnly) / ZoomMultiplierRatio > MinimumZoomMultiplier;
4015 }
4016
4017 HRESULT STDMETHODCALLTYPE WebView::makeTextSmaller( 
4018         /* [in] */ IUnknown* /*sender*/)
4019 {
4020     return zoomOut(m_zoomsTextOnly);
4021 }
4022
4023 HRESULT STDMETHODCALLTYPE WebView::zoomPageOut( 
4024         /* [in] */ IUnknown* /*sender*/)
4025 {
4026     return zoomOut(false);
4027 }
4028
4029 HRESULT WebView::zoomOut(bool isTextOnly)
4030 {
4031     if (!canZoomOut(isTextOnly))
4032         return E_FAIL;
4033     setZoomMultiplier(zoomMultiplier(isTextOnly) / ZoomMultiplierRatio, isTextOnly);
4034     return S_OK;
4035 }
4036
4037 HRESULT STDMETHODCALLTYPE WebView::canMakeTextStandardSize( 
4038     /* [in] */ IUnknown* /*sender*/,
4039     /* [retval][out] */ BOOL* result)
4040 {
4041     // 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.
4042     bool notAlreadyStandard = canResetZoom(true);
4043     *result = notAlreadyStandard ? TRUE : FALSE;
4044     return S_OK;
4045 }
4046
4047 HRESULT STDMETHODCALLTYPE WebView::canResetPageZoom( 
4048     /* [in] */ IUnknown* /*sender*/,
4049     /* [retval][out] */ BOOL* result)
4050 {
4051     bool notAlreadyStandard = canResetZoom(false);
4052     *result = notAlreadyStandard ? TRUE : FALSE;
4053     return S_OK;
4054 }
4055
4056 bool WebView::canResetZoom(bool isTextOnly)
4057 {
4058     return zoomMultiplier(isTextOnly) != 1.0f;
4059 }
4060
4061 HRESULT STDMETHODCALLTYPE WebView::makeTextStandardSize( 
4062     /* [in] */ IUnknown* /*sender*/)
4063 {
4064     return resetZoom(true);
4065 }
4066
4067 HRESULT STDMETHODCALLTYPE WebView::resetPageZoom( 
4068     /* [in] */ IUnknown* /*sender*/)
4069 {
4070     return resetZoom(false);
4071 }
4072
4073 HRESULT WebView::resetZoom(bool isTextOnly)
4074 {
4075     if (!canResetZoom(isTextOnly))
4076         return E_FAIL;
4077     setZoomMultiplier(1.0f, isTextOnly);
4078     return S_OK;
4079 }
4080
4081 HRESULT STDMETHODCALLTYPE WebView::toggleContinuousSpellChecking( 
4082     /* [in] */ IUnknown* /*sender*/)
4083 {
4084     HRESULT hr;
4085     BOOL enabled;
4086     if (FAILED(hr = isContinuousSpellCheckingEnabled(&enabled)))
4087         return hr;
4088     return setContinuousSpellCheckingEnabled(enabled ? FALSE : TRUE);
4089 }
4090
4091 HRESULT STDMETHODCALLTYPE WebView::toggleSmartInsertDelete( 
4092     /* [in] */ IUnknown* /*sender*/)
4093 {
4094     BOOL enabled = FALSE;
4095     HRESULT hr = smartInsertDeleteEnabled(&enabled);
4096     if (FAILED(hr))
4097         return hr;
4098
4099     return setSmartInsertDeleteEnabled(enabled ? FALSE : TRUE);
4100 }
4101
4102 HRESULT STDMETHODCALLTYPE WebView::toggleGrammarChecking( 
4103     /* [in] */ IUnknown* /*sender*/)
4104 {
4105     BOOL enabled;
4106     HRESULT hr = isGrammarCheckingEnabled(&enabled);
4107     if (FAILED(hr))
4108         return hr;
4109
4110     return setGrammarCheckingEnabled(enabled ? FALSE : TRUE);
4111 }
4112
4113 HRESULT STDMETHODCALLTYPE WebView::reloadFromOrigin( 
4114         /* [in] */ IUnknown* /*sender*/)
4115 {
4116     if (!m_mainFrame)
4117         return E_FAIL;
4118
4119     return m_mainFrame->reloadFromOrigin();
4120 }
4121
4122 // IWebViewCSS -----------------------------------------------------------------
4123
4124 HRESULT STDMETHODCALLTYPE WebView::computedStyleForElement( 
4125         /* [in] */ IDOMElement* /*element*/,
4126         /* [in] */ BSTR /*pseudoElement*/,
4127         /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
4128 {
4129     ASSERT_NOT_REACHED();
4130     return E_NOTIMPL;
4131 }
4132
4133 // IWebViewEditing -------------------------------------------------------------
4134
4135 HRESULT STDMETHODCALLTYPE WebView::editableDOMRangeForPoint( 
4136         /* [in] */ LPPOINT /*point*/,
4137         /* [retval][out] */ IDOMRange** /*range*/)
4138 {
4139     ASSERT_NOT_REACHED();
4140     return E_NOTIMPL;
4141 }
4142     
4143 HRESULT STDMETHODCALLTYPE WebView::setSelectedDOMRange( 
4144         /* [in] */ IDOMRange* /*range*/,
4145         /* [in] */ WebSelectionAffinity /*affinity*/)
4146 {
4147     ASSERT_NOT_REACHED();
4148     return E_NOTIMPL;
4149 }
4150     
4151 HRESULT STDMETHODCALLTYPE WebView::selectedDOMRange( 
4152         /* [retval][out] */ IDOMRange** /*range*/)
4153 {
4154     ASSERT_NOT_REACHED();
4155     return E_NOTIMPL;
4156 }
4157     
4158 HRESULT STDMETHODCALLTYPE WebView::selectionAffinity( 
4159         /* [retval][out][retval][out] */ WebSelectionAffinity* /*affinity*/)
4160 {
4161     ASSERT_NOT_REACHED();
4162     return E_NOTIMPL;
4163 }
4164     
4165 HRESULT STDMETHODCALLTYPE WebView::setEditable( 
4166         /* [in] */ BOOL /*flag*/)
4167 {
4168     ASSERT_NOT_REACHED();
4169     return E_NOTIMPL;
4170 }
4171     
4172 HRESULT STDMETHODCALLTYPE WebView::isEditable( 
4173         /* [retval][out] */ BOOL* /*isEditable*/)
4174 {
4175     ASSERT_NOT_REACHED();
4176     return E_NOTIMPL;
4177 }
4178     
4179 HRESULT STDMETHODCALLTYPE WebView::setTypingStyle( 
4180         /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
4181 {
4182     ASSERT_NOT_REACHED();
4183     return E_NOTIMPL;
4184 }
4185     
4186 HRESULT STDMETHODCALLTYPE WebView::typingStyle( 
4187         /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
4188 {
4189     ASSERT_NOT_REACHED();
4190     return E_NOTIMPL;
4191 }
4192     
4193 HRESULT STDMETHODCALLTYPE WebView::setSmartInsertDeleteEnabled( 
4194         /* [in] */ BOOL flag)
4195 {
4196     if (m_page->settings().smartInsertDeleteEnabled() != !!flag) {
4197         m_page->settings().setSmartInsertDeleteEnabled(!!flag);
4198         setSelectTrailingWhitespaceEnabled(!flag);
4199     }
4200     return S_OK;
4201 }
4202     
4203 HRESULT STDMETHODCALLTYPE WebView::smartInsertDeleteEnabled( 
4204         /* [retval][out] */ BOOL* enabled)
4205 {
4206     *enabled = m_page->settings().smartInsertDeleteEnabled() ? TRUE : FALSE;
4207     return S_OK;
4208 }
4209  
4210 HRESULT STDMETHODCALLTYPE WebView::setSelectTrailingWhitespaceEnabled( 
4211         /* [in] */ BOOL flag)
4212 {
4213     if (m_page->settings().selectTrailingWhitespaceEnabled() != !!flag) {
4214         m_page->settings().setSelectTrailingWhitespaceEnabled(!!flag);
4215         setSmartInsertDeleteEnabled(!flag);
4216     }
4217     return S_OK;
4218 }
4219     
4220 HRESULT STDMETHODCALLTYPE WebView::isSelectTrailingWhitespaceEnabled( 
4221         /* [retval][out] */ BOOL* enabled)
4222 {
4223     *enabled = m_page->settings().selectTrailingWhitespaceEnabled() ? TRUE : FALSE;
4224     return S_OK;
4225 }
4226
4227 HRESULT STDMETHODCALLTYPE WebView::setContinuousSpellCheckingEnabled( 
4228         /* [in] */ BOOL flag)
4229 {
4230     if (continuousSpellCheckingEnabled != !!flag) {
4231         continuousSpellCheckingEnabled = !!flag;
4232         COMPtr<IWebPreferences> prefs;
4233         if (SUCCEEDED(preferences(&prefs)))
4234             prefs->setContinuousSpellCheckingEnabled(flag);
4235     }
4236     
4237     BOOL spellCheckingEnabled;
4238     if (SUCCEEDED(isContinuousSpellCheckingEnabled(&spellCheckingEnabled)) && spellCheckingEnabled)
4239         preflightSpellChecker();
4240     else
4241         m_mainFrame->unmarkAllMisspellings();
4242
4243     return S_OK;
4244 }
4245     
4246 HRESULT STDMETHODCALLTYPE WebView::isContinuousSpellCheckingEnabled( 
4247         /* [retval][out] */ BOOL* enabled)
4248 {
4249     *enabled = (continuousSpellCheckingEnabled && continuousCheckingAllowed()) ? TRUE : FALSE;
4250     return S_OK;
4251 }
4252     
4253 HRESULT STDMETHODCALLTYPE WebView::spellCheckerDocumentTag( 
4254         /* [retval][out] */ int* tag)
4255 {
4256     // we just use this as a flag to indicate that we've spell checked the document
4257     // and need to close the spell checker out when the view closes.
4258     *tag = 0;
4259     m_hasSpellCheckerDocumentTag = true;
4260     return S_OK;
4261 }
4262
4263 static COMPtr<IWebEditingDelegate> spellingDelegateForTimer;
4264
4265 static void preflightSpellCheckerNow()
4266 {
4267     spellingDelegateForTimer->preflightChosenSpellServer();
4268     spellingDelegateForTimer = 0;
4269 }
4270
4271 static void CALLBACK preflightSpellCheckerTimerCallback(HWND, UINT, UINT_PTR id, DWORD)
4272 {
4273     ::KillTimer(0, id);
4274     preflightSpellCheckerNow();
4275 }
4276
4277 void WebView::preflightSpellChecker()
4278 {
4279     // As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
4280     if (!m_editingDelegate)
4281         return;
4282
4283     BOOL exists;
4284     spellingDelegateForTimer = m_editingDelegate;
4285     if (SUCCEEDED(m_editingDelegate->sharedSpellCheckerExists(&exists)) && exists)
4286         preflightSpellCheckerNow();
4287     else
4288         ::SetTimer(0, 0, 2000, preflightSpellCheckerTimerCallback);
4289 }
4290
4291 bool WebView::continuousCheckingAllowed()
4292 {
4293     static bool allowContinuousSpellChecking = true;
4294     static bool readAllowContinuousSpellCheckingDefault = false;
4295     if (!readAllowContinuousSpellCheckingDefault) {
4296         COMPtr<IWebPreferences> prefs;
4297         if (SUCCEEDED(preferences(&prefs))) {
4298     &