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