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