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