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