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