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