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