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