1ebd45e24f68c8cc1654fbf90d442db998ebaed2
[vuplus_webkit] / Source / WebKit / win / WebView.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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 "WebBackForwardList.h"
37 #include "WebChromeClient.h"
38 #include "WebContextMenuClient.h"
39 #include "WebCoreTextRenderer.h"
40 #include "WebDatabaseManager.h"
41 #include "WebDocumentLoader.h"
42 #include "WebDownload.h"
43 #include "WebDragClient.h"
44 #include "WebEditorClient.h"
45 #include "WebElementPropertyBag.h"
46 #include "WebFrame.h"
47 #include "WebGeolocationClient.h"
48 #include "WebGeolocationPosition.h"
49 #include "WebIconDatabase.h"
50 #include "WebInspector.h"
51 #include "WebInspectorClient.h"
52 #include "WebKit.h"
53 #include "WebKitDLL.h"
54 #include "WebKitLogging.h"
55 #include "WebKitStatisticsPrivate.h"
56 #include "WebKitSystemBits.h"
57 #include "WebMutableURLRequest.h"
58 #include "WebNotificationCenter.h"
59 #include "WebPlatformStrategies.h"
60 #include "WebPreferences.h"
61 #include "WebScriptWorld.h"
62 #include "resource.h"
63 #include <JavaScriptCore/APICast.h>
64 #include <JavaScriptCore/InitializeThreading.h>
65 #include <JavaScriptCore/JSLock.h>
66 #include <JavaScriptCore/JSValue.h>
67 #include <WebCore/AXObjectCache.h>
68 #include <WebCore/AbstractDatabase.h>
69 #include <WebCore/ApplicationCacheStorage.h>
70 #include <WebCore/BString.h>
71 #include <WebCore/BackForwardListImpl.h>
72 #include <WebCore/BitmapInfo.h>
73 #include <WebCore/Chrome.h>
74 #include <WebCore/ContextMenu.h>
75 #include <WebCore/ContextMenuController.h>
76 #include <WebCore/Cursor.h>
77 #include <WebCore/Document.h>
78 #include <WebCore/DocumentMarkerController.h>
79 #include <WebCore/DragController.h>
80 #include <WebCore/DragData.h>
81 #include <WebCore/Editor.h>
82 #include <WebCore/EventHandler.h>
83 #include <WebCore/EventNames.h>
84 #include <WebCore/FileSystem.h>
85 #include <WebCore/FloatQuad.h>
86 #include <WebCore/FocusController.h>
87 #include <WebCore/Frame.h>
88 #include <WebCore/FrameLoader.h>
89 #include <WebCore/FrameSelection.h>
90 #include <WebCore/FrameTree.h>
91 #include <WebCore/FrameView.h>
92 #include <WebCore/FrameWin.h>
93 #include <WebCore/GDIObjectCounter.h>
94 #include <WebCore/GraphicsContext.h>
95 #include <WebCore/HTMLMediaElement.h>
96 #include <WebCore/HTMLNames.h>
97 #include <WebCore/HistoryItem.h>
98 #include <WebCore/HitTestRequest.h>
99 #include <WebCore/HitTestResult.h>
100 #include <WebCore/IntRect.h>
101 #include <WebCore/JSElement.h>
102 #include <WebCore/KeyboardEvent.h>
103 #include <WebCore/Logging.h>
104 #include <WebCore/MIMETypeRegistry.h>
105 #include <WebCore/MemoryCache.h>
106 #include <WebCore/Page.h>
107 #include <WebCore/PageCache.h>
108 #include <WebCore/PageGroup.h>
109 #include <WebCore/PlatformKeyboardEvent.h>
110 #include <WebCore/PlatformMouseEvent.h>
111 #include <WebCore/PlatformWheelEvent.h>
112 #include <WebCore/PluginData.h>
113 #include <WebCore/PluginDatabase.h>
114 #include <WebCore/PluginView.h>
115 #include <WebCore/PopupMenu.h>
116 #include <WebCore/PopupMenuWin.h>
117 #include <WebCore/ProgressTracker.h>
118 #include <WebCore/RenderLayer.h>
119 #include <WebCore/RenderTheme.h>
120 #include <WebCore/RenderTreeAsText.h>
121 #include <WebCore/RenderView.h>
122 #include <WebCore/RenderWidget.h>
123 #include <WebCore/ResourceHandle.h>
124 #include <WebCore/ResourceHandleClient.h>
125 #include <WebCore/ResourceRequest.h>
126 #include <WebCore/SchemeRegistry.h>
127 #include <WebCore/ScriptValue.h>
128 #include <WebCore/Scrollbar.h>
129 #include <WebCore/ScrollbarTheme.h>
130 #include <WebCore/SecurityOrigin.h>
131 #include <WebCore/Settings.h>
132 #include <WebCore/SimpleFontData.h>
133 #include <WebCore/SystemInfo.h>
134 #include <WebCore/TypingCommand.h>
135 #include <WebCore/WindowMessageBroadcaster.h>
136 #include <WebCore/WindowsTouch.h>
137 #include <wtf/MainThread.h>
138
139 #if ENABLE(CLIENT_BASED_GEOLOCATION)
140 #include <WebCore/GeolocationController.h>
141 #include <WebCore/GeolocationError.h>
142 #endif
143
144 #if USE(CG)
145 #include <CoreGraphics/CGContext.h>
146 #endif
147
148 #if USE(CF)
149 #include <CoreFoundation/CoreFoundation.h>
150 #endif
151
152 #if USE(CFNETWORK)
153 #include <CFNetwork/CFURLCachePriv.h>
154 #include <CFNetwork/CFURLProtocolPriv.h>
155 #include <WebCore/CookieStorageCFNet.h>
156 #include <WebKitSystemInterface/WebKitSystemInterface.h> 
157 #endif
158
159 #if USE(ACCELERATED_COMPOSITING)
160 #include <WebCore/CACFLayerTreeHost.h>
161 #include <WebCore/PlatformCALayer.h>
162 #endif
163
164 #if ENABLE(FULLSCREEN_API)
165 #include <WebCore/FullScreenController.h>
166 #endif
167
168 #include <ShlObj.h>
169 #include <comutil.h>
170 #include <dimm.h>
171 #include <oleacc.h>
172 #include <wchar.h>
173 #include <windowsx.h>
174 #include <wtf/HashSet.h>
175 #include <wtf/text/CString.h>
176 #include <wtf/text/StringConcatenate.h>
177
178 // Soft link functions for gestures and panning feedback
179 SOFT_LINK_LIBRARY(USER32);
180 SOFT_LINK_OPTIONAL(USER32, GetGestureInfo, BOOL, WINAPI, (HGESTUREINFO, PGESTUREINFO));
181 SOFT_LINK_OPTIONAL(USER32, SetGestureConfig, BOOL, WINAPI, (HWND, DWORD, UINT, PGESTURECONFIG, UINT));
182 SOFT_LINK_OPTIONAL(USER32, CloseGestureInfoHandle, BOOL, WINAPI, (HGESTUREINFO));
183 SOFT_LINK_LIBRARY(Uxtheme);
184 SOFT_LINK_OPTIONAL(Uxtheme, BeginPanningFeedback, BOOL, WINAPI, (HWND));
185 SOFT_LINK_OPTIONAL(Uxtheme, EndPanningFeedback, BOOL, WINAPI, (HWND, BOOL));
186 SOFT_LINK_OPTIONAL(Uxtheme, UpdatePanningFeedback, BOOL, WINAPI, (HWND, LONG, LONG, BOOL));
187
188 using namespace WebCore;
189 using namespace std;
190 using JSC::JSLock;
191
192 static HMODULE accessibilityLib;
193 static HashSet<WebView*> pendingDeleteBackingStoreSet;
194
195 static String webKitVersionString();
196
197 WebView* kit(Page* page)
198 {
199     return page ? static_cast<WebView*>(static_cast<WebChromeClient*>(page->chrome()->client())->webView()) : 0;
200 }
201
202 class PreferencesChangedOrRemovedObserver : public IWebNotificationObserver {
203 public:
204     static PreferencesChangedOrRemovedObserver* sharedInstance();
205
206 private:
207     PreferencesChangedOrRemovedObserver() {}
208     ~PreferencesChangedOrRemovedObserver() {}
209
210     virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) { return E_FAIL; }
211     virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; }
212     virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; }
213
214 public:
215     // IWebNotificationObserver
216     virtual HRESULT STDMETHODCALLTYPE onNotify( 
217         /* [in] */ IWebNotification* notification);
218
219 private:
220     HRESULT notifyPreferencesChanged(WebCacheModel);
221     HRESULT notifyPreferencesRemoved(WebCacheModel);
222 };
223
224 PreferencesChangedOrRemovedObserver* PreferencesChangedOrRemovedObserver::sharedInstance()
225 {
226     static PreferencesChangedOrRemovedObserver* shared = new PreferencesChangedOrRemovedObserver;
227     return shared;
228 }
229
230 HRESULT PreferencesChangedOrRemovedObserver::onNotify(IWebNotification* notification)
231 {
232     HRESULT hr = S_OK;
233
234     COMPtr<IUnknown> unkPrefs;
235     hr = notification->getObject(&unkPrefs);
236     if (FAILED(hr))
237         return hr;
238
239     COMPtr<IWebPreferences> preferences(Query, unkPrefs);
240     if (!preferences)
241         return E_NOINTERFACE;
242
243     WebCacheModel cacheModel;
244     hr = preferences->cacheModel(&cacheModel);
245     if (FAILED(hr))
246         return hr;
247
248     BSTR nameBSTR;
249     hr = notification->name(&nameBSTR);
250     if (FAILED(hr))
251         return hr;
252     BString name;
253     name.adoptBSTR(nameBSTR);
254
255     if (wcscmp(name, WebPreferences::webPreferencesChangedNotification()) == 0)
256         return notifyPreferencesChanged(cacheModel);
257
258     if (wcscmp(name, WebPreferences::webPreferencesRemovedNotification()) == 0)
259         return notifyPreferencesRemoved(cacheModel);
260
261     ASSERT_NOT_REACHED();
262     return E_FAIL;
263 }
264
265 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesChanged(WebCacheModel cacheModel)
266 {
267     HRESULT hr = S_OK;
268
269     if (!WebView::didSetCacheModel() || cacheModel > WebView::cacheModel())
270         WebView::setCacheModel(cacheModel);
271     else if (cacheModel < WebView::cacheModel()) {
272         WebCacheModel sharedPreferencesCacheModel;
273         hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
274         if (FAILED(hr))
275             return hr;
276         WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
277     }
278
279     return hr;
280 }
281
282 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesRemoved(WebCacheModel cacheModel)
283 {
284     HRESULT hr = S_OK;
285
286     if (cacheModel == WebView::cacheModel()) {
287         WebCacheModel sharedPreferencesCacheModel;
288         hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
289         if (FAILED(hr))
290             return hr;
291         WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
292     }
293
294     return hr;
295 }
296
297
298 const LPCWSTR kWebViewWindowClassName = L"WebViewWindowClass";
299
300 const int WM_XP_THEMECHANGED = 0x031A;
301 const int WM_VISTA_MOUSEHWHEEL = 0x020E;
302
303 static const int maxToolTipWidth = 250;
304
305 static const int delayBeforeDeletingBackingStoreMsec = 5000;
306
307 static ATOM registerWebView();
308
309 static void initializeStaticObservers();
310
311 static HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences*);
312
313 HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches);
314
315 static bool continuousSpellCheckingEnabled;
316 static bool grammarCheckingEnabled;
317
318 static bool s_didSetCacheModel;
319 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
320
321 enum {
322     UpdateActiveStateTimer = 1,
323     DeleteBackingStoreTimer = 2,
324 };
325
326 // WebView ----------------------------------------------------------------
327
328 bool WebView::s_allowSiteSpecificHacks = false;
329
330 WebView::WebView()
331     : m_refCount(0)
332 #if !ASSERT_DISABLED
333     , m_deletionHasBegun(false)
334 #endif
335     , m_hostWindow(0)
336     , m_viewWindow(0)
337     , m_mainFrame(0)
338     , m_page(0)
339     , m_hasCustomDropTarget(false)
340     , m_useBackForwardList(true)
341     , m_userAgentOverridden(false)
342     , m_zoomMultiplier(1.0f)
343     , m_zoomsTextOnly(false)
344     , m_mouseActivated(false)
345     , m_dragData(0)
346     , m_currentCharacterCode(0)
347     , m_isBeingDestroyed(false)
348     , m_paintCount(0)
349     , m_hasSpellCheckerDocumentTag(false)
350     , m_smartInsertDeleteEnabled(false)
351     , m_didClose(false)
352     , m_inIMEComposition(0)
353     , m_toolTipHwnd(0)
354     , m_closeWindowTimer(0)
355     , m_topLevelParent(0)
356     , m_deleteBackingStoreTimerActive(false)
357     , m_transparent(false)
358     , m_selectTrailingWhitespaceEnabled(false)
359     , m_lastPanX(0)
360     , m_lastPanY(0)
361     , m_xOverpan(0)
362     , m_yOverpan(0)
363 #if USE(ACCELERATED_COMPOSITING)
364     , m_isAcceleratedCompositing(false)
365 #endif
366     , m_nextDisplayIsSynchronous(false)
367     , m_lastSetCursor(0)
368     , m_usesLayeredWindow(false)
369 {
370     JSC::initializeThreading();
371     WTF::initializeMainThread();
372
373     m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
374
375     CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper,(void**)&m_dropTargetHelper);
376
377     initializeStaticObservers();
378
379     WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
380     BOOL enabled;
381     if (SUCCEEDED(sharedPreferences->continuousSpellCheckingEnabled(&enabled)))
382         continuousSpellCheckingEnabled = !!enabled;
383     if (SUCCEEDED(sharedPreferences->grammarCheckingEnabled(&enabled)))
384         grammarCheckingEnabled = !!enabled;
385
386     WebViewCount++;
387     gClassCount++;
388     gClassNameCount.add("WebView");
389 }
390
391 WebView::~WebView()
392 {
393     deleteBackingStore();
394
395     // the tooltip window needs to be explicitly destroyed since it isn't a WS_CHILD
396     if (::IsWindow(m_toolTipHwnd))
397         ::DestroyWindow(m_toolTipHwnd);
398
399     ASSERT(!m_page);
400     ASSERT(!m_preferences);
401     ASSERT(!m_viewWindow);
402
403 #if USE(ACCELERATED_COMPOSITING)
404     ASSERT(!m_layerTreeHost);
405     ASSERT(!m_backingLayer);
406 #endif
407
408     WebViewCount--;
409     gClassCount--;
410     gClassNameCount.remove("WebView");
411 }
412
413 WebView* WebView::createInstance()
414 {
415     WebView* instance = new WebView();
416     instance->AddRef();
417     return instance;
418 }
419
420 void initializeStaticObservers()
421 {
422     static bool initialized;
423     if (initialized)
424         return;
425     initialized = true;
426
427     IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
428     notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesChangedNotification(), 0);
429     notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesRemovedNotification(), 0);
430 }
431
432 static HashSet<WebView*>& allWebViewsSet()
433 {
434     static HashSet<WebView*> allWebViewsSet;
435     return allWebViewsSet;
436 }
437
438 void WebView::addToAllWebViewsSet()
439 {
440     allWebViewsSet().add(this);
441 }
442
443 void WebView::removeFromAllWebViewsSet()
444 {
445     allWebViewsSet().remove(this);
446 }
447
448 void WebView::setCacheModel(WebCacheModel cacheModel)
449 {
450 #if USE(CFNETWORK)
451     if (s_didSetCacheModel && cacheModel == s_cacheModel)
452         return;
453
454     RetainPtr<CFURLCacheRef> cfurlCache(AdoptCF, CFURLCacheCopySharedURLCache());
455     RetainPtr<CFStringRef> cfurlCacheDirectory(AdoptCF, wkCopyFoundationCacheDirectory(0));
456     if (!cfurlCacheDirectory)
457         cfurlCacheDirectory.adoptCF(WebCore::localUserSpecificStorageDirectory().createCFString());
458
459     // As a fudge factor, use 1000 instead of 1024, in case the reported byte 
460     // count doesn't align exactly to a megabyte boundary.
461     unsigned long long memSize = WebMemorySize() / 1024 / 1000;
462     unsigned long long diskFreeSize = WebVolumeFreeSize(cfurlCacheDirectory.get()) / 1024 / 1000;
463
464     unsigned cacheTotalCapacity = 0;
465     unsigned cacheMinDeadCapacity = 0;
466     unsigned cacheMaxDeadCapacity = 0;
467     double deadDecodedDataDeletionInterval = 0;
468
469     unsigned pageCacheCapacity = 0;
470
471     CFIndex cfurlCacheMemoryCapacity = 0;
472     CFIndex cfurlCacheDiskCapacity = 0;
473
474     switch (cacheModel) {
475     case WebCacheModelDocumentViewer: {
476         // Page cache capacity (in pages)
477         pageCacheCapacity = 0;
478
479         // Object cache capacities (in bytes)
480         if (memSize >= 2048)
481             cacheTotalCapacity = 96 * 1024 * 1024;
482         else if (memSize >= 1536)
483             cacheTotalCapacity = 64 * 1024 * 1024;
484         else if (memSize >= 1024)
485             cacheTotalCapacity = 32 * 1024 * 1024;
486         else if (memSize >= 512)
487             cacheTotalCapacity = 16 * 1024 * 1024; 
488
489         cacheMinDeadCapacity = 0;
490         cacheMaxDeadCapacity = 0;
491
492         // Foundation memory cache capacity (in bytes)
493         cfurlCacheMemoryCapacity = 0;
494
495         // Foundation disk cache capacity (in bytes)
496         cfurlCacheDiskCapacity = CFURLCacheDiskCapacity(cfurlCache.get());
497
498         break;
499     }
500     case WebCacheModelDocumentBrowser: {
501         // Page cache capacity (in pages)
502         if (memSize >= 1024)
503             pageCacheCapacity = 3;
504         else if (memSize >= 512)
505             pageCacheCapacity = 2;
506         else if (memSize >= 256)
507             pageCacheCapacity = 1;
508         else
509             pageCacheCapacity = 0;
510
511         // Object cache capacities (in bytes)
512         if (memSize >= 2048)
513             cacheTotalCapacity = 96 * 1024 * 1024;
514         else if (memSize >= 1536)
515             cacheTotalCapacity = 64 * 1024 * 1024;
516         else if (memSize >= 1024)
517             cacheTotalCapacity = 32 * 1024 * 1024;
518         else if (memSize >= 512)
519             cacheTotalCapacity = 16 * 1024 * 1024; 
520
521         cacheMinDeadCapacity = cacheTotalCapacity / 8;
522         cacheMaxDeadCapacity = cacheTotalCapacity / 4;
523
524         // Foundation memory cache capacity (in bytes)
525         if (memSize >= 2048)
526             cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
527         else if (memSize >= 1024)
528             cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
529         else if (memSize >= 512)
530             cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
531         else
532             cfurlCacheMemoryCapacity =      512 * 1024; 
533
534         // Foundation disk cache capacity (in bytes)
535         if (diskFreeSize >= 16384)
536             cfurlCacheDiskCapacity = 50 * 1024 * 1024;
537         else if (diskFreeSize >= 8192)
538             cfurlCacheDiskCapacity = 40 * 1024 * 1024;
539         else if (diskFreeSize >= 4096)
540             cfurlCacheDiskCapacity = 30 * 1024 * 1024;
541         else
542             cfurlCacheDiskCapacity = 20 * 1024 * 1024;
543
544         break;
545     }
546     case WebCacheModelPrimaryWebBrowser: {
547         // Page cache capacity (in pages)
548         // (Research indicates that value / page drops substantially after 3 pages.)
549         if (memSize >= 2048)
550             pageCacheCapacity = 5;
551         else if (memSize >= 1024)
552             pageCacheCapacity = 4;
553         else if (memSize >= 512)
554             pageCacheCapacity = 3;
555         else if (memSize >= 256)
556             pageCacheCapacity = 2;
557         else
558             pageCacheCapacity = 1;
559
560         // Object cache capacities (in bytes)
561         // (Testing indicates that value / MB depends heavily on content and
562         // browsing pattern. Even growth above 128MB can have substantial 
563         // value / MB for some content / browsing patterns.)
564         if (memSize >= 2048)
565             cacheTotalCapacity = 128 * 1024 * 1024;
566         else if (memSize >= 1536)
567             cacheTotalCapacity = 96 * 1024 * 1024;
568         else if (memSize >= 1024)
569             cacheTotalCapacity = 64 * 1024 * 1024;
570         else if (memSize >= 512)
571             cacheTotalCapacity = 32 * 1024 * 1024; 
572
573         cacheMinDeadCapacity = cacheTotalCapacity / 4;
574         cacheMaxDeadCapacity = cacheTotalCapacity / 2;
575
576         // This code is here to avoid a PLT regression. We can remove it if we
577         // can prove that the overall system gain would justify the regression.
578         cacheMaxDeadCapacity = max(24u, cacheMaxDeadCapacity);
579
580         deadDecodedDataDeletionInterval = 60;
581
582         // Foundation memory cache capacity (in bytes)
583         // (These values are small because WebCore does most caching itself.)
584         if (memSize >= 1024)
585             cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
586         else if (memSize >= 512)
587             cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
588         else if (memSize >= 256)
589             cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
590         else
591             cfurlCacheMemoryCapacity =      512 * 1024; 
592
593         // Foundation disk cache capacity (in bytes)
594         if (diskFreeSize >= 16384)
595             cfurlCacheDiskCapacity = 175 * 1024 * 1024;
596         else if (diskFreeSize >= 8192)
597             cfurlCacheDiskCapacity = 150 * 1024 * 1024;
598         else if (diskFreeSize >= 4096)
599             cfurlCacheDiskCapacity = 125 * 1024 * 1024;
600         else if (diskFreeSize >= 2048)
601             cfurlCacheDiskCapacity = 100 * 1024 * 1024;
602         else if (diskFreeSize >= 1024)
603             cfurlCacheDiskCapacity = 75 * 1024 * 1024;
604         else
605             cfurlCacheDiskCapacity = 50 * 1024 * 1024;
606
607         break;
608     }
609     default:
610         ASSERT_NOT_REACHED();
611     }
612
613     // Don't shrink a big disk cache, since that would cause churn.
614     cfurlCacheDiskCapacity = max(cfurlCacheDiskCapacity, CFURLCacheDiskCapacity(cfurlCache.get()));
615
616     memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
617     memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
618     pageCache()->setCapacity(pageCacheCapacity);
619
620     CFURLCacheSetMemoryCapacity(cfurlCache.get(), cfurlCacheMemoryCapacity);
621     CFURLCacheSetDiskCapacity(cfurlCache.get(), cfurlCacheDiskCapacity);
622
623     s_didSetCacheModel = true;
624     s_cacheModel = cacheModel;
625     return;
626 #endif
627 }
628
629 WebCacheModel WebView::cacheModel()
630 {
631     return s_cacheModel;
632 }
633
634 bool WebView::didSetCacheModel()
635 {
636     return s_didSetCacheModel;
637 }
638
639 WebCacheModel WebView::maxCacheModelInAnyInstance()
640 {
641     WebCacheModel cacheModel = WebCacheModelDocumentViewer;
642
643     HashSet<WebView*>::iterator end = allWebViewsSet().end();
644     for (HashSet<WebView*>::iterator it = allWebViewsSet().begin(); it != end; ++it) {
645         COMPtr<IWebPreferences> pref;
646         if (FAILED((*it)->preferences(&pref)))
647             continue;
648         WebCacheModel prefCacheModel = WebCacheModelDocumentViewer;
649         if (FAILED(pref->cacheModel(&prefCacheModel)))
650             continue;
651
652         cacheModel = max(cacheModel, prefCacheModel);
653     }
654
655     return cacheModel;
656 }
657
658 HRESULT STDMETHODCALLTYPE WebView::close()
659 {
660     if (m_didClose)
661         return S_OK;
662
663     m_didClose = true;
664
665 #if USE(ACCELERATED_COMPOSITING)
666     setAcceleratedCompositing(false);
667 #endif
668
669     WebNotificationCenter::defaultCenterInternal()->postNotificationName(_bstr_t(WebViewWillCloseNotification).GetBSTR(), static_cast<IWebView*>(this), 0);
670
671     if (m_uiDelegatePrivate)
672         m_uiDelegatePrivate->webViewClosing(this);
673
674     removeFromAllWebViewsSet();
675
676     if (m_page) {
677         if (Frame* frame = m_page->mainFrame())
678             frame->loader()->detachFromParent();
679     }
680
681     if (m_mouseOutTracker) {
682         m_mouseOutTracker->dwFlags = TME_CANCEL;
683         ::TrackMouseEvent(m_mouseOutTracker.get());
684         m_mouseOutTracker.clear();
685     }
686     
687     revokeDragDrop();
688
689     if (m_viewWindow) {
690         // We can't check IsWindow(m_viewWindow) here, because that will return true even while
691         // we're already handling WM_DESTROY. So we check !isBeingDestroyed() instead.
692         if (!isBeingDestroyed())
693             DestroyWindow(m_viewWindow);
694         // Either we just destroyed m_viewWindow, or it's in the process of being destroyed. Either
695         // way, we clear it out to make sure we don't try to use it later.
696         m_viewWindow = 0;
697     }
698
699     setHostWindow(0);
700
701     setDownloadDelegate(0);
702     setEditingDelegate(0);
703     setFrameLoadDelegate(0);
704     setFrameLoadDelegatePrivate(0);
705     setHistoryDelegate(0);
706     setPolicyDelegate(0);
707     setResourceLoadDelegate(0);
708     setUIDelegate(0);
709     setFormDelegate(0);
710
711     if (m_webInspector)
712         m_webInspector->webViewClosed();
713
714     delete m_page;
715     m_page = 0;
716
717     registerForIconNotification(false);
718     IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
719     notifyCenter->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
720
721     if (COMPtr<WebPreferences> preferences = m_preferences) {
722         BSTR identifier = 0;
723         preferences->identifier(&identifier);
724
725         m_preferences = 0;
726         preferences->didRemoveFromWebView();
727         // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
728         preferences = 0;
729         if (identifier) {
730             WebPreferences::removeReferenceForIdentifier(identifier);
731             SysFreeString(identifier);
732         }
733     }
734
735     deleteBackingStore();
736     return S_OK;
737 }
738
739 void WebView::repaint(const WebCore::IntRect& windowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
740 {
741 #if USE(ACCELERATED_COMPOSITING)
742     if (isAcceleratedCompositing()) {
743         // The contentChanged, immediate, and repaintContentOnly parameters are all based on a non-
744         // compositing painting/scrolling model.
745         addToDirtyRegion(windowRect);
746         return;
747     }
748 #endif
749
750     if (!repaintContentOnly) {
751         RECT rect = windowRect;
752         ::InvalidateRect(m_viewWindow, &rect, false);
753     }
754     if (contentChanged)
755         addToDirtyRegion(windowRect);
756     if (immediate) {
757         if (repaintContentOnly)
758             updateBackingStore(core(topLevelFrame())->view());
759         else
760             ::UpdateWindow(m_viewWindow);
761     }
762 }
763
764 void WebView::deleteBackingStore()
765 {
766     pendingDeleteBackingStoreSet.remove(this);
767
768     if (m_deleteBackingStoreTimerActive) {
769         KillTimer(m_viewWindow, DeleteBackingStoreTimer);
770         m_deleteBackingStoreTimerActive = false;
771     }
772     m_backingStoreBitmap.clear();
773     m_backingStoreDirtyRegion.clear();
774     m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
775 }
776
777 bool WebView::ensureBackingStore()
778 {
779     RECT windowRect;
780     ::GetClientRect(m_viewWindow, &windowRect);
781     LONG width = windowRect.right - windowRect.left;
782     LONG height = windowRect.bottom - windowRect.top;
783     if (width > 0 && height > 0 && (width != m_backingStoreSize.cx || height != m_backingStoreSize.cy)) {
784         deleteBackingStore();
785
786         m_backingStoreSize.cx = width;
787         m_backingStoreSize.cy = height;
788         BitmapInfo bitmapInfo = BitmapInfo::createBottomUp(IntSize(m_backingStoreSize));
789
790         void* pixels = NULL;
791         m_backingStoreBitmap = RefCountedHBITMAP::create(::CreateDIBSection(0, &bitmapInfo, DIB_RGB_COLORS, &pixels, 0, 0));
792         return true;
793     }
794
795     return false;
796 }
797
798 void WebView::addToDirtyRegion(const IntRect& dirtyRect)
799 {
800     // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
801     // but it was being hit during our layout tests, and is being investigated in
802     // http://webkit.org/b/29350.
803
804 #if USE(ACCELERATED_COMPOSITING)
805     if (isAcceleratedCompositing()) {
806         m_backingLayer->setNeedsDisplayInRect(dirtyRect);
807         return;
808     }
809 #endif
810
811     HRGN newRegion = ::CreateRectRgn(dirtyRect.x(), dirtyRect.y(),
812                                      dirtyRect.maxX(), dirtyRect.maxY());
813     addToDirtyRegion(newRegion);
814 }
815
816 void WebView::addToDirtyRegion(HRGN newRegion)
817 {
818 #if USE(ACCELERATED_COMPOSITING)
819     ASSERT(!isAcceleratedCompositing());
820 #endif
821
822     LOCAL_GDI_COUNTER(0, __FUNCTION__);
823
824     if (m_backingStoreDirtyRegion) {
825         HRGN combinedRegion = ::CreateRectRgn(0,0,0,0);
826         ::CombineRgn(combinedRegion, m_backingStoreDirtyRegion->handle(), newRegion, RGN_OR);
827         ::DeleteObject(newRegion);
828         m_backingStoreDirtyRegion = RefCountedHRGN::create(combinedRegion);
829     } else
830         m_backingStoreDirtyRegion = RefCountedHRGN::create(newRegion);
831
832     if (m_uiDelegatePrivate)
833         m_uiDelegatePrivate->webViewDidInvalidate(this);
834 }
835
836 void WebView::scrollBackingStore(FrameView* frameView, int dx, int dy, const IntRect& scrollViewRect, const IntRect& clipRect)
837 {
838 #if USE(ACCELERATED_COMPOSITING)
839     if (isAcceleratedCompositing()) {
840         // FIXME: We should be doing something smarter here, like moving tiles around and painting
841         // any newly-exposed tiles. <http://webkit.org/b/52714>
842         m_backingLayer->setNeedsDisplayInRect(scrollViewRect);
843         return;
844     }
845 #endif
846
847     LOCAL_GDI_COUNTER(0, __FUNCTION__);
848
849     // If there's no backing store we don't need to update it
850     if (!m_backingStoreBitmap) {
851         if (m_uiDelegatePrivate)
852             m_uiDelegatePrivate->webViewScrolled(this);
853
854         return;
855     }
856
857     // Make a region to hold the invalidated scroll area.
858     HRGN updateRegion = ::CreateRectRgn(0, 0, 0, 0);
859
860     // Collect our device context info and select the bitmap to scroll.
861     HDC windowDC = ::GetDC(m_viewWindow);
862     HDC bitmapDC = ::CreateCompatibleDC(windowDC);
863     HGDIOBJ oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
864     
865     // Scroll the bitmap.
866     RECT scrollRectWin(scrollViewRect);
867     RECT clipRectWin(clipRect);
868     ::ScrollDC(bitmapDC, dx, dy, &scrollRectWin, &clipRectWin, updateRegion, 0);
869     RECT regionBox;
870     ::GetRgnBox(updateRegion, &regionBox);
871
872     // Flush.
873     GdiFlush();
874
875     // Add the dirty region to the backing store's dirty region.
876     addToDirtyRegion(updateRegion);
877
878     if (m_uiDelegatePrivate)
879         m_uiDelegatePrivate->webViewScrolled(this);
880
881     // Update the backing store.
882     updateBackingStore(frameView, bitmapDC, false);
883
884     // Clean up.
885     ::SelectObject(bitmapDC, oldBitmap);
886     ::DeleteDC(bitmapDC);
887     ::ReleaseDC(m_viewWindow, windowDC);
888 }
889
890 void WebView::sizeChanged(const IntSize& newSize)
891 {
892     deleteBackingStore();
893
894     if (Frame* coreFrame = core(topLevelFrame()))
895         coreFrame->view()->resize(newSize);
896
897 #if USE(ACCELERATED_COMPOSITING)
898     if (m_layerTreeHost)
899         m_layerTreeHost->resize();
900     if (m_backingLayer) {
901         m_backingLayer->setSize(newSize);
902         m_backingLayer->setNeedsDisplay();
903     }
904 #endif
905 }
906
907 // This emulates the Mac smarts for painting rects intelligently.  This is very
908 // important for us, since we double buffer based off dirty rects.
909 static void getUpdateRects(HRGN region, const IntRect& dirtyRect, Vector<IntRect>& rects)
910 {
911     ASSERT_ARG(region, region);
912
913     const int cRectThreshold = 10;
914     const float cWastedSpaceThreshold = 0.75f;
915
916     rects.clear();
917
918     DWORD regionDataSize = GetRegionData(region, sizeof(RGNDATA), NULL);
919     if (!regionDataSize) {
920         rects.append(dirtyRect);
921         return;
922     }
923
924     Vector<unsigned char> buffer(regionDataSize);
925     RGNDATA* regionData = reinterpret_cast<RGNDATA*>(buffer.data());
926     GetRegionData(region, regionDataSize, regionData);
927     if (regionData->rdh.nCount > cRectThreshold) {
928         rects.append(dirtyRect);
929         return;
930     }
931
932     double singlePixels = 0.0;
933     unsigned i;
934     RECT* rect;
935     for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
936         singlePixels += (rect->right - rect->left) * (rect->bottom - rect->top);
937
938     double unionPixels = dirtyRect.width() * dirtyRect.height();
939     double wastedSpace = 1.0 - (singlePixels / unionPixels);
940     if (wastedSpace <= cWastedSpaceThreshold) {
941         rects.append(dirtyRect);
942         return;
943     }
944
945     for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
946         rects.append(*rect);
947 }
948
949 void WebView::updateBackingStore(FrameView* frameView, HDC dc, bool backingStoreCompletelyDirty, WindowsToPaint windowsToPaint)
950 {
951 #if USE(ACCELERATED_COMPOSITING)
952     ASSERT(!isAcceleratedCompositing());
953 #endif
954
955     LOCAL_GDI_COUNTER(0, __FUNCTION__);
956
957     HDC windowDC = 0;
958     HDC bitmapDC = dc;
959     HGDIOBJ oldBitmap = 0;
960     if (!dc) {
961         windowDC = ::GetDC(m_viewWindow);
962         bitmapDC = ::CreateCompatibleDC(windowDC);
963         oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
964     }
965
966     if (m_backingStoreBitmap && (m_backingStoreDirtyRegion || backingStoreCompletelyDirty)) {
967         // Do a layout first so that everything we render to the backing store is always current.
968         if (Frame* coreFrame = core(m_mainFrame))
969             if (FrameView* view = coreFrame->view())
970                 view->updateLayoutAndStyleIfNeededRecursive();
971
972         Vector<IntRect> paintRects;
973         if (!backingStoreCompletelyDirty && m_backingStoreDirtyRegion) {
974             RECT regionBox;
975             ::GetRgnBox(m_backingStoreDirtyRegion->handle(), &regionBox);
976             getUpdateRects(m_backingStoreDirtyRegion->handle(), regionBox, paintRects);
977         } else {
978             RECT clientRect;
979             ::GetClientRect(m_viewWindow, &clientRect);
980             paintRects.append(clientRect);
981         }
982
983         for (unsigned i = 0; i < paintRects.size(); ++i)
984             paintIntoBackingStore(frameView, bitmapDC, paintRects[i], windowsToPaint);
985
986         if (m_uiDelegatePrivate)
987             m_uiDelegatePrivate->webViewPainted(this);
988
989         m_backingStoreDirtyRegion.clear();
990     }
991
992     if (!dc) {
993         ::SelectObject(bitmapDC, oldBitmap);
994         ::DeleteDC(bitmapDC);
995         ::ReleaseDC(m_viewWindow, windowDC);
996     }
997
998     GdiFlush();
999 }
1000
1001 void WebView::performLayeredWindowUpdate()
1002 {
1003     // The backing store may have been destroyed if the window rect was set to zero height or zero width.
1004     if (!m_backingStoreBitmap)
1005         return;
1006
1007     HDC hdcScreen = ::GetDC(m_viewWindow);
1008     OwnPtr<HDC> hdcMem = adoptPtr(::CreateCompatibleDC(hdcScreen));
1009     HBITMAP hbmOld = static_cast<HBITMAP>(::SelectObject(hdcMem.get(), m_backingStoreBitmap->handle()));
1010
1011     BITMAP bmpInfo;
1012     ::GetObject(m_backingStoreBitmap->handle(), sizeof(bmpInfo), &bmpInfo);
1013     SIZE windowSize = { bmpInfo.bmWidth, bmpInfo.bmHeight };
1014
1015     BLENDFUNCTION blendFunction;
1016     blendFunction.BlendOp = AC_SRC_OVER;
1017     blendFunction.BlendFlags = 0;
1018     blendFunction.SourceConstantAlpha = 0xFF;
1019     blendFunction.AlphaFormat = AC_SRC_ALPHA;
1020
1021     POINT layerPos = { 0, 0 };
1022     ::UpdateLayeredWindow(m_viewWindow, hdcScreen, 0, &windowSize, hdcMem.get(), &layerPos, 0, &blendFunction, ULW_ALPHA);
1023
1024     ::SelectObject(hdcMem.get(), hbmOld);
1025     ::ReleaseDC(0, hdcScreen);
1026 }
1027
1028 void WebView::paint(HDC dc, LPARAM options)
1029 {
1030     LOCAL_GDI_COUNTER(0, __FUNCTION__);
1031
1032 #if USE(ACCELERATED_COMPOSITING)
1033     if (isAcceleratedCompositing() && !usesLayeredWindow()) {
1034         m_layerTreeHost->flushPendingLayerChangesNow();
1035         // Flushing might have taken us out of compositing mode.
1036         if (isAcceleratedCompositing()) {
1037             // FIXME: We need to paint into dc (if provided). <http://webkit.org/b/52578>
1038             m_layerTreeHost->paint();
1039             ::ValidateRect(m_viewWindow, 0);
1040             return;
1041         }
1042     }
1043 #endif
1044
1045     Frame* coreFrame = core(m_mainFrame);
1046     if (!coreFrame)
1047         return;
1048     FrameView* frameView = coreFrame->view();
1049
1050     RECT rcPaint;
1051     HDC hdc;
1052     OwnPtr<HRGN> region;
1053     int regionType = NULLREGION;
1054     PAINTSTRUCT ps;
1055     WindowsToPaint windowsToPaint;
1056     if (!dc) {
1057         region = adoptPtr(CreateRectRgn(0,0,0,0));
1058         regionType = GetUpdateRgn(m_viewWindow, region.get(), false);
1059         hdc = BeginPaint(m_viewWindow, &ps);
1060         rcPaint = ps.rcPaint;
1061         // We're painting to the screen, and our child windows can handle
1062         // painting themselves to the screen.
1063         windowsToPaint = PaintWebViewOnly;
1064     } else {
1065         hdc = dc;
1066         ::GetClientRect(m_viewWindow, &rcPaint);
1067         if (options & PRF_ERASEBKGND)
1068             ::FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
1069         // Since we aren't painting to the screen, we want to paint all our
1070         // children into the HDC.
1071         windowsToPaint = PaintWebViewAndChildren;
1072     }
1073
1074     bool backingStoreCompletelyDirty = ensureBackingStore();
1075     if (!m_backingStoreBitmap) {
1076         if (!dc)
1077             EndPaint(m_viewWindow, &ps);
1078         return;
1079     }
1080
1081     m_paintCount++;
1082
1083     HDC bitmapDC = ::CreateCompatibleDC(hdc);
1084     HGDIOBJ oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
1085
1086     // Update our backing store if needed.
1087     updateBackingStore(frameView, bitmapDC, backingStoreCompletelyDirty, windowsToPaint);
1088
1089     // Now we blit the updated backing store
1090     IntRect windowDirtyRect = rcPaint;
1091     
1092     // Apply the same heuristic for this update region too.
1093     Vector<IntRect> blitRects;
1094     if (region && regionType == COMPLEXREGION)
1095         getUpdateRects(region.get(), windowDirtyRect, blitRects);
1096     else
1097         blitRects.append(windowDirtyRect);
1098
1099     for (unsigned i = 0; i < blitRects.size(); ++i)
1100         paintIntoWindow(bitmapDC, hdc, blitRects[i]);
1101
1102     ::SelectObject(bitmapDC, oldBitmap);
1103     ::DeleteDC(bitmapDC);
1104
1105     if (!dc)
1106         EndPaint(m_viewWindow, &ps);
1107
1108     m_paintCount--;
1109
1110     if (active())
1111         cancelDeleteBackingStoreSoon();
1112     else
1113         deleteBackingStoreSoon();
1114 }
1115
1116 void WebView::paintIntoBackingStore(FrameView* frameView, HDC bitmapDC, const IntRect& dirtyRect, WindowsToPaint windowsToPaint)
1117 {
1118     // FIXME: This function should never be called in accelerated compositing mode, and we should
1119     // assert as such. But currently it *is* sometimes called, so we can't assert yet. See
1120     // <http://webkit.org/b/58539>.
1121
1122     LOCAL_GDI_COUNTER(0, __FUNCTION__);
1123
1124     // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
1125     // but it was being hit during our layout tests, and is being investigated in
1126     // http://webkit.org/b/29350.
1127
1128     RECT rect = dirtyRect;
1129
1130 #if FLASH_BACKING_STORE_REDRAW
1131     HDC dc = ::GetDC(m_viewWindow);
1132     OwnPtr<HBRUSH> yellowBrush(CreateSolidBrush(RGB(255, 255, 0)));
1133     FillRect(dc, &rect, yellowBrush.get());
1134     GdiFlush();
1135     Sleep(50);
1136     paintIntoWindow(bitmapDC, dc, dirtyRect);
1137     ::ReleaseDC(m_viewWindow, dc);
1138 #endif
1139
1140     GraphicsContext gc(bitmapDC, m_transparent);
1141     gc.setShouldIncludeChildWindows(windowsToPaint == PaintWebViewAndChildren);
1142     gc.save();
1143     if (m_transparent)
1144         gc.clearRect(dirtyRect);
1145     else
1146         FillRect(bitmapDC, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
1147
1148     COMPtr<IWebUIDelegatePrivate2> uiPrivate(Query, m_uiDelegate);
1149     if (uiPrivate)
1150         uiPrivate->drawBackground(this, reinterpret_cast<OLE_HANDLE>(bitmapDC), &rect);
1151
1152     if (frameView && frameView->frame() && frameView->frame()->contentRenderer()) {
1153         gc.clip(dirtyRect);
1154         frameView->paint(&gc, dirtyRect);
1155     }
1156     gc.restore();
1157 }
1158
1159 void WebView::paintIntoWindow(HDC bitmapDC, HDC windowDC, const IntRect& dirtyRect)
1160 {
1161     // FIXME: This function should never be called in accelerated compositing mode, and we should
1162     // assert as such. But currently it *is* sometimes called, so we can't assert yet. See
1163     // <http://webkit.org/b/58539>.
1164
1165     LOCAL_GDI_COUNTER(0, __FUNCTION__);
1166 #if FLASH_WINDOW_REDRAW
1167     OwnPtr<HBRUSH> greenBrush = CreateSolidBrush(RGB(0, 255, 0));
1168     RECT rect = dirtyRect;
1169     FillRect(windowDC, &rect, greenBrush.get());
1170     GdiFlush();
1171     Sleep(50);
1172 #endif
1173
1174     // Blit the dirty rect from the backing store into the same position
1175     // in the destination DC.
1176     BitBlt(windowDC, dirtyRect.x(), dirtyRect.y(), dirtyRect.width(), dirtyRect.height(), bitmapDC,
1177            dirtyRect.x(), dirtyRect.y(), SRCCOPY);
1178 }
1179
1180 void WebView::frameRect(RECT* rect)
1181 {
1182     ::GetWindowRect(m_viewWindow, rect);
1183 }
1184
1185 class WindowCloseTimer : public WebCore::SuspendableTimer {
1186 public:
1187     static WindowCloseTimer* create(WebView*);
1188
1189 private:
1190     WindowCloseTimer(ScriptExecutionContext*, WebView*);
1191     virtual void contextDestroyed();
1192     virtual void fired();
1193
1194     WebView* m_webView;
1195 };
1196
1197 WindowCloseTimer* WindowCloseTimer::create(WebView* webView)
1198 {
1199     ASSERT_ARG(webView, webView);
1200     Frame* frame = core(webView->topLevelFrame());
1201     ASSERT(frame);
1202     if (!frame)
1203         return 0;
1204
1205     Document* document = frame->document();
1206     ASSERT(document);
1207     if (!document)
1208         return 0;
1209
1210     return new WindowCloseTimer(document, webView);
1211 }
1212
1213 WindowCloseTimer::WindowCloseTimer(ScriptExecutionContext* context, WebView* webView)
1214     : SuspendableTimer(context)
1215     , m_webView(webView)
1216 {
1217     ASSERT_ARG(context, context);
1218     ASSERT_ARG(webView, webView);
1219 }
1220
1221 void WindowCloseTimer::contextDestroyed()
1222 {
1223     SuspendableTimer::contextDestroyed();
1224     delete this;
1225 }
1226
1227 void WindowCloseTimer::fired()
1228 {
1229     m_webView->closeWindowTimerFired();
1230 }
1231
1232 void WebView::closeWindowSoon()
1233 {
1234     if (m_closeWindowTimer)
1235         return;
1236
1237     m_closeWindowTimer = WindowCloseTimer::create(this);
1238     if (!m_closeWindowTimer)
1239         return;
1240     m_closeWindowTimer->startOneShot(0);
1241
1242     AddRef();
1243 }
1244
1245 void WebView::closeWindowTimerFired()
1246 {
1247     closeWindow();
1248     Release();
1249 }
1250
1251 void WebView::closeWindow()
1252 {
1253     if (m_hasSpellCheckerDocumentTag) {
1254         if (m_editingDelegate)
1255             m_editingDelegate->closeSpellDocument(this);
1256         m_hasSpellCheckerDocumentTag = false;
1257     }
1258
1259     COMPtr<IWebUIDelegate> ui;
1260     if (SUCCEEDED(uiDelegate(&ui)))
1261         ui->webViewClose(this);
1262 }
1263
1264 bool WebView::canHandleRequest(const WebCore::ResourceRequest& request)
1265 {
1266     // On the mac there's an about url protocol implementation but CFNetwork doesn't have that.
1267     if (equalIgnoringCase(String(request.url().protocol()), "about"))
1268         return true;
1269
1270 #if USE(CFNETWORK)
1271     if (CFURLProtocolCanHandleRequest(request.cfURLRequest()))
1272         return true;
1273
1274     // FIXME: Mac WebKit calls _representationExistsForURLScheme here
1275     return false;
1276 #else
1277     return true;
1278 #endif
1279 }
1280
1281 String WebView::standardUserAgentWithApplicationName(const String& applicationName)
1282 {
1283     DEFINE_STATIC_LOCAL(String, osVersion, (windowsVersionForUAString()));
1284     DEFINE_STATIC_LOCAL(String, webKitVersion, (webKitVersionString()));
1285
1286     return makeString("Mozilla/5.0 (", osVersion, ") AppleWebKit/", webKitVersion, " (KHTML, like Gecko)", applicationName.isEmpty() ? "" : " ", applicationName);
1287 }
1288
1289 Page* WebView::page()
1290 {
1291     return m_page;
1292 }
1293
1294 bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam)
1295 {
1296     // Translate the screen coordinates into window coordinates
1297     POINT coords = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
1298     if (coords.x == -1 || coords.y == -1) {
1299         // The contextMenuController() holds onto the last context menu that was popped up on the
1300         // page until a new one is created. We need to clear this menu before propagating the event
1301         // through the DOM so that we can detect if we create a new menu for this event, since we
1302         // won't create a new menu if the DOM swallows the event and the defaultEventHandler does
1303         // not run.
1304         m_page->contextMenuController()->clearContextMenu();
1305
1306         Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
1307         return focusedFrame->eventHandler()->sendContextMenuEventForKey();
1308
1309     } else {
1310         if (!::ScreenToClient(m_viewWindow, &coords))
1311             return false;
1312     }
1313
1314     lParam = MAKELPARAM(coords.x, coords.y);
1315
1316     m_page->contextMenuController()->clearContextMenu();
1317
1318     IntPoint documentPoint(m_page->mainFrame()->view()->windowToContents(coords));
1319     HitTestResult result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(documentPoint, false);
1320     Frame* targetFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : m_page->focusController()->focusedOrMainFrame();
1321
1322     targetFrame->view()->setCursor(pointerCursor());
1323     PlatformMouseEvent mouseEvent(m_viewWindow, WM_RBUTTONUP, wParam, lParam);
1324     bool handledEvent = targetFrame->eventHandler()->sendContextMenuEvent(mouseEvent);
1325     if (!handledEvent)
1326         return false;
1327
1328     ContextMenuController* contextMenuController = m_page->contextMenuController();
1329
1330     // Show the menu
1331     ContextMenu* coreMenu = contextMenuController->contextMenu();
1332     if (!coreMenu)
1333         return false;
1334
1335     Node* node = contextMenuController->hitTestResult().innerNonSharedNode();
1336     if (!node)
1337         return false;
1338
1339     Frame* frame = node->document()->frame();
1340     if (!frame)
1341         return false;
1342
1343     FrameView* view = frame->view();
1344     if (!view)
1345         return false;
1346
1347     POINT point(view->contentsToWindow(contextMenuController->hitTestResult().point()));
1348
1349     // Translate the point to screen coordinates
1350     if (!::ClientToScreen(m_viewWindow, &point))
1351         return false;
1352
1353     BOOL hasCustomMenus = false;
1354     if (m_uiDelegate)
1355         m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1356
1357     if (hasCustomMenus)
1358         m_uiDelegate->trackCustomPopupMenu((IWebView*)this, (OLE_HANDLE)(ULONG64)coreMenu->nativeMenu(), &point);
1359     else {
1360         // Surprisingly, TPM_RIGHTBUTTON means that items are selectable with either the right OR left mouse button
1361         UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL
1362             | TPM_LEFTALIGN | TPM_HORPOSANIMATION;
1363         ::TrackPopupMenuEx(coreMenu->nativeMenu(), flags, point.x, point.y, m_viewWindow, 0);
1364     }
1365
1366     return true;
1367 }
1368
1369 bool WebView::onMeasureItem(WPARAM /*wParam*/, LPARAM lParam)
1370 {
1371     if (!m_uiDelegate)
1372         return false;
1373
1374     BOOL hasCustomMenus = false;
1375     m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1376     if (!hasCustomMenus)
1377         return false;
1378
1379     m_uiDelegate->measureCustomMenuItem((IWebView*)this, (void*)lParam);
1380     return true;
1381 }
1382
1383 bool WebView::onDrawItem(WPARAM /*wParam*/, LPARAM lParam)
1384 {
1385     if (!m_uiDelegate)
1386         return false;
1387
1388     BOOL hasCustomMenus = false;
1389     m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1390     if (!hasCustomMenus)
1391         return false;
1392
1393     m_uiDelegate->drawCustomMenuItem((IWebView*)this, (void*)lParam);
1394     return true;
1395 }
1396
1397 bool WebView::onInitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1398 {
1399     if (!m_uiDelegate)
1400         return false;
1401
1402     HMENU menu = (HMENU)wParam;
1403     if (!menu)
1404         return false;
1405
1406     BOOL hasCustomMenus = false;
1407     m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1408     if (!hasCustomMenus)
1409         return false;
1410
1411     m_uiDelegate->addCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1412     return true;
1413 }
1414
1415 bool WebView::onUninitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1416 {
1417     if (!m_uiDelegate)
1418         return false;
1419
1420     HMENU menu = (HMENU)wParam;
1421     if (!menu)
1422         return false;
1423
1424     BOOL hasCustomMenus = false;
1425     m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1426     if (!hasCustomMenus)
1427         return false;
1428
1429     m_uiDelegate->cleanUpCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1430     return true;
1431 }
1432
1433 void WebView::performContextMenuAction(WPARAM wParam, LPARAM lParam, bool byPosition)
1434 {
1435     ContextMenu* menu = m_page->contextMenuController()->contextMenu();
1436     ASSERT(menu);
1437
1438     ContextMenuItem* item = byPosition ? menu->itemAtIndex((unsigned)wParam) : menu->itemWithAction((ContextMenuAction)wParam);
1439     if (!item)
1440         return;
1441     m_page->contextMenuController()->contextMenuItemSelected(item);
1442 }
1443
1444 bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
1445 {
1446     static LONG globalClickCount;
1447     static IntPoint globalPrevPoint;
1448     static MouseButton globalPrevButton;
1449     static LONG globalPrevMouseDownTime;
1450
1451     if (message == WM_CANCELMODE) {
1452         m_page->mainFrame()->eventHandler()->lostMouseCapture();
1453         return true;
1454     }
1455
1456     // Create our event.
1457     // On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
1458     // of the event to be at (MINSHORT, MINSHORT).
1459     LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
1460     PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
1461
1462     setMouseActivated(false);
1463
1464     bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.pos().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
1465                            abs(globalPrevPoint.y() - mouseEvent.pos().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
1466     LONG messageTime = ::GetMessageTime();
1467
1468     bool handled = false;
1469
1470     if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
1471         // FIXME: I'm not sure if this is the "right" way to do this
1472         // but without this call, we never become focused since we don't allow
1473         // the default handling of mouse events.
1474         SetFocus(m_viewWindow);
1475
1476         // Always start capturing events when the mouse goes down in our HWND.
1477         ::SetCapture(m_viewWindow);
1478
1479         if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) && 
1480             insideThreshold &&
1481             mouseEvent.button() == globalPrevButton)
1482             globalClickCount++;
1483         else
1484             // Reset the click count.
1485             globalClickCount = 1;
1486         globalPrevMouseDownTime = messageTime;
1487         globalPrevButton = mouseEvent.button();
1488         globalPrevPoint = mouseEvent.pos();
1489         
1490         mouseEvent.setClickCount(globalClickCount);
1491         handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1492     } else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
1493         globalClickCount++;
1494         mouseEvent.setClickCount(globalClickCount);
1495         handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1496     } else if (message == WM_LBUTTONUP || message == WM_MBUTTONUP || message == WM_RBUTTONUP) {
1497         // Record the global position and the button of the up.
1498         globalPrevButton = mouseEvent.button();
1499         globalPrevPoint = mouseEvent.pos();
1500         mouseEvent.setClickCount(globalClickCount);
1501         m_page->mainFrame()->eventHandler()->handleMouseReleaseEvent(mouseEvent);
1502         ::ReleaseCapture();
1503     } else if (message == WM_MOUSELEAVE && m_mouseOutTracker) {
1504         // Once WM_MOUSELEAVE is fired windows clears this tracker
1505         // so there is no need to disable it ourselves.
1506         m_mouseOutTracker.clear();
1507         m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1508         handled = true;
1509     } else if (message == WM_MOUSEMOVE) {
1510         if (!insideThreshold)
1511             globalClickCount = 0;
1512         mouseEvent.setClickCount(globalClickCount);
1513         handled = m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1514         if (!m_mouseOutTracker) {
1515             m_mouseOutTracker = adoptPtr(new TRACKMOUSEEVENT);
1516             m_mouseOutTracker->cbSize = sizeof(TRACKMOUSEEVENT);
1517             m_mouseOutTracker->dwFlags = TME_LEAVE;
1518             m_mouseOutTracker->hwndTrack = m_viewWindow;
1519             ::TrackMouseEvent(m_mouseOutTracker.get());
1520         }
1521     }
1522     return handled;
1523 }
1524
1525 bool WebView::gestureNotify(WPARAM wParam, LPARAM lParam)
1526 {
1527     GESTURENOTIFYSTRUCT* gn = reinterpret_cast<GESTURENOTIFYSTRUCT*>(lParam);
1528
1529     Frame* coreFrame = core(m_mainFrame);
1530     if (!coreFrame)
1531         return false;
1532
1533     ScrollView* view = coreFrame->view();
1534     if (!view)
1535         return false;
1536
1537     // If we don't have this function, we shouldn't be receiving this message
1538     ASSERT(SetGestureConfigPtr());
1539
1540     bool hitScrollbar = false;
1541     POINT gestureBeginPoint = {gn->ptsLocation.x, gn->ptsLocation.y};
1542     HitTestRequest request(HitTestRequest::ReadOnly);
1543     for (Frame* childFrame = m_page->mainFrame(); childFrame; childFrame = EventHandler::subframeForTargetNode(m_gestureTargetNode.get())) {
1544         FrameView* frameView = childFrame->view();
1545         if (!frameView)
1546             break;
1547         RenderView* renderView = childFrame->document()->renderView();
1548         if (!renderView)
1549             break;
1550         RenderLayer* layer = renderView->layer();
1551         if (!layer)
1552             break;
1553
1554         HitTestResult result(frameView->screenToContents(gestureBeginPoint));
1555         layer->hitTest(request, result);
1556         m_gestureTargetNode = result.innerNode();
1557
1558         if (!hitScrollbar)
1559             hitScrollbar = result.scrollbar();
1560     }
1561
1562     if (!hitScrollbar) {
1563         // The hit testing above won't detect if we've hit the main frame's vertical scrollbar. Check that manually now.
1564         RECT webViewRect;
1565         GetWindowRect(m_viewWindow, &webViewRect);
1566         hitScrollbar = view->verticalScrollbar() && (gestureBeginPoint.x > (webViewRect.right - view->verticalScrollbar()->theme()->scrollbarThickness()));  
1567     }
1568
1569     bool canBeScrolled = false;
1570     if (m_gestureTargetNode) {
1571         for (RenderObject* renderer = m_gestureTargetNode->renderer(); renderer; renderer = renderer->parent()) {
1572             if (renderer->isBox() && toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()) {
1573                 canBeScrolled = true;
1574                 break;
1575             }
1576         }
1577     }
1578
1579     // We always allow two-fingered panning with inertia and a gutter (which limits movement to one
1580     // direction in most cases).
1581     DWORD dwPanWant = GC_PAN | GC_PAN_WITH_INERTIA | GC_PAN_WITH_GUTTER;
1582     // We never allow single-fingered horizontal panning. That gesture is reserved for creating text
1583     // selections. This matches IE.
1584     DWORD dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
1585
1586     if (hitScrollbar || !canBeScrolled) {
1587         // The part of the page under the gesture can't be scrolled, or the gesture is on a scrollbar.
1588         // Disallow single-fingered vertical panning in this case, too, so we'll fall back to the default
1589         // behavior (which allows the scrollbar thumb to be dragged, text selections to be made, etc.).
1590         dwPanBlock |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
1591     } else {
1592         // The part of the page the gesture is under can be scrolled, and we're not under a scrollbar.
1593         // Allow single-fingered vertical panning in this case, so the user will be able to pan the page
1594         // with one or two fingers.
1595         dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
1596     }
1597
1598     GESTURECONFIG gc = { GID_PAN, dwPanWant, dwPanBlock };
1599     return SetGestureConfigPtr()(m_viewWindow, 0, 1, &gc, sizeof(GESTURECONFIG));
1600 }
1601
1602 bool WebView::gesture(WPARAM wParam, LPARAM lParam) 
1603 {
1604     // We want to bail out if we don't have either of these functions
1605     if (!GetGestureInfoPtr() || !CloseGestureInfoHandlePtr())
1606         return false;
1607
1608     HGESTUREINFO gestureHandle = reinterpret_cast<HGESTUREINFO>(lParam);
1609     
1610     GESTUREINFO gi = {0};
1611     gi.cbSize = sizeof(GESTUREINFO);
1612
1613     if (!GetGestureInfoPtr()(gestureHandle, reinterpret_cast<PGESTUREINFO>(&gi)))
1614         return false;
1615
1616     switch (gi.dwID) {
1617     case GID_BEGIN:
1618         m_lastPanX = gi.ptsLocation.x;
1619         m_lastPanY = gi.ptsLocation.y;
1620
1621         break;
1622     case GID_END:
1623         m_gestureTargetNode = 0;
1624         break;
1625     case GID_PAN: {
1626         // Where are the fingers currently?
1627         long currentX = gi.ptsLocation.x;
1628         long currentY = gi.ptsLocation.y;
1629         // How far did we pan in each direction?
1630         long deltaX = currentX - m_lastPanX;
1631         long deltaY = currentY - m_lastPanY;
1632         // Calculate the overpan for window bounce
1633         m_yOverpan -= m_lastPanY - currentY;
1634         m_xOverpan -= m_lastPanX - currentX;
1635         // Update our class variables with updated values
1636         m_lastPanX = currentX;
1637         m_lastPanY = currentY;
1638
1639         Frame* coreFrame = core(m_mainFrame);
1640         if (!coreFrame) {
1641             CloseGestureInfoHandlePtr()(gestureHandle);
1642             return false;
1643         }
1644
1645         if (!m_gestureTargetNode || !m_gestureTargetNode->renderer())
1646             return false;
1647
1648         // We negate here since panning up moves the content up, but moves the scrollbar down.
1649         m_gestureTargetNode->renderer()->enclosingLayer()->scrollByRecursively(-deltaX, -deltaY);
1650            
1651         if (!(UpdatePanningFeedbackPtr() && BeginPanningFeedbackPtr() && EndPanningFeedbackPtr())) {
1652             CloseGestureInfoHandlePtr()(gestureHandle);
1653             return true;
1654         }
1655
1656         if (gi.dwFlags & GF_BEGIN) {
1657             BeginPanningFeedbackPtr()(m_viewWindow);
1658             m_yOverpan = 0;
1659         } else if (gi.dwFlags & GF_END) {
1660             EndPanningFeedbackPtr()(m_viewWindow, true);
1661             m_yOverpan = 0;
1662         }
1663
1664         ScrollView* view = coreFrame->view();
1665         if (!view) {
1666             CloseGestureInfoHandlePtr()(gestureHandle);
1667             return true;
1668         }
1669         Scrollbar* vertScrollbar = view->verticalScrollbar();
1670         if (!vertScrollbar) {
1671             CloseGestureInfoHandlePtr()(gestureHandle);
1672             return true;
1673         }
1674
1675         // FIXME: Support Horizontal Window Bounce. <https://webkit.org/b/28500>.
1676         // FIXME: If the user starts panning down after a window bounce has started, the window doesn't bounce back 
1677         // until they release their finger. <https://webkit.org/b/28501>.
1678         if (vertScrollbar->currentPos() == 0)
1679             UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
1680         else if (vertScrollbar->currentPos() >= vertScrollbar->maximum())
1681             UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
1682
1683         CloseGestureInfoHandlePtr()(gestureHandle);
1684         return true;
1685     }
1686     default:
1687         break;
1688     }
1689
1690     // If we get to this point, the gesture has not been handled. We forward
1691     // the call to DefWindowProc by returning false, and we don't need to 
1692     // to call CloseGestureInfoHandle. 
1693     // http://msdn.microsoft.com/en-us/library/dd353228(VS.85).aspx
1694     return false;
1695 }
1696
1697 bool WebView::mouseWheel(WPARAM wParam, LPARAM lParam, bool isMouseHWheel)
1698 {
1699     // Ctrl+Mouse wheel doesn't ever go into WebCore.  It is used to
1700     // zoom instead (Mac zooms the whole Desktop, but Windows browsers trigger their
1701     // own local zoom modes for Ctrl+wheel).
1702     if (wParam & MK_CONTROL) {
1703         short delta = short(HIWORD(wParam));
1704         if (delta < 0)
1705             makeTextSmaller(0);
1706         else
1707             makeTextLarger(0);
1708         return true;
1709     }
1710     
1711     // 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.
1712     HWND focusedWindow = GetFocus();
1713     if (focusedWindow && focusedWindow != m_viewWindow) {
1714         // 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).
1715         WCHAR className[256];
1716
1717         // Make sure truncation won't affect the comparison.
1718         ASSERT(WTF_ARRAY_LENGTH(className) > wcslen(PopupMenuWin::popupClassName()));
1719
1720         if (GetClassNameW(focusedWindow, className, WTF_ARRAY_LENGTH(className)) && !wcscmp(className, PopupMenuWin::popupClassName())) {
1721             // We don't let the WebView scroll here for two reasons - 1) To match Firefox behavior, 2) If we do scroll, we lose the
1722             // focus ring around the select menu.
1723             SetFocus(m_viewWindow);
1724             return true;
1725         }
1726     }
1727
1728     PlatformWheelEvent wheelEvent(m_viewWindow, wParam, lParam, isMouseHWheel);
1729     Frame* coreFrame = core(m_mainFrame);
1730     if (!coreFrame)
1731         return false;
1732
1733     return coreFrame->eventHandler()->handleWheelEvent(wheelEvent);
1734 }
1735
1736 bool WebView::verticalScroll(WPARAM wParam, LPARAM /*lParam*/)
1737 {
1738     ScrollDirection direction;
1739     ScrollGranularity granularity;
1740     switch (LOWORD(wParam)) {
1741     case SB_LINEDOWN:
1742         granularity = ScrollByLine;
1743         direction = ScrollDown;
1744         break;
1745     case SB_LINEUP:
1746         granularity = ScrollByLine;
1747         direction = ScrollUp;
1748         break;
1749     case SB_PAGEDOWN:
1750         granularity = ScrollByDocument;
1751         direction = ScrollDown;
1752         break;
1753     case SB_PAGEUP:
1754         granularity = ScrollByDocument;
1755         direction = ScrollUp;
1756         break;
1757     default:
1758         return false;
1759         break;
1760     }
1761     
1762     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1763     return frame->eventHandler()->scrollRecursively(direction, granularity);
1764 }
1765
1766 bool WebView::horizontalScroll(WPARAM wParam, LPARAM /*lParam*/)
1767 {
1768     ScrollDirection direction;
1769     ScrollGranularity granularity;
1770     switch (LOWORD(wParam)) {
1771     case SB_LINELEFT:
1772         granularity = ScrollByLine;
1773         direction = ScrollLeft;
1774         break;
1775     case SB_LINERIGHT:
1776         granularity = ScrollByLine;
1777         direction = ScrollRight;
1778         break;
1779     case SB_PAGELEFT:
1780         granularity = ScrollByDocument;
1781         direction = ScrollLeft;
1782         break;
1783     case SB_PAGERIGHT:
1784         granularity = ScrollByDocument;
1785         direction = ScrollRight;
1786         break;
1787     default:
1788         return false;
1789     }
1790
1791     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1792     return frame->eventHandler()->scrollRecursively(direction, granularity);
1793 }
1794
1795
1796 bool WebView::execCommand(WPARAM wParam, LPARAM /*lParam*/)
1797 {
1798     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1799     switch (LOWORD(wParam)) {
1800         case SelectAll:
1801             return frame->editor()->command("SelectAll").execute();
1802         case Undo:
1803             return frame->editor()->command("Undo").execute();
1804         case Redo:
1805             return frame->editor()->command("Redo").execute();
1806     }
1807     return false;
1808 }
1809
1810 bool WebView::keyUp(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1811 {
1812     PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::KeyUp, systemKeyDown);
1813
1814     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1815     m_currentCharacterCode = 0;
1816
1817     return frame->eventHandler()->keyEvent(keyEvent);
1818 }
1819
1820 static const unsigned CtrlKey = 1 << 0;
1821 static const unsigned AltKey = 1 << 1;
1822 static const unsigned ShiftKey = 1 << 2;
1823
1824
1825 struct KeyDownEntry {
1826     unsigned virtualKey;
1827     unsigned modifiers;
1828     const char* name;
1829 };
1830
1831 struct KeyPressEntry {
1832     unsigned charCode;
1833     unsigned modifiers;
1834     const char* name;
1835 };
1836
1837 static const KeyDownEntry keyDownEntries[] = {
1838     { VK_LEFT,   0,                  "MoveLeft"                                    },
1839     { VK_LEFT,   ShiftKey,           "MoveLeftAndModifySelection"                  },
1840     { VK_LEFT,   CtrlKey,            "MoveWordLeft"                                },
1841     { VK_LEFT,   CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection"              },
1842     { VK_RIGHT,  0,                  "MoveRight"                                   },
1843     { VK_RIGHT,  ShiftKey,           "MoveRightAndModifySelection"                 },
1844     { VK_RIGHT,  CtrlKey,            "MoveWordRight"                               },
1845     { VK_RIGHT,  CtrlKey | ShiftKey, "MoveWordRightAndModifySelection"             },
1846     { VK_UP,     0,                  "MoveUp"                                      },
1847     { VK_UP,     ShiftKey,           "MoveUpAndModifySelection"                    },
1848     { VK_PRIOR,  ShiftKey,           "MovePageUpAndModifySelection"                },
1849     { VK_DOWN,   0,                  "MoveDown"                                    },
1850     { VK_DOWN,   ShiftKey,           "MoveDownAndModifySelection"                  },
1851     { VK_NEXT,   ShiftKey,           "MovePageDownAndModifySelection"              },
1852     { VK_PRIOR,  0,                  "MovePageUp"                                  },
1853     { VK_NEXT,   0,                  "MovePageDown"                                },
1854     { VK_HOME,   0,                  "MoveToBeginningOfLine"                       },
1855     { VK_HOME,   ShiftKey,           "MoveToBeginningOfLineAndModifySelection"     },
1856     { VK_HOME,   CtrlKey,            "MoveToBeginningOfDocument"                   },
1857     { VK_HOME,   CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
1858
1859     { VK_END,    0,                  "MoveToEndOfLine"                             },
1860     { VK_END,    ShiftKey,           "MoveToEndOfLineAndModifySelection"           },
1861     { VK_END,    CtrlKey,            "MoveToEndOfDocument"                         },
1862     { VK_END,    CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection"       },
1863
1864     { VK_BACK,   0,                  "DeleteBackward"                              },
1865     { VK_BACK,   ShiftKey,           "DeleteBackward"                              },
1866     { VK_DELETE, 0,                  "DeleteForward"                               },
1867     { VK_BACK,   CtrlKey,            "DeleteWordBackward"                          },
1868     { VK_DELETE, CtrlKey,            "DeleteWordForward"                           },
1869     
1870     { 'B',       CtrlKey,            "ToggleBold"                                  },
1871     { 'I',       CtrlKey,            "ToggleItalic"                                },
1872
1873     { VK_ESCAPE, 0,                  "Cancel"                                      },
1874     { VK_OEM_PERIOD, CtrlKey,        "Cancel"                                      },
1875     { VK_TAB,    0,                  "InsertTab"                                   },
1876     { VK_TAB,    ShiftKey,           "InsertBacktab"                               },
1877     { VK_RETURN, 0,                  "InsertNewline"                               },
1878     { VK_RETURN, CtrlKey,            "InsertNewline"                               },
1879     { VK_RETURN, AltKey,             "InsertNewline"                               },
1880     { VK_RETURN, ShiftKey,           "InsertNewline"                               },
1881     { VK_RETURN, AltKey | ShiftKey,  "InsertNewline"                               },
1882
1883     // It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled
1884     // in the application or in WebKit. We chose WebKit.
1885     { 'C',       CtrlKey,            "Copy"                                        },
1886     { 'V',       CtrlKey,            "Paste"                                       },
1887     { 'X',       CtrlKey,            "Cut"                                         },
1888     { 'A',       CtrlKey,            "SelectAll"                                   },
1889     { VK_INSERT, CtrlKey,            "Copy"                                        },
1890     { VK_DELETE, ShiftKey,           "Cut"                                         },
1891     { VK_INSERT, ShiftKey,           "Paste"                                       },
1892     { 'Z',       CtrlKey,            "Undo"                                        },
1893     { 'Z',       CtrlKey | ShiftKey, "Redo"                                        },
1894 };
1895
1896 static const KeyPressEntry keyPressEntries[] = {
1897     { '\t',   0,                  "InsertTab"                                   },
1898     { '\t',   ShiftKey,           "InsertBacktab"                               },
1899     { '\r',   0,                  "InsertNewline"                               },
1900     { '\r',   CtrlKey,            "InsertNewline"                               },
1901     { '\r',   AltKey,             "InsertNewline"                               },
1902     { '\r',   ShiftKey,           "InsertNewline"                               },
1903     { '\r',   AltKey | ShiftKey,  "InsertNewline"                               },
1904 };
1905
1906 const char* WebView::interpretKeyEvent(const KeyboardEvent* evt)
1907 {
1908     ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
1909
1910     static HashMap<int, const char*>* keyDownCommandsMap = 0;
1911     static HashMap<int, const char*>* keyPressCommandsMap = 0;
1912
1913     if (!keyDownCommandsMap) {
1914         keyDownCommandsMap = new HashMap<int, const char*>;
1915         keyPressCommandsMap = new HashMap<int, const char*>;
1916
1917         for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyDownEntries); ++i)
1918             keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
1919
1920         for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyPressEntries); ++i)
1921             keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
1922     }
1923
1924     unsigned modifiers = 0;
1925     if (evt->shiftKey())
1926         modifiers |= ShiftKey;
1927     if (evt->altKey())
1928         modifiers |= AltKey;
1929     if (evt->ctrlKey())
1930         modifiers |= CtrlKey;
1931
1932     if (evt->type() == eventNames().keydownEvent) {
1933         int mapKey = modifiers << 16 | evt->keyCode();
1934         return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
1935     }
1936
1937     int mapKey = modifiers << 16 | evt->charCode();
1938     return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
1939 }
1940
1941 bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
1942 {
1943     Node* node = evt->target()->toNode();
1944     ASSERT(node);
1945     Frame* frame = node->document()->frame();
1946     ASSERT(frame);
1947
1948     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1949     if (!keyEvent || keyEvent->isSystemKey())  // do not treat this as text input if it's a system key event
1950         return false;
1951
1952     Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1953
1954     if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1955         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1956         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1957         // (e.g. Tab that inserts a Tab character, or Enter).
1958         return !command.isTextInsertion() && command.execute(evt);
1959     }
1960
1961      if (command.execute(evt))
1962         return true;
1963
1964     // Don't insert null or control characters as they can result in unexpected behaviour
1965     if (evt->charCode() < ' ')
1966         return false;
1967
1968     return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1969 }
1970
1971 bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1972 {
1973 #if ENABLE(FULLSCREEN_API)
1974     // Trap the ESC key when in full screen mode.
1975     if (virtualKeyCode == VK_ESCAPE && isFullScreen()) {
1976         m_fullscreenController->exitFullScreen();
1977         return false;
1978     }
1979 #endif
1980     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1981
1982     PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::RawKeyDown, systemKeyDown);
1983     bool handled = frame->eventHandler()->keyEvent(keyEvent);
1984
1985     // These events cannot be canceled, and we have no default handling for them.
1986     // FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
1987     if (systemKeyDown && virtualKeyCode != VK_RETURN)
1988         return false;
1989
1990     if (handled) {
1991         // FIXME: remove WM_UNICHAR, too
1992         MSG msg;
1993         // WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
1994         if (!systemKeyDown)
1995             ::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
1996         return true;
1997     }
1998
1999     // We need to handle back/forward using either Ctrl+Left/Right Arrow keys.
2000     // FIXME: This logic should probably be in EventHandler::defaultArrowEventHandler().
2001     // FIXME: Should check that other modifiers aren't pressed.
2002     if (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey())
2003         return m_page->goForward();
2004     if (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey())
2005         return m_page->goBack();
2006
2007     // Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
2008     ScrollDirection direction;
2009     ScrollGranularity granularity;
2010     switch (virtualKeyCode) {
2011         case VK_LEFT:
2012             granularity = ScrollByLine;
2013             direction = ScrollLeft;
2014             break;
2015         case VK_RIGHT:
2016             granularity = ScrollByLine;
2017             direction = ScrollRight;
2018             break;
2019         case VK_UP:
2020             granularity = ScrollByLine;
2021             direction = ScrollUp;
2022             break;
2023         case VK_DOWN:
2024             granularity = ScrollByLine;
2025             direction = ScrollDown;
2026             break;
2027         case VK_HOME:
2028             granularity = ScrollByDocument;
2029             direction = ScrollUp;
2030             break;
2031         case VK_END:
2032             granularity = ScrollByDocument;
2033             direction = ScrollDown;
2034             break;
2035         case VK_PRIOR:
2036             granularity = ScrollByPage;
2037             direction = ScrollUp;
2038             break;
2039         case VK_NEXT:
2040             granularity = ScrollByPage;
2041             direction = ScrollDown;
2042             break;
2043         default:
2044             return false;
2045     }
2046
2047     return frame->eventHandler()->scrollRecursively(direction, granularity);
2048 }
2049
2050 bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
2051 {
2052     Frame* frame = m_page->focusController()->focusedOrMainFrame();
2053
2054     PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformKeyboardEvent::Char, systemKeyDown);
2055     // IE does not dispatch keypress event for WM_SYSCHAR.
2056     if (systemKeyDown)
2057         return frame->eventHandler()->handleAccessKey(keyEvent);
2058     return frame->eventHandler()->keyEvent(keyEvent);
2059 }
2060
2061 void WebView::setIsBeingDestroyed()
2062 {
2063     m_isBeingDestroyed = true;
2064
2065     // Remove our this pointer from the window so we won't try to handle any more window messages.
2066     // See <http://webkit.org/b/55054>.
2067     ::SetWindowLongPtrW(m_viewWindow, 0, 0);
2068 }
2069
2070 bool WebView::registerWebViewWindowClass()
2071 {
2072     static bool haveRegisteredWindowClass = false;
2073     if (haveRegisteredWindowClass)
2074         return true;
2075
2076     haveRegisteredWindowClass = true;
2077
2078     WNDCLASSEX wcex;
2079
2080     wcex.cbSize = sizeof(WNDCLASSEX);
2081
2082     wcex.style          = CS_DBLCLKS;
2083     wcex.lpfnWndProc    = WebViewWndProc;
2084     wcex.cbClsExtra     = 0;
2085     wcex.cbWndExtra     = 4; // 4 bytes for the IWebView pointer
2086     wcex.hInstance      = gInstance;
2087     wcex.hIcon          = 0;
2088     wcex.hCursor        = ::LoadCursor(0, IDC_ARROW);
2089     wcex.hbrBackground  = 0;
2090     wcex.lpszMenuName   = 0;
2091     wcex.lpszClassName  = kWebViewWindowClassName;
2092     wcex.hIconSm        = 0;
2093
2094     return !!RegisterClassEx(&wcex);
2095 }
2096
2097 static HWND findTopLevelParent(HWND window)
2098 {
2099     if (!window)
2100         return 0;
2101
2102     HWND current = window;
2103     for (HWND parent = GetParent(current); current; current = parent, parent = GetParent(parent))
2104         if (!parent || !(GetWindowLongPtr(current, GWL_STYLE) & (WS_POPUP | WS_CHILD)))
2105             return current;
2106     ASSERT_NOT_REACHED();
2107     return 0;
2108 }
2109
2110 LRESULT CALLBACK WebView::WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
2111 {
2112     LRESULT lResult = 0;
2113     LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
2114     WebView* webView = reinterpret_cast<WebView*>(longPtr);
2115     WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
2116     if (!mainFrameImpl)
2117         return DefWindowProc(hWnd, message, wParam, lParam);
2118
2119     // We shouldn't be trying to handle any window messages after WM_DESTROY.
2120     // See <http://webkit.org/b/55054>.
2121     ASSERT(!webView->isBeingDestroyed());
2122
2123     // hold a ref, since the WebView could go away in an event handler.
2124     COMPtr<WebView> protector(webView);
2125     ASSERT(webView);
2126
2127     // Windows Media Player has a modal message loop that will deliver messages
2128     // to us at inappropriate times and we will crash if we handle them when
2129     // they are delivered. We repost paint messages so that we eventually get
2130     // a chance to paint once the modal loop has exited, but other messages
2131     // aren't safe to repost, so we just drop them.
2132     if (PluginView::isCallingPlugin()) {
2133         if (message == WM_PAINT)
2134             PostMessage(hWnd, message, wParam, lParam);
2135         return 0;
2136     }
2137
2138     bool handled = true;
2139
2140     switch (message) {
2141         case WM_PAINT: {
2142             webView->paint(0, 0);
2143             if (webView->usesLayeredWindow())
2144                 webView->performLayeredWindowUpdate();
2145             break;
2146         }
2147         case WM_ERASEBKGND:
2148             if (webView->usesLayeredWindow()) {
2149                 // Don't perform a background erase for transparent views.
2150                 handled = true;
2151                 lResult = 1;
2152             }
2153             break;
2154         case WM_PRINTCLIENT:
2155             webView->paint((HDC)wParam, lParam);
2156             break;
2157         case WM_DESTROY:
2158             webView->setIsBeingDestroyed();
2159             webView->close();
2160             break;
2161         case WM_GESTURENOTIFY:
2162             handled = webView->gestureNotify(wParam, lParam);
2163             break;
2164         case WM_GESTURE:
2165             handled = webView->gesture(wParam, lParam);
2166             break;
2167         case WM_MOUSEMOVE:
2168         case WM_LBUTTONDOWN:
2169         case WM_MBUTTONDOWN:
2170         case WM_RBUTTONDOWN:
2171         case WM_LBUTTONDBLCLK:
2172         case WM_MBUTTONDBLCLK:
2173         case WM_RBUTTONDBLCLK:
2174         case WM_LBUTTONUP:
2175         case WM_MBUTTONUP:
2176         case WM_RBUTTONUP:
2177         case WM_MOUSELEAVE:
2178         case WM_CANCELMODE:
2179             if (Frame* coreFrame = core(mainFrameImpl))
2180                 if (coreFrame->view()->didFirstLayout())
2181                     handled = webView->handleMouseEvent(message, wParam, lParam);
2182             break;
2183         case WM_MOUSEWHEEL:
2184         case WM_VISTA_MOUSEHWHEEL:
2185             if (Frame* coreFrame = core(mainFrameImpl))
2186                 if (coreFrame->view()->didFirstLayout())
2187                     handled = webView->mouseWheel(wParam, lParam, message == WM_VISTA_MOUSEHWHEEL);
2188             break;
2189         case WM_SYSKEYDOWN:
2190             handled = webView->keyDown(wParam, lParam, true);
2191             break;
2192         case WM_KEYDOWN:
2193             handled = webView->keyDown(wParam, lParam);
2194             break;
2195         case WM_SYSKEYUP:
2196             handled = webView->keyUp(wParam, lParam, true);
2197             break;
2198         case WM_KEYUP:
2199             handled = webView->keyUp(wParam, lParam);
2200             break;
2201         case WM_SYSCHAR:
2202             handled = webView->keyPress(wParam, lParam, true);
2203             break;
2204         case WM_CHAR:
2205             handled = webView->keyPress(wParam, lParam);
2206             break;
2207         // FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
2208         case WM_SIZE:
2209             if (lParam != 0)
2210                 webView->sizeChanged(IntSize(LOWORD(lParam), HIWORD(lParam)));
2211             break;
2212         case WM_SHOWWINDOW:
2213             lResult = DefWindowProc(hWnd, message, wParam, lParam);
2214             if (wParam == 0) {
2215                 // The window is being hidden (e.g., because we switched tabs).
2216                 // Null out our backing store.
2217                 webView->deleteBackingStore();
2218             }
2219             break;
2220         case WM_SETFOCUS: {
2221             COMPtr<IWebUIDelegate> uiDelegate;
2222             COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2223             if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2224                 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2225                 uiDelegatePrivate->webViewReceivedFocus(webView);
2226
2227             FocusController* focusController = webView->page()->focusController();
2228             if (Frame* frame = focusController->focusedFrame()) {
2229                 // Send focus events unless the previously focused window is a
2230                 // child of ours (for example a plugin).
2231                 if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
2232                     focusController->setFocused(true);
2233             } else
2234                 focusController->setFocused(true);
2235             break;
2236         }
2237         case WM_KILLFOCUS: {
2238             COMPtr<IWebUIDelegate> uiDelegate;
2239             COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2240             HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
2241             if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2242                 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2243                 uiDelegatePrivate->webViewLostFocus(webView, (OLE_HANDLE)(ULONG64)newFocusWnd);
2244
2245             FocusController* focusController = webView->page()->focusController();
2246             Frame* frame = focusController->focusedOrMainFrame();
2247             webView->resetIME(frame);
2248             // Send blur events unless we're losing focus to a child of ours.
2249             if (!IsChild(hWnd, newFocusWnd))
2250                 focusController->setFocused(false);
2251
2252             // If we are pan-scrolling when we lose focus, stop the pan scrolling.
2253             frame->eventHandler()->stopAutoscrollTimer();
2254
2255             break;
2256         }
2257         case WM_WINDOWPOSCHANGED:
2258             if (reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW)
2259                 webView->updateActiveStateSoon();
2260             handled = false;
2261             break;
2262         case WM_CUT:
2263             webView->cut(0);
2264             break;
2265         case WM_COPY:
2266             webView->copy(0);
2267             break;
2268         case WM_PASTE:
2269             webView->paste(0);
2270             break;
2271         case WM_CLEAR:
2272             webView->delete_(0);
2273             break;
2274         case WM_COMMAND:
2275             if (HIWORD(wParam))
2276                 handled = webView->execCommand(wParam, lParam);
2277             else // If the high word of wParam is 0, the message is from a menu
2278                 webView->performContextMenuAction(wParam, lParam, false);
2279             break;
2280         case WM_MENUCOMMAND:
2281             webView->performContextMenuAction(wParam, lParam, true);
2282             break;
2283         case WM_CONTEXTMENU:
2284             handled = webView->handleContextMenuEvent(wParam, lParam);
2285             break;
2286         case WM_INITMENUPOPUP:
2287             handled = webView->onInitMenuPopup(wParam, lParam);
2288             break;
2289         case WM_MEASUREITEM:
2290             handled = webView->onMeasureItem(wParam, lParam);
2291             break;
2292         case WM_DRAWITEM:
2293             handled = webView->onDrawItem(wParam, lParam);
2294             break;
2295         case WM_UNINITMENUPOPUP:
2296             handled = webView->onUninitMenuPopup(wParam, lParam);
2297             break;
2298         case WM_XP_THEMECHANGED:
2299             if (Frame* coreFrame = core(mainFrameImpl)) {
2300                 webView->deleteBackingStore();
2301                 coreFrame->page()->theme()->themeChanged();
2302                 ScrollbarTheme::nativeTheme()->themeChanged();
2303                 RECT windowRect;
2304                 ::GetClientRect(hWnd, &windowRect);
2305                 ::InvalidateRect(hWnd, &windowRect, false);
2306 #if USE(ACCELERATED_COMPOSITING)
2307                 if (webView->isAcceleratedCompositing())
2308                     webView->m_backingLayer->setNeedsDisplay();
2309 #endif
2310            }
2311             break;
2312         case WM_MOUSEACTIVATE:
2313             webView->setMouseActivated(true);
2314             handled = false;
2315             break;
2316         case WM_GETDLGCODE: {
2317             COMPtr<IWebUIDelegate> uiDelegate;
2318             COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2319             LONG_PTR dlgCode = 0;
2320             UINT keyCode = 0;
2321             if (lParam) {
2322                 LPMSG lpMsg = (LPMSG)lParam;
2323                 if (lpMsg->message == WM_KEYDOWN)
2324                     keyCode = (UINT) lpMsg->wParam;
2325             }
2326             if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2327                 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate
2328                 && SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
2329                 return dlgCode;
2330             handled = false;
2331             break;
2332         }
2333         case WM_GETOBJECT:
2334             handled = webView->onGetObject(wParam, lParam, lResult);
2335             break;
2336         case WM_IME_STARTCOMPOSITION:
2337             handled = webView->onIMEStartComposition();
2338             break;
2339         case WM_IME_REQUEST:
2340             lResult = webView->onIMERequest(wParam, lParam);
2341             break;
2342         case WM_IME_COMPOSITION:
2343             handled = webView->onIMEComposition(lParam);
2344             break;
2345         case WM_IME_ENDCOMPOSITION:
2346             handled = webView->onIMEEndComposition();
2347             break;
2348         case WM_IME_CHAR:
2349             handled = webView->onIMEChar(wParam, lParam);
2350             break;
2351         case WM_IME_NOTIFY:
2352             handled = webView->onIMENotify(wParam, lParam, &lResult);
2353             break;
2354         case WM_IME_SELECT:
2355             handled = webView->onIMESelect(wParam, lParam);
2356             break;
2357         case WM_IME_SETCONTEXT:
2358             handled = webView->onIMESetContext(wParam, lParam);
2359             break;
2360         case WM_TIMER:
2361             switch (wParam) {
2362                 case UpdateActiveStateTimer:
2363                     KillTimer(hWnd, UpdateActiveStateTimer);
2364                     webView->updateActiveState();
2365                     break;
2366                 case DeleteBackingStoreTimer:
2367                     webView->deleteBackingStore();
2368                     break;
2369             }
2370             break;
2371         case WM_SETCURSOR:
2372             handled = ::SetCursor(webView->m_lastSetCursor);
2373             break;
2374         case WM_VSCROLL:
2375             handled = webView->verticalScroll(wParam, lParam);
2376             break;
2377         case WM_HSCROLL:
2378             handled = webView->horizontalScroll(wParam, lParam);
2379             break;
2380         default:
2381             handled = false;
2382             break;
2383     }
2384
2385     if (!handled)
2386         lResult = DefWindowProc(hWnd, message, wParam, lParam);
2387     
2388     // Let the client know whether we consider this message handled.
2389     return (message == WM_KEYDOWN || message == WM_SYSKEYDOWN || message == WM_KEYUP || message == WM_SYSKEYUP) ? !handled : lResult;
2390 }
2391
2392 bool WebView::developerExtrasEnabled() const
2393 {
2394     if (m_preferences->developerExtrasDisabledByOverride())
2395         return false;
2396
2397 #ifdef NDEBUG
2398     BOOL enabled;
2399     return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
2400 #else
2401     return true;
2402 #endif
2403 }
2404
2405 static String webKitVersionString()
2406 {
2407     LPWSTR buildNumberStringPtr;
2408     if (!::LoadStringW(gInstance, BUILD_NUMBER, reinterpret_cast<LPWSTR>(&buildNumberStringPtr), 0) || !buildNumberStringPtr)
2409         return "534+";
2410
2411     return buildNumberStringPtr;
2412 }
2413
2414 const String& WebView::userAgentForKURL(const KURL&)
2415 {
2416     if (m_userAgentOverridden)
2417         return m_userAgentCustom;
2418
2419     if (!m_userAgentStandard.length())
2420         m_userAgentStandard = WebView::standardUserAgentWithApplicationName(m_applicationName);
2421     return m_userAgentStandard;
2422 }
2423
2424 // IUnknown -------------------------------------------------------------------
2425
2426 HRESULT STDMETHODCALLTYPE WebView::QueryInterface(REFIID riid, void** ppvObject)
2427 {
2428     *ppvObject = 0;
2429     if (IsEqualGUID(riid, CLSID_WebView))
2430         *ppvObject = this;
2431     else if (IsEqualGUID(riid, IID_IUnknown))
2432         *ppvObject = static_cast<IWebView*>(this);
2433     else if (IsEqualGUID(riid, IID_IWebView))
2434         *ppvObject = static_cast<IWebView*>(this);
2435     else if (IsEqualGUID(riid, IID_IWebViewPrivate))
2436         *ppvObject = static_cast<IWebViewPrivate*>(this);
2437     else if (IsEqualGUID(riid, IID_IWebIBActions))
2438         *ppvObject = static_cast<IWebIBActions*>(this);
2439     else if (IsEqualGUID(riid, IID_IWebViewCSS))
2440         *ppvObject = static_cast<IWebViewCSS*>(this);
2441     else if (IsEqualGUID(riid, IID_IWebViewEditing))
2442         *ppvObject = static_cast<IWebViewEditing*>(this);
2443     else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
2444         *ppvObject = static_cast<IWebViewUndoableEditing*>(this);
2445     else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
2446         *ppvObject = static_cast<IWebViewEditingActions*>(this);
2447     else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
2448         *ppvObject = static_cast<IWebNotificationObserver*>(this);
2449     else if (IsEqualGUID(riid, IID_IDropTarget))
2450         *ppvObject = static_cast<IDropTarget*>(this);
2451     else
2452         return E_NOINTERFACE;
2453
2454     AddRef();
2455     return S_OK;
2456 }
2457
2458 ULONG STDMETHODCALLTYPE WebView::AddRef(void)
2459 {
2460     ASSERT(!m_deletionHasBegun);
2461     return ++m_refCount;
2462 }
2463
2464 ULONG STDMETHODCALLTYPE WebView::Release(void)
2465 {
2466     ASSERT(!m_deletionHasBegun);
2467
2468     if (m_refCount == 1) {
2469         // Call close() now so that clients don't have to. (It's harmless to call close() multiple
2470         // times.) We do this here instead of in our destructor because close() can cause AddRef()
2471         // and Release() to be called, and if that happened in our destructor we would be destroyed
2472         // more than once.
2473         close();
2474     }
2475
2476     ULONG newRef = --m_refCount;
2477     if (!newRef) {
2478 #if !ASSERT_DISABLED
2479         m_deletionHasBegun = true;
2480 #endif
2481         delete(this);
2482     }
2483
2484     return newRef;
2485 }
2486
2487 // IWebView --------------------------------------------------------------------
2488
2489 HRESULT STDMETHODCALLTYPE WebView::canShowMIMEType( 
2490     /* [in] */ BSTR mimeType,
2491     /* [retval][out] */ BOOL* canShow)
2492 {
2493     String mimeTypeStr(mimeType, SysStringLen(mimeType));
2494
2495     if (!canShow)
2496         return E_POINTER;
2497
2498     *canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeTypeStr) ||
2499         MIMETypeRegistry::isSupportedNonImageMIMEType(mimeTypeStr) ||
2500         (m_page && m_page->pluginData() && m_page->pluginData()->supportsMimeType(mimeTypeStr)) ||
2501         shouldUseEmbeddedView(mimeTypeStr);
2502     
2503     return S_OK;
2504 }
2505
2506 HRESULT STDMETHODCALLTYPE WebView::canShowMIMETypeAsHTML( 
2507     /* [in] */ BSTR /*mimeType*/,
2508     /* [retval][out] */ BOOL* canShow)
2509 {
2510     // FIXME
2511     *canShow = TRUE;
2512     return S_OK;
2513 }
2514
2515 HRESULT STDMETHODCALLTYPE WebView::MIMETypesShownAsHTML( 
2516     /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
2517 {
2518     ASSERT_NOT_REACHED();
2519     return E_NOTIMPL;
2520 }
2521
2522 HRESULT STDMETHODCALLTYPE WebView::setMIMETypesShownAsHTML( 
2523         /* [size_is][in] */ BSTR* /*mimeTypes*/,
2524         /* [in] */ int /*cMimeTypes*/)
2525 {
2526     ASSERT_NOT_REACHED();
2527     return E_NOTIMPL;
2528 }
2529
2530 HRESULT STDMETHODCALLTYPE WebView::URLFromPasteboard( 
2531     /* [in] */ IDataObject* /*pasteboard*/,
2532     /* [retval][out] */ BSTR* /*url*/)
2533 {
2534     ASSERT_NOT_REACHED();
2535     return E_NOTIMPL;
2536 }
2537
2538 HRESULT STDMETHODCALLTYPE WebView::URLTitleFromPasteboard( 
2539     /* [in] */ IDataObject* /*pasteboard*/,
2540     /* [retval][out] */ BSTR* /*urlTitle*/)
2541 {
2542     ASSERT_NOT_REACHED();
2543     return E_NOTIMPL;
2544 }
2545
2546 static void WebKitSetApplicationCachePathIfNecessary()
2547 {
2548     static bool initialized = false;
2549     if (initialized)
2550         return;
2551
2552     String path = localUserSpecificStorageDirectory();
2553     if (!path.isNull())
2554         cacheStorage().setCacheDirectory(path);
2555
2556     initialized = true;
2557 }
2558
2559 bool WebView::shouldInitializeTrackPointHack()
2560 {
2561     static bool shouldCreateScrollbars;
2562     static bool hasRunTrackPointCheck;
2563
2564     if (hasRunTrackPointCheck)
2565         return shouldCreateScrollbars;
2566
2567     hasRunTrackPointCheck = true;
2568     const WCHAR trackPointKeys[][50] = { L"Software\\Lenovo\\TrackPoint",
2569         L"Software\\Lenovo\\UltraNav",
2570         L"Software\\Alps\\Apoint\\TrackPoint",
2571         L"Software\\Synaptics\\SynTPEnh\\UltraNavUSB",
2572         L"Software\\Synaptics\\SynTPEnh\\UltraNavPS2" };
2573
2574     for (int i = 0; i < 5; ++i) {
2575         HKEY trackPointKey;
2576         int readKeyResult = ::RegOpenKeyExW(HKEY_CURRENT_USER, trackPointKeys[i], 0, KEY_READ, &trackPointKey);
2577         ::RegCloseKey(trackPointKey);
2578         if (readKeyResult == ERROR_SUCCESS) {
2579             shouldCreateScrollbars = true;
2580             return shouldCreateScrollbars;
2581         }
2582     }
2583
2584     return shouldCreateScrollbars;
2585 }
2586     
2587 HRESULT STDMETHODCALLTYPE WebView::initWithFrame( 
2588     /* [in] */ RECT frame,
2589     /* [in] */ BSTR frameName,
2590     /* [in] */ BSTR groupName)
2591 {
2592     HRESULT hr = S_OK;
2593
2594     if (m_viewWindow)
2595         return E_FAIL;
2596
2597     registerWebViewWindowClass();
2598
2599     m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
2600         frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow ? m_hostWindow : HWND_MESSAGE, 0, gInstance, 0);
2601     ASSERT(::IsWindow(m_viewWindow));
2602
2603     if (shouldInitializeTrackPointHack()) {
2604         // If we detected a registry key belonging to a TrackPoint driver, then create fake trackpoint
2605         // scrollbars, so the WebView will receive WM_VSCROLL and WM_HSCROLL messages. We create one
2606         // vertical scrollbar and one horizontal to allow for receiving both types of messages.
2607         ::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTHSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_HORZ, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
2608         ::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTVSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_VERT, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
2609     }
2610
2611     hr = registerDragDrop();
2612     if (FAILED(hr))
2613         return hr;
2614
2615     WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
2616     sharedPreferences->willAddToWebView();
2617     m_preferences = sharedPreferences;
2618
2619     static bool didOneTimeInitialization;
2620     if (!didOneTimeInitialization) {
2621         InitializeLoggingChannelsIfNecessary();
2622 #if ENABLE(SQL_DATABASE)
2623         WebKitInitializeWebDatabasesIfNecessary();
2624 #endif
2625         WebKitSetApplicationCachePathIfNecessary();
2626         WebPlatformStrategies::initialize();
2627         Settings::setDefaultMinDOMTimerInterval(0.004);
2628
2629         didOneTimeInitialization = true;
2630      }
2631
2632 #if USE(SAFARI_THEME)
2633     BOOL shouldPaintNativeControls;
2634     if (SUCCEEDED(m_preferences->shouldPaintNativeControls(&shouldPaintNativeControls)))
2635         Settings::setShouldPaintNativeControls(shouldPaintNativeControls);
2636 #endif
2637
2638     BOOL useHighResolutionTimer;
2639     if (SUCCEEDED(m_preferences->shouldUseHighResolutionTimers(&useHighResolutionTimer)))
2640         Settings::setShouldUseHighResolutionTimers(useHighResolutionTimer);
2641
2642     Page::PageClients pageClients;
2643     pageClients.chromeClient = new WebChromeClient(this);
2644     pageClients.contextMenuClient = new WebContextMenuClient(this);
2645     pageClients.editorClient = new WebEditorClient(this);
2646     pageClients.dragClient = new WebDragClient(this);
2647     pageClients.inspectorClient = new WebInspectorClient(this);
2648 #if ENABLE(CLIENT_BASED_GEOLOCATION)
2649     pageClients.geolocationClient = new WebGeolocationClient(this);
2650 #endif
2651     m_page = new Page(pageClients);
2652
2653     BSTR localStoragePath;
2654     if (SUCCEEDED(m_preferences->localStorageDatabasePath(&localStoragePath))) {
2655         m_page->settings()->setLocalStorageDatabasePath(String(localStoragePath, SysStringLen(localStoragePath)));
2656         SysFreeString(localStoragePath);
2657     }
2658
2659     if (m_uiDelegate) {
2660         BSTR path;
2661         if (SUCCEEDED(m_uiDelegate->ftpDirectoryTemplatePath(this, &path))) {
2662             m_page->settings()->setFTPDirectoryTemplatePath(String(path, SysStringLen(path)));
2663             SysFreeString(path);
2664         }
2665     }
2666
2667     WebFrame* webFrame = WebFrame::createInstance();
2668     RefPtr<Frame> coreFrame = webFrame->init(this, m_page, 0);
2669     m_mainFrame = webFrame;
2670     webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
2671
2672     coreFrame->tree()->setName(String(frameName, SysStringLen(frameName)));
2673     coreFrame->init();
2674     setGroupName(groupName);
2675
2676     addToAllWebViewsSet();
2677
2678     #pragma warning(suppress: 4244)
2679     SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
2680     ShowWindow(m_viewWindow, SW_SHOW);
2681
2682     initializeToolTipWindow();
2683     windowAncestryDidChange();
2684
2685     IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
2686     notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2687     m_preferences->postPreferencesChangesNotification();
2688
2689     setSmartInsertDeleteEnabled(TRUE);
2690     return hr;
2691 }
2692
2693 static bool initCommonControls()
2694 {
2695     static bool haveInitialized = false;
2696     if (haveInitialized)
2697         return true;
2698
2699     INITCOMMONCONTROLSEX init;
2700     init.dwSize = sizeof(init);
2701     init.dwICC = ICC_TREEVIEW_CLASSES;
2702     haveInitialized = !!::InitCommonControlsEx(&init);
2703     return haveInitialized;
2704 }
2705
2706 void WebView::initializeToolTipWindow()
2707 {
2708     if (!initCommonControls())
2709         return;
2710
2711     m_toolTipHwnd = CreateWindowEx(WS_EX_TRANSPARENT, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
2712                                    CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
2713                                    m_viewWindow, 0, 0, 0);
2714     if (!m_toolTipHwnd)
2715         return;
2716
2717     TOOLINFO info = {0};
2718     info.cbSize = sizeof(info);
2719     info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
2720     info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2721
2722     ::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
2723     ::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, maxToolTipWidth);
2724
2725     ::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
2726 }
2727
2728 void WebView::setToolTip(const String& toolTip)
2729 {
2730     if (!m_toolTipHwnd)
2731         return;
2732
2733     if (toolTip == m_toolTip)
2734         return;
2735
2736     m_toolTip = toolTip;
2737
2738     if (!m_toolTip.isEmpty()) {
2739         TOOLINFO info = {0};
2740         info.cbSize = sizeof(info);
2741         info.uFlags = TTF_IDISHWND;
2742         info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2743         info.lpszText = const_cast<UChar*>(m_toolTip.charactersWithNullTermination());
2744         ::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
2745     }
2746
2747     ::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
2748 }
2749
2750 HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
2751 {
2752     COMPtr<IPropertyBag> propertyBag;
2753     HRESULT hr = notification->userInfo(&propertyBag);
2754     if (FAILED(hr))
2755         return hr;
2756     if (!propertyBag)
2757         return E_FAIL;
2758
2759     COMPtr<CFDictionaryPropertyBag> dictionaryPropertyBag;
2760     hr = propertyBag->QueryInterface(&dictionaryPropertyBag);
2761     if (FAILED(hr))
2762         return hr;
2763
2764     CFDictionaryRef dictionary = dictionaryPropertyBag->dictionary();
2765     if (!dictionary)
2766         return E_FAIL;
2767
2768     CFTypeRef value = CFDictionaryGetValue(dictionary, WebIconDatabase::iconDatabaseNotificationUserInfoURLKey());
2769     if (!value)
2770         return E_FAIL;
2771     if (CFGetTypeID(value) != CFStringGetTypeID())
2772         return E_FAIL;
2773
2774     String mainFrameURL;
2775     if (m_mainFrame)
2776         mainFrameURL = m_mainFrame->url().string();
2777
2778     if (!mainFrameURL.isEmpty() && mainFrameURL == String((CFStringRef)value))
2779         dispatchDidReceiveIconFromWebFrame(m_mainFrame);
2780
2781     return hr;
2782 }
2783
2784 void WebView::registerForIconNotification(bool listen)
2785 {
2786     IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2787     if (listen)
2788         nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2789     else
2790         nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2791 }
2792
2793 void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
2794 {
2795     registerForIconNotification(false);
2796
2797     if (m_frameLoadDelegate)
2798         // FIXME: <rdar://problem/5491010> - Pass in the right HBITMAP. 
2799         m_frameLoadDelegate->didReceiveIcon(this, 0, frame);
2800 }
2801
2802 HRESULT STDMETHODCALLTYPE WebView::setUIDelegate( 
2803     /* [in] */ IWebUIDelegate* d)
2804 {
2805     m_uiDelegate = d;
2806
2807     if (m_uiDelegatePrivate)
2808         m_uiDelegatePrivate = 0;
2809
2810     if (d) {
2811         if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
2812             m_uiDelegatePrivate = 0;
2813     }
2814
2815     return S_OK;
2816 }
2817
2818 HRESULT STDMETHODCALLTYPE WebView::uiDelegate( 
2819     /* [out][retval] */ IWebUIDelegate** d)
2820 {
2821     if (!m_uiDelegate)
2822         return E_FAIL;
2823
2824     return m_uiDelegate.copyRefTo(d);
2825 }
2826
2827 HRESULT STDMETHODCALLTYPE WebView::setResourceLoadDelegate( 
2828     /* [in] */ IWebResourceLoadDelegate* d)
2829 {
2830     m_resourceLoadDelegate = d;
2831     return S_OK;
2832 }
2833
2834 HRESULT STDMETHODCALLTYPE WebView::resourceLoadDelegate( 
2835     /* [out][retval] */ IWebResourceLoadDelegate** d)
2836 {
2837     if (!m_resourceLoadDelegate)
2838         return E_FAIL;
2839
2840     return m_resourceLoadDelegate.copyRefTo(d);
2841 }
2842
2843 HRESULT STDMETHODCALLTYPE WebView::setDownloadDelegate( 
2844     /* [in] */ IWebDownloadDelegate* d)
2845 {
2846     m_downloadDelegate = d;
2847     return S_OK;
2848 }
2849
2850 HRESULT STDMETHODCALLTYPE WebView::downloadDelegate( 
2851     /* [out][retval] */ IWebDownloadDelegate** d)
2852 {
2853     if (!m_downloadDelegate)
2854         return E_FAIL;
2855
2856     return m_downloadDelegate.copyRefTo(d);
2857 }
2858
2859 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegate( 
2860     /* [in] */ IWebFrameLoadDelegate* d)
2861 {
2862     m_frameLoadDelegate = d;
2863     return S_OK;
2864 }
2865
2866 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegate( 
2867     /* [out][retval] */ IWebFrameLoadDelegate** d)
2868 {
2869     if (!m_frameLoadDelegate)
2870         return E_FAIL;
2871
2872     return m_frameLoadDelegate.copyRefTo(d);
2873 }
2874
2875 HRESULT STDMETHODCALLTYPE WebView::setPolicyDelegate( 
2876     /* [in] */ IWebPolicyDelegate* d)
2877 {
2878     m_policyDelegate = d;
2879     return S_OK;
2880 }
2881
2882 HRESULT STDMETHODCALLTYPE WebView::policyDelegate( 
2883     /* [out][retval] */ IWebPolicyDelegate** d)
2884 {
2885     if (!m_policyDelegate)
2886         return E_FAIL;
2887     return m_policyDelegate.copyRefTo(d);
2888 }
2889
2890 HRESULT STDMETHODCALLTYPE WebView::mainFrame( 
2891     /* [out][retval] */ IWebFrame** frame)
2892 {
2893     if (!frame) {
2894         ASSERT_NOT_REACHED();
2895         return E_POINTER;
2896     }
2897
2898     *frame = m_mainFrame;
2899     if (!m_mainFrame)
2900         return E_FAIL;
2901
2902     m_mainFrame->AddRef();
2903     return S_OK;
2904 }
2905
2906 HRESULT STDMETHODCALLTYPE WebView::focusedFrame( 
2907     /* [out][retval] */ IWebFrame** frame)
2908 {
2909     if (!frame) {
2910         ASSERT_NOT_REACHED();
2911         return E_POINTER;
2912     }
2913
2914     *frame = 0;
2915     Frame* f = m_page->focusController()->focusedFrame();
2916     if (!f)
2917         return E_FAIL;
2918
2919     WebFrame* webFrame = kit(f);
2920     if (!webFrame)
2921         return E_FAIL;
2922
2923     return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
2924 }
2925
2926 HRESULT STDMETHODCALLTYPE WebView::backForwardList( 
2927     /* [out][retval] */ IWebBackForwardList** list)
2928 {
2929     if (!m_useBackForwardList)
2930         return E_FAIL;
2931  
2932     *list = WebBackForwardList::createInstance(static_cast<WebCore::BackForwardListImpl*>(m_page->backForwardList()));
2933
2934     return S_OK;
2935 }
2936
2937 HRESULT STDMETHODCALLTYPE WebView::setMaintainsBackForwardList( 
2938     /* [in] */ BOOL flag)
2939 {
2940     m_useBackForwardList = !!flag;
2941     return S_OK;
2942 }
2943
2944 HRESULT STDMETHODCALLTYPE WebView::goBack( 
2945     /* [retval][out] */ BOOL* succeeded)
2946 {
2947     *succeeded = m_page->goBack();
2948     return S_OK;
2949 }
2950
2951 HRESULT STDMETHODCALLTYPE WebView::goForward( 
2952     /* [retval][out] */ BOOL* succeeded)
2953 {
2954     *succeeded = m_page->goForward();
2955     return S_OK;
2956 }
2957
2958 HRESULT STDMETHODCALLTYPE WebView::goToBackForwardItem( 
2959     /* [in] */ IWebHistoryItem* item,
2960     /* [retval][out] */ BOOL* succeeded)
2961 {
2962     *succeeded = FALSE;
2963
2964     COMPtr<WebHistoryItem> webHistoryItem;
2965     HRESULT hr = item->QueryInterface(&webHistoryItem);
2966     if (FAILED(hr))
2967         return hr;
2968
2969     m_page->goToItem(webHistoryItem->historyItem(), FrameLoadTypeIndexedBackForward);
2970     *succeeded = TRUE;
2971
2972     return S_OK;
2973 }
2974
2975 HRESULT STDMETHODCALLTYPE WebView::setTextSizeMultiplier( 
2976     /* [in] */ float multiplier)
2977 {
2978     if (!m_mainFrame)
2979         return E_FAIL;
2980     setZoomMultiplier(multiplier, true);
2981     return S_OK;
2982 }
2983
2984 HRESULT STDMETHODCALLTYPE WebView::setPageSizeMultiplier( 
2985     /* [in] */ float multiplier)
2986 {
2987     if (!m_mainFrame)
2988         return E_FAIL;
2989     setZoomMultiplier(multiplier, false);
2990     return S_OK;
2991 }
2992
2993 void WebView::setZoomMultiplier(float multiplier, bool isTextOnly)
2994 {
2995     m_zoomMultiplier = multiplier;
2996     m_zoomsTextOnly = isTextOnly;
2997
2998     if (Frame* coreFrame = core(m_mainFrame)) {
2999         if (m_zoomsTextOnly)
3000             coreFrame->setPageAndTextZoomFactors(1, multiplier);
3001         else
3002             coreFrame->setPageAndTextZoomFactors(multiplier, 1);
3003     }
3004 }
3005
3006 HRESULT STDMETHODCALLTYPE WebView::textSizeMultiplier( 
3007     /* [retval][out] */ float* multiplier)
3008 {
3009     *multiplier = zoomMultiplier(true);
3010     return S_OK;
3011 }
3012
3013 HRESULT STDMETHODCALLTYPE WebView::pageSizeMultiplier( 
3014     /* [retval][out] */ float* multiplier)
3015 {
3016     *multiplier = zoomMultiplier(false);
3017     return S_OK;
3018 }
3019
3020 float WebView::zoomMultiplier(bool isTextOnly)
3021 {
3022     if (isTextOnly != m_zoomsTextOnly)
3023         return 1.0f;
3024     return m_zoomMultiplier;
3025 }
3026
3027 HRESULT STDMETHODCALLTYPE WebView::setApplicationNameForUserAgent( 
3028     /* [in] */ BSTR applicationName)
3029 {
3030     m_applicationName = String(applicationName, SysStringLen(applicationName));
3031     m_userAgentStandard = String();
3032     return S_OK;
3033 }
3034
3035 HRESULT STDMETHODCALLTYPE WebView::applicationNameForUserAgent( 
3036     /* [retval][out] */ BSTR* applicationName)
3037 {
3038     *applicationName = SysAllocStringLen(m_applicationName.characters(), m_applicationName.length());
3039     if (!*applicationName && m_applicationName.length())
3040         return E_OUTOFMEMORY;
3041     return S_OK;
3042 }
3043
3044 HRESULT STDMETHODCALLTYPE WebView::setCustomUserAgent( 
3045     /* [in] */ BSTR userAgentString)
3046 {
3047     m_userAgentOverridden = userAgentString;
3048     m_userAgentCustom = String(userAgentString, SysStringLen(userAgentString));
3049     return S_OK;
3050 }
3051
3052 HRESULT STDMETHODCALLTYPE WebView::customUserAgent( 
3053     /* [retval][out] */ BSTR* userAgentString)
3054 {
3055     *userAgentString = 0;
3056     if (!m_userAgentOverridden)
3057         return S_OK;
3058     *userAgentString = SysAllocStringLen(m_userAgentCustom.characters(), m_userAgentCustom.length());
3059     if (!*userAgentString && m_userAgentCustom.length())
3060         return E_OUTOFMEMORY;
3061     return S_OK;
3062 }
3063
3064 HRESULT STDMETHODCALLTYPE WebView::userAgentForURL( 
3065     /* [in] */ BSTR url,
3066     /* [retval][out] */ BSTR* userAgent)
3067 {
3068     String userAgentString = userAgentForKURL(MarshallingHelpers::BSTRToKURL(url));
3069     *userAgent = SysAllocStringLen(userAgentString.characters(), userAgentString.length());
3070     if (!*userAgent && userAgentString.length())
3071         return E_OUTOFMEMORY;
3072     return S_OK;
3073 }
3074
3075 HRESULT STDMETHODCALLTYPE WebView::supportsTextEncoding( 
3076     /* [retval][out] */ BOOL* supports)
3077 {
3078     *supports = TRUE;
3079     return S_OK;
3080 }
3081
3082 HRESULT STDMETHODCALLTYPE WebView::setCustomTextEncodingName( 
3083     /* [in] */ BSTR encodingName)
3084 {
3085     if (!m_mainFrame)
3086         return E_FAIL;
3087
3088     HRESULT hr;
3089     BSTR oldEncoding;
3090     hr = customTextEncodingName(&oldEncoding);
3091     if (FAILED(hr))
3092         return hr;
3093
3094     if (oldEncoding != encodingName && (!oldEncoding || !encodingName || wcscmp(oldEncoding, encodingName))) {
3095         if (Frame* coreFrame = core(m_mainFrame))
3096             coreFrame->loader()->reloadWithOverrideEncoding(String(encodingName, SysStringLen(encodingName)));
3097     }
3098
3099     return S_OK;
3100 }
3101
3102 HRESULT STDMETHODCALLTYPE WebView::customTextEncodingName( 
3103     /* [retval][out] */ BSTR* encodingName)
3104 {
3105     HRESULT hr = S_OK;
3106     COMPtr<IWebDataSource> dataSource;
3107     COMPtr<WebDataSource> dataSourceImpl;
3108     *encodingName = 0;
3109
3110     if (!m_mainFrame)
3111         return E_FAIL;
3112
3113     if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
3114         hr = m_mainFrame->dataSource(&dataSource);
3115         if (FAILED(hr) || !dataSource)
3116             return hr;
3117     }
3118
3119     hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
3120     if (FAILED(hr))
3121         return hr;
3122
3123     BString str = dataSourceImpl->documentLoader()->overrideEncoding();
3124     if (FAILED(hr))
3125         return hr;
3126
3127     if (!*encodingName)
3128         *encodingName = SysAllocStringLen(m_overrideEncoding.characters(), m_overrideEncoding.length());
3129
3130     if (!*encodingName && m_overrideEncoding.length())
3131         return E_OUTOFMEMORY;
3132
3133     return S_OK;
3134 }
3135
3136 HRESULT STDMETHODCALLTYPE WebView::setMediaStyle( 
3137     /* [in] */ BSTR /*media*/)
3138 {
3139     ASSERT_NOT_REACHED();
3140     return E_NOTIMPL;
3141 }
3142
3143 HRESULT STDMETHODCALLTYPE WebView::mediaStyle( 
3144     /* [retval][out] */ BSTR* /*media*/)
3145 {
3146     ASSERT_NOT_REACHED();
3147     return E_NOTIMPL;
3148 }
3149
3150 HRESULT STDMETHODCALLTYPE WebView::stringByEvaluatingJavaScriptFromString( 
3151     /* [in] */ BSTR script, // assumes input does not have "JavaScript" at the begining.
3152     /* [retval][out] */ BSTR* result)
3153 {
3154     if (!result) {
3155         ASSERT_NOT_REACHED();
3156         return E_POINTER;
3157     }
3158
3159     *result = 0;
3160
3161     Frame* coreFrame = core(m_mainFrame);
3162     if (!coreFrame)
3163         return E_FAIL;
3164
3165     JSC::JSValue scriptExecutionResult = coreFrame->script()->executeScript(WTF::String(script), true).jsValue();
3166     if (!scriptExecutionResult)
3167         return E_FAIL;
3168     else if (scriptExecutionResult.isString()) {
3169         JSLock lock(JSC::SilenceAssertionsOnly);
3170         JSC::ExecState* exec = coreFrame->script()->globalObject(mainThreadNormalWorld())->globalExec();
3171         *result = BString(ustringToString(scriptExecutionResult.getString(exec)));
3172     }
3173
3174     return S_OK;
3175 }
3176
3177 HRESULT STDMETHODCALLTYPE WebView::windowScriptObject( 
3178     /* [retval][out] */ IWebScriptObject** /*webScriptObject*/)
3179 {
3180     ASSERT_NOT_REACHED();
3181     return E_NOTIMPL;
3182 }
3183
3184 HRESULT STDMETHODCALLTYPE WebView::setPreferences( 
3185     /* [in] */ IWebPreferences* prefs)
3186 {
3187     if (!prefs)
3188         prefs = WebPreferences::sharedStandardPreferences();
3189
3190     if (m_preferences == prefs)
3191         return S_OK;
3192
3193     COMPtr<WebPreferences> webPrefs(Query, prefs);
3194     if (!webPrefs)
3195         return E_NOINTERFACE;
3196     webPrefs->willAddToWebView();
3197
3198     COMPtr<WebPreferences> oldPrefs = m_preferences;
3199
3200     IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
3201     nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3202
3203     BSTR identifier = 0;
3204     oldPrefs->identifier(&identifier);
3205     oldPrefs->didRemoveFromWebView();
3206     oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
3207
3208     m_preferences = webPrefs;
3209
3210     if (identifier) {
3211         WebPreferences::removeReferenceForIdentifier(identifier);
3212         SysFreeString(identifier);
3213     }
3214
3215     nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3216
3217     m_preferences->postPreferencesChangesNotification();
3218
3219     return S_OK;
3220 }
3221
3222 HRESULT STDMETHODCALLTYPE WebView::preferences( 
3223     /* [retval][out] */ IWebPreferences** prefs)
3224 {
3225     if (!prefs)
3226         return E_POINTER;
3227     *prefs = m_preferences.get();
3228     if (m_preferences)
3229         m_preferences->AddRef();
3230     return S_OK;
3231 }
3232
3233 HRESULT STDMETHODCALLTYPE WebView::setPreferencesIdentifier( 
3234     /* [in] */ BSTR /*anIdentifier*/)
3235 {
3236     ASSERT_NOT_REACHED();
3237     return E_NOTIMPL;
3238 }
3239
3240 HRESULT STDMETHODCALLTYPE WebView::preferencesIdentifier( 
3241     /* [retval][out] */ BSTR* /*anIdentifier*/)
3242 {
3243     ASSERT_NOT_REACHED();
3244     return E_NOTIMPL;
3245 }
3246
3247 static void systemParameterChanged(WPARAM parameter)
3248 {
3249 #if USE(CG)
3250     if (parameter == SPI_SETFONTSMOOTHING || parameter == SPI_SETFONTSMOOTHINGTYPE || parameter == SPI_SETFONTSMOOTHINGCONTRAST || parameter == SPI_SETFONTSMOOTHINGORIENTATION)
3251         wkSystemFontSmoothingChanged();
3252 #endif
3253 }
3254
3255 void WebView::windowReceivedMessage(HWND, UINT message, WPARAM wParam, LPARAM)
3256 {
3257     switch (message) {
3258     case WM_NCACTIVATE:
3259         updateActiveStateSoon();
3260         if (!wParam)
3261             deleteBackingStoreSoon();
3262         break;
3263     case WM_SETTINGCHANGE:
3264         systemParameterChanged(wParam);
3265         break;
3266     }
3267 }
3268
3269 void WebView::updateActiveStateSoon() const
3270 {
3271     // This function is called while processing the WM_NCACTIVATE message.
3272     // While processing WM_NCACTIVATE when we are being deactivated, GetActiveWindow() will
3273     // still return our window. If we were to call updateActiveState() in that case, we would
3274     // wrongly think that we are still the active window. To work around this, we update our
3275     // active state after a 0-delay timer fires, at which point GetActiveWindow() will return
3276     // the newly-activated window.
3277
3278     SetTimer(m_viewWindow, UpdateActiveStateTimer, 0, 0);
3279 }
3280
3281 void WebView::deleteBackingStoreSoon()
3282 {
3283     if (pendingDeleteBackingStoreSet.size() > 2) {
3284         Vector<WebView*> views;
3285         HashSet<WebView*>::iterator end = pendingDeleteBackingStoreSet.end();
3286         for (HashSet<WebView*>::iterator it = pendingDeleteBackingStoreSet.begin(); it != end; ++it)
3287             views.append(*it);
3288         for (int i = 0; i < views.size(); ++i)
3289             views[i]->deleteBackingStore();
3290         ASSERT(pendingDeleteBackingStoreSet.isEmpty());
3291     }
3292
3293     pendingDeleteBackingStoreSet.add(this);
3294     m_deleteBackingStoreTimerActive = true;
3295     SetTimer(m_viewWindow, DeleteBackingStoreTimer, delayBeforeDeletingBackingStoreMsec, 0);
3296 }
3297
3298 void WebView::cancelDeleteBackingStoreSoon()
3299 {
3300     if (!m_deleteBackingStoreTimerActive)
3301         return;
3302     pendingDeleteBackingStoreSet.remove(this);
3303     m_deleteBackingStoreTimerActive = false;
3304     KillTimer(m_viewWindow, DeleteBackingStoreTimer);
3305 }
3306
3307 HRESULT STDMETHODCALLTYPE WebView::setHostWindow( 
3308     /* [in] */ OLE_HANDLE oleWindow)
3309 {
3310     HWND window = (HWND)(ULONG64)oleWindow;
3311     if (m_viewWindow) {
3312         if (window)
3313             SetParent(m_viewWindow, window);
3314         else if (!isBeingDestroyed()) {
3315             // Turn the WebView into a message-only window so it will no longer be a child of the
3316             // old host window and will be hidden from screen. We only do this when
3317             // isBeingDestroyed() is false because doing this while handling WM_DESTROY can leave
3318             // m_viewWindow in a weird state (see <http://webkit.org/b/29337>).
3319             SetParent(m_viewWindow, HWND_MESSAGE);
3320         }
3321     }
3322
3323     m_hostWindow = window;
3324
3325     windowAncestryDidChange();
3326
3327     return S_OK;
3328 }
3329
3330 HRESULT STDMETHODCALLTYPE WebView::hostWindow( 
3331     /* [retval][out] */ OLE_HANDLE* window)
3332 {
3333     *window = (OLE_HANDLE)(ULONG64)m_hostWindow;
3334     return S_OK;
3335 }
3336
3337
3338 static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
3339 {
3340     return forward
3341         ? curr->tree()->traverseNextWithWrap(wrapFlag)
3342         : curr->tree()->traversePreviousWithWrap(wrapFlag);
3343 }
3344
3345 HRESULT STDMETHODCALLTYPE WebView::searchFor( 
3346     /* [in] */ BSTR str,
3347     /* [in] */ BOOL forward,
3348     /* [in] */ BOOL caseFlag,
3349     /* [in] */ BOOL wrapFlag,
3350     /* [retval][out] */ BOOL* found)
3351 {
3352     if (!found)
3353         return E_INVALIDARG;
3354     
3355     if (!m_page || !m_page->mainFrame())
3356         return E_UNEXPECTED;
3357
3358     if (!str || !SysStringLen(str))
3359         return E_INVALIDARG;
3360
3361     *found = m_page->findString(String(str, SysStringLen(str)), caseFlag ? TextCaseSensitive : TextCaseInsensitive, forward ? FindDirectionForward : FindDirectionBackward, wrapFlag);
3362     return S_OK;
3363 }
3364
3365 bool WebView::active()
3366 {
3367     HWND activeWindow = GetActiveWindow();
3368     if (usesLayeredWindow() && activeWindow == m_viewWindow)
3369         return true;
3370
3371     return (activeWindow && m_topLevelParent == findTopLevelParent(activeWindow));
3372 }
3373
3374 void WebView::updateActiveState()
3375 {
3376     m_page->focusController()->setActive(active());
3377 }
3378
3379 HRESULT STDMETHODCALLTYPE WebView::updateFocusedAndActiveState()
3380 {
3381     updateActiveState();
3382
3383     bool active = m_page->focusController()->isActive();
3384     Frame* mainFrame = m_page->mainFrame();
3385     Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
3386     mainFrame->selection()->setFocused(active && mainFrame == focusedFrame);
3387
3388     return S_OK;
3389 }
3390
3391 HRESULT STDMETHODCALLTYPE WebView::executeCoreCommandByName(BSTR bName, BSTR bValue)
3392 {
3393     String name(bName, SysStringLen(bName));
3394     String value(bValue, SysStringLen(bValue));
3395
3396     m_page->focusController()->focusedOrMainFrame()->editor()->command(name).execute(value);
3397
3398     return S_OK;
3399 }
3400
3401 HRESULT STDMETHODCALLTYPE WebView::clearMainFrameName()
3402 {
3403     m_page->mainFrame()->tree()->clearName();
3404
3405     return S_OK;
3406 }
3407
3408 HRESULT STDMETHODCALLTYPE WebView::markAllMatchesForText(
3409     BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, UINT* matches)
3410 {
3411     if (!matches)
3412         return E_INVALIDARG;
3413
3414     if (!m_page || !m_page->mainFrame())
3415         return E_UNEXPECTED;
3416
3417     if (!str || !SysStringLen(str))
3418         return E_INVALIDARG;
3419
3420     *matches = m_page->markAllMatchesForText(String(str, SysStringLen(str)), caseSensitive ? TextCaseSensitive : TextCaseInsensitive, highlight, limit);
3421     return S_OK;
3422 }
3423
3424 HRESULT STDMETHODCALLTYPE WebView::unmarkAllTextMatches()
3425 {
3426     if (!m_page || !m_page->mainFrame())
3427         return E_UNEXPECTED;
3428
3429     m_page->unmarkAllTextMatches();
3430     return S_OK;
3431 }
3432
3433 HRESULT STDMETHODCALLTYPE WebView::rectsForTextMatches(
3434     IEnumTextMatches** pmatches)
3435 {
3436     Vector<IntRect> allRects;
3437     WebCore::Frame* frame = m_page->mainFrame();
3438     do {
3439         if (Document* document = frame->document()) {
3440             IntRect visibleRect = frame->view()->visibleContentRect();
3441             Vector<IntRect> frameRects = document->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
3442             IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
3443             frameOffset = frame->view()->convertToContainingWindow(frameOffset);
3444
3445             Vector<IntRect>::iterator end = frameRects.end();
3446             for (Vector<IntRect>::iterator it = frameRects.begin(); it < end; it++) {
3447                 it->intersect(visibleRect);
3448                 it->move(frameOffset.x(), frameOffset.y());
3449                 allRects.append(*it);
3450             }
3451         }
3452         frame = incrementFrame(frame, true, false);
3453     } while (frame);
3454
3455     return createMatchEnumerator(&allRects, pmatches);
3456 }
3457
3458 HRESULT STDMETHODCALLTYPE WebView::generateSelectionImage(BOOL forceWhiteText, OLE_HANDLE* hBitmap)
3459 {
3460     *hBitmap = 0;
3461
3462     WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
3463
3464     if (frame) {
3465         HBITMAP bitmap = imageFromSelection(frame, forceWhiteText ? TRUE : FALSE);
3466         *hBitmap = (OLE_HANDLE)(ULONG64)bitmap;
3467     }
3468
3469     return S_OK;
3470 }
3471
3472 HRESULT STDMETHODCALLTYPE WebView::selectionRect(RECT* rc)
3473 {
3474     WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
3475
3476     if (frame) {
3477         IntRect ir = enclosingIntRect(frame->selection()->bounds());
3478         ir = frame->view()->convertToContainingWindow(ir);
3479         ir.move(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
3480         rc->left = ir.x();
3481         rc->top = ir.y();
3482         rc->bottom = rc->top + ir.height();
3483         rc->right = rc->left + ir.width();
3484     }
3485
3486     return S_OK;
3487 }
3488
3489 HRESULT STDMETHODCALLTYPE WebView::registerViewClass( 
3490     /* [in] */ IWebDocumentView* /*view*/,
3491     /* [in] */ IWebDocumentRepresentation* /*representation*/,
3492     /* [in] */ BSTR /*forMIMEType*/)
3493 {
3494     ASSERT_NOT_REACHED();
3495     return E_NOTIMPL;
3496 }
3497
3498 HRESULT STDMETHODCALLTYPE WebView::setGroupName( 
3499         /* [in] */ BSTR groupName)
3500 {
3501     if (!m_page)
3502         return S_OK;
3503     m_page->setGroupName(String(groupName, SysStringLen(groupName)));
3504     return S_OK;
3505 }
3506     
3507 HRESULT STDMETHODCALLTYPE WebView::groupName( 
3508         /* [retval][out] */ BSTR* groupName)
3509 {
3510     *groupName = 0;
3511     if (!m_page)
3512         return S_OK;
3513     String groupNameString = m_page->groupName();
3514     *groupName = SysAllocStringLen(groupNameString.characters(), groupNameString.length());
3515     if (!*groupName && groupNameString.length())
3516         return E_OUTOFMEMORY;
3517     return S_OK;
3518 }
3519     
3520 HRESULT STDMETHODCALLTYPE WebView::estimatedProgress( 
3521         /* [retval][out] */ double* estimatedProgress)
3522 {
3523     *estimatedProgress = m_page->progress()->estimatedProgress();
3524     return S_OK;
3525 }
3526     
3527 HRESULT STDMETHODCALLTYPE WebView::isLoading( 
3528         /* [retval][out] */ BOOL* isLoading)
3529 {
3530     COMPtr<IWebDataSource> dataSource;
3531     COMPtr<IWebDataSource> provisionalDataSource;
3532
3533     if (!isLoading)
3534         return E_POINTER;
3535
3536     *isLoading = FALSE;
3537
3538     if (!m_mainFrame)
3539         return E_FAIL;
3540
3541     if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
3542         dataSource->isLoading(isLoading);
3543
3544     if (*isLoading)
3545         return S_OK;
3546
3547     if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
3548         provisionalDataSource->isLoading(isLoading);
3549     return S_OK;
3550 }
3551     
3552 HRESULT STDMETHODCALLTYPE WebView::elementAtPoint( 
3553         /* [in] */ LPPOINT point,
3554         /* [retval][out] */ IPropertyBag** elementDictionary)
3555 {
3556     if (!elementDictionary) {
3557         ASSERT_NOT_REACHED();
3558         return E_POINTER;
3559     }
3560
3561     *elementDictionary = 0;
3562
3563     Frame* frame = core(m_mainFrame);
3564     if (!frame)
3565         return E_FAIL;
3566
3567     IntPoint webCorePoint = IntPoint(point->x, point->y);
3568     HitTestResult result = HitTestResult(webCorePoint);
3569     if (frame->contentRenderer())
3570         result = frame->eventHandler()->hitTestResultAtPoint(webCorePoint, false);
3571     *elementDictionary = WebElementPropertyBag::createInstance(result);
3572     return S_OK;
3573 }
3574     
3575 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForSelection( 
3576     /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3577 {
3578     ASSERT_NOT_REACHED();
3579     return E_NOTIMPL;
3580 }
3581     
3582 HRESULT STDMETHODCALLTYPE WebView::writeSelectionWithPasteboardTypes( 
3583         /* [size_is][in] */ BSTR* /*types*/,
3584         /* [in] */ int /*cTypes*/,
3585         /* [in] */ IDataObject* /*pasteboard*/)
3586 {
3587     ASSERT_NOT_REACHED();
3588     return E_NOTIMPL;
3589 }
3590     
3591 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForElement( 
3592     /* [in] */ IPropertyBag* /*elementDictionary*/,
3593     /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3594 {
3595     ASSERT_NOT_REACHED();
3596     return E_NOTIMPL;
3597 }
3598     
3599 HRESULT STDMETHODCALLTYPE WebView::writeElement( 
3600         /* [in] */ IPropertyBag* /*elementDictionary*/,
3601         /* [size_is][in] */ BSTR* /*withPasteboardTypes*/,
3602         /* [in] */ int /*cWithPasteboardTypes*/,
3603         /* [in] */ IDataObject* /*pasteboard*/)
3604 {
3605     ASSERT_NOT_REACHED();
3606     return E_NOTIMPL;
3607 }
3608     
3609 HRESULT STDMETHODCALLTYPE WebView::selectedText(
3610         /* [out, retval] */ BSTR* text)
3611 {
3612     if (!text) {
3613         ASSERT_NOT_REACHED();
3614         return E_POINTER;
3615     }
3616
3617     *text = 0;
3618
3619     Frame* focusedFrame = (m_page && m_page->focusController()) ? m_page->focusController()->focusedOrMainFrame() : 0;
3620     if (!focusedFrame)
3621         return E_FAIL;
3622
3623     String frameSelectedText = focusedFrame->editor()->selectedText();
3624     *text = SysAllocStringLen(frameSelectedText.characters(), frameSelectedText.length());
3625     if (!*text && frameSelectedText.length())
3626         return E_OUTOFMEMORY;
3627     return S_OK;
3628 }
3629
3630 HRESULT STDMETHODCALLTYPE WebView::centerSelectionInVisibleArea(
3631         /* [in] */ IUnknown* /* sender */)
3632 {
3633     Frame* coreFrame = core(m_mainFrame);
3634     if (!coreFrame)
3635         return E_FAIL;
3636
3637     coreFrame->selection()->revealSelection(ScrollAlignment::alignCenterAlways);
3638     return S_OK;
3639 }
3640
3641
3642 HRESULT STDMETHODCALLTYPE WebView::moveDragCaretToPoint( 
3643         /* [in] */ LPPOINT /*point*/)
3644 {
3645     ASSERT_NOT_REACHED();
3646     return E_NOTIMPL;
3647 }
3648     
3649 HRESULT STDMETHODCALLTYPE WebView::removeDragCaret( void)
3650 {
3651     ASSERT_NOT_REACHED();
3652     return E_NOTIMPL;
3653 }
3654     
3655 HRESULT STDMETHODCALLTYPE WebView::setDrawsBackground( 
3656         /* [in] */ BOOL /*drawsBackground*/)
3657 {
3658     ASSERT_NOT_REACHED();
3659     return E_NOTIMPL;
3660 }
3661     
3662 HRESULT STDMETHODCALLTYPE WebView::drawsBackground( 
3663         /* [retval][out] */ BOOL* /*drawsBackground*/)
3664 {
3665     ASSERT_NOT_REACHED();
3666     return E_NOTIMPL;
3667 }
3668     
3669 HRESULT STDMETHODCALLTYPE WebView::setMainFrameURL( 
3670         /* [in] */ BSTR /*urlString*/)
3671 {
3672     ASSERT_NOT_REACHED();
3673     return E_NOTIMPL;
3674 }
3675     
3676 HRESULT STDMETHODCALLTYPE WebView::mainFrameURL( 
3677         /* [retval][out] */ BSTR* urlString)
3678 {
3679     if (!urlString)
3680         return E_POINTER;
3681
3682     if (!m_mainFrame)
3683         return E_FAIL;
3684
3685     COMPtr<IWebDataSource> dataSource;
3686
3687     if (FAILED(m_mainFrame->provisionalDataSource(&dataSource))) {
3688         if (FAILED(m_mainFrame->dataSource(&dataSource)))
3689             return E_FAIL;
3690     }
3691
3692     if (!dataSource) {
3693         *urlString = 0;
3694         return S_OK;
3695     }
3696     
3697     COMPtr<IWebMutableURLRequest> request;
3698     if (FAILED(dataSource->request(&request)) || !request)
3699         return E_FAIL;
3700
3701     if (FAILED(request->URL(urlString)))
3702         return E_FAIL;
3703
3704     return S_OK;
3705 }
3706     
3707 HRESULT STDMETHODCALLTYPE WebView::mainFrameDocument( 
3708         /* [retval][out] */ IDOMDocument** document)
3709 {
3710     if (document)
3711         *document = 0;
3712     if (!m_mainFrame)
3713         return E_FAIL;
3714     return m_mainFrame->DOMDocument(document);
3715 }
3716     
3717 HRESULT STDMETHODCALLTYPE WebView::mainFrameTitle( 
3718         /* [retval][out] */ BSTR* /*title*/)
3719 {
3720     ASSERT_NOT_REACHED();
3721     return E_NOTIMPL;
3722 }
3723     
3724 HRESULT STDMETHODCALLTYPE WebView::mainFrameIcon( 
3725         /* [retval][out] */ OLE_HANDLE* /*hBitmap*/)
3726 {
3727     ASSERT_NOT_REACHED();
3728     return E_NOTIMPL;
3729 }
3730
3731 HRESULT STDMETHODCALLTYPE WebView::registerURLSchemeAsLocal( 
3732         /* [in] */ BSTR scheme)
3733 {
3734     if (!scheme)
3735         return E_POINTER;
3736
3737     SchemeRegistry::registerURLSchemeAsLocal(String(scheme, ::SysStringLen(scheme)));
3738
3739     return S_OK;
3740 }
3741
3742 // IWebIBActions ---------------------------------------------------------------
3743
3744 HRESULT STDMETHODCALLTYPE WebView::takeStringURLFrom( 
3745         /* [in] */ IUnknown* /*sender*/)
3746 {
3747     ASSERT_NOT_REACHED();
3748     return E_NOTIMPL;
3749 }
3750     
3751 HRESULT STDMETHODCALLTYPE WebView::stopLoading( 
3752         /* [in] */ IUnknown* /*sender*/)
3753 {
3754     if (!m_mainFrame)
3755         return E_FAIL;
3756
3757     return m_mainFrame->stopLoading();
3758 }
3759     
3760 HRESULT STDMETHODCALLTYPE WebView::reload( 
3761         /* [in] */ IUnknown* /*sender*/)
3762 {
3763     if (!m_mainFrame)
3764         return E_FAIL;
3765
3766     return m_mainFrame->reload();
3767 }
3768     
3769 HRESULT STDMETHODCALLTYPE WebView::canGoBack( 
3770         /* [in] */ IUnknown* /*sender*/,
3771         /* [retval][out] */ BOOL* result)
3772 {
3773     *result = !!(m_page->backForwardList()->backItem() && !m_page->defersLoading());
3774     return S_OK;
3775 }
3776     
3777 HRESULT STDMETHODCALLTYPE WebView::goBack( 
3778         /* [in] */ IUnknown* /*sender*/)
3779 {
3780     ASSERT_NOT_REACHED();
3781     return E_NOTIMPL;
3782 }
3783     
3784 HRESULT STDMETHODCALLTYPE WebView::canGoForward( 
3785         /* [in] */ IUnknown* /*sender*/,
3786         /* [retval][out] */ BOOL* result)
3787 {
3788     *result = !!(m_page->backForwardList()->forwardItem() && !m_page->defersLoading());
3789     return S_OK;
3790 }
3791     
3792 HRESULT STDMETHODCALLTYPE WebView::goForward( 
3793         /* [in] */ IUnknown* /*sender*/)
3794 {
3795     ASSERT_NOT_REACHED();
3796     return E_NOTIMPL;
3797 }
3798
3799 // FIXME: This code should move into WebCore so it can be shared by all the WebKits.
3800 #define MinimumZoomMultiplier   0.5f
3801 #define MaximumZoomMultiplier   3.0f
3802 #define ZoomMultiplierRatio     1.2f
3803
3804 HRESULT STDMETHODCALLTYPE WebView::canMakeTextLarger( 
3805         /* [in] */ IUnknown* /*sender*/,
3806         /* [retval][out] */ BOOL* result)
3807 {
3808     bool canGrowMore = canZoomIn(m_zoomsTextOnly);
3809     *result = canGrowMore ? TRUE : FALSE;
3810     return S_OK;
3811 }
3812
3813 HRESULT STDMETHODCALLTYPE WebView::canZoomPageIn( 
3814         /* [in] */ IUnknown* /*sender*/,
3815         /* [retval][out] */ BOOL* result)
3816 {
3817     bool canGrowMore = canZoomIn(false);
3818     *result = canGrowMore ? TRUE : FALSE;
3819     return S_OK;
3820 }
3821
3822 bool WebView::canZoomIn(bool isTextOnly)
3823 {
3824     return zoomMultiplier(isTextOnly) * ZoomMultiplierRatio < MaximumZoomMultiplier;
3825 }
3826     
3827 HRESULT STDMETHODCALLTYPE WebView::makeTextLarger( 
3828         /* [in] */ IUnknown* /*sender*/)
3829 {
3830     return zoomIn(m_zoomsTextOnly);
3831 }
3832
3833 HRESULT STDMETHODCALLTYPE WebView::zoomPageIn( 
3834         /* [in] */ IUnknown* /*sender*/)
3835 {
3836     return zoomIn(false);
3837 }
3838
3839 HRESULT WebView::zoomIn(bool isTextOnly)
3840 {
3841     if (!canZoomIn(isTextOnly))
3842         return E_FAIL;
3843     setZoomMultiplier(zoomMultiplier(isTextOnly) * ZoomMultiplierRatio, isTextOnly);
3844     return S_OK;
3845 }
3846
3847 HRESULT STDMETHODCALLTYPE WebView::canMakeTextSmaller( 
3848         /* [in] */ IUnknown* /*sender*/,
3849         /* [retval][out] */ BOOL* result)
3850 {
3851     bool canShrinkMore = canZoomOut(m_zoomsTextOnly);
3852     *result = canShrinkMore ? TRUE : FALSE;
3853     return S_OK;
3854 }
3855
3856 HRESULT STDMETHODCALLTYPE WebView::canZoomPageOut( 
3857         /* [in] */ IUnknown* /*sender*/,
3858         /* [retval][out] */ BOOL* result)
3859 {
3860     bool canShrinkMore = canZoomOut(false);
3861     *result = canShrinkMore ? TRUE : FALSE;
3862     return S_OK;
3863 }
3864
3865 bool WebView::canZoomOut(bool isTextOnly)
3866 {
3867     return zoomMultiplier(isTextOnly) / ZoomMultiplierRatio > MinimumZoomMultiplier;
3868 }
3869
3870 HRESULT STDMETHODCALLTYPE WebView::makeTextSmaller( 
3871         /* [in] */ IUnknown* /*sender*/)
3872 {
3873     return zoomOut(m_zoomsTextOnly);
3874 }
3875
3876 HRESULT STDMETHODCALLTYPE WebView::zoomPageOut( 
3877         /* [in] */ IUnknown* /*sender*/)
3878 {
3879     return zoomOut(false);
3880 }
3881
3882 HRESULT WebView::zoomOut(bool isTextOnly)
3883 {
3884     if (!canZoomOut(isTextOnly))
3885         return E_FAIL;
3886     setZoomMultiplier(zoomMultiplier(isTextOnly) / ZoomMultiplierRatio, isTextOnly);
3887     return S_OK;
3888 }
3889
3890 HRESULT STDMETHODCALLTYPE WebView::canMakeTextStandardSize( 
3891     /* [in] */ IUnknown* /*sender*/,
3892     /* [retval][out] */ BOOL* result)
3893 {
3894     // 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.
3895     bool notAlreadyStandard = canResetZoom(true);
3896     *result = notAlreadyStandard ? TRUE : FALSE;
3897     return S_OK;
3898 }
3899
3900 HRESULT STDMETHODCALLTYPE WebView::canResetPageZoom( 
3901     /* [in] */ IUnknown* /*sender*/,
3902     /* [retval][out] */ BOOL* result)
3903 {
3904     bool notAlreadyStandard = canResetZoom(false);
3905     *result = notAlreadyStandard ? TRUE : FALSE;
3906     return S_OK;
3907 }
3908
3909 bool WebView::canResetZoom(bool isTextOnly)
3910 {
3911     return zoomMultiplier(isTextOnly) != 1.0f;
3912 }
3913
3914 HRESULT STDMETHODCALLTYPE WebView::makeTextStandardSize( 
3915     /* [in] */ IUnknown* /*sender*/)
3916 {
3917     return resetZoom(true);
3918 }
3919
3920 HRESULT STDMETHODCALLTYPE WebView::resetPageZoom( 
3921     /* [in] */ IUnknown* /*sender*/)
3922 {
3923     return resetZoom(false);
3924 }
3925
3926 HRESULT WebView::resetZoom(bool isTextOnly)
3927 {
3928     if (!canResetZoom(isTextOnly))
3929         return E_FAIL;
3930     setZoomMultiplier(1.0f, isTextOnly);
3931     return S_OK;
3932 }
3933
3934 HRESULT STDMETHODCALLTYPE WebView::toggleContinuousSpellChecking( 
3935     /* [in] */ IUnknown* /*sender*/)
3936 {
3937     HRESULT hr;
3938     BOOL enabled;
3939     if (FAILED(hr = isContinuousSpellCheckingEnabled(&enabled)))
3940         return hr;
3941     return setContinuousSpellCheckingEnabled(enabled ? FALSE : TRUE);
3942 }
3943
3944 HRESULT STDMETHODCALLTYPE WebView::toggleSmartInsertDelete( 
3945     /* [in] */ IUnknown* /*sender*/)
3946 {
3947     BOOL enabled = FALSE;
3948     HRESULT hr = smartInsertDeleteEnabled(&enabled);
3949     if (FAILED(hr))
3950         return hr;
3951
3952     return setSmartInsertDeleteEnabled(enabled ? FALSE : TRUE);
3953 }
3954
3955 HRESULT STDMETHODCALLTYPE WebView::toggleGrammarChecking( 
3956     /* [in] */ IUnknown* /*sender*/)
3957 {
3958     BOOL enabled;
3959     HRESULT hr = isGrammarCheckingEnabled(&enabled);
3960     if (FAILED(hr))
3961         return hr;
3962
3963     return setGrammarCheckingEnabled(enabled ? FALSE : TRUE);
3964 }
3965
3966 HRESULT STDMETHODCALLTYPE WebView::reloadFromOrigin( 
3967         /* [in] */ IUnknown* /*sender*/)
3968 {
3969     if (!m_mainFrame)
3970         return E_FAIL;
3971
3972     return m_mainFrame->reloadFromOrigin();
3973 }
3974
3975 // IWebViewCSS -----------------------------------------------------------------
3976
3977 HRESULT STDMETHODCALLTYPE WebView::computedStyleForElement( 
3978         /* [in] */ IDOMElement* /*element*/,
3979         /* [in] */ BSTR /*pseudoElement*/,
3980         /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3981 {
3982     ASSERT_NOT_REACHED();
3983     return E_NOTIMPL;
3984 }
3985
3986 // IWebViewEditing -------------------------------------------------------------
3987
3988 HRESULT STDMETHODCALLTYPE WebView::editableDOMRangeForPoint( 
3989         /* [in] */ LPPOINT /*point*/,
3990         /* [retval][out] */ IDOMRange** /*range*/)
3991 {
3992     ASSERT_NOT_REACHED();
3993     return E_NOTIMPL;
3994 }
3995     
3996 HRESULT STDMETHODCALLTYPE WebView::setSelectedDOMRange( 
3997         /* [in] */ IDOMRange* /*range*/,
3998         /* [in] */ WebSelectionAffinity /*affinity*/)
3999 {
4000     ASSERT_NOT_REACHED();
4001     return E_NOTIMPL;
4002 }
4003     
4004 HRESULT STDMETHODCALLTYPE WebView::selectedDOMRange( 
4005         /* [retval][out] */ IDOMRange** /*range*/)
4006 {
4007     ASSERT_NOT_REACHED();
4008     return E_NOTIMPL;
4009 }
4010     
4011 HRESULT STDMETHODCALLTYPE WebView::selectionAffinity( 
4012         /* [retval][out][retval][out] */ WebSelectionAffinity* /*affinity*/)
4013 {
4014     ASSERT_NOT_REACHED();
4015     return E_NOTIMPL;
4016 }
4017     
4018 HRESULT STDMETHODCALLTYPE WebView::setEditable( 
4019         /* [in] */ BOOL /*flag*/)
4020 {
4021     ASSERT_NOT_REACHED();
4022     return E_NOTIMPL;
4023 }
4024     
4025 HRESULT STDMETHODCALLTYPE WebView::isEditable( 
4026         /* [retval][out] */ BOOL* /*isEditable*/)
4027 {
4028     ASSERT_NOT_REACHED();
4029     return E_NOTIMPL;
4030 }
4031     
4032 HRESULT STDMETHODCALLTYPE WebView::setTypingStyle( 
4033         /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
4034 {
4035     ASSERT_NOT_REACHED();
4036     return E_NOTIMPL;
4037 }
4038     
4039 HRESULT STDMETHODCALLTYPE WebView::typingStyle( 
4040         /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
4041 {
4042     ASSERT_NOT_REACHED();
4043     return E_NOTIMPL;
4044 }
4045     
4046 HRESULT STDMETHODCALLTYPE WebView::setSmartInsertDeleteEnabled( 
4047         /* [in] */ BOOL flag)
4048 {
4049     m_smartInsertDeleteEnabled = !!flag;
4050     if (m_smartInsertDeleteEnabled)
4051         setSelectTrailingWhitespaceEnabled(false);
4052     return S_OK;
4053 }
4054     
4055 HRESULT STDMETHODCALLTYPE WebView::smartInsertDeleteEnabled( 
4056         /* [retval][out] */ BOOL* enabled)
4057 {
4058     *enabled = m_smartInsertDeleteEnabled ? TRUE : FALSE;
4059     return S_OK;
4060 }
4061  
4062 HRESULT STDMETHODCALLTYPE WebView::setSelectTrailingWhitespaceEnabled( 
4063         /* [in] */ BOOL flag)
4064 {
4065     m_selectTrailingWhitespaceEnabled = !!flag;
4066     if (m_selectTrailingWhitespaceEnabled)
4067         setSmartInsertDeleteEnabled(false);
4068     return S_OK;
4069 }
4070     
4071 HRESULT STDMETHODCALLTYPE WebView::isSelectTrailingWhitespaceEnabled( 
4072         /* [retval][out] */ BOOL* enabled)
4073 {
4074     *enabled = m_selectTrailingWhitespaceEnabled ? TRUE : FALSE;
4075     return S_OK;
4076 }
4077
4078 HRESULT STDMETHODCALLTYPE WebView::setContinuousSpellCheckingEnabled( 
4079         /* [in] */ BOOL flag)
4080 {
4081     if (continuousSpellCheckingEnabled != !!flag) {
4082         continuousSpellCheckingEnabled = !!flag;
4083         COMPtr<IWebPreferences> prefs;
4084         if (SUCCEEDED(preferences(&prefs)))
4085             prefs->setContinuousSpellCheckingEnabled(flag);
4086     }
4087     
4088     BOOL spellCheckingEnabled;
4089     if (SUCCEEDED(isContinuousSpellCheckingEnabled(&spellCheckingEnabled)) && spellCheckingEnabled)
4090         preflightSpellChecker();
4091     else
4092         m_mainFrame->unmarkAllMisspellings();
4093
4094     return S_OK;
4095 }
4096     
4097 HRESULT STDMETHODCALLTYPE WebView::isContinuousSpellCheckingEnabled( 
4098         /* [retval][out] */ BOOL* enabled)
4099 {
4100     *enabled = (continuousSpellCheckingEnabled && continuousCheckingAllowed()) ? TRUE : FALSE;
4101     return S_OK;
4102 }
4103     
4104 HRESULT STDMETHODCALLTYPE WebView::spellCheckerDocumentTag( 
4105         /* [retval][out] */ int* tag)
4106 {
4107     // we just use this as a flag to indicate that we've spell checked the document
4108     // and need to close the spell checker out when the view closes.
4109     *tag = 0;
4110     m_hasSpellCheckerDocumentTag = true;
4111     return S_OK;
4112 }
4113
4114 static COMPtr<IWebEditingDelegate> spellingDelegateForTimer;
4115
4116 static void preflightSpellCheckerNow()
4117 {
4118     spellingDelegateForTimer->preflightChosenSpellServer();
4119     spellingDelegateForTimer = 0;
4120 }
4121
4122 static void CALLBACK preflightSpellCheckerTimerCallback(HWND, UINT, UINT_PTR id, DWORD)
4123 {
4124     ::KillTimer(0, id);
4125     preflightSpellCheckerNow();
4126 }
4127
4128 void WebView::preflightSpellChecker()
4129 {
4130     // As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
4131     if (!m_editingDelegate)
4132         return;
4133
4134     BOOL exists;
4135     spellingDelegateForTimer = m_editingDelegate;
4136     if (SUCCEEDED(m_editingDelegate->sharedSpellCheckerExists(&exists)) && exists)
4137         preflightSpellCheckerNow();
4138     else
4139         ::SetTimer(0, 0, 2000, preflightSpellCheckerTimerCallback);
4140 }
4141
4142 bool WebView::continuousCheckingAllowed()
4143 {
4144     static bool allowContinuousSpellChecking = true;
4145     static bool readAllowContinuousSpellCheckingDefault = false;
4146     if (!readAllowContinuousSpellCheckingDefault) {
4147         COMPtr<IWebPreferences> prefs;
4148         if (SUCCEEDED(preferences(&prefs))) {
4149             BOOL allowed;
4150             prefs->allowContinuousSpellChecking(&allowed);
4151             allowContinuousSpellChecking = !!allowed;
4152         }
4153         readAllowContinuousSpellCheckingDefault = true;
4154     }
4155     return allowContinuousSpellChecking;
4156 }
4157
4158 HRESULT STDMETHODCALLTYPE WebView::undoManager( 
4159         /* [retval][out] */ IWebUndoManager** /*manager*/)
4160 {
4161     ASSERT_NOT_REACHED();
4162     return E_NOTIMPL;
4163 }
4164     
4165 HRESULT STDMETHODCALLTYPE WebView::setEditingDelegate( 
4166         /* [in] */ IWebEditingDelegate* d)
4167 {
4168     m_editingDelegate = d;
4169     return S_OK;
4170 }
4171     
4172 HRESULT STDMETHODCALLTYPE WebView::editingDelegate( 
4173         /* [retval][out] */ IWebEditingDelegate** d)
4174 {
4175     if (!d) {
4176         ASSERT_NOT_REACHED();
4177         return E_POINTER;
4178     }
4179
4180     *d = m_editingDelegate.get();
4181     if (!*d)
4182         return E_FAIL;
4183
4184     (*d)->AddRef();
4185     return S_OK;
4186 }
4187     
4188 HRESULT STDMETHODCALLTYPE WebView::styleDeclarationWithText( 
4189         /* [in] */ BSTR /*text*/,
4190         /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
4191 {
4192     ASSERT_NOT_REACHED();
4193     return E_NOTIMPL;
4194 }
4195     
4196 HRESULT STDMETHODCALLTYPE WebView::hasSelectedRange( 
4197         /* [retval][out] */ BOOL* hasSelectedRange)
4198 {
4199     *hasSelectedRange = m_page->mainFrame()->selection()->isRange();
4200     return S_OK;
4201 }
4202     
4203 HRESULT STDMETHODCALLTYPE WebView::cutEnabled( 
4204         /* [retval][out] */ BOOL* enabled)
4205 {
4206     Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
4207     *enabled = editor->canCut() || editor->canDHTMLCut();
4208     return S_OK;
4209 }
4210     
4211 HRESULT STDMETHODCALLTYPE WebView::copyEnabled( 
4212         /* [retval][out] */ BOOL* enabled)
4213 {
4214     Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
4215     *enabled = editor->canCopy() || editor->canDHTMLCopy();
4216     return S_OK;
4217 }
4218     
4219 HRESULT STDMETHODCALLTYPE WebView::pasteEnabled( 
4220         /* [retval][out] */ BOOL* enabled)
4221 {
4222     Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
4223     *enabled = editor->canPaste() || editor->canDHTMLPaste();
4224     return S_OK;
4225 }
4226     
4227 HRESULT STDMETHODCALLTYPE WebView::deleteEnabled( 
4228         /* [retval][out] */ BOOL* enabled)
4229 {
4230     *enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canDelete();
4231     return S_OK;
4232 }
4233     
4234 HRESULT STDMETHODCALLTYPE WebView::editingEnabled( 
4235         /* [retval][out] */ BOOL* enabled)
4236 {
4237     *enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canEdit();
4238     return S_OK;
4239 }
4240
4241 HRESULT STDMETHODCALLTYPE WebView::isGrammarCheckingEnabled( 
4242     /* [retval][out] */ BOOL* enabled)
4243 {
4244     *enabled = grammarCheckingEnabled ? TRUE : FALSE;
4245     return S_OK;
4246 }
4247
4248 HRESULT STDMETHODCALLTYPE WebView::setGrammarCheckingEnabled( 
4249     BOOL enabled)
4250 {
4251     if (!m_editingDelegate) {
4252         LOG_ERROR("No NSSpellChecker");
4253         return E_FAIL;
4254     }
4255
4256     if (grammarCheckingEnabled == !!enabled)
4257         return S_OK;
4258     
4259     grammarCheckingEnabled = !!enabled;
4260     COMPtr<IWebPreferences> prefs;
4261     if (SUCCEEDED(preferences(&prefs)))
4262         prefs->setGrammarCheckingEnabled(enabled);
4263     
4264     m_editingDelegate->updateGrammar();
4265
4266     // We call _preflightSpellChecker when turning continuous spell checking on, but we don't need to do that here
4267     // because grammar checking only occurs on code paths that already preflight spell checking appropriately.
4268     
4269     BOOL grammarEnabled;
4270     if (SUCCEEDED(isGrammarCheckingEnabled(&grammarEnabled)) && !grammarEnabled)
4271         m_mainFrame->unmarkAllBadGrammar();
4272
4273     return S_OK;
4274 }
4275
4276 // IWebViewUndoableEditing -----------------------------------------------------
4277
4278 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithNode( 
4279         /* [in] */ IDOMNode* /*node*/)
4280 {
4281     ASSERT_NOT_REACHED();
4282     return E_NOTIMPL;
4283 }
4284     
4285 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithText( 
4286         /* [in] */ BSTR text)
4287 {
4288     String textString(text, ::SysStringLen(text));
4289     Position start = m_page->mainFrame()->selection()->selection().start();
4290     m_page->focusController()->focusedOrMainFrame()->editor()->insertText(textString, 0);
4291     m_page->mainFrame()->selection()->setBase(start);
4292     return S_OK;
4293 }
4294     
4295 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithMarkupString( 
4296         /* [in] */ BSTR /*markupString*/)
4297 {
4298     ASSERT_NOT_REACHED();
4299     return E_NOTIMPL;
4300 }
4301     
4302 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithArchive( 
4303         /* [in] */ IWebArchive* /*archive*/)
4304 {
4305     ASSERT_NOT_REACHED();
4306     return E_NOTIMPL;
4307 }
4308     
4309 HRESULT STDMETHODCALLTYPE WebView::deleteSelection( void)
4310 {
4311     Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
4312     editor->deleteSelectionWithSmartDelete(editor->canSmartCopyOrDelete());
4313     return S_OK;
4314 }
4315
4316 HRESULT STDMETHODCALLTYPE WebView::clearSelection( void)
4317 {
4318     m_page->focusController()->focusedOrMainFrame()->selection()->clear();
4319     return S_OK;
4320 }
4321     
4322 HRESULT STDMETHODCALLTYPE WebView::applyStyle( 
4323         /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
4324 {
4325     ASSERT_NOT_REACHED();
4326     return E_NOTIMPL;
4327 }
4328
4329 // IWebViewEditingActions ------------------------------------------------------
4330
4331 HRESULT STDMETHODCALLTYPE WebView::copy( 
4332         /* [in] */ IUnknown* /*sender*/)
4333 {
4334     m_page->focusController()->focusedOrMainFrame()->editor()->command("Copy").execute();
4335     return S_OK;
4336 }
4337
4338 HRESULT STDMETHODCALLTYPE WebView::cut( 
4339         /* [in] */ IUnknown* /*sender*/)
4340 {
4341     m_page->focusController()->focusedOrMainFrame()->editor()->command("Cut").execute();
4342     return S_OK;
4343 }
4344
4345 HRESULT STDMETHODCALLTYPE WebView::paste( 
4346         /* [in] */ IUnknown* /*sender*/)
4347 {
4348     m_page->focusController()->focusedOrMainFrame()->editor()->command("Paste").execute();
4349     return S_OK;
4350 }
4351
4352 HRESULT STDMETHODCALLTYPE WebView::copyURL( 
4353         /* [in] */ BSTR url)
4354 {
4355     m_page->focusController()->focusedOrMainFrame()->editor()->copyURL(MarshallingHelpers::BSTRToKURL(url), "");
4356     return S_OK;
4357 }
4358
4359
4360 HRESULT STDMETHODCALLTYPE WebView::copyFont( 
4361         /* [in] */ IUnknown* /*sender*/)
4362 {
4363     ASSERT_NOT_REACHED();
4364     return E_NOTIMPL;
4365 }
4366     
4367 HRESULT STDMETHODCALLTYPE WebView::pasteFont( 
4368         /* [in] */ IUnknown* /*sender*/)
4369 {
4370     ASSERT_NOT_REACHED();
4371     return E_NOTIMPL;
4372 }
4373     
4374 HRESULT STDMETHODCALLTYPE WebView::delete_( 
4375         /* [in] */ IUnknown* /*sender*/)
4376 {
4377     m_page->focusController()->focusedOrMainFrame()->editor()->command("Delete").execute();
4378     return S_OK;
4379 }
4380     
4381 HRESULT STDMETHODCALLTYPE WebView::pasteAsPlainText( 
4382         /* [in] */ IUnknown* /*sender*/)
4383 {
4384     ASSERT_NOT_REACHED();
4385     return E_NOTIMPL;
4386 }
4387     
4388 HRESULT STDMETHODCALLTYPE WebView::pasteAsRichText( 
4389         /* [in] */ IUnknown* /*sender*/)
4390 {
4391     ASSERT_NOT_REACHED();
4392     return E_NOTIMPL;
4393 }
4394     
4395 HRESULT STDMETHODCALLTYPE WebView::changeFont( 
4396         /* [in] */ IUnknown* /*sender*/)
4397 {
4398     ASSERT_NOT_REACHED();
4399     return E_NOTIMPL;
4400 }
4401     
4402 HRESULT STDMETHODCALLTYPE WebView::changeAttributes( 
4403         /* [in] */ IUnknown* /*sender*/)
4404 {
4405     ASSERT_NOT_REACHED();
4406     return E_NOTIMPL;
4407 }
4408     
4409 HRESULT STDMETHODCALLTYPE WebView::changeDocumentBackgroundColor( 
4410         /* [in] */ IUnknown* /*sender*/)
4411 {
4412     ASSERT_NOT_REACHED();
4413     return E_NOTIMPL;
4414 }
4415     
4416 HRESULT STDMETHODCALLTYPE WebView::changeColor( 
4417         /* [in] */ IUnknown* /*sender*/)
4418 {
4419     ASSERT_NOT_REACHED();
4420     return E_NOTIMPL;
4421 }
4422     
4423 HRESULT STDMETHODCALLTYPE WebView::alignCenter( 
4424         /* [in] */ IUnknown* /*sender*/)
4425 {
4426     ASSERT_NOT_REACHED();
4427     return E_NOTIMPL;
4428 }
4429     
4430 HRESULT STDMETHODCALLTYPE WebView::alignJustified( 
4431         /* [in] */ IUnknown* /*sender*/)
4432 {
4433     ASSERT_NOT_REACHED();
4434     return E_NOTIMPL;
4435 }
4436     
4437 HRESULT STDMETHODCALLTYPE WebView::alignLeft( 
4438         /* [in] */ IUnknown* /*sender*/)
4439 {
4440     ASSERT_NOT_REACHED();
4441     return E_NOTIMPL;
4442 }
4443     
4444 HRESULT STDMETHODCALLTYPE WebView::alignRight( 
4445         /* [in] */ IUnknown* /*sender*/)
4446 {
4447     ASSERT_NOT_REACHED();
4448     return E_NOTIMPL;
4449 }
4450     
4451 HRESULT STDMETHODCALLTYPE WebView::checkSpelling( 
4452         /* [in] */ IUnknown* /*sender*/)
4453 {
4454     if (!m_editingDelegate) {
4455         LOG_ERROR("No NSSpellChecker");
4456         return E_FAIL;
4457     }
4458     
4459     core(m_mainFrame)->editor()->advanceToNextMisspelling();
4460     return S_OK;
4461 }
4462     
4463 HRESULT STDMETHODCALLTYPE WebView::showGuessPanel( 
4464         /* [in] */ IUnknown* /*sender*/)
4465 {
4466     if (!m_editingDelegate) {
4467         LOG_ERROR("No NSSpellChecker");
4468         return E_FAIL;
4469     }
4470     
4471     // Post-Tiger, this menu item is a show/hide toggle, to match AppKit. Leave Tiger behavior alone
4472     // to match rest of OS X.
4473     BOOL showing;
4474     if (SUCCEEDED(m_editingDelegate->spellingUIIsShowing(&showing)) && showing) {
4475         m_editingDelegate->showSpellingUI(FALSE);
4476     }
4477     
4478     core(m_mainFrame)->editor()->advanceToNextMisspelling(true);
4479     m_editingDelegate->showSpellingUI(TRUE);
4480     return S_OK;
4481 }
4482     
4483 HRESULT STDMETHODCALLTYPE WebView::performFindPanelAction( 
4484         /* [in] */ IUnknown* /*sender*/)
4485 {
4486     ASSERT_NOT_REACHED();
4487     return E_NOTIMPL;
4488 }
4489     
4490 HRESULT STDMETHODCALLTYPE WebView::startSpeaking( 
4491         /* [in] */ IUnknown* /*sender*/)
4492 {
4493     ASSERT_NOT_REACHED();
4494     return E_NOTIMPL;
4495 }
4496     
4497 HRESULT STDMETHODCALLTYPE WebView::stopSpeaking( 
4498         /* [in] */ IUnknown* /*sender*/)
4499 {
4500     ASSERT_NOT_REACHED();
4501     return E_NOTIMPL;
4502 }
4503
4504 // IWebNotificationObserver -----------------------------------------------------------------
4505
4506 HRESULT STDMETHODCALLTYPE WebView::onNotify( 
4507     /* [in] */ IWebNotification* notification)
4508 {
4509     BSTR nameBSTR;
4510     HRESULT hr = notification->name(&nameBSTR);
4511     if (FAILED(hr))
4512         return hr;
4513
4514     BString name;
4515     name.adoptBSTR(nameBSTR);
4516
4517     if (!wcscmp(name, WebIconDatabase::iconDatabaseDidAddIconNotification()))
4518         return notifyDidAddIcon(notification);
4519
4520     if (!wcscmp(name, WebPreferences::webPreferencesChangedNotification()))
4521         return notifyPreferencesChanged(notification);
4522
4523     return hr;
4524 }
4525
4526 HRESULT WebView::notifyPreferencesChanged(IWebNotification* notification)
4527 {
4528     HRESULT hr;
4529
4530     COMPtr<IUnknown> unkPrefs;
4531     hr = notification->getObject(&unkPrefs);
4532     if (FAILED(hr))
4533         return hr;
4534
4535     COMPtr<IWebPreferences> preferences(Query, unkPrefs);
4536     if (!preferences)
4537         return E_NOINTERFACE;
4538
4539     ASSERT(preferences == m_preferences);
4540
4541     BSTR str;
4542     int size;
4543     BOOL enabled;
4544
4545     Settings* settings = m_page->settings();
4546
4547     hr = preferences->cursiveFontFamily(&str);
4548     if (FAILED(hr))
4549         return hr;
4550     settings->setCursiveFontFamily(AtomicString(str, SysStringLen(str)));
4551     SysFreeString(str);
4552
4553     hr = preferences->defaultFixedFontSize(&size);
4554     if (FAILED(hr))
4555         return hr;
4556     settings->setDefaultFixedFontSize(size);
4557
4558     hr = preferences->defaultFontSize(&size);
4559     if (FAILED(hr))
4560         return hr;
4561     settings->setDefaultFontSize(size);
4562     
4563     hr = preferences->defaultTextEncodingName(&str);
4564     if (FAILED(hr))
4565         return hr;
4566     settings->setDefaultTextEncodingName(String(str, SysStringLen(str)));
4567     SysFreeString(str);
4568
4569     hr = preferences->fantasyFontFamily(&str);
4570     if (FAILED(hr))
4571         return hr;
4572     settings->setFantasyFontFamily(AtomicString(str, SysStringLen(str)));
4573     SysFreeString(str);
4574
4575     hr = preferences->fixedFontFamily(&str);
4576     if (FAILED(hr))
4577         return hr;
4578     settings->setFixedFontFamily(AtomicString(str, SysStringLen(str)));
4579     SysFreeString(str);
4580
4581     hr = preferences->pictographFontFamily(&str);
4582     if (FAILED(hr))
4583         return hr;
4584     settings->setPictographFontFamily(AtomicString(str, SysStringLen(str)));
4585     SysFreeString(str);
4586
4587     hr = preferences->isJavaEnabled(&enabled);
4588     if (FAILED(hr))
4589         return hr;
4590     settings->setJavaEnabled(!!enabled);
4591
4592     hr = preferences->isJavaScriptEnabled(&enabled);
4593     if (FAILED(hr))
4594         return hr;
4595     settings->setJavaScriptEnabled(!!enabled);
4596
4597     hr = preferences->javaScriptCanOpenWindowsAutomatically(&enabled);
4598     if (FAILED(hr))
4599         return hr;
4600     settings->setJavaScriptCanOpenWindowsAutomatically(!!enabled);
4601
4602     hr = preferences->minimumFontSize(&size);
4603     if (FAILED(hr))
4604         return hr;
4605     settings->setMinimumFontSize(size);
4606
4607     hr = preferences->minimumLogicalFontSize(&size);
4608     if (FAILED(hr))
4609         return hr;
4610     settings->setMinimumLogicalFontSize(size);
4611
4612     hr = preferences->arePlugInsEnabled(&enabled);
4613     if (FAILED(hr))
4614         return hr;
4615     settings->setPluginsEnabled(!!enabled);
4616
4617     hr = preferences->privateBrowsingEnabled(&enabled);
4618     if (FAILED(hr))
4619         return hr;
4620     settings->setPrivateBrowsingEnabled(!!enabled);
4621
4622     hr = preferences->sansSerifFontFamily(&str);
4623     if (FAILED(hr))
4624         return hr;
4625     settings->setSansSerifFontFamily(AtomicString(str, SysStringLen(str)));
4626     SysFreeString(str);
4627
4628     hr = preferences->serifFontFamily(&str);
4629     if (FAILED(hr))
4630         return hr;
4631     settings->setSerifFontFamily(AtomicString(str, SysStringLen(str)));
4632     SysFreeString(str);
4633
4634     hr = preferences->standardFontFamily(&str);
4635     if (FAILED(hr))
4636         return hr;
4637     settings->setStandardFontFamily(AtomicString(str, SysStringLen(str)));
4638     SysFreeString(str);
4639
4640     hr = preferences->loadsImagesAutomatically(&enabled);
4641     if (FAILED(hr))
4642         return hr;
4643     settings->setLoadsImagesAutomatically(!!enabled);
4644
4645     hr = preferences->userStyleSheetEnabled(&enabled);
4646     if (FAILED(hr))
4647         return hr;
4648     if (enabled) {
4649         hr = preferences->userStyleSheetLocation(&str);
4650         if (FAILED(hr))
4651             return hr;
4652
4653         RetainPtr<CFStringRef> urlString(AdoptCF, String(str, SysStringLen(str)).createCFString());
4654         RetainPtr<CFURLRef> url(AdoptCF, CFURLCreateWithString(kCFAllocatorDefault, urlString.get(), 0));
4655
4656         // Check if the passed in string is a path and convert it to a URL.
4657         // FIXME: This is a workaround for nightly builds until we can get Safari to pass 
4658         // in an URL here. See <rdar://problem/5478378>
4659         if (!url) {
4660             DWORD len = SysStringLen(str) + 1;
4661
4662             int result = WideCharToMultiByte(CP_UTF8, 0, str, len, 0, 0, 0, 0);
4663             Vector<UInt8> utf8Path(result);
4664             if (!WideCharToMultiByte(CP_UTF8, 0, str, len, (LPSTR)utf8Path.data(), result, 0, 0))
4665                 return E_FAIL;
4666
4667             url.adoptCF(CFURLCreateFromFileSystemRepresentation(0, utf8Path.data(), result - 1, false));
4668         }
4669
4670         settings->setUserStyleSheetLocation(url.get());
4671         SysFreeString(str);
4672     } else {
4673         settings->setUserStyleSheetLocation(KURL());
4674     }
4675
4676     hr = preferences->shouldPrintBackgrounds(&enabled);
4677     if (FAILED(hr))
4678         return hr;
4679     settings->setShouldPrintBackgrounds(!!enabled);
4680
4681     hr = preferences->textAreasAreResizable(&enabled);
4682     if (FAILED(hr))
4683         return hr;
4684     settings->setTextAreasAreResizable(!!enabled);
4685
4686     WebKitEditableLinkBehavior behavior;
4687     hr = preferences->editableLinkBehavior(&behavior);
4688     if (FAILED(hr))
4689         return hr;
4690     settings->setEditableLinkBehavior((EditableLinkBehavior)behavior);
4691
4692     WebKitEditingBehavior editingBehavior;
4693     hr = preferences->editingBehavior(&editingBehavior);
4694     if (FAILED(hr))
4695         return hr;
4696     settings->setEditingBehaviorType((EditingBehaviorType)editingBehavior);
4697
4698     hr = preferences->usesPageCache(&enabled);
4699     if (FAILED(hr))
4700         return hr;
4701     settings->setUsesPageCache(!!enabled);
4702
4703     hr = preferences->isDOMPasteAllowed(&enabled);
4704     if (FAILED(hr))
4705         return hr;
4706     settings->setDOMPasteAllowed(!!enabled);
4707
4708     hr = preferences->shouldPaintCustomScrollbars(&enabled);
4709     if (FAILED(hr))
4710         return hr;
4711     settings->setShouldPaintCustomScrollbars(!!enabled);
4712
4713     hr = preferences->zoomsTextOnly(&enabled);
4714     if (FAILED(hr))
4715         return hr;
4716
4717     if (m_zoomsTextOnly != !!enabled)
4718         setZoomMultiplier(m_zoomMultiplier, enabled);
4719
4720     settings->setShowsURLsInToolTips(false);
4721
4722     settings->setForceFTPDirectoryListings(true);
4723     settings->setDeveloperExtrasEnabled(developerExtrasEnabled());
4724     settings->setNeedsSiteSpecificQuirks(s_allowSiteSpecificHacks);
4725
4726     FontSmoothingType smoothingType;
4727     hr = preferences->fontSmoothing(&smoothingType);
4728     if (FAILED(hr))
4729         return hr;
4730     settings->setFontRenderingMode(smoothingType != FontSmoothingTypeWindows ? NormalRenderingMode : AlternateRenderingMode);
4731
4732 #if USE(AVFOUNDATION)
4733     hr = preferences->avFoundationEnabled(&enabled);
4734     if (FAILED(hr))
4735         return hr;
4736     settings->setAVFoundationEnabled(enabled);
4737 #endif
4738
4739     COMPtr<IWebPreferencesPrivate> prefsPrivate(Query, preferences);
4740     if (prefsPrivate) {
4741         hr = prefsPrivate->authorAndUserStylesEnabled(&enabled);
4742         if (FAILED(hr))
4743             return hr;
4744         settings->setAuthorAndUserStylesEnabled(enabled);
4745     }
4746
4747     hr = prefsPrivate->inApplicationChromeMode(&enabled);
4748     if (FAILED(hr))
4749         return hr;
4750     settings->setApplicationChromeMode(enabled);
4751
4752     hr = prefsPrivate->offlineWebApplicationCacheEnabled(&enabled);
4753     if (FAILED(hr))
4754         return hr;
4755     settings->setOfflineWebApplicationCacheEnabled(enabled);
4756
4757 #if ENABLE(SQL_DATABASE)
4758     hr = prefsPrivate->databasesEnabled(&enabled);
4759     if (FAILED(hr))
4760         return hr;
4761     AbstractDatabase::setIsAvailable(enabled);
4762 #endif
4763
4764     hr = prefsPrivate->localStorageEnabled(&enabled);
4765     if (FAILED(hr))
4766         return hr;
4767     settings->setLocalStorageEnabled(enabled);
4768
4769     hr = prefsPrivate->experimentalNotificationsEnabled(&enabled);
4770     if (FAILED(hr))
4771         return hr;
4772     settings->setExperimentalNotificationsEnabled(enabled);
4773
4774     hr = prefsPrivate->isWebSecurityEnabled(&enabled);
4775     if (FAILED(hr))
4776         return hr;
4777     settings->setWebSecurityEnabled(!!enabled);
4778
4779     hr = prefsPrivate->allowUniversalAccessFromFileURLs(&enabled);
4780     if (FAILED(hr))
4781         return hr;
4782     settings->setAllowUniversalAccessFromFileURLs(!!enabled);
4783
4784     hr = prefsPrivate->allowFileAccessFromFileURLs(&enabled);
4785     if (FAILED(hr))
4786         return hr;
4787     settings->setAllowFileAccessFromFileURLs(!!enabled);
4788
4789     hr = prefsPrivate->javaScriptCanAccessClipboard(&enabled);
4790     if (FAILED(hr))
4791         return hr;
4792     settings->setJavaScriptCanAccessClipboard(!!enabled);
4793
4794     hr = prefsPrivate->isXSSAuditorEnabled(&enabled);
4795     if (FAILED(hr))
4796         return hr;
4797     settings->setXSSAuditorEnabled(!!enabled);
4798
4799 #if USE(SAFARI_THEME)
4800     hr = prefsPrivate->shouldPaintNativeControls(&enabled);
4801     if (FAILED(hr))
4802         return hr;
4803     settings->setShouldPaintNativeControls(!!enabled);
4804 #endif
4805
4806     hr = prefsPrivate->shouldUseHighResolutionTimers(&enabled);
4807     if (FAILED(hr))
4808         return hr;
4809     settings->setShouldUseHighResolutionTimers(enabled);
4810
4811     hr = prefsPrivate->isFrameFlatteningEnabled(&enabled);
4812     if (FAILED(hr))
4813         return hr;
4814     settings->setFrameFlatteningEnabled(enabled);
4815
4816 #if USE(ACCELERATED_COMPOSITING)
4817     hr = prefsPrivate->acceleratedCompositingEnabled(&enabled);
4818     if (FAILED(hr))
4819         return hr;
4820     settings->setAcceleratedCompositingEnabled(enabled);
4821 #endif
4822
4823     hr = prefsPrivate->showDebugBorders(&enabled);
4824     if (FAILED(hr))
4825         return hr;
4826     settings->setShowDebugBorders(enabled);
4827
4828     hr = prefsPrivate->showRepaintCounter(&enabled);
4829     if (FAILED(hr))
4830         return hr;
4831     settings->setShowRepaintCounter(enabled);
4832
4833 #if ENABLE(WEB_AUDIO)
4834     settings->setWebAudioEnabled(true);
4835 #endif // ENABLE(WEB_AUDIO)
4836
4837 #if ENABLE(WEBGL)
4838     settings->setWebGLEnabled(true);
4839 #endif // ENABLE(WEBGL)
4840
4841     hr = prefsPrivate->isDNSPrefetchingEnabled(&enabled);
4842     if (FAILED(hr))
4843         return hr;
4844     settings->setDNSPrefetchingEnabled(enabled);
4845
4846     hr = prefsPrivate->memoryInfoEnabled(&enabled);
4847     if (FAILED(hr))
4848         return hr;
4849     settings->setMemoryInfoEnabled(enabled);
4850     
4851     hr = prefsPrivate->hyperlinkAuditingEnabled(&enabled);
4852     if (FAILED(hr))
4853         return hr;
4854     settings->setHyperlinkAuditingEnabled(enabled);
4855
4856     hr = prefsPrivate->loadsSiteIconsIgnoringImageLoadingPreference(&enabled);
4857     if (FAILED(hr))
4858         return hr;
4859     settings->setLoadsSiteIconsIgnoringImageLoadingSetting(!!enabled);
4860
4861 #if ENABLE(WEB_SOCKETS)
4862     hr = prefsPrivate->hixie76WebSocketProtocolEnabled(&enabled);
4863     if (FAILED(hr))
4864         return hr;
4865     settings->setUseHixie76WebSocketProtocol(enabled);
4866 #endif
4867
4868     hr = prefsPrivate->showsToolTipOverTruncatedText(&enabled);
4869     if (FAILED(hr))
4870         return hr;
4871
4872     settings->setShowsToolTipOverTruncatedText(enabled);
4873
4874     if (!m_closeWindowTimer)
4875         m_mainFrame->invalidate(); // FIXME
4876
4877     hr = updateSharedSettingsFromPreferencesIfNeeded(preferences.get());
4878     if (FAILED(hr))
4879         return hr;
4880
4881 #if ENABLE(FULLSCREEN_API)
4882     hr = prefsPrivate->isFullScreenEnabled(&enabled);
4883     if (FAILED(hr))
4884         return hr;
4885     settings->setFullScreenEnabled(enabled);
4886 #endif
4887
4888     hr = prefsPrivate->mediaPlaybackRequiresUserGesture(&enabled);
4889     if (FAILED(hr))
4890         return hr;
4891     settings->setMediaPlaybackRequiresUserGesture(enabled);
4892
4893     hr = prefsPrivate->mediaPlaybackAllowsInline(&enabled);
4894     if (FAILED(hr))
4895         return hr;
4896     settings->setMediaPlaybackAllowsInline(enabled);
4897
4898     return S_OK;
4899 }
4900
4901 HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences* preferences)
4902 {
4903     if (preferences != WebPreferences::sharedStandardPreferences())
4904         return S_OK;
4905
4906     WebKitCookieStorageAcceptPolicy acceptPolicy;
4907     HRESULT hr = preferences->cookieStorageAcceptPolicy(&acceptPolicy);
4908     if (FAILED(hr))
4909         return hr;
4910
4911 #if USE(CFNETWORK)
4912     // Set cookie storage accept policy
4913     if (RetainPtr<CFHTTPCookieStorageRef> cookieStorage = currentCFHTTPCookieStorage())
4914         CFHTTPCookieStorageSetCookieAcceptPolicy(cookieStorage.get(), acceptPolicy);
4915 #endif
4916
4917     return S_OK;
4918 }
4919
4920 // IWebViewPrivate ------------------------------------------------------------
4921
4922 HRESULT STDMETHODCALLTYPE WebView::MIMETypeForExtension(
4923     /* [in] */ BSTR extension,
4924     /* [retval][out] */ BSTR* mimeType)
4925 {
4926     if (!mimeType)
4927         return E_POINTER;
4928
4929     String extensionStr(extension, SysStringLen(extension));
4930
4931     *mimeType = BString(MIMETypeRegistry::getMIMETypeForExtension(extensionStr)).release();
4932
4933     return S_OK;
4934 }
4935
4936 HRESULT STDMETHODCALLTYPE WebView::setCustomDropTarget(
4937     /* [in] */ IDropTarget* dt)
4938 {
4939     ASSERT(::IsWindow(m_viewWindow));
4940     if (!dt)
4941         return E_POINTER;
4942     m_hasCustomDropTarget = true;
4943     revokeDragDrop();
4944     return ::RegisterDragDrop(m_viewWindow,dt);
4945 }
4946
4947 HRESULT STDMETHODCALLTYPE WebView::removeCustomDropTarget()
4948 {
4949     if (!m_hasCustomDropTarget)
4950         return S_OK;
4951     m_hasCustomDropTarget = false;
4952     revokeDragDrop();
4953     return registerDragDrop();
4954 }
4955
4956 HRESULT STDMETHODCALLTYPE WebView::setInViewSourceMode( 
4957         /* [in] */ BOOL flag)
4958 {
4959     if (!m_mainFrame)
4960         return E_FAIL;
4961
4962     return m_mainFrame->setInViewSourceMode(flag);
4963 }
4964     
4965 HRESULT STDMETHODCALLTYPE WebView::inViewSourceMode( 
4966         /* [retval][out] */ BOOL* flag)
4967 {
4968     if (!m_mainFrame)
4969         return E_FAIL;
4970
4971     return m_mainFrame->inViewSourceMode(flag);
4972 }
4973
4974 HRESULT STDMETHODCALLTYPE WebView::viewWindow( 
4975         /* [retval][out] */ OLE_HANDLE *window)
4976 {
4977     *window = (OLE_HANDLE)(ULONG64)m_viewWindow;
4978     return S_OK;
4979 }
4980
4981 HRESULT STDMETHODCALLTYPE WebView::setFormDelegate( 
4982     /* [in] */ IWebFormDelegate *formDelegate)
4983 {
4984     m_formDelegate = formDelegate;
4985     return S_OK;
4986 }
4987
4988 HRESULT STDMETHODCALLTYPE WebView::formDelegate( 
4989     /* [retval][out] */ IWebFormDelegate **formDelegate)
4990 {
4991     if (!m_formDelegate)
4992         return E_FAIL;
4993
4994     return m_formDelegate.copyRefTo(formDelegate);
4995 }
4996
4997 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegatePrivate( 
4998     /* [in] */ IWebFrameLoadDelegatePrivate* d)
4999 {
5000     m_frameLoadDelegatePrivate = d;
5001     return S_OK;
5002 }
5003
5004 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegatePrivate( 
5005     /* [out][retval] */ IWebFrameLoadDelegatePrivate** d)
5006 {
5007     if (!m_frameLoadDelegatePrivate)
5008         return E_FAIL;
5009         
5010     return m_frameLoadDelegatePrivate.copyRefTo(d);
5011 }
5012
5013 HRESULT STDMETHODCALLTYPE WebView::scrollOffset( 
5014     /* [retval][out] */ LPPOINT offset)
5015 {
5016     if (!offset)
5017         return E_POINTER;
5018     IntSize offsetIntSize = m_page->mainFrame()->view()->scrollOffset();
5019     offset->x = offsetIntSize.width();
5020     offset->y = offsetIntSize.height();
5021     return S_OK;
5022 }
5023
5024 HRESULT STDMETHODCALLTYPE WebView::scrollBy( 
5025     /* [in] */ LPPOINT offset)
5026 {
5027     if (!offset)
5028         return E_POINTER;
5029     m_page->mainFrame()->view()->scrollBy(IntSize(offset->x, offset->y));
5030     return S_OK;
5031 }
5032
5033 HRESULT STDMETHODCALLTYPE WebView::visibleContentRect( 
5034     /* [retval][out] */ LPRECT rect)
5035 {
5036     if (!rect)
5037         return E_POINTER;
5038     FloatRect visibleContent = m_page->mainFrame()->view()->visibleContentRect();
5039     rect->left = (LONG) visibleContent.x();
5040     rect->top = (LONG) visibleContent.y();
5041     rect->right = (LONG) visibleContent.maxX();
5042     rect->bottom = (LONG) visibleContent.maxY();
5043     return S_OK;
5044 }
5045
5046 static DWORD dragOperationToDragCursor(DragOperation op) {
5047     DWORD res = DROPEFFECT_NONE;
5048     if (op & DragOperationCopy) 
5049         res = DROPEFFECT_COPY;
5050     else if (op & DragOperationLink) 
5051         res = DROPEFFECT_LINK;
5052     else if (op & DragOperationMove) 
5053         res = DROPEFFECT_MOVE;
5054     else if (op & DragOperationGeneric) 
5055         res = DROPEFFECT_MOVE; //This appears to be the Firefox behaviour
5056     return res;
5057 }
5058
5059 DragOperation WebView::keyStateToDragOperation(DWORD grfKeyState) const
5060 {
5061     if (!m_page)
5062         return DragOperationNone;
5063
5064     // Conforms to Microsoft's key combinations as documented for 
5065     // IDropTarget::DragOver. Note, grfKeyState is the current 
5066     // state of the keyboard modifier keys on the keyboard. See:
5067     // <http://msdn.microsoft.com/en-us/library/ms680129(VS.85).aspx>.
5068     DragOperation operation = m_page->dragController()->sourceDragOperation();
5069
5070     if ((grfKeyState & (MK_CONTROL | MK_SHIFT)) == (MK_CONTROL | MK_SHIFT))
5071         operation = DragOperationLink;
5072     else if ((grfKeyState & MK_CONTROL) == MK_CONTROL)
5073         operation = DragOperationCopy;
5074     else if ((grfKeyState & MK_SHIFT) == MK_SHIFT)
5075         operation = DragOperationGeneric;
5076
5077     return operation;
5078 }
5079
5080 HRESULT STDMETHODCALLTYPE WebView::DragEnter(
5081         IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
5082 {
5083     m_dragData = 0;
5084
5085     if (m_dropTargetHelper)
5086         m_dropTargetHelper->DragEnter(m_viewWindow, pDataObject, (POINT*)&pt, *pdwEffect);
5087
5088     POINTL localpt = pt;
5089     ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
5090     DragData data(pDataObject, IntPoint(localpt.x, localpt.y), 
5091         IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
5092     *pdwEffect = dragOperationToDragCursor(m_page->dragController()->dragEntered(&data));
5093
5094     m_lastDropEffect = *pdwEffect;
5095     m_dragData = pDataObject;
5096
5097     return S_OK;
5098 }
5099
5100 HRESULT STDMETHODCALLTYPE WebView::DragOver(
5101         DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
5102 {
5103     if (m_dropTargetHelper)
5104         m_dropTargetHelper->DragOver((POINT*)&pt, *pdwEffect);
5105
5106     if (m_dragData) {
5107         POINTL localpt = pt;
5108         ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
5109         DragData data(m_dragData.get(), IntPoint(localpt.x, localpt.y), 
5110             IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
5111         *pdwEffect = dragOperationToDragCursor(m_page->dragController()->dragUpdated(&data));
5112     } else
5113         *pdwEffect = DROPEFFECT_NONE;
5114
5115     m_lastDropEffect = *pdwEffect;
5116     return S_OK;
5117 }
5118
5119 HRESULT STDMETHODCALLTYPE WebView::DragLeave()
5120 {
5121     if (m_dropTargetHelper)
5122         m_dropTargetHelper->DragLeave();
5123
5124     if (m_dragData) {
5125         DragData data(m_dragData.get(), IntPoint(), IntPoint(), 
5126             DragOperationNone);
5127         m_page->dragController()->dragExited(&data);
5128         m_dragData = 0;
5129     }
5130     return S_OK;
5131 }
5132
5133 HRESULT STDMETHODCALLTYPE WebView::Drop(
5134         IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
5135 {
5136     if (m_dropTargetHelper)
5137         m_dropTargetHelper->Drop(pDataObject, (POINT*)&pt, *pdwEffect);
5138
5139     m_dragData = 0;
5140     *pdwEffect = m_lastDropEffect;
5141     POINTL localpt = pt;
5142     ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
5143     DragData data(pDataObject, IntPoint(localpt.x, localpt.y), 
5144         IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
5145     m_page->dragController()->performDrag(&data);
5146     return S_OK;
5147 }
5148
5149 HRESULT STDMETHODCALLTYPE WebView::canHandleRequest( 
5150     IWebURLRequest *request,
5151     BOOL *result)
5152 {
5153     COMPtr<WebMutableURLRequest> requestImpl;
5154
5155     HRESULT hr = request->QueryInterface(&requestImpl);
5156     if (FAILED(hr))
5157         return hr;
5158
5159     *result = !!canHandleRequest(requestImpl->resourceRequest());
5160     return S_OK;
5161 }
5162
5163 HRESULT STDMETHODCALLTYPE WebView::standardUserAgentWithApplicationName( 
5164     BSTR applicationName,
5165     BSTR* groupName)
5166 {
5167     if (!groupName) {
5168         ASSERT_NOT_REACHED();
5169         return E_POINTER;
5170     }
5171
5172     *groupName;
5173
5174     if (!applicationName) {
5175         ASSERT_NOT_REACHED();
5176         return E_POINTER;
5177     }
5178
5179     BString applicationNameBString(applicationName);
5180     *groupName = BString(standardUserAgentWithApplicationName(String(applicationNameBString, SysStringLen(applicationNameBString)))).release();
5181     return S_OK;
5182 }
5183
5184 HRESULT STDMETHODCALLTYPE WebView::clearFocusNode()
5185 {
5186     if (m_page && m_page->focusController())
5187         m_page->focusController()->setFocusedNode(0, 0);
5188     return S_OK;
5189 }
5190
5191 HRESULT STDMETHODCALLTYPE WebView::setInitialFocus(
5192     /* [in] */ BOOL forward)
5193 {
5194     if (m_page && m_page->focusController()) {
5195         Frame* frame = m_page->focusController()->focusedOrMainFrame();
5196         frame->document()->setFocusedNode(0);
5197         m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
5198     }
5199     return S_OK;
5200 }
5201
5202 HRESULT STDMETHODCALLTYPE WebView::setTabKeyCyclesThroughElements( 
5203     /* [in] */ BOOL cycles)
5204 {
5205     if (m_page)
5206         m_page->setTabKeyCyclesThroughElements(!!cycles);
5207
5208     return S_OK;
5209 }
5210
5211 HRESULT STDMETHODCALLTYPE WebView::tabKeyCyclesThroughElements( 
5212     /* [retval][out] */ BOOL* result)
5213 {
5214     if (!result) {
5215         ASSERT_NOT_REACHED();
5216         return E_POINTER;
5217     }
5218
5219     *result = m_page && m_page->tabKeyCyclesThroughElements() ? TRUE : FALSE;
5220     return S_OK;
5221 }
5222
5223 HRESULT STDMETHODCALLTYPE WebView::setAllowSiteSpecificHacks(
5224     /* [in] */ BOOL allow)
5225 {
5226     s_allowSiteSpecificHacks = !!allow;
5227     // FIXME: This sets a global so it needs to call notifyPreferencesChanged
5228     // on all WebView objects (not just itself).
5229     return S_OK;
5230 }
5231
5232 HRESULT STDMETHODCALLTYPE WebView::addAdditionalPluginDirectory( 
5233         /* [in] */ BSTR directory)
5234 {
5235     PluginDatabase::installedPlugins()->addExtraPluginDirectory(String(directory, SysStringLen(directory)));
5236     return S_OK;
5237 }
5238
5239 HRESULT STDMETHODCALLTYPE WebView::loadBackForwardListFromOtherView( 
5240     /* [in] */ IWebView* otherView)
5241 {
5242     if (!m_page)
5243         return E_FAIL;
5244     
5245     // It turns out the right combination of behavior is done with the back/forward load
5246     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
5247     // in the back forward list, and go to the current one.
5248     BackForwardList* backForwardList = m_page->backForwardList();
5249     ASSERT(!backForwardList->currentItem()); // destination list should be empty
5250
5251     COMPtr<WebView> otherWebView;
5252     if (FAILED(otherView->QueryInterface(&otherWebView)))
5253         return E_FAIL;
5254     BackForwardList* otherBackForwardList = otherWebView->m_page->backForwardList();
5255     if (!otherBackForwardList->currentItem())
5256         return S_OK; // empty back forward list, bail
5257     
5258     HistoryItem* newItemToGoTo = 0;
5259
5260     int lastItemIndex = otherBackForwardList->forwardListCount();
5261     for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
5262         if (!i) {
5263             // If this item is showing , save away its current scroll and form state,
5264             // since that might have changed since loading and it is normally not saved
5265             // until we leave that page.
5266             otherWebView->m_page->mainFrame()->loader()->history()->saveDocumentAndScrollState();
5267         }
5268         RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
5269         if (!i) 
5270             newItemToGoTo = newItem.get();
5271         backForwardList->addItem(newItem.release());
5272     }
5273     
5274     ASSERT(newItemToGoTo);
5275     m_page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
5276     return S_OK;
5277 }
5278
5279 HRESULT STDMETHODCALLTYPE WebView::clearUndoRedoOperations()
5280 {
5281     if (Frame* frame = m_page->focusController()->focusedOrMainFrame())
5282         frame->editor()->clearUndoRedoOperations();
5283     return S_OK;
5284 }
5285
5286 HRESULT STDMETHODCALLTYPE WebView::shouldClose( 
5287     /* [retval][out] */ BOOL* result)
5288 {
5289     if (!result) {
5290         ASSERT_NOT_REACHED();
5291         return E_POINTER;
5292     }
5293
5294     *result = TRUE;
5295     if (Frame* frame = m_page->mainFrame())
5296         *result = frame->loader()->shouldClose();
5297     return S_OK;
5298 }
5299
5300 HRESULT WebView::registerDragDrop()
5301 {
5302     ASSERT(::IsWindow(m_viewWindow));
5303     return ::RegisterDragDrop(m_viewWindow, this);
5304 }
5305
5306 HRESULT WebView::revokeDragDrop()
5307 {
5308     if (!m_viewWindow)
5309         return S_OK;
5310
5311     return ::RevokeDragDrop(m_viewWindow);
5312 }
5313
5314 HRESULT WebView::setProhibitsMainFrameScrolling(BOOL b)
5315 {
5316     if (!m_page)
5317         return E_FAIL;
5318
5319     m_page->mainFrame()->view()->setProhibitsScrolling(b);
5320     return S_OK;
5321 }
5322
5323 HRESULT WebView::setShouldApplyMacFontAscentHack(BOOL b)
5324 {
5325     SimpleFontData::setShouldApplyMacAscentHack(b);
5326     return S_OK;
5327 }
5328
5329 class IMMDict {
5330     typedef HIMC (CALLBACK *getContextPtr)(HWND);
5331     typedef BOOL (CALLBACK *releaseContextPtr)(HWND, HIMC);
5332     typedef LONG (CALLBACK *getCompositionStringPtr)(HIMC, DWORD, LPVOID, DWORD);
5333     typedef BOOL (CALLBACK *setCandidateWindowPtr)(HIMC, LPCANDIDATEFORM);
5334     typedef BOOL (CALLBACK *setOpenStatusPtr)(HIMC, BOOL);
5335     typedef BOOL (CALLBACK *notifyIMEPtr)(HIMC, DWORD, DWORD, DWORD);
5336     typedef BOOL (CALLBACK *associateContextExPtr)(HWND, HIMC, DWORD);
5337
5338 public:
5339     getContextPtr getContext;
5340     releaseContextPtr releaseContext;
5341     getCompositionStringPtr getCompositionString;
5342     setCandidateWindowPtr setCandidateWindow;
5343     setOpenStatusPtr setOpenStatus;
5344     notifyIMEPtr notifyIME;
5345     associateContextExPtr associateContextEx;
5346
5347     static const IMMDict& dict();
5348 private:
5349     IMMDict();
5350     HMODULE m_instance;
5351 };
5352
5353 const IMMDict& IMMDict::dict()
5354 {
5355     static IMMDict instance;
5356     return instance;
5357 }
5358
5359 IMMDict::IMMDict()
5360 {
5361     m_instance = ::LoadLibraryW(L"IMM32.DLL");
5362     getContext = reinterpret_cast<getContextPtr>(::GetProcAddress(m_instance, "ImmGetContext"));
5363     ASSERT(getContext);
5364     releaseContext = reinterpret_cast<releaseContextPtr>(::GetProcAddress(m_instance, "ImmReleaseContext"));
5365     ASSERT(releaseContext);
5366     getCompositionString = reinterpret_cast<getCompositionStringPtr>(::GetProcAddress(m_instance, "ImmGetCompositionStringW"));
5367     ASSERT(getCompositionString);
5368     setCandidateWindow = reinterpret_cast<setCandidateWindowPtr>(::GetProcAddress(m_instance, "ImmSetCandidateWindow"));
5369     ASSERT(setCandidateWindow);
5370     setOpenStatus = reinterpret_cast<setOpenStatusPtr>(::GetProcAddress(m_instance, "ImmSetOpenStatus"));
5371     ASSERT(setOpenStatus);
5372     notifyIME = reinterpret_cast<notifyIMEPtr>(::GetProcAddress(m_instance, "ImmNotifyIME"));
5373     ASSERT(notifyIME);
5374     associateContextEx = reinterpret_cast<associateContextExPtr>(::GetProcAddress(m_instance, "ImmAssociateContextEx"));
5375     ASSERT(associateContextEx);
5376 }
5377
5378 HIMC WebView::getIMMContext() 
5379 {
5380     HIMC context = IMMDict::dict().getContext(m_viewWindow);
5381     return context;
5382 }
5383
5384 void WebView::releaseIMMContext(HIMC hIMC)
5385 {
5386     if (!hIMC)
5387         return;
5388     IMMDict::dict().releaseContext(m_viewWindow, hIMC);
5389 }
5390
5391 void WebView::prepareCandidateWindow(Frame* targetFrame, HIMC hInputContext) 
5392 {
5393     IntRect caret;
5394     if (RefPtr<Range> range = targetFrame->selection()->selection().toNormalizedRange()) {
5395         ExceptionCode ec = 0;
5396         RefPtr<Range> tempRange = range->cloneRange(ec);
5397         caret = targetFrame->editor()->firstRectForRange(tempRange.get());
5398     }
5399     caret = targetFrame->view()->contentsToWindow(caret);
5400     CANDIDATEFORM form;
5401     form.dwIndex = 0;
5402     form.dwStyle = CFS_EXCLUDE;
5403     form.ptCurrentPos.x = caret.x();
5404     form.ptCurrentPos.y = caret.y() + caret.height();
5405     form.rcArea.top = caret.y();
5406     form.rcArea.bottom = caret.maxY();
5407     form.rcArea.left = caret.x();
5408     form.rcArea.right = caret.maxX();
5409     IMMDict::dict().setCandidateWindow(hInputContext, &form);
5410 }
5411
5412 void WebView::resetIME(Frame* targetFrame)
5413 {
5414     if (targetFrame)
5415         targetFrame->editor()->cancelComposition();
5416
5417     if (HIMC hInputContext = getIMMContext()) {
5418         IMMDict::dict().notifyIME(hInputContext, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
5419         releaseIMMContext(hInputContext);
5420     }
5421 }
5422
5423 void WebView::updateSelectionForIME()
5424 {
5425     Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
5426     if (!targetFrame || !targetFrame->editor()->hasComposition())
5427         return;
5428     
5429     if (targetFrame->editor()->ignoreCompositionSelectionChange())
5430         return;
5431
5432     unsigned start;
5433     unsigned end;
5434     if (!targetFrame->editor()->getCompositionSelection(start, end))
5435         resetIME(targetFrame);
5436 }
5437
5438 void WebView::setInputMethodState(bool enabled)
5439 {
5440     IMMDict::dict().associateContextEx(m_viewWindow, 0, enabled ? IACE_DEFAULT : 0);
5441 }
5442
5443 void WebView::selectionChanged()
5444 {
5445     updateSelectionForIME();
5446 }
5447
5448 bool WebView::onIMEStartComposition()
5449 {
5450     LOG(TextInput, "onIMEStartComposition");
5451     m_inIMEComposition++;
5452     Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
5453     if (!targetFrame)
5454         return true;
5455
5456     HIMC hInputContext = getIMMContext();
5457     prepareCandidateWindow(targetFrame, hInputContext);
5458     releaseIMMContext(hInputContext);
5459     return true;
5460 }
5461
5462 static bool getCompositionString(HIMC hInputContext, DWORD type, String& result)
5463 {
5464     int compositionLength = IMMDict::dict().getCompositionString(hInputContext, type, 0, 0);
5465     if (compositionLength <= 0)
5466         return false;
5467     Vector<UChar> compositionBuffer(compositionLength / 2);
5468     compositionLength = IMMDict::dict().getCompositionString(hInputContext, type, (LPVOID)compositionBuffer.data(), compositionLength);
5469     result = String(compositionBuffer.data(), compositionLength / 2);
5470     ASSERT(!compositionLength || compositionBuffer[0]);
5471     ASSERT(!compositionLength || compositionBuffer[compositionLength / 2 - 1]);
5472     return true;
5473 }
5474
5475 static void compositionToUnderlines(const Vector<DWORD>& clauses, const Vector<BYTE>& attributes, Vector<CompositionUnderline>& underlines)
5476 {
5477     if (clauses.isEmpty()) {
5478         underlines.clear();
5479         return;
5480     }
5481   
5482     const size_t numBoundaries = clauses.size() - 1;
5483     underlines.resize(numBoundaries);
5484     for (unsigned i = 0; i < numBoundaries; i++) {
5485         underlines[i].startOffset = clauses[i];
5486         underlines[i].endOffset = clauses[i + 1];
5487         BYTE attribute = attributes[clauses[i]];
5488         underlines[i].thick = attribute == ATTR_TARGET_CONVERTED || attribute == ATTR_TARGET_NOTCONVERTED;
5489         underlines[i].color = Color(0,0,0);
5490     }
5491 }
5492
5493 #if !LOG_DISABLED
5494 #define APPEND_ARGUMENT_NAME(name) \
5495     if (lparam & name) { \
5496         if (needsComma) \
5497             result += ", "; \
5498             result += #name; \
5499         needsComma = true; \
5500     }
5501
5502 static String imeCompositionArgumentNames(LPARAM lparam)
5503 {
5504     String result;
5505     bool needsComma = false;
5506     if (lparam & GCS_COMPATTR) {
5507         result = "GCS_COMPATTR";
5508         needsComma = true;
5509     }
5510     APPEND_ARGUMENT_NAME(GCS_COMPCLAUSE);
5511     APPEND_ARGUMENT_NAME(GCS_COMPREADSTR);
5512     APPEND_ARGUMENT_NAME(GCS_COMPREADATTR);
5513     APPEND_ARGUMENT_NAME(GCS_COMPREADCLAUSE);
5514     APPEND_ARGUMENT_NAME(GCS_COMPSTR);
5515     APPEND_ARGUMENT_NAME(GCS_CURSORPOS);
5516     APPEND_ARGUMENT_NAME(GCS_DELTASTART);
5517     APPEND_ARGUMENT_NAME(GCS_RESULTCLAUSE);
5518     APPEND_ARGUMENT_NAME(GCS_RESULTREADCLAUSE);
5519     APPEND_ARGUMENT_NAME(GCS_RESULTREADSTR);
5520     APPEND_ARGUMENT_NAME(GCS_RESULTSTR);
5521     APPEND_ARGUMENT_NAME(CS_INSERTCHAR);
5522     APPEND_ARGUMENT_NAME(CS_NOMOVECARET);
5523
5524     return result;
5525 }
5526
5527 static String imeNotificationName(WPARAM wparam)
5528 {
5529     switch (wparam) {
5530     case IMN_CHANGECANDIDATE:
5531         return "IMN_CHANGECANDIDATE";
5532     case IMN_CLOSECANDIDATE:
5533         return "IMN_CLOSECANDIDATE";
5534     case IMN_CLOSESTATUSWINDOW:
5535         return "IMN_CLOSESTATUSWINDOW";
5536     case IMN_GUIDELINE:
5537         return "IMN_GUIDELINE";
5538     case IMN_OPENCANDIDATE:
5539         return "IMN_OPENCANDIDATE";
5540     case IMN_OPENSTATUSWINDOW:
5541         return "IMN_OPENSTATUSWINDOW";
5542     case IMN_SETCANDIDATEPOS:
5543         return "IMN_SETCANDIDATEPOS";
5544     case IMN_SETCOMPOSITIONFONT:
5545         return "IMN_SETCOMPOSITIONFONT";
5546     case IMN_SETCOMPOSITIONWINDOW:
5547         return "IMN_SETCOMPOSITIONWINDOW";
5548     case IMN_SETCONVERSIONMODE:
5549         return "IMN_SETCONVERSIONMODE";
5550     case IMN_SETOPENSTATUS:
5551         return "IMN_SETOPENSTATUS";
5552     case IMN_SETSENTENCEMODE:
5553         return "IMN_SETSENTENCEMODE";
5554     case IMN_SETSTATUSWINDOWPOS:
5555         return "IMN_SETSTATUSWINDOWPOS";
5556     default:
5557         return "Unknown (" + String::number(wparam) + ")";
5558     }
5559 }
5560
5561 static String imeRequestName(WPARAM wparam)
5562 {
5563     switch (wparam) {
5564     case IMR_CANDIDATEWINDOW:
5565         return "IMR_CANDIDATEWINDOW";
5566     case IMR_COMPOSITIONFONT:
5567         return "IMR_COMPOSITIONFONT";
5568     case IMR_COMPOSITIONWINDOW:
5569         return "IMR_COMPOSITIONWINDOW";
5570     case IMR_CONFIRMRECONVERTSTRING:
5571         return "IMR_CONFIRMRECONVERTSTRING";
5572     case IMR_DOCUMENTFEED:
5573         return "IMR_DOCUMENTFEED";
5574     case IMR_QUERYCHARPOSITION:
5575         return "IMR_QUERYCHARPOSITION";
5576     case IMR_RECONVERTSTRING:
5577         return "IMR_RECONVERTSTRING";
5578     default:
5579         return "Unknown (" + String::number(wparam) + ")";
5580     }
5581 }
5582 #endif
5583
5584 bool WebView::onIMEComposition(LPARAM lparam)
5585 {
5586     LOG(TextInput, "onIMEComposition %s", imeCompositionArgumentNames(lparam).latin1().data());
5587     HIMC hInputContext = getIMMContext();
5588     if (!hInputContext)
5589         return true;
5590
5591     Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
5592     if (!targetFrame || !targetFrame->editor()->canEdit())
5593         return true;
5594
5595     prepareCandidateWindow(targetFrame, hInputContext);
5596
5597     if (lparam & GCS_RESULTSTR || !lparam) {
5598         String compositionString;
5599         if (!getCompositionString(hInputContext, GCS_RESULTSTR, compositionString) && lparam)
5600             return true;
5601         
5602         targetFrame->editor()->confirmComposition(compositionString);
5603     } else {
5604         String compositionString;
5605         if (!getCompositionString(hInputContext, GCS_COMPSTR, compositionString))
5606             return true;
5607         
5608         // Composition string attributes
5609         int numAttributes = IMMDict::dict().getCompositionString(hInputContext, GCS_COMPATTR, 0, 0);
5610         Vector<BYTE> attributes(numAttributes);
5611         IMMDict::dict().getCompositionString(hInputContext, GCS_COMPATTR, attributes.data(), numAttributes);
5612
5613         // Get clauses
5614         int numClauses = IMMDict::dict().getCompositionString(hInputContext, GCS_COMPCLAUSE, 0, 0);
5615         Vector<DWORD> clauses(numClauses / sizeof(DWORD));
5616         IMMDict::dict().getCompositionString(hInputContext, GCS_COMPCLAUSE, clauses.data(), numClauses);
5617
5618         Vector<CompositionUnderline> underlines;
5619         compositionToUnderlines(clauses, attributes, underlines);
5620
5621         int cursorPosition = LOWORD(IMMDict::dict().getCompositionString(hInputContext, GCS_CURSORPOS, 0, 0));
5622
5623         targetFrame->editor()->setComposition(compositionString, underlines, cursorPosition, 0);
5624     }
5625
5626     return true;
5627 }
5628
5629 bool WebView::onIMEEndComposition()
5630 {
5631     LOG(TextInput, "onIMEEndComposition");
5632     // If the composition hasn't been confirmed yet, it needs to be cancelled.
5633     // This happens after deleting the last character from inline input hole.
5634     Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
5635     if (targetFrame && targetFrame->editor()->hasComposition())
5636         targetFrame->editor()->confirmComposition(String());
5637
5638     if (m_inIMEComposition)
5639         m_inIMEComposition--;
5640
5641     return true;
5642 }
5643
5644 bool WebView::onIMEChar(WPARAM wparam, LPARAM lparam)
5645 {
5646     UNUSED_PARAM(wparam);
5647     UNUSED_PARAM(lparam);
5648     LOG(TextInput, "onIMEChar U+%04X %08X", wparam, lparam);
5649     return true;
5650 }
5651
5652 bool WebView::onIMENotify(WPARAM wparam, LPARAM, LRESULT*)
5653 {
5654     UNUSED_PARAM(wparam);
5655     LOG(TextInput, "onIMENotify %s", imeNotificationName(wparam).latin1().data());
5656     return false;
5657 }
5658
5659 LRESULT WebView::onIMERequestCharPosition(Frame* targetFrame, IMECHARPOSITION* charPos)
5660 {
5661     if (charPos->dwCharPos && !targetFrame->editor()->hasComposition())
5662         return 0;
5663     IntRect caret;
5664     if (RefPtr<Range> range = targetFrame->editor()->hasComposition() ? targetFrame->editor()->compositionRange() : targetFrame->selection()->selection().toNormalizedRange()) {
5665         ExceptionCode ec = 0;
5666         RefPtr<Range> tempRange = range->cloneRange(ec);
5667         tempRange->setStart(tempRange->startContainer(ec), tempRange->startOffset(ec) + charPos->dwCharPos, ec);
5668         caret = targetFrame->editor()->firstRectForRange(tempRange.get());
5669     }
5670     caret = targetFrame->view()->contentsToWindow(caret);
5671     charPos->pt.x = caret.x();
5672     charPos->pt.y = caret.y();
5673     ::ClientToScreen(m_viewWindow, &charPos->pt);
5674     charPos->cLineHeight = caret.height();
5675     ::GetWindowRect(m_viewWindow, &charPos->rcDocument);
5676     return true;
5677 }
5678
5679 LRESULT WebView::onIMERequestReconvertString(Frame* targetFrame, RECONVERTSTRING* reconvertString)
5680 {
5681     RefPtr<Range> selectedRange = targetFrame->selection()->toNormalizedRange();
5682     String text = selectedRange->text();
5683     if (!reconvertString)
5684         return sizeof(RECONVERTSTRING) + text.length() * sizeof(UChar);
5685
5686     unsigned totalSize = sizeof(RECONVERTSTRING) + text.length() * sizeof(UChar);
5687     if (totalSize > reconvertString->dwSize)
5688         return 0;
5689     reconvertString->dwCompStrLen = text.length();
5690     reconvertString->dwStrLen = text.length();
5691     reconvertString->dwTargetStrLen = text.length();
5692     reconvertString->dwStrOffset = sizeof(RECONVERTSTRING);
5693     memcpy(reconvertString + 1, text.characters(), text.length() * sizeof(UChar));
5694     return totalSize;
5695 }
5696
5697 LRESULT WebView::onIMERequest(WPARAM request, LPARAM data)
5698 {
5699     LOG(TextInput, "onIMERequest %s", imeRequestName(request).latin1().data());
5700     Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
5701     if (!targetFrame || !targetFrame->editor()->canEdit())
5702         return 0;
5703
5704     switch (request) {
5705         case IMR_RECONVERTSTRING:
5706             return onIMERequestReconvertString(targetFrame, (RECONVERTSTRING*)data);
5707
5708         case IMR_QUERYCHARPOSITION:
5709             return onIMERequestCharPosition(targetFrame, (IMECHARPOSITION*)data);
5710     }
5711     return 0;
5712 }
5713
5714 bool WebView::onIMESelect(WPARAM wparam, LPARAM lparam)
5715 {
5716     UNUSED_PARAM(wparam);
5717     UNUSED_PARAM(lparam);
5718     LOG(TextInput, "onIMESelect locale %ld %s", lparam, wparam ? "select" : "deselect");
5719     return false;
5720 }
5721
5722 bool WebView::onIMESetContext(WPARAM wparam, LPARAM)
5723 {
5724     LOG(TextInput, "onIMESetContext %s", wparam ? "active" : "inactive");
5725     return false;
5726 }
5727
5728 HRESULT STDMETHODCALLTYPE WebView::inspector(IWebInspector** inspector)
5729 {
5730     if (!m_webInspector)
5731         m_webInspector.adoptRef(WebInspector::createInstance(this));
5732
5733     return m_webInspector.copyRefTo(inspector);
5734 }
5735
5736 HRESULT STDMETHODCALLTYPE WebView::windowAncestryDidChange()
5737 {
5738     HWND newParent;
5739     if (m_viewWindow)
5740         newParent = findTopLevelParent(m_hostWindow);
5741     else {
5742         // There's no point in tracking active state changes of our parent window if we don't have
5743         // a window ourselves.
5744         newParent = 0;
5745     }
5746
5747     if (newParent == m_topLevelParent)
5748         return S_OK;
5749
5750     if (m_topLevelParent)
5751         WindowMessageBroadcaster::removeListener(m_topLevelParent, this);
5752
5753     m_topLevelParent = newParent;
5754
5755     if (m_topLevelParent)
5756         WindowMessageBroadcaster::addListener(m_topLevelParent, this);
5757
5758     updateActiveState();
5759
5760     return S_OK;
5761 }
5762
5763 HRESULT STDMETHODCALLTYPE WebView::paintDocumentRectToContext(
5764     /* [in] */ RECT rect,
5765     /* [in] */ OLE_HANDLE deviceContext)
5766 {
5767     if (!deviceContext)
5768         return E_POINTER;
5769
5770     if (!m_mainFrame)
5771         return E_FAIL;
5772
5773     return m_mainFrame->paintDocumentRectToContext(rect, deviceContext);
5774 }
5775
5776 HRESULT STDMETHODCALLTYPE WebView::paintScrollViewRectToContextAtPoint(
5777     /* [in] */ RECT rect,
5778     /* [in] */ POINT pt,
5779     /* [in] */ OLE_HANDLE deviceContext)
5780 {
5781     if (!deviceContext)
5782         return E_POINTER;
5783
5784     if (!m_mainFrame)
5785         return E_FAIL;
5786
5787     return m_mainFrame->paintScrollViewRectToContextAtPoint(rect, pt, deviceContext);
5788 }
5789
5790 HRESULT STDMETHODCALLTYPE WebView::reportException(
5791     /* [in] */ JSContextRef context,
5792     /* [in] */ JSValueRef exception)
5793 {
5794     if (!context || !exception)
5795         return E_FAIL;
5796
5797     JSLock lock(JSC::SilenceAssertionsOnly);
5798     JSC::ExecState* execState = toJS(context);
5799
5800     // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
5801     if (!toJSDOMWindow(execState->lexicalGlobalObject()))
5802         return E_FAIL;
5803
5804     WebCore::reportException(execState, toJS(execState, exception));
5805     return S_OK;
5806 }
5807
5808 HRESULT STDMETHODCALLTYPE WebView::elementFromJS(
5809     /* [in] */ JSContextRef context,
5810     /* [in] */ JSValueRef nodeObject,
5811     /* [retval][out] */ IDOMElement **element)
5812 {
5813     if (!element)
5814         return E_POINTER;
5815
5816     *element = 0;
5817
5818     if (!context)
5819         return E_FAIL;
5820
5821     if (!nodeObject)
5822         return E_FAIL;
5823
5824     JSLock lock(JSC::SilenceAssertionsOnly);
5825     Element* elt = toElement(toJS(toJS(context), nodeObject));
5826     if (!elt)
5827         return E_FAIL;
5828
5829     *element = DOMElement::createInstance(elt);
5830     return S_OK;
5831 }
5832
5833 HRESULT STDMETHODCALLTYPE WebView::setCustomHTMLTokenizerTimeDelay(
5834     /* [in] */ double timeDelay)
5835 {
5836     if (!m_page)
5837         return E_FAIL;
5838
5839     m_page->setCustomHTMLTokenizerTimeDelay(timeDelay);
5840     return S_OK;
5841 }
5842
5843 HRESULT STDMETHODCALLTYPE WebView::setCustomHTMLTokenizerChunkSize(
5844     /* [in] */ int chunkSize)
5845 {
5846     if (!m_page)
5847         return E_FAIL;
5848
5849     m_page->setCustomHTMLTokenizerChunkSize(chunkSize);
5850     return S_OK;
5851 }
5852
5853 HRESULT STDMETHODCALLTYPE WebView::backingStore(
5854     /* [out, retval] */ OLE_HANDLE* hBitmap)
5855 {
5856     if (!hBitmap)
5857         return E_POINTER;
5858     if (!m_backingStoreBitmap)
5859         return E_FAIL;
5860     *hBitmap = reinterpret_cast<OLE_HANDLE>(m_backingStoreBitmap->handle());
5861     return S_OK;
5862 }
5863
5864 HRESULT STDMETHODCALLTYPE WebView::setTransparent(BOOL transparent)
5865 {
5866     if (m_transparent == !!transparent)
5867         return S_OK;
5868
5869     m_transparent = transparent;
5870     m_mainFrame->updateBackground();
5871     return S_OK;
5872 }
5873
5874 HRESULT STDMETHODCALLTYPE WebView::transparent(BOOL* transparent)
5875 {
5876     if (!transparent)
5877         return E_POINTER;
5878
5879     *transparent = this->transparent() ? TRUE : FALSE;
5880     return S_OK;
5881 }
5882
5883 static bool setWindowStyle(HWND window, int index, LONG_PTR newValue)
5884 {
5885     // According to MSDN, if the last value of the flag we are setting was zero,
5886     // then SetWindowLongPtr returns zero, even though the call succeeded. So,
5887     // we have to clear the error state, then check the last error after
5888     // setting the value to see if it actually was a failure.
5889     ::SetLastError(0);
5890     return ::SetWindowLongPtr(window, index, newValue) || !::GetLastError();
5891 }
5892
5893 HRESULT WebView::setUsesLayeredWindow(BOOL usesLayeredWindow)
5894 {
5895     if (m_usesLayeredWindow == !!usesLayeredWindow)
5896         return S_OK;
5897
5898     if (!m_viewWindow)
5899         return E_FAIL;
5900
5901     RECT rect;
5902     ::GetWindowRect(m_viewWindow, &rect);
5903
5904     LONG_PTR origExStyle = ::GetWindowLongPtr(m_viewWindow, GWL_EXSTYLE);
5905     LONG_PTR origStyle = ::GetWindowLongPtr(m_viewWindow, GWL_STYLE);
5906
5907     // The logic here has to account for the way SetParent works.
5908     // According to MSDN, to go from a child window to a popup window,
5909     // you must clear the child bit after setting the parent to 0.
5910     // On the other hand, to go from a popup window to a child, you
5911     // must clear the popup state before setting the parent.
5912     if (usesLayeredWindow) {
5913         LONG_PTR newExStyle = origExStyle | WS_EX_LAYERED;
5914         LONG_PTR newStyle = (origStyle & ~(WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN)) | WS_POPUP;
5915
5916         HWND origParent = ::SetParent(m_viewWindow, 0);
5917
5918         if (!setWindowStyle(m_viewWindow, GWL_STYLE, newStyle)) {
5919             ::SetParent(m_viewWindow, origParent);
5920             return E_FAIL;
5921         }
5922
5923         if (!setWindowStyle(m_viewWindow, GWL_EXSTYLE, newExStyle)) {
5924             setWindowStyle(m_viewWindow, GWL_STYLE, origStyle);
5925             ::SetParent(m_viewWindow, origParent);
5926             return E_FAIL;
5927         }
5928     } else {
5929         LONG_PTR newExStyle = origExStyle & ~WS_EX_LAYERED;
5930         LONG_PTR newStyle = (origStyle & ~WS_POPUP) | WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
5931
5932         if (!setWindowStyle(m_viewWindow, GWL_EXSTYLE, newExStyle))
5933             return E_FAIL;
5934
5935         if (!setWindowStyle(m_viewWindow, GWL_STYLE, newStyle)) {
5936             setWindowStyle(m_viewWindow, GWL_EXSTYLE, origExStyle);
5937             return E_FAIL;
5938         }
5939
5940         ::SetParent(m_viewWindow, m_hostWindow ? m_hostWindow : HWND_MESSAGE);
5941     }
5942
5943     // MSDN indicates that SetWindowLongPtr doesn't take effect for some settings until a
5944     // SetWindowPos is called.
5945     ::SetWindowPos(m_viewWindow, 0, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
5946         SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
5947
5948     m_usesLayeredWindow = usesLayeredWindow;
5949     return S_OK;
5950 }
5951
5952 HRESULT WebView::usesLayeredWindow(BOOL* usesLayeredWindow)
5953 {
5954     if (!usesLayeredWindow)
5955         return E_POINTER;
5956
5957     *usesLayeredWindow = this->usesLayeredWindow() ? TRUE : FALSE;
5958     return S_OK;
5959 }
5960
5961 HRESULT STDMETHODCALLTYPE WebView::setCookieEnabled(BOOL enable)
5962 {
5963     if (!m_page)
5964         return E_FAIL;
5965
5966     m_page->setCookieEnabled(enable);
5967     return S_OK;
5968 }
5969
5970 HRESULT STDMETHODCALLTYPE WebView::cookieEnabled(BOOL* enabled)
5971 {
5972     if (!enabled)
5973         return E_POINTER;
5974
5975     if (!m_page)
5976         return E_FAIL;
5977
5978     *enabled = m_page->cookieEnabled();
5979     return S_OK;
5980 }
5981
5982 HRESULT STDMETHODCALLTYPE WebView::setMediaVolume(float volume)
5983 {
5984     if (!m_page)
5985         return E_FAIL;
5986
5987     m_page->setMediaVolume(volume);
5988     return S_OK;
5989 }
5990
5991 HRESULT STDMETHODCALLTYPE WebView::mediaVolume(float* volume)
5992 {
5993     if (!volume)
5994         return E_POINTER;
5995
5996     if (!m_page)
5997         return E_FAIL;
5998
5999     *volume = m_page->mediaVolume();
6000     return S_OK;
6001 }
6002
6003 HRESULT STDMETHODCALLTYPE WebView::setDefersCallbacks(BOOL defersCallbacks)
6004 {
6005     if (!m_page)
6006         return E_FAIL;
6007
6008     m_page->setDefersLoading(defersCallbacks);
6009     return S_OK;
6010 }
6011
6012 HRESULT STDMETHODCALLTYPE WebView::defersCallbacks(BOOL* defersCallbacks)
6013 {
6014     if (!defersCallbacks)
6015         return E_POINTER;
6016
6017     if (!m_page)
6018         return E_FAIL;
6019
6020     *defersCallbacks = m_page->defersLoading();
6021     return S_OK;
6022 }
6023
6024 HRESULT STDMETHODCALLTYPE WebView::globalHistoryItem(IWebHistoryItem** item)
6025 {
6026     if (!item)
6027         return E_POINTER;
6028
6029     if (!m_page)
6030         return E_FAIL;
6031
6032     if (!m_globalHistoryItem) {
6033         *item = 0;
6034         return S_OK;
6035     }
6036
6037     *item = WebHistoryItem::createInstance(m_globalHistoryItem);
6038     return S_OK;
6039 }
6040
6041 HRESULT STDMETHODCALLTYPE WebView::setAlwaysUsesComplexTextCodePath(BOOL complex)
6042 {
6043     WebCoreSetAlwaysUsesComplexTextCodePath(complex);
6044
6045     return S_OK;
6046 }
6047
6048 HRESULT STDMETHODCALLTYPE WebView::alwaysUsesComplexTextCodePath(BOOL* complex)
6049 {
6050     if (!complex)
6051         return E_POINTER;
6052
6053     *complex = WebCoreAlwaysUsesComplexTextCodePath();
6054     return S_OK;
6055 }
6056
6057 HRESULT STDMETHODCALLTYPE WebView::registerEmbeddedViewMIMEType(BSTR mimeType)
6058 {
6059     if (!mimeType)
6060         return E_POINTER;
6061
6062     if (!m_embeddedViewMIMETypes)
6063         m_embeddedViewMIMETypes = adoptPtr(new HashSet<String>);
6064
6065     m_embeddedViewMIMETypes->add(String(mimeType, ::SysStringLen(mimeType)));
6066     return S_OK;
6067 }
6068
6069 bool WebView::shouldUseEmbeddedView(const WTF::String& mimeType) const
6070 {
6071     if (!m_embeddedViewMIMETypes)
6072         return false;
6073
6074     return m_embeddedViewMIMETypes->contains(mimeType);
6075 }
6076
6077 bool WebView::onGetObject(WPARAM wParam, LPARAM lParam, LRESULT& lResult) const
6078 {
6079     lResult = 0;
6080
6081     if (lParam != OBJID_CLIENT)
6082         return false;
6083
6084     AXObjectCache::enableAccessibility();
6085
6086     // Get the accessible object for the top-level frame.
6087     WebFrame* mainFrameImpl = topLevelFrame();
6088     if (!mainFrameImpl)
6089         return false;
6090
6091     COMPtr<IAccessible> accessible = mainFrameImpl->accessible();
6092     if (!accessible)
6093         return false;
6094
6095     if (!accessibilityLib) {
6096         if (!(accessibilityLib = ::LoadLibraryW(L"oleacc.dll")))
6097             return false;
6098     }
6099
6100     static LPFNLRESULTFROMOBJECT procPtr = reinterpret_cast<LPFNLRESULTFROMOBJECT>(::GetProcAddress(accessibilityLib, "LresultFromObject"));
6101     if (!procPtr)
6102         return false;
6103
6104     // LresultFromObject returns a reference to the accessible object, stored
6105     // in an LRESULT. If this call is not successful, Windows will handle the
6106     // request through DefWindowProc.
6107     return SUCCEEDED(lResult = procPtr(__uuidof(IAccessible), wParam, accessible.get()));
6108 }
6109
6110 STDMETHODIMP WebView::AccessibleObjectFromWindow(HWND hwnd, DWORD objectID, REFIID riid, void** ppObject)
6111 {
6112     ASSERT(accessibilityLib);
6113     static LPFNACCESSIBLEOBJECTFROMWINDOW procPtr = reinterpret_cast<LPFNACCESSIBLEOBJECTFROMWINDOW>(::GetProcAddress(accessibilityLib, "AccessibleObjectFromWindow"));
6114     if (!procPtr)
6115         return E_FAIL;
6116     return procPtr(hwnd, objectID, riid, ppObject);
6117 }
6118
6119 HRESULT WebView::setMemoryCacheDelegateCallsEnabled(BOOL enabled)
6120 {
6121     m_page->setMemoryCacheClientCallsEnabled(enabled);
6122     return S_OK;
6123 }
6124
6125 HRESULT WebView::setJavaScriptURLsAreAllowed(BOOL areAllowed)
6126 {
6127     m_page->setJavaScriptURLsAreAllowed(areAllowed);
6128     return S_OK;
6129 }
6130
6131 HRESULT WebView::setCanStartPlugins(BOOL canStartPlugins)
6132 {
6133     m_page->setCanStartMedia(canStartPlugins);
6134     return S_OK;
6135 }
6136
6137 static String toString(BSTR bstr)
6138 {
6139     return String(bstr, SysStringLen(bstr));
6140 }
6141
6142 static KURL toKURL(BSTR bstr)
6143 {
6144     return KURL(KURL(), toString(bstr));
6145 }
6146
6147 void WebView::enterFullscreenForNode(Node* node)
6148 {
6149     if (!node->hasTagName(HTMLNames::videoTag) || !node->isElementNode())
6150         return;
6151
6152 #if ENABLE(VIDEO)
6153     if (!static_cast<Element*>(node)->isMediaElement())
6154         return;
6155     HTMLMediaElement* videoElement = static_cast<HTMLMediaElement*>(node);
6156
6157     if (m_fullScreenVideoController) {
6158         if (m_fullScreenVideoController->mediaElement() == videoElement) {
6159             // The backend may just warn us that the underlaying plaftormMovie()
6160             // has changed. Just force an update.
6161             m_fullScreenVideoController->setMediaElement(videoElement);
6162             return; // No more to do.
6163         }
6164
6165         // First exit Fullscreen for the old mediaElement.
6166         m_fullScreenVideoController->mediaElement()->exitFullscreen();
6167         // This previous call has to trigger exitFullscreen,
6168         // which has to clear m_fullScreenVideoController.
6169         ASSERT(!m_fullScreenVideoController);
6170     }
6171
6172     m_fullScreenVideoController = adoptPtr(new FullscreenVideoController);
6173     m_fullScreenVideoController->setMediaElement(videoElement);
6174     m_fullScreenVideoController->enterFullscreen();
6175 #endif
6176 }
6177
6178 void WebView::exitFullscreen()
6179 {
6180 #if ENABLE(VIDEO)
6181     if (m_fullScreenVideoController)
6182         m_fullScreenVideoController->exitFullscreen();
6183     
6184 #endif
6185 }
6186
6187 static PassOwnPtr<Vector<String> > toStringVector(unsigned patternsCount, BSTR* patterns)
6188 {
6189     // Convert the patterns into a Vector.
6190     if (patternsCount == 0)
6191         return nullptr;
6192     OwnPtr<Vector<String> > patternsVector = adoptPtr(new Vector<String>);
6193     for (unsigned i = 0; i < patternsCount; ++i)
6194         patternsVector->append(toString(patterns[i]));
6195     return patternsVector.release();
6196 }
6197
6198 HRESULT WebView::addUserScriptToGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR source, BSTR url, 
6199                                       unsigned whitelistCount, BSTR* whitelist,
6200                                       unsigned blacklistCount, BSTR* blacklist,
6201                                       WebUserScriptInjectionTime injectionTime)
6202 {
6203     COMPtr<WebScriptWorld> world(Query, iWorld);
6204     if (!world)
6205         return E_POINTER;
6206
6207     String group = toString(groupName);
6208     if (group.isEmpty())
6209         return E_INVALIDARG;
6210
6211     PageGroup* pageGroup = PageGroup::pageGroup(group);
6212     ASSERT(pageGroup);
6213     if (!pageGroup)
6214         return E_FAIL;
6215
6216     pageGroup->addUserScriptToWorld(world->world(), toString(source), toKURL(url),
6217                                     toStringVector(whitelistCount, whitelist), toStringVector(blacklistCount, blacklist),
6218                                     injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd,
6219                                     InjectInAllFrames);
6220
6221     return S_OK;
6222 }
6223
6224 HRESULT WebView::addUserStyleSheetToGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR source, BSTR url,
6225                                           unsigned whitelistCount, BSTR* whitelist,
6226                                           unsigned blacklistCount, BSTR* blacklist)
6227 {
6228     COMPtr<WebScriptWorld> world(Query, iWorld);
6229     if (!world)
6230         return E_POINTER;
6231
6232     String group = toString(groupName);
6233     if (group.isEmpty())
6234         return E_INVALIDARG;
6235
6236     PageGroup* pageGroup = PageGroup::pageGroup(group);
6237     ASSERT(pageGroup);
6238     if (!pageGroup)
6239         return E_FAIL;
6240
6241     pageGroup->addUserStyleSheetToWorld(world->world(), toString(source), toKURL(url),
6242                                         toStringVector(whitelistCount, whitelist), toStringVector(blacklistCount, blacklist),
6243                                         InjectInAllFrames);
6244
6245     return S_OK;
6246 }
6247
6248 HRESULT WebView::removeUserScriptFromGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR url)
6249 {
6250     COMPtr<WebScriptWorld> world(Query, iWorld);
6251     if (!world)
6252         return E_POINTER;
6253
6254     String group = toString(groupName);
6255     if (group.isEmpty())
6256         return E_INVALIDARG;
6257
6258     PageGroup* pageGroup = PageGroup::pageGroup(group);
6259     ASSERT(pageGroup);
6260     if (!pageGroup)
6261         return E_FAIL;
6262
6263     pageGroup->removeUserScriptFromWorld(world->world(), toKURL(url));
6264
6265     return S_OK;
6266 }
6267
6268 HRESULT WebView::removeUserStyleSheetFromGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR url)
6269 {
6270     COMPtr<WebScriptWorld> world(Query, iWorld);
6271     if (!world)
6272         return E_POINTER;
6273
6274     String group = toString(groupName);
6275     if (group.isEmpty())
6276         return E_INVALIDARG;
6277
6278     PageGroup* pageGroup = PageGroup::pageGroup(group);
6279     ASSERT(pageGroup);
6280     if (!pageGroup)
6281         return E_FAIL;
6282
6283     pageGroup->removeUserStyleSheetFromWorld(world->world(), toKURL(url));
6284
6285     return S_OK;
6286 }
6287
6288 HRESULT WebView::removeUserScriptsFromGroup(BSTR groupName, IWebScriptWorld* iWorld)
6289 {
6290     COMPtr<WebScriptWorld> world(Query, iWorld);
6291     if (!world)
6292         return E_POINTER;
6293
6294     String group = toString(groupName);
6295     if (group.isEmpty())
6296         return E_INVALIDARG;
6297
6298     PageGroup* pageGroup = PageGroup::pageGroup(group);
6299     ASSERT(pageGroup);
6300     if (!pageGroup)
6301         return E_FAIL;
6302
6303     pageGroup->removeUserScriptsFromWorld(world->world());
6304     return S_OK;
6305 }
6306
6307 HRESULT WebView::removeUserStyleSheetsFromGroup(BSTR groupName, IWebScriptWorld* iWorld)
6308 {
6309     COMPtr<WebScriptWorld> world(Query, iWorld);
6310     if (!world)
6311         return E_POINTER;
6312
6313     String group = toString(groupName);
6314     if (group.isEmpty())
6315         return E_INVALIDARG;
6316
6317     PageGroup* pageGroup = PageGroup::pageGroup(group);
6318     ASSERT(pageGroup);
6319     if (!pageGroup)
6320         return E_FAIL;
6321
6322     pageGroup->removeUserStyleSheetsFromWorld(world->world());
6323     return S_OK;
6324 }
6325
6326 HRESULT WebView::removeAllUserContentFromGroup(BSTR groupName)
6327 {
6328     String group = toString(groupName);
6329     if (group.isEmpty())
6330         return E_INVALIDARG;
6331
6332     PageGroup* pageGroup = PageGroup::pageGroup(group);
6333     ASSERT(pageGroup);
6334     if (!pageGroup)
6335         return E_FAIL;
6336
6337     pageGroup->removeAllUserContent();
6338     return S_OK;
6339 }
6340
6341 HRESULT WebView::invalidateBackingStore(const RECT* rect)
6342 {
6343     if (!IsWindow(m_viewWindow))
6344         return S_OK;
6345
6346     RECT clientRect;
6347     if (!GetClientRect(m_viewWindow, &clientRect))
6348         return E_FAIL;
6349
6350     RECT rectToInvalidate;
6351     if (!rect)
6352         rectToInvalidate = clientRect;
6353     else if (!IntersectRect(&rectToInvalidate, &clientRect, rect))
6354         return S_OK;
6355
6356     repaint(rectToInvalidate, true);
6357     return S_OK;
6358 }
6359
6360 HRESULT WebView::addOriginAccessWhitelistEntry(BSTR sourceOrigin, BSTR destinationProtocol, BSTR destinationHost, BOOL allowDestinationSubdomains)
6361 {
6362     SecurityOrigin::addOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(String(sourceOrigin, SysStringLen(sourceOrigin))), String(destinationProtocol, SysStringLen(destinationProtocol)), String(destinationHost, SysStringLen(destinationHost)), allowDestinationSubdomains);
6363     return S_OK;
6364 }
6365
6366 HRESULT WebView::removeOriginAccessWhitelistEntry(BSTR sourceOrigin, BSTR destinationProtocol, BSTR destinationHost, BOOL allowDestinationSubdomains)
6367 {
6368     SecurityOrigin::removeOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(String(sourceOrigin, SysStringLen(sourceOrigin))), String(destinationProtocol, SysStringLen(destinationProtocol)), String(destinationHost, SysStringLen(destinationHost)), allowDestinationSubdomains);
6369     return S_OK;
6370 }
6371
6372 HRESULT WebView::resetOriginAccessWhitelists()
6373 {
6374     SecurityOrigin::resetOriginAccessWhitelists();
6375     return S_OK;
6376 }
6377  
6378 HRESULT WebView::setHistoryDelegate(IWebHistoryDelegate* historyDelegate)
6379 {
6380     m_historyDelegate = historyDelegate;
6381     return S_OK;
6382 }
6383
6384 HRESULT WebView::historyDelegate(IWebHistoryDelegate** historyDelegate)
6385 {
6386     if (!historyDelegate)
6387         return E_POINTER;
6388
6389     return m_historyDelegate.copyRefTo(historyDelegate);
6390 }
6391
6392 HRESULT WebView::addVisitedLinks(BSTR* visitedURLs, unsigned visitedURLCount)
6393 {
6394     PageGroup& group = core(this)->group();
6395     
6396     for (unsigned i = 0; i < visitedURLCount; ++i) {
6397         BSTR url = visitedURLs[i];
6398         unsigned length = SysStringLen(url);
6399         group.addVisitedLink(url, length);
6400     }
6401
6402     return S_OK;
6403 }
6404
6405 void WebView::downloadURL(const KURL& url)
6406 {
6407     // It's the delegate's job to ref the WebDownload to keep it alive - otherwise it will be
6408     // destroyed when this function returns.
6409     COMPtr<WebDownload> download(AdoptCOM, WebDownload::createInstance(url, m_downloadDelegate.get()));
6410     download->start();
6411 }
6412
6413 #if USE(ACCELERATED_COMPOSITING)
6414 void WebView::setRootChildLayer(GraphicsLayer* layer)
6415 {
6416     setAcceleratedCompositing(layer ? true : false);
6417     if (!m_backingLayer)
6418         return;
6419     m_backingLayer->addChild(layer);
6420 }
6421
6422 void WebView::flushPendingGraphicsLayerChangesSoon()
6423 {
6424     if (!m_layerTreeHost)
6425         return;
6426     m_layerTreeHost->flushPendingGraphicsLayerChangesSoon();
6427 }
6428
6429 void WebView::setAcceleratedCompositing(bool accelerated)
6430 {
6431     if (m_isAcceleratedCompositing == accelerated || !CACFLayerTreeHost::acceleratedCompositingAvailable())
6432         return;
6433
6434     if (accelerated) {
6435         m_layerTreeHost = CACFLayerTreeHost::create();
6436         if (m_layerTreeHost) {
6437             m_isAcceleratedCompositing = true;
6438
6439             m_layerTreeHost->setClient(this);
6440             ASSERT(m_viewWindow);
6441             m_layerTreeHost->setWindow(m_viewWindow);
6442
6443             // FIXME: We could perhaps get better performance by never allowing this layer to
6444             // become tiled (or choosing a higher-than-normal tiling threshold).
6445             // <http://webkit.org/b/52603>
6446             m_backingLayer = GraphicsLayer::create(this);
6447             m_backingLayer->setDrawsContent(true);
6448             m_backingLayer->setContentsOpaque(true);
6449             RECT clientRect;
6450             ::GetClientRect(m_viewWindow, &clientRect);
6451             m_backingLayer->setSize(IntRect(clientRect).size());
6452             m_backingLayer->setNeedsDisplay();
6453
6454             m_layerTreeHost->setRootChildLayer(PlatformCALayer::platformCALayer(m_backingLayer->platformLayer()));
6455
6456             // We aren't going to be using our backing store while we're in accelerated compositing
6457             // mode. But don't delete it immediately, in case we switch out of accelerated
6458             // compositing mode soon (e.g., if we're only compositing for a :hover animation).
6459             deleteBackingStoreSoon();
6460         }
6461     } else {
6462         ASSERT(m_layerTreeHost);
6463         m_layerTreeHost->setClient(0);
6464         m_layerTreeHost->setWindow(0);
6465         m_layerTreeHost = 0;
6466         m_backingLayer = nullptr;
6467         m_isAcceleratedCompositing = false;
6468     }
6469 }
6470 #endif
6471
6472 HRESULT WebView::unused1()
6473 {
6474     ASSERT_NOT_REACHED();
6475     return E_FAIL;
6476 }
6477
6478 HRESULT WebView::unused2()
6479 {
6480     ASSERT_NOT_REACHED();
6481     return E_FAIL;
6482 }
6483
6484 HRESULT WebView::unused3()
6485 {
6486     ASSERT_NOT_REACHED();
6487     return E_FAIL;
6488 }
6489
6490 HRESULT WebView::unused4()
6491 {
6492     ASSERT_NOT_REACHED();
6493     return E_FAIL;
6494 }
6495
6496 HRESULT WebView::unused5()
6497 {
6498     ASSERT_NOT_REACHED();
6499     return E_FAIL;
6500 }
6501
6502 HRESULT WebView::setGeolocationProvider(IWebGeolocationProvider* locationProvider)
6503 {
6504     m_geolocationProvider = locationProvider;
6505     return S_OK;
6506 }
6507
6508 HRESULT WebView::geolocationProvider(IWebGeolocationProvider** locationProvider)
6509 {
6510     if (!locationProvider)
6511         return E_POINTER;
6512
6513     if (!m_geolocationProvider)
6514         return E_FAIL;
6515
6516     return m_geolocationProvider.copyRefTo(locationProvider);
6517 }
6518
6519 HRESULT WebView::geolocationDidChangePosition(IWebGeolocationPosition* position)
6520 {
6521 #if ENABLE(CLIENT_BASED_GEOLOCATION)
6522     if (!m_page)
6523         return E_FAIL;
6524     m_page->geolocationController()->positionChanged(core(position));
6525     return S_OK;
6526 #else
6527     return E_NOTIMPL;
6528 #endif
6529 }
6530
6531 HRESULT WebView::geolocationDidFailWithError(IWebError* error)
6532 {
6533 #if ENABLE(CLIENT_BASED_GEOLOCATION)
6534     if (!m_page)
6535         return E_FAIL;
6536     if (!error)
6537         return E_POINTER;
6538
6539     BSTR descriptionBSTR;
6540     if (FAILED(error->localizedDescription(&descriptionBSTR)))
6541         return E_FAIL;
6542     String descriptionString(descriptionBSTR, SysStringLen(descriptionBSTR));
6543     SysFreeString(descriptionBSTR);
6544
6545     RefPtr<GeolocationError> geolocationError = GeolocationError::create(GeolocationError::PositionUnavailable, descriptionString);
6546     m_page->geolocationController()->errorOccurred(geolocationError.get());
6547     return S_OK;
6548 #else
6549     return E_NOTIMPL;
6550 #endif
6551 }
6552
6553 HRESULT WebView::setDomainRelaxationForbiddenForURLScheme(BOOL forbidden, BSTR scheme)
6554 {
6555     SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme, SysStringLen(scheme)));
6556     return S_OK;
6557 }
6558
6559 HRESULT WebView::registerURLSchemeAsSecure(BSTR scheme)
6560 {
6561     SchemeRegistry::registerURLSchemeAsSecure(toString(scheme));
6562     return S_OK;
6563 }
6564
6565 HRESULT WebView::nextDisplayIsSynchronous()
6566 {
6567     m_nextDisplayIsSynchronous = true;
6568     return S_OK;
6569 }
6570
6571 #if USE(ACCELERATED_COMPOSITING)
6572 void WebView::notifyAnimationStarted(const GraphicsLayer*, double)
6573 {
6574     // We never set any animations on our backing layer.
6575     ASSERT_NOT_REACHED();
6576 }
6577
6578 void WebView::notifySyncRequired(const GraphicsLayer*)
6579 {
6580     flushPendingGraphicsLayerChangesSoon();
6581 }
6582
6583 void WebView::paintContents(const GraphicsLayer*, GraphicsContext& context, GraphicsLayerPaintingPhase, const IntRect& inClip)
6584 {
6585     Frame* frame = core(m_mainFrame);
6586     if (!frame)
6587         return;
6588
6589     context.save();
6590     context.clip(inClip);
6591     frame->view()->paint(&context, inClip);
6592     context.restore();
6593 }
6594
6595 bool WebView::showDebugBorders() const
6596 {
6597     return m_page->settings()->showDebugBorders();
6598 }
6599
6600 bool WebView::showRepaintCounter() const
6601 {
6602     return m_page->settings()->showRepaintCounter();
6603 }
6604
6605 void WebView::flushPendingGraphicsLayerChanges()
6606 {
6607     Frame* coreFrame = core(m_mainFrame);
6608     if (!coreFrame)
6609         return;
6610     FrameView* view = coreFrame->view();
6611     if (!view)
6612         return;
6613     if (!m_backingLayer)
6614         return;
6615
6616     view->updateLayoutAndStyleIfNeededRecursive();
6617
6618     // Updating layout might have taken us out of compositing mode.
6619     if (m_backingLayer)
6620         m_backingLayer->syncCompositingStateForThisLayerOnly();
6621
6622     view->syncCompositingStateIncludingSubframes();
6623 }
6624
6625 #endif
6626
6627 class EnumTextMatches : public IEnumTextMatches
6628 {
6629     long m_ref;
6630     UINT m_index;
6631     Vector<IntRect> m_rects;
6632 public:
6633     EnumTextMatches(Vector<IntRect>* rects) : m_index(0), m_ref(1)
6634     {
6635         m_rects = *rects;
6636     }
6637
6638     virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv)
6639     {
6640         if (IsEqualGUID(riid, IID_IUnknown) || IsEqualGUID(riid, IID_IEnumTextMatches)) {
6641             *ppv = this;
6642             AddRef();
6643         }
6644
6645         return *ppv?S_OK:E_NOINTERFACE;
6646     }
6647
6648     virtual ULONG STDMETHODCALLTYPE AddRef()
6649     {
6650         return m_ref++;
6651     }
6652     
6653     virtual ULONG STDMETHODCALLTYPE Release()
6654     {
6655         if (m_ref == 1) {
6656             delete this;
6657             return 0;
6658         }
6659         else
6660             return m_ref--;
6661     }
6662
6663     virtual HRESULT STDMETHODCALLTYPE Next(ULONG, RECT* rect, ULONG* pceltFetched)
6664     {
6665         if (m_index < m_rects.size()) {
6666             if (pceltFetched)
6667                 *pceltFetched = 1;
6668             *rect = m_rects[m_index];
6669             m_index++;
6670             return S_OK;
6671         }
6672
6673         if (pceltFetched)
6674             *pceltFetched = 0;
6675
6676         return S_FALSE;
6677     }
6678     virtual HRESULT STDMETHODCALLTYPE Skip(ULONG celt)
6679     {
6680         m_index += celt;
6681         return S_OK;
6682     }
6683     virtual HRESULT STDMETHODCALLTYPE Reset(void)
6684     {
6685         m_index = 0;
6686         return S_OK;
6687     }
6688     virtual HRESULT STDMETHODCALLTYPE Clone(IEnumTextMatches**)
6689     {
6690         return E_NOTIMPL;
6691     }
6692 };
6693
6694 HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches)
6695 {
6696     *matches = new EnumTextMatches(rects);
6697     return (*matches)?S_OK:E_OUTOFMEMORY;
6698 }
6699
6700 Page* core(IWebView* iWebView)
6701 {
6702     Page* page = 0;
6703
6704     COMPtr<WebView> webView;
6705     if (SUCCEEDED(iWebView->QueryInterface(&webView)) && webView)
6706         page = webView->page();
6707
6708     return page;
6709 }
6710
6711 HRESULT WebView::defaultMinimumTimerInterval(double* interval)
6712 {
6713     if (!interval)
6714         return E_POINTER;
6715     *interval = Settings::defaultMinDOMTimerInterval();
6716     return S_OK;
6717 }
6718
6719 HRESULT WebView::setMinimumTimerInterval(double interval)
6720 {
6721     page()->settings()->setMinDOMTimerInterval(interval);
6722     return S_OK;
6723 }
6724
6725 HRESULT WebView::httpPipeliningEnabled(BOOL* enabled)
6726 {
6727     if (!enabled)
6728         return E_POINTER;
6729     *enabled = ResourceRequest::httpPipeliningEnabled();
6730     return S_OK;
6731 }
6732
6733 HRESULT WebView::setHTTPPipeliningEnabled(BOOL enabled)
6734 {
6735     ResourceRequest::setHTTPPipeliningEnabled(enabled);
6736     return S_OK;
6737 }
6738
6739 void WebView::setGlobalHistoryItem(HistoryItem* historyItem)
6740 {
6741     m_globalHistoryItem = historyItem;
6742 }
6743
6744 #if ENABLE(FULLSCREEN_API)
6745 bool WebView::supportsFullScreenForElement(const WebCore::Element*, bool withKeyboard) const
6746 {
6747     if (withKeyboard)
6748         return false;
6749
6750     BOOL enabled = FALSE;
6751     if (!m_preferences || FAILED(m_preferences->isFullScreenEnabled(&enabled)))
6752         return false;
6753
6754     return enabled;
6755 }
6756
6757 bool WebView::isFullScreen() const 
6758 {
6759     return m_fullscreenController && m_fullscreenController->isFullScreen();
6760 }
6761
6762 FullScreenController* WebView::fullScreenController()
6763 {
6764     if (!m_fullscreenController)
6765         m_fullscreenController = adoptPtr(new FullScreenController(this));
6766     return m_fullscreenController.get();
6767 }
6768
6769 void WebView::setFullScreenElement(PassRefPtr<Element> element)
6770 {
6771     m_fullScreenElement = element;
6772 }
6773
6774 HWND WebView::fullScreenClientWindow() const
6775 {
6776     return m_viewWindow;
6777 }
6778
6779 HWND WebView::fullScreenClientParentWindow() const
6780 {
6781     return m_hostWindow;
6782 }
6783
6784 void WebView::fullScreenClientSetParentWindow(HWND hostWindow)
6785 {
6786     setHostWindow(reinterpret_cast<OLE_HANDLE>(hostWindow));
6787 }
6788
6789 void WebView::fullScreenClientWillEnterFullScreen()
6790 {
6791     ASSERT(m_fullScreenElement);
6792     m_fullScreenElement->document()->webkitWillEnterFullScreenForElement(m_fullScreenElement.get());
6793 }
6794
6795 void WebView::fullScreenClientDidEnterFullScreen()
6796 {
6797     ASSERT(m_fullScreenElement);
6798     m_fullScreenElement->document()->webkitDidEnterFullScreenForElement(m_fullScreenElement.get());
6799 }
6800
6801 void WebView::fullScreenClientWillExitFullScreen()
6802 {
6803     ASSERT(m_fullScreenElement);
6804     m_fullScreenElement->document()->webkitWillExitFullScreenForElement(m_fullScreenElement.get());
6805 }
6806
6807 void WebView::fullScreenClientDidExitFullScreen()
6808 {
6809     ASSERT(m_fullScreenElement);
6810     m_fullScreenElement->document()->webkitDidExitFullScreenForElement(m_fullScreenElement.get());
6811     m_fullScreenElement = nullptr;
6812 }
6813
6814 void WebView::fullScreenClientForceRepaint()
6815 {
6816     ASSERT(m_fullScreenElement);
6817     RECT windowRect = {0};
6818     frameRect(&windowRect);
6819     repaint(windowRect, true /*contentChanged*/, true /*immediate*/, false /*contentOnly*/);
6820     m_fullscreenController->repaintCompleted();
6821 }
6822
6823 #endif