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