2 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple, Inc. All rights reserved.
3 * Copyright (C) 2009, 2010, 2011 Appcelerator, Inc. All rights reserved.
4 * Copyright (C) 2011 Brent Fulgham. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
16 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
19 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include "CFDictionaryPropertyBag.h"
32 #include "DOMCoreClasses.h"
33 #include "FullscreenVideoController.h"
34 #include "MarshallingHelpers.h"
35 #include "SoftLinking.h"
36 #include "WebBackForwardList.h"
37 #include "WebChromeClient.h"
38 #include "WebContextMenuClient.h"
39 #include "WebCoreTextRenderer.h"
40 #include "WebDatabaseManager.h"
41 #include "WebDocumentLoader.h"
42 #include "WebDownload.h"
43 #include "WebDragClient.h"
44 #include "WebEditorClient.h"
45 #include "WebElementPropertyBag.h"
47 #include "WebGeolocationClient.h"
48 #include "WebGeolocationPosition.h"
49 #include "WebIconDatabase.h"
50 #include "WebInspector.h"
51 #include "WebInspectorClient.h"
53 #include "WebKitDLL.h"
54 #include "WebKitLogging.h"
55 #include "WebKitStatisticsPrivate.h"
56 #include "WebKitSystemBits.h"
57 #include "WebMutableURLRequest.h"
58 #include "WebNotificationCenter.h"
59 #include "WebPlatformStrategies.h"
60 #include "WebPluginHalterClient.h"
61 #include "WebPreferences.h"
62 #include "WebScriptWorld.h"
64 #include <JavaScriptCore/APICast.h>
65 #include <JavaScriptCore/InitializeThreading.h>
66 #include <JavaScriptCore/JSLock.h>
67 #include <JavaScriptCore/JSValue.h>
68 #include <WebCore/AbstractDatabase.h>
69 #include <WebCore/AXObjectCache.h>
70 #include <WebCore/ApplicationCacheStorage.h>
71 #include <WebCore/BString.h>
72 #include <WebCore/BackForwardListImpl.h>
73 #include <WebCore/BitmapInfo.h>
74 #include <WebCore/MemoryCache.h>
75 #include <WebCore/Chrome.h>
76 #include <WebCore/ContextMenu.h>
77 #include <WebCore/ContextMenuController.h>
78 #include <WebCore/Cursor.h>
79 #include <WebCore/Document.h>
80 #include <WebCore/DocumentMarkerController.h>
81 #include <WebCore/DragController.h>
82 #include <WebCore/DragData.h>
83 #include <WebCore/Editor.h>
84 #include <WebCore/EventHandler.h>
85 #include <WebCore/EventNames.h>
86 #include <WebCore/FileSystem.h>
87 #include <WebCore/FloatQuad.h>
88 #include <WebCore/FocusController.h>
89 #include <WebCore/FrameLoader.h>
90 #include <WebCore/FrameSelection.h>
91 #include <WebCore/FrameTree.h>
92 #include <WebCore/FrameView.h>
93 #include <WebCore/FrameWin.h>
94 #include <WebCore/GDIObjectCounter.h>
95 #include <WebCore/GraphicsContext.h>
96 #include <WebCore/HTMLMediaElement.h>
97 #include <WebCore/HTMLNames.h>
98 #include <WebCore/HistoryItem.h>
99 #include <WebCore/HitTestRequest.h>
100 #include <WebCore/HitTestResult.h>
101 #include <WebCore/IntRect.h>
102 #include <WebCore/JSElement.h>
103 #include <WebCore/KeyboardEvent.h>
104 #include <WebCore/Logging.h>
105 #include <WebCore/MIMETypeRegistry.h>
106 #include <WebCore/Page.h>
107 #include <WebCore/PageCache.h>
108 #include <WebCore/PageGroup.h>
109 #include <WebCore/PlatformKeyboardEvent.h>
110 #include <WebCore/PlatformMouseEvent.h>
111 #include <WebCore/PlatformWheelEvent.h>
112 #include <WebCore/PluginData.h>
113 #include <WebCore/PluginDatabase.h>
114 #include <WebCore/PluginView.h>
115 #include <WebCore/PopupMenu.h>
116 #include <WebCore/PopupMenuWin.h>
117 #include <WebCore/ProgressTracker.h>
118 #include <WebCore/RenderLayer.h>
119 #include <WebCore/RenderTheme.h>
120 #include <WebCore/RenderTreeAsText.h>
121 #include <WebCore/RenderView.h>
122 #include <WebCore/RenderWidget.h>
123 #include <WebCore/ResourceHandle.h>
124 #include <WebCore/ResourceHandleClient.h>
125 #include <WebCore/ResourceRequest.h>
126 #include <WebCore/SchemeRegistry.h>
127 #include <WebCore/ScriptValue.h>
128 #include <WebCore/Scrollbar.h>
129 #include <WebCore/ScrollbarTheme.h>
130 #include <WebCore/SecurityOrigin.h>
131 #include <WebCore/Settings.h>
132 #include <WebCore/SimpleFontData.h>
133 #include <WebCore/SystemInfo.h>
134 #include <WebCore/TypingCommand.h>
135 #include <WebCore/WindowMessageBroadcaster.h>
136 #include <WebCore/WindowsTouch.h>
137 #include <wtf/Threading.h>
139 #if ENABLE(CLIENT_BASED_GEOLOCATION)
140 #include <WebCore/GeolocationController.h>
141 #include <WebCore/GeolocationError.h>
145 #include <CoreGraphics/CGContext.h>
149 #include <CoreFoundation/CoreFoundation.h>
153 #include <CFNetwork/CFURLCachePriv.h>
154 #include <CFNetwork/CFURLProtocolPriv.h>
155 #include <WebCore/CookieStorageCFNet.h>
156 #include <WebKitSystemInterface/WebKitSystemInterface.h>
159 #if USE(ACCELERATED_COMPOSITING)
160 #include <WebCore/CACFLayerTreeHost.h>
161 #include <WebCore/PlatformCALayer.h>
164 #if ENABLE(FULLSCREEN_API)
165 #include <WebCore/FullScreenController.h>
173 #include <windowsx.h>
174 #include <wtf/HashSet.h>
175 #include <wtf/text/CString.h>
176 #include <wtf/text/StringConcatenate.h>
178 // Soft link functions for gestures and panning feedback
179 SOFT_LINK_LIBRARY(USER32);
180 SOFT_LINK_OPTIONAL(USER32, GetGestureInfo, BOOL, WINAPI, (HGESTUREINFO, PGESTUREINFO));
181 SOFT_LINK_OPTIONAL(USER32, SetGestureConfig, BOOL, WINAPI, (HWND, DWORD, UINT, PGESTURECONFIG, UINT));
182 SOFT_LINK_OPTIONAL(USER32, CloseGestureInfoHandle, BOOL, WINAPI, (HGESTUREINFO));
183 SOFT_LINK_LIBRARY(Uxtheme);
184 SOFT_LINK_OPTIONAL(Uxtheme, BeginPanningFeedback, BOOL, WINAPI, (HWND));
185 SOFT_LINK_OPTIONAL(Uxtheme, EndPanningFeedback, BOOL, WINAPI, (HWND, BOOL));
186 SOFT_LINK_OPTIONAL(Uxtheme, UpdatePanningFeedback, BOOL, WINAPI, (HWND, LONG, LONG, BOOL));
188 using namespace WebCore;
192 static HMODULE accessibilityLib;
193 static HashSet<WebView*> pendingDeleteBackingStoreSet;
195 static String webKitVersionString();
197 WebView* kit(Page* page)
199 return page ? static_cast<WebView*>(static_cast<WebChromeClient*>(page->chrome()->client())->webView()) : 0;
202 class PreferencesChangedOrRemovedObserver : public IWebNotificationObserver {
204 static PreferencesChangedOrRemovedObserver* sharedInstance();
207 PreferencesChangedOrRemovedObserver() {}
208 ~PreferencesChangedOrRemovedObserver() {}
210 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) { return E_FAIL; }
211 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; }
212 virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; }
215 // IWebNotificationObserver
216 virtual HRESULT STDMETHODCALLTYPE onNotify(
217 /* [in] */ IWebNotification* notification);
220 HRESULT notifyPreferencesChanged(WebCacheModel);
221 HRESULT notifyPreferencesRemoved(WebCacheModel);
224 PreferencesChangedOrRemovedObserver* PreferencesChangedOrRemovedObserver::sharedInstance()
226 static PreferencesChangedOrRemovedObserver* shared = new PreferencesChangedOrRemovedObserver;
230 HRESULT PreferencesChangedOrRemovedObserver::onNotify(IWebNotification* notification)
234 COMPtr<IUnknown> unkPrefs;
235 hr = notification->getObject(&unkPrefs);
239 COMPtr<IWebPreferences> preferences(Query, unkPrefs);
241 return E_NOINTERFACE;
243 WebCacheModel cacheModel;
244 hr = preferences->cacheModel(&cacheModel);
249 hr = notification->name(&nameBSTR);
253 name.adoptBSTR(nameBSTR);
255 if (wcscmp(name, WebPreferences::webPreferencesChangedNotification()) == 0)
256 return notifyPreferencesChanged(cacheModel);
258 if (wcscmp(name, WebPreferences::webPreferencesRemovedNotification()) == 0)
259 return notifyPreferencesRemoved(cacheModel);
261 ASSERT_NOT_REACHED();
265 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesChanged(WebCacheModel cacheModel)
269 if (!WebView::didSetCacheModel() || cacheModel > WebView::cacheModel())
270 WebView::setCacheModel(cacheModel);
271 else if (cacheModel < WebView::cacheModel()) {
272 WebCacheModel sharedPreferencesCacheModel;
273 hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
276 WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
282 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesRemoved(WebCacheModel cacheModel)
286 if (cacheModel == WebView::cacheModel()) {
287 WebCacheModel sharedPreferencesCacheModel;
288 hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
291 WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
298 const LPCWSTR kWebViewWindowClassName = L"WebViewWindowClass";
300 const int WM_XP_THEMECHANGED = 0x031A;
301 const int WM_VISTA_MOUSEHWHEEL = 0x020E;
303 static const int maxToolTipWidth = 250;
305 static const int delayBeforeDeletingBackingStoreMsec = 5000;
307 static ATOM registerWebView();
309 static void initializeStaticObservers();
311 static HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences*);
313 HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches);
315 static bool continuousSpellCheckingEnabled;
316 static bool grammarCheckingEnabled;
318 static bool s_didSetCacheModel;
319 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
322 UpdateActiveStateTimer = 1,
323 DeleteBackingStoreTimer = 2,
326 // WebView ----------------------------------------------------------------
328 bool WebView::s_allowSiteSpecificHacks = false;
333 , m_deletionHasBegun(false)
339 , m_hasCustomDropTarget(false)
340 , m_useBackForwardList(true)
341 , m_userAgentOverridden(false)
342 , m_zoomMultiplier(1.0f)
343 , m_zoomsTextOnly(false)
344 , m_mouseActivated(false)
346 , m_currentCharacterCode(0)
347 , m_isBeingDestroyed(false)
349 , m_hasSpellCheckerDocumentTag(false)
350 , m_smartInsertDeleteEnabled(false)
352 , m_inIMEComposition(0)
354 , m_closeWindowTimer(0)
355 , m_topLevelParent(0)
356 , m_deleteBackingStoreTimerActive(false)
357 , m_transparent(false)
358 , m_selectTrailingWhitespaceEnabled(false)
363 #if USE(ACCELERATED_COMPOSITING)
364 , m_isAcceleratedCompositing(false)
366 , m_nextDisplayIsSynchronous(false)
368 , m_usesLayeredWindow(false)
370 JSC::initializeThreading();
371 WTF::initializeMainThread();
373 m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
375 CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper,(void**)&m_dropTargetHelper);
377 initializeStaticObservers();
379 WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
381 if (SUCCEEDED(sharedPreferences->continuousSpellCheckingEnabled(&enabled)))
382 continuousSpellCheckingEnabled = !!enabled;
383 if (SUCCEEDED(sharedPreferences->grammarCheckingEnabled(&enabled)))
384 grammarCheckingEnabled = !!enabled;
388 gClassNameCount.add("WebView");
393 deleteBackingStore();
395 // the tooltip window needs to be explicitly destroyed since it isn't a WS_CHILD
396 if (::IsWindow(m_toolTipHwnd))
397 ::DestroyWindow(m_toolTipHwnd);
400 ASSERT(!m_preferences);
401 ASSERT(!m_viewWindow);
403 #if USE(ACCELERATED_COMPOSITING)
404 ASSERT(!m_layerTreeHost);
405 ASSERT(!m_backingLayer);
410 gClassNameCount.remove("WebView");
413 WebView* WebView::createInstance()
415 WebView* instance = new WebView();
420 void initializeStaticObservers()
422 static bool initialized;
427 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
428 notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesChangedNotification(), 0);
429 notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesRemovedNotification(), 0);
432 static HashSet<WebView*>& allWebViewsSet()
434 static HashSet<WebView*> allWebViewsSet;
435 return allWebViewsSet;
438 void WebView::addToAllWebViewsSet()
440 allWebViewsSet().add(this);
443 void WebView::removeFromAllWebViewsSet()
445 allWebViewsSet().remove(this);
448 void WebView::setCacheModel(WebCacheModel cacheModel)
451 if (s_didSetCacheModel && cacheModel == s_cacheModel)
454 RetainPtr<CFURLCacheRef> cfurlCache(AdoptCF, CFURLCacheCopySharedURLCache());
455 RetainPtr<CFStringRef> cfurlCacheDirectory(AdoptCF, wkCopyFoundationCacheDirectory(0));
456 if (!cfurlCacheDirectory)
457 cfurlCacheDirectory.adoptCF(WebCore::localUserSpecificStorageDirectory().createCFString());
459 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
460 // count doesn't align exactly to a megabyte boundary.
461 unsigned long long memSize = WebMemorySize() / 1024 / 1000;
462 unsigned long long diskFreeSize = WebVolumeFreeSize(cfurlCacheDirectory.get()) / 1024 / 1000;
464 unsigned cacheTotalCapacity = 0;
465 unsigned cacheMinDeadCapacity = 0;
466 unsigned cacheMaxDeadCapacity = 0;
467 double deadDecodedDataDeletionInterval = 0;
469 unsigned pageCacheCapacity = 0;
471 CFIndex cfurlCacheMemoryCapacity = 0;
472 CFIndex cfurlCacheDiskCapacity = 0;
474 switch (cacheModel) {
475 case WebCacheModelDocumentViewer: {
476 // Page cache capacity (in pages)
477 pageCacheCapacity = 0;
479 // Object cache capacities (in bytes)
481 cacheTotalCapacity = 96 * 1024 * 1024;
482 else if (memSize >= 1536)
483 cacheTotalCapacity = 64 * 1024 * 1024;
484 else if (memSize >= 1024)
485 cacheTotalCapacity = 32 * 1024 * 1024;
486 else if (memSize >= 512)
487 cacheTotalCapacity = 16 * 1024 * 1024;
489 cacheMinDeadCapacity = 0;
490 cacheMaxDeadCapacity = 0;
492 // Foundation memory cache capacity (in bytes)
493 cfurlCacheMemoryCapacity = 0;
495 // Foundation disk cache capacity (in bytes)
496 cfurlCacheDiskCapacity = CFURLCacheDiskCapacity(cfurlCache.get());
500 case WebCacheModelDocumentBrowser: {
501 // Page cache capacity (in pages)
503 pageCacheCapacity = 3;
504 else if (memSize >= 512)
505 pageCacheCapacity = 2;
506 else if (memSize >= 256)
507 pageCacheCapacity = 1;
509 pageCacheCapacity = 0;
511 // Object cache capacities (in bytes)
513 cacheTotalCapacity = 96 * 1024 * 1024;
514 else if (memSize >= 1536)
515 cacheTotalCapacity = 64 * 1024 * 1024;
516 else if (memSize >= 1024)
517 cacheTotalCapacity = 32 * 1024 * 1024;
518 else if (memSize >= 512)
519 cacheTotalCapacity = 16 * 1024 * 1024;
521 cacheMinDeadCapacity = cacheTotalCapacity / 8;
522 cacheMaxDeadCapacity = cacheTotalCapacity / 4;
524 // Foundation memory cache capacity (in bytes)
526 cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
527 else if (memSize >= 1024)
528 cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
529 else if (memSize >= 512)
530 cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
532 cfurlCacheMemoryCapacity = 512 * 1024;
534 // Foundation disk cache capacity (in bytes)
535 if (diskFreeSize >= 16384)
536 cfurlCacheDiskCapacity = 50 * 1024 * 1024;
537 else if (diskFreeSize >= 8192)
538 cfurlCacheDiskCapacity = 40 * 1024 * 1024;
539 else if (diskFreeSize >= 4096)
540 cfurlCacheDiskCapacity = 30 * 1024 * 1024;
542 cfurlCacheDiskCapacity = 20 * 1024 * 1024;
546 case WebCacheModelPrimaryWebBrowser: {
547 // Page cache capacity (in pages)
548 // (Research indicates that value / page drops substantially after 3 pages.)
550 pageCacheCapacity = 5;
551 else if (memSize >= 1024)
552 pageCacheCapacity = 4;
553 else if (memSize >= 512)
554 pageCacheCapacity = 3;
555 else if (memSize >= 256)
556 pageCacheCapacity = 2;
558 pageCacheCapacity = 1;
560 // Object cache capacities (in bytes)
561 // (Testing indicates that value / MB depends heavily on content and
562 // browsing pattern. Even growth above 128MB can have substantial
563 // value / MB for some content / browsing patterns.)
565 cacheTotalCapacity = 128 * 1024 * 1024;
566 else if (memSize >= 1536)
567 cacheTotalCapacity = 96 * 1024 * 1024;
568 else if (memSize >= 1024)
569 cacheTotalCapacity = 64 * 1024 * 1024;
570 else if (memSize >= 512)
571 cacheTotalCapacity = 32 * 1024 * 1024;
573 cacheMinDeadCapacity = cacheTotalCapacity / 4;
574 cacheMaxDeadCapacity = cacheTotalCapacity / 2;
576 // This code is here to avoid a PLT regression. We can remove it if we
577 // can prove that the overall system gain would justify the regression.
578 cacheMaxDeadCapacity = max(24u, cacheMaxDeadCapacity);
580 deadDecodedDataDeletionInterval = 60;
582 // Foundation memory cache capacity (in bytes)
583 // (These values are small because WebCore does most caching itself.)
585 cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
586 else if (memSize >= 512)
587 cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
588 else if (memSize >= 256)
589 cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
591 cfurlCacheMemoryCapacity = 512 * 1024;
593 // Foundation disk cache capacity (in bytes)
594 if (diskFreeSize >= 16384)
595 cfurlCacheDiskCapacity = 175 * 1024 * 1024;
596 else if (diskFreeSize >= 8192)
597 cfurlCacheDiskCapacity = 150 * 1024 * 1024;
598 else if (diskFreeSize >= 4096)
599 cfurlCacheDiskCapacity = 125 * 1024 * 1024;
600 else if (diskFreeSize >= 2048)
601 cfurlCacheDiskCapacity = 100 * 1024 * 1024;
602 else if (diskFreeSize >= 1024)
603 cfurlCacheDiskCapacity = 75 * 1024 * 1024;
605 cfurlCacheDiskCapacity = 50 * 1024 * 1024;
610 ASSERT_NOT_REACHED();
613 // Don't shrink a big disk cache, since that would cause churn.
614 cfurlCacheDiskCapacity = max(cfurlCacheDiskCapacity, CFURLCacheDiskCapacity(cfurlCache.get()));
616 memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
617 memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
618 pageCache()->setCapacity(pageCacheCapacity);
620 CFURLCacheSetMemoryCapacity(cfurlCache.get(), cfurlCacheMemoryCapacity);
621 CFURLCacheSetDiskCapacity(cfurlCache.get(), cfurlCacheDiskCapacity);
623 s_didSetCacheModel = true;
624 s_cacheModel = cacheModel;
629 WebCacheModel WebView::cacheModel()
634 bool WebView::didSetCacheModel()
636 return s_didSetCacheModel;
639 WebCacheModel WebView::maxCacheModelInAnyInstance()
641 WebCacheModel cacheModel = WebCacheModelDocumentViewer;
643 HashSet<WebView*>::iterator end = allWebViewsSet().end();
644 for (HashSet<WebView*>::iterator it = allWebViewsSet().begin(); it != end; ++it) {
645 COMPtr<IWebPreferences> pref;
646 if (FAILED((*it)->preferences(&pref)))
648 WebCacheModel prefCacheModel = WebCacheModelDocumentViewer;
649 if (FAILED(pref->cacheModel(&prefCacheModel)))
652 cacheModel = max(cacheModel, prefCacheModel);
658 HRESULT STDMETHODCALLTYPE WebView::close()
665 #if USE(ACCELERATED_COMPOSITING)
666 setAcceleratedCompositing(false);
669 WebNotificationCenter::defaultCenterInternal()->postNotificationName(_bstr_t(WebViewWillCloseNotification).GetBSTR(), static_cast<IWebView*>(this), 0);
671 if (m_uiDelegatePrivate)
672 m_uiDelegatePrivate->webViewClosing(this);
674 removeFromAllWebViewsSet();
677 if (Frame* frame = m_page->mainFrame())
678 frame->loader()->detachFromParent();
681 if (m_mouseOutTracker) {
682 m_mouseOutTracker->dwFlags = TME_CANCEL;
683 ::TrackMouseEvent(m_mouseOutTracker.get());
684 m_mouseOutTracker.clear();
690 // We can't check IsWindow(m_viewWindow) here, because that will return true even while
691 // we're already handling WM_DESTROY. So we check !isBeingDestroyed() instead.
692 if (!isBeingDestroyed())
693 DestroyWindow(m_viewWindow);
694 // Either we just destroyed m_viewWindow, or it's in the process of being destroyed. Either
695 // way, we clear it out to make sure we don't try to use it later.
701 setDownloadDelegate(0);
702 setEditingDelegate(0);
703 setFrameLoadDelegate(0);
704 setFrameLoadDelegatePrivate(0);
705 setHistoryDelegate(0);
706 setPolicyDelegate(0);
707 setResourceLoadDelegate(0);
710 setPluginHalterDelegate(0);
713 m_webInspector->webViewClosed();
718 registerForIconNotification(false);
719 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
720 notifyCenter->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
722 if (COMPtr<WebPreferences> preferences = m_preferences) {
724 preferences->identifier(&identifier);
727 preferences->didRemoveFromWebView();
728 // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
731 WebPreferences::removeReferenceForIdentifier(identifier);
732 SysFreeString(identifier);
736 deleteBackingStore();
740 void WebView::repaint(const WebCore::IntRect& windowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
742 #if USE(ACCELERATED_COMPOSITING)
743 if (isAcceleratedCompositing()) {
744 // The contentChanged, immediate, and repaintContentOnly parameters are all based on a non-
745 // compositing painting/scrolling model.
746 addToDirtyRegion(windowRect);
751 if (!repaintContentOnly) {
752 RECT rect = windowRect;
753 ::InvalidateRect(m_viewWindow, &rect, false);
756 addToDirtyRegion(windowRect);
758 if (repaintContentOnly)
759 updateBackingStore(core(topLevelFrame())->view());
761 ::UpdateWindow(m_viewWindow);
765 void WebView::deleteBackingStore()
767 pendingDeleteBackingStoreSet.remove(this);
769 if (m_deleteBackingStoreTimerActive) {
770 KillTimer(m_viewWindow, DeleteBackingStoreTimer);
771 m_deleteBackingStoreTimerActive = false;
773 m_backingStoreBitmap.clear();
774 m_backingStoreDirtyRegion.clear();
775 m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
778 bool WebView::ensureBackingStore()
781 ::GetClientRect(m_viewWindow, &windowRect);
782 LONG width = windowRect.right - windowRect.left;
783 LONG height = windowRect.bottom - windowRect.top;
784 if (width > 0 && height > 0 && (width != m_backingStoreSize.cx || height != m_backingStoreSize.cy)) {
785 deleteBackingStore();
787 m_backingStoreSize.cx = width;
788 m_backingStoreSize.cy = height;
789 BitmapInfo bitmapInfo = BitmapInfo::createBottomUp(IntSize(m_backingStoreSize));
792 m_backingStoreBitmap = RefCountedHBITMAP::create(::CreateDIBSection(0, &bitmapInfo, DIB_RGB_COLORS, &pixels, 0, 0));
799 void WebView::addToDirtyRegion(const IntRect& dirtyRect)
801 // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
802 // but it was being hit during our layout tests, and is being investigated in
803 // http://webkit.org/b/29350.
805 #if USE(ACCELERATED_COMPOSITING)
806 if (isAcceleratedCompositing()) {
807 m_backingLayer->setNeedsDisplayInRect(dirtyRect);
812 HRGN newRegion = ::CreateRectRgn(dirtyRect.x(), dirtyRect.y(),
813 dirtyRect.maxX(), dirtyRect.maxY());
814 addToDirtyRegion(newRegion);
817 void WebView::addToDirtyRegion(HRGN newRegion)
819 #if USE(ACCELERATED_COMPOSITING)
820 ASSERT(!isAcceleratedCompositing());
823 LOCAL_GDI_COUNTER(0, __FUNCTION__);
825 if (m_backingStoreDirtyRegion) {
826 HRGN combinedRegion = ::CreateRectRgn(0,0,0,0);
827 ::CombineRgn(combinedRegion, m_backingStoreDirtyRegion->handle(), newRegion, RGN_OR);
828 ::DeleteObject(newRegion);
829 m_backingStoreDirtyRegion = RefCountedHRGN::create(combinedRegion);
831 m_backingStoreDirtyRegion = RefCountedHRGN::create(newRegion);
833 if (m_uiDelegatePrivate)
834 m_uiDelegatePrivate->webViewDidInvalidate(this);
837 void WebView::scrollBackingStore(FrameView* frameView, int dx, int dy, const IntRect& scrollViewRect, const IntRect& clipRect)
839 #if USE(ACCELERATED_COMPOSITING)
840 if (isAcceleratedCompositing()) {
841 // FIXME: We should be doing something smarter here, like moving tiles around and painting
842 // any newly-exposed tiles. <http://webkit.org/b/52714>
843 m_backingLayer->setNeedsDisplayInRect(scrollViewRect);
848 LOCAL_GDI_COUNTER(0, __FUNCTION__);
850 // If there's no backing store we don't need to update it
851 if (!m_backingStoreBitmap) {
852 if (m_uiDelegatePrivate)
853 m_uiDelegatePrivate->webViewScrolled(this);
858 // Make a region to hold the invalidated scroll area.
859 HRGN updateRegion = ::CreateRectRgn(0, 0, 0, 0);
861 // Collect our device context info and select the bitmap to scroll.
862 HDC windowDC = ::GetDC(m_viewWindow);
863 HDC bitmapDC = ::CreateCompatibleDC(windowDC);
864 HGDIOBJ oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
866 // Scroll the bitmap.
867 RECT scrollRectWin(scrollViewRect);
868 RECT clipRectWin(clipRect);
869 ::ScrollDC(bitmapDC, dx, dy, &scrollRectWin, &clipRectWin, updateRegion, 0);
871 ::GetRgnBox(updateRegion, ®ionBox);
876 // Add the dirty region to the backing store's dirty region.
877 addToDirtyRegion(updateRegion);
879 if (m_uiDelegatePrivate)
880 m_uiDelegatePrivate->webViewScrolled(this);
882 // Update the backing store.
883 updateBackingStore(frameView, bitmapDC, false);
886 ::SelectObject(bitmapDC, oldBitmap);
887 ::DeleteDC(bitmapDC);
888 ::ReleaseDC(m_viewWindow, windowDC);
891 void WebView::sizeChanged(const IntSize& newSize)
893 deleteBackingStore();
895 if (Frame* coreFrame = core(topLevelFrame()))
896 coreFrame->view()->resize(newSize);
898 #if USE(ACCELERATED_COMPOSITING)
900 m_layerTreeHost->resize();
901 if (m_backingLayer) {
902 m_backingLayer->setSize(newSize);
903 m_backingLayer->setNeedsDisplay();
908 // This emulates the Mac smarts for painting rects intelligently. This is very
909 // important for us, since we double buffer based off dirty rects.
910 static void getUpdateRects(HRGN region, const IntRect& dirtyRect, Vector<IntRect>& rects)
912 ASSERT_ARG(region, region);
914 const int cRectThreshold = 10;
915 const float cWastedSpaceThreshold = 0.75f;
919 DWORD regionDataSize = GetRegionData(region, sizeof(RGNDATA), NULL);
920 if (!regionDataSize) {
921 rects.append(dirtyRect);
925 Vector<unsigned char> buffer(regionDataSize);
926 RGNDATA* regionData = reinterpret_cast<RGNDATA*>(buffer.data());
927 GetRegionData(region, regionDataSize, regionData);
928 if (regionData->rdh.nCount > cRectThreshold) {
929 rects.append(dirtyRect);
933 double singlePixels = 0.0;
936 for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
937 singlePixels += (rect->right - rect->left) * (rect->bottom - rect->top);
939 double unionPixels = dirtyRect.width() * dirtyRect.height();
940 double wastedSpace = 1.0 - (singlePixels / unionPixels);
941 if (wastedSpace <= cWastedSpaceThreshold) {
942 rects.append(dirtyRect);
946 for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
950 void WebView::updateBackingStore(FrameView* frameView, HDC dc, bool backingStoreCompletelyDirty, WindowsToPaint windowsToPaint)
952 #if USE(ACCELERATED_COMPOSITING)
953 ASSERT(!isAcceleratedCompositing());
956 LOCAL_GDI_COUNTER(0, __FUNCTION__);
960 HGDIOBJ oldBitmap = 0;
962 windowDC = ::GetDC(m_viewWindow);
963 bitmapDC = ::CreateCompatibleDC(windowDC);
964 oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
967 if (m_backingStoreBitmap && (m_backingStoreDirtyRegion || backingStoreCompletelyDirty)) {
968 // Do a layout first so that everything we render to the backing store is always current.
969 if (Frame* coreFrame = core(m_mainFrame))
970 if (FrameView* view = coreFrame->view())
971 view->updateLayoutAndStyleIfNeededRecursive();
973 Vector<IntRect> paintRects;
974 if (!backingStoreCompletelyDirty && m_backingStoreDirtyRegion) {
976 ::GetRgnBox(m_backingStoreDirtyRegion->handle(), ®ionBox);
977 getUpdateRects(m_backingStoreDirtyRegion->handle(), regionBox, paintRects);
980 ::GetClientRect(m_viewWindow, &clientRect);
981 paintRects.append(clientRect);
984 for (unsigned i = 0; i < paintRects.size(); ++i)
985 paintIntoBackingStore(frameView, bitmapDC, paintRects[i], windowsToPaint);
987 if (m_uiDelegatePrivate)
988 m_uiDelegatePrivate->webViewPainted(this);
990 m_backingStoreDirtyRegion.clear();
994 ::SelectObject(bitmapDC, oldBitmap);
995 ::DeleteDC(bitmapDC);
996 ::ReleaseDC(m_viewWindow, windowDC);
1002 void WebView::performLayeredWindowUpdate()
1004 HDC hdcScreen = ::GetDC(m_viewWindow);
1005 OwnPtr<HDC> hdcMem = adoptPtr(::CreateCompatibleDC(hdcScreen));
1006 HBITMAP hbmOld = static_cast<HBITMAP>(::SelectObject(hdcMem.get(), m_backingStoreBitmap->handle()));
1009 ::GetObject(m_backingStoreBitmap->handle(), sizeof(bmpInfo), &bmpInfo);
1010 SIZE windowSize = { bmpInfo.bmWidth, bmpInfo.bmHeight };
1012 BLENDFUNCTION blendFunction;
1013 blendFunction.BlendOp = AC_SRC_OVER;
1014 blendFunction.BlendFlags = 0;
1015 blendFunction.SourceConstantAlpha = 0xFF;
1016 blendFunction.AlphaFormat = AC_SRC_ALPHA;
1018 POINT layerPos = { 0, 0 };
1019 ::UpdateLayeredWindow(m_viewWindow, hdcScreen, 0, &windowSize, hdcMem.get(), &layerPos, 0, &blendFunction, ULW_ALPHA);
1021 ::SelectObject(hdcMem.get(), hbmOld);
1022 ::ReleaseDC(0, hdcScreen);
1025 void WebView::paint(HDC dc, LPARAM options)
1027 LOCAL_GDI_COUNTER(0, __FUNCTION__);
1029 #if USE(ACCELERATED_COMPOSITING)
1030 if (isAcceleratedCompositing() && !usesLayeredWindow()) {
1031 m_layerTreeHost->flushPendingLayerChangesNow();
1032 // Flushing might have taken us out of compositing mode.
1033 if (isAcceleratedCompositing()) {
1034 // FIXME: We need to paint into dc (if provided). <http://webkit.org/b/52578>
1035 m_layerTreeHost->paint();
1036 ::ValidateRect(m_viewWindow, 0);
1042 Frame* coreFrame = core(m_mainFrame);
1045 FrameView* frameView = coreFrame->view();
1049 OwnPtr<HRGN> region;
1050 int regionType = NULLREGION;
1052 WindowsToPaint windowsToPaint;
1054 region = adoptPtr(CreateRectRgn(0,0,0,0));
1055 regionType = GetUpdateRgn(m_viewWindow, region.get(), false);
1056 hdc = BeginPaint(m_viewWindow, &ps);
1057 rcPaint = ps.rcPaint;
1058 // We're painting to the screen, and our child windows can handle
1059 // painting themselves to the screen.
1060 windowsToPaint = PaintWebViewOnly;
1063 ::GetClientRect(m_viewWindow, &rcPaint);
1064 if (options & PRF_ERASEBKGND)
1065 ::FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
1066 // Since we aren't painting to the screen, we want to paint all our
1067 // children into the HDC.
1068 windowsToPaint = PaintWebViewAndChildren;
1071 bool backingStoreCompletelyDirty = ensureBackingStore();
1072 if (!m_backingStoreBitmap) {
1074 EndPaint(m_viewWindow, &ps);
1080 HDC bitmapDC = ::CreateCompatibleDC(hdc);
1081 HGDIOBJ oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
1083 // Update our backing store if needed.
1084 updateBackingStore(frameView, bitmapDC, backingStoreCompletelyDirty, windowsToPaint);
1086 // Now we blit the updated backing store
1087 IntRect windowDirtyRect = rcPaint;
1089 // Apply the same heuristic for this update region too.
1090 Vector<IntRect> blitRects;
1091 if (region && regionType == COMPLEXREGION)
1092 getUpdateRects(region.get(), windowDirtyRect, blitRects);
1094 blitRects.append(windowDirtyRect);
1096 for (unsigned i = 0; i < blitRects.size(); ++i)
1097 paintIntoWindow(bitmapDC, hdc, blitRects[i]);
1099 ::SelectObject(bitmapDC, oldBitmap);
1100 ::DeleteDC(bitmapDC);
1103 EndPaint(m_viewWindow, &ps);
1108 cancelDeleteBackingStoreSoon();
1110 deleteBackingStoreSoon();
1113 void WebView::paintIntoBackingStore(FrameView* frameView, HDC bitmapDC, const IntRect& dirtyRect, WindowsToPaint windowsToPaint)
1115 // FIXME: This function should never be called in accelerated compositing mode, and we should
1116 // assert as such. But currently it *is* sometimes called, so we can't assert yet. See
1117 // <http://webkit.org/b/58539>.
1119 LOCAL_GDI_COUNTER(0, __FUNCTION__);
1121 // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
1122 // but it was being hit during our layout tests, and is being investigated in
1123 // http://webkit.org/b/29350.
1125 RECT rect = dirtyRect;
1127 #if FLASH_BACKING_STORE_REDRAW
1128 HDC dc = ::GetDC(m_viewWindow);
1129 OwnPtr<HBRUSH> yellowBrush(CreateSolidBrush(RGB(255, 255, 0)));
1130 FillRect(dc, &rect, yellowBrush.get());
1133 paintIntoWindow(bitmapDC, dc, dirtyRect);
1134 ::ReleaseDC(m_viewWindow, dc);
1137 GraphicsContext gc(bitmapDC, m_transparent);
1138 gc.setShouldIncludeChildWindows(windowsToPaint == PaintWebViewAndChildren);
1141 gc.clearRect(dirtyRect);
1143 FillRect(bitmapDC, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
1145 COMPtr<IWebUIDelegatePrivate2> uiPrivate(Query, m_uiDelegate);
1147 uiPrivate->drawBackground(this, reinterpret_cast<OLE_HANDLE>(bitmapDC), &rect);
1149 if (frameView && frameView->frame() && frameView->frame()->contentRenderer()) {
1151 frameView->paint(&gc, dirtyRect);
1156 void WebView::paintIntoWindow(HDC bitmapDC, HDC windowDC, const IntRect& dirtyRect)
1158 // FIXME: This function should never be called in accelerated compositing mode, and we should
1159 // assert as such. But currently it *is* sometimes called, so we can't assert yet. See
1160 // <http://webkit.org/b/58539>.
1162 LOCAL_GDI_COUNTER(0, __FUNCTION__);
1163 #if FLASH_WINDOW_REDRAW
1164 OwnPtr<HBRUSH> greenBrush = CreateSolidBrush(RGB(0, 255, 0));
1165 RECT rect = dirtyRect;
1166 FillRect(windowDC, &rect, greenBrush.get());
1171 // Blit the dirty rect from the backing store into the same position
1172 // in the destination DC.
1173 BitBlt(windowDC, dirtyRect.x(), dirtyRect.y(), dirtyRect.width(), dirtyRect.height(), bitmapDC,
1174 dirtyRect.x(), dirtyRect.y(), SRCCOPY);
1177 void WebView::frameRect(RECT* rect)
1179 ::GetWindowRect(m_viewWindow, rect);
1182 class WindowCloseTimer : public WebCore::SuspendableTimer {
1184 static WindowCloseTimer* create(WebView*);
1187 WindowCloseTimer(ScriptExecutionContext*, WebView*);
1188 virtual void contextDestroyed();
1189 virtual void fired();
1194 WindowCloseTimer* WindowCloseTimer::create(WebView* webView)
1196 ASSERT_ARG(webView, webView);
1197 Frame* frame = core(webView->topLevelFrame());
1202 Document* document = frame->document();
1207 return new WindowCloseTimer(document, webView);
1210 WindowCloseTimer::WindowCloseTimer(ScriptExecutionContext* context, WebView* webView)
1211 : SuspendableTimer(context)
1212 , m_webView(webView)
1214 ASSERT_ARG(context, context);
1215 ASSERT_ARG(webView, webView);
1218 void WindowCloseTimer::contextDestroyed()
1220 SuspendableTimer::contextDestroyed();
1224 void WindowCloseTimer::fired()
1226 m_webView->closeWindowTimerFired();
1229 void WebView::closeWindowSoon()
1231 if (m_closeWindowTimer)
1234 m_closeWindowTimer = WindowCloseTimer::create(this);
1235 if (!m_closeWindowTimer)
1237 m_closeWindowTimer->startOneShot(0);
1242 void WebView::closeWindowTimerFired()
1248 void WebView::closeWindow()
1250 if (m_hasSpellCheckerDocumentTag) {
1251 if (m_editingDelegate)
1252 m_editingDelegate->closeSpellDocument(this);
1253 m_hasSpellCheckerDocumentTag = false;
1256 COMPtr<IWebUIDelegate> ui;
1257 if (SUCCEEDED(uiDelegate(&ui)))
1258 ui->webViewClose(this);
1261 bool WebView::canHandleRequest(const WebCore::ResourceRequest& request)
1263 // On the mac there's an about url protocol implementation but CFNetwork doesn't have that.
1264 if (equalIgnoringCase(String(request.url().protocol()), "about"))
1268 if (CFURLProtocolCanHandleRequest(request.cfURLRequest()))
1271 // FIXME: Mac WebKit calls _representationExistsForURLScheme here
1278 String WebView::standardUserAgentWithApplicationName(const String& applicationName)
1280 DEFINE_STATIC_LOCAL(String, osVersion, (windowsVersionForUAString()));
1281 DEFINE_STATIC_LOCAL(String, webKitVersion, (webKitVersionString()));
1283 return makeString("Mozilla/5.0 (", osVersion, ") AppleWebKit/", webKitVersion, " (KHTML, like Gecko)", applicationName.isEmpty() ? "" : " ", applicationName);
1286 Page* WebView::page()
1291 bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam)
1293 // Translate the screen coordinates into window coordinates
1294 POINT coords = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
1295 if (coords.x == -1 || coords.y == -1) {
1296 // The contextMenuController() holds onto the last context menu that was popped up on the
1297 // page until a new one is created. We need to clear this menu before propagating the event
1298 // through the DOM so that we can detect if we create a new menu for this event, since we
1299 // won't create a new menu if the DOM swallows the event and the defaultEventHandler does
1301 m_page->contextMenuController()->clearContextMenu();
1303 Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
1304 return focusedFrame->eventHandler()->sendContextMenuEventForKey();
1307 if (!::ScreenToClient(m_viewWindow, &coords))
1311 lParam = MAKELPARAM(coords.x, coords.y);
1313 m_page->contextMenuController()->clearContextMenu();
1315 IntPoint documentPoint(m_page->mainFrame()->view()->windowToContents(coords));
1316 HitTestResult result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(documentPoint, false);
1317 Frame* targetFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : m_page->focusController()->focusedOrMainFrame();
1319 targetFrame->view()->setCursor(pointerCursor());
1320 PlatformMouseEvent mouseEvent(m_viewWindow, WM_RBUTTONUP, wParam, lParam);
1321 bool handledEvent = targetFrame->eventHandler()->sendContextMenuEvent(mouseEvent);
1325 ContextMenuController* contextMenuController = m_page->contextMenuController();
1328 ContextMenu* coreMenu = contextMenuController->contextMenu();
1332 Node* node = contextMenuController->hitTestResult().innerNonSharedNode();
1336 Frame* frame = node->document()->frame();
1340 FrameView* view = frame->view();
1344 POINT point(view->contentsToWindow(contextMenuController->hitTestResult().point()));
1346 // Translate the point to screen coordinates
1347 if (!::ClientToScreen(m_viewWindow, &point))
1350 BOOL hasCustomMenus = false;
1352 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1355 m_uiDelegate->trackCustomPopupMenu((IWebView*)this, (OLE_HANDLE)(ULONG64)coreMenu->nativeMenu(), &point);
1357 // Surprisingly, TPM_RIGHTBUTTON means that items are selectable with either the right OR left mouse button
1358 UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL
1359 | TPM_LEFTALIGN | TPM_HORPOSANIMATION;
1360 ::TrackPopupMenuEx(coreMenu->nativeMenu(), flags, point.x, point.y, m_viewWindow, 0);
1366 bool WebView::onMeasureItem(WPARAM /*wParam*/, LPARAM lParam)
1371 BOOL hasCustomMenus = false;
1372 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1373 if (!hasCustomMenus)
1376 m_uiDelegate->measureCustomMenuItem((IWebView*)this, (void*)lParam);
1380 bool WebView::onDrawItem(WPARAM /*wParam*/, LPARAM lParam)
1385 BOOL hasCustomMenus = false;
1386 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1387 if (!hasCustomMenus)
1390 m_uiDelegate->drawCustomMenuItem((IWebView*)this, (void*)lParam);
1394 bool WebView::onInitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1399 HMENU menu = (HMENU)wParam;
1403 BOOL hasCustomMenus = false;
1404 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1405 if (!hasCustomMenus)
1408 m_uiDelegate->addCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1412 bool WebView::onUninitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1417 HMENU menu = (HMENU)wParam;
1421 BOOL hasCustomMenus = false;
1422 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1423 if (!hasCustomMenus)
1426 m_uiDelegate->cleanUpCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1430 void WebView::performContextMenuAction(WPARAM wParam, LPARAM lParam, bool byPosition)
1432 ContextMenu* menu = m_page->contextMenuController()->contextMenu();
1435 ContextMenuItem* item = byPosition ? menu->itemAtIndex((unsigned)wParam) : menu->itemWithAction((ContextMenuAction)wParam);
1438 m_page->contextMenuController()->contextMenuItemSelected(item);
1441 bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
1443 static LONG globalClickCount;
1444 static IntPoint globalPrevPoint;
1445 static MouseButton globalPrevButton;
1446 static LONG globalPrevMouseDownTime;
1448 if (message == WM_CANCELMODE) {
1449 m_page->mainFrame()->eventHandler()->lostMouseCapture();
1453 // Create our event.
1454 // On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
1455 // of the event to be at (MINSHORT, MINSHORT).
1456 LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
1457 PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
1459 setMouseActivated(false);
1461 bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.pos().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
1462 abs(globalPrevPoint.y() - mouseEvent.pos().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
1463 LONG messageTime = ::GetMessageTime();
1465 bool handled = false;
1467 if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
1468 // FIXME: I'm not sure if this is the "right" way to do this
1469 // but without this call, we never become focused since we don't allow
1470 // the default handling of mouse events.
1471 SetFocus(m_viewWindow);
1473 // Always start capturing events when the mouse goes down in our HWND.
1474 ::SetCapture(m_viewWindow);
1476 if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) &&
1478 mouseEvent.button() == globalPrevButton)
1481 // Reset the click count.
1482 globalClickCount = 1;
1483 globalPrevMouseDownTime = messageTime;
1484 globalPrevButton = mouseEvent.button();
1485 globalPrevPoint = mouseEvent.pos();
1487 mouseEvent.setClickCount(globalClickCount);
1488 handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1489 } else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
1491 mouseEvent.setClickCount(globalClickCount);
1492 handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1493 } else if (message == WM_LBUTTONUP || message == WM_MBUTTONUP || message == WM_RBUTTONUP) {
1494 // Record the global position and the button of the up.
1495 globalPrevButton = mouseEvent.button();
1496 globalPrevPoint = mouseEvent.pos();
1497 mouseEvent.setClickCount(globalClickCount);
1498 m_page->mainFrame()->eventHandler()->handleMouseReleaseEvent(mouseEvent);
1500 } else if (message == WM_MOUSELEAVE && m_mouseOutTracker) {
1501 // Once WM_MOUSELEAVE is fired windows clears this tracker
1502 // so there is no need to disable it ourselves.
1503 m_mouseOutTracker.clear();
1504 m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1506 } else if (message == WM_MOUSEMOVE) {
1507 if (!insideThreshold)
1508 globalClickCount = 0;
1509 mouseEvent.setClickCount(globalClickCount);
1510 handled = m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1511 if (!m_mouseOutTracker) {
1512 m_mouseOutTracker = adoptPtr(new TRACKMOUSEEVENT);
1513 m_mouseOutTracker->cbSize = sizeof(TRACKMOUSEEVENT);
1514 m_mouseOutTracker->dwFlags = TME_LEAVE;
1515 m_mouseOutTracker->hwndTrack = m_viewWindow;
1516 ::TrackMouseEvent(m_mouseOutTracker.get());
1522 bool WebView::gestureNotify(WPARAM wParam, LPARAM lParam)
1524 GESTURENOTIFYSTRUCT* gn = reinterpret_cast<GESTURENOTIFYSTRUCT*>(lParam);
1526 Frame* coreFrame = core(m_mainFrame);
1530 ScrollView* view = coreFrame->view();
1534 // If we don't have this function, we shouldn't be receiving this message
1535 ASSERT(SetGestureConfigPtr());
1537 bool hitScrollbar = false;
1538 POINT gestureBeginPoint = {gn->ptsLocation.x, gn->ptsLocation.y};
1539 HitTestRequest request(HitTestRequest::ReadOnly);
1540 for (Frame* childFrame = m_page->mainFrame(); childFrame; childFrame = EventHandler::subframeForTargetNode(m_gestureTargetNode.get())) {
1541 FrameView* frameView = childFrame->view();
1544 RenderView* renderView = childFrame->document()->renderView();
1547 RenderLayer* layer = renderView->layer();
1551 HitTestResult result(frameView->screenToContents(gestureBeginPoint));
1552 layer->hitTest(request, result);
1553 m_gestureTargetNode = result.innerNode();
1556 hitScrollbar = result.scrollbar();
1559 if (!hitScrollbar) {
1560 // The hit testing above won't detect if we've hit the main frame's vertical scrollbar. Check that manually now.
1562 GetWindowRect(m_viewWindow, &webViewRect);
1563 hitScrollbar = view->verticalScrollbar() && (gestureBeginPoint.x > (webViewRect.right - view->verticalScrollbar()->theme()->scrollbarThickness()));
1566 bool canBeScrolled = false;
1567 if (m_gestureTargetNode) {
1568 for (RenderObject* renderer = m_gestureTargetNode->renderer(); renderer; renderer = renderer->parent()) {
1569 if (renderer->isBox() && toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()) {
1570 canBeScrolled = true;
1576 // We always allow two-fingered panning with inertia and a gutter (which limits movement to one
1577 // direction in most cases).
1578 DWORD dwPanWant = GC_PAN | GC_PAN_WITH_INERTIA | GC_PAN_WITH_GUTTER;
1579 // We never allow single-fingered horizontal panning. That gesture is reserved for creating text
1580 // selections. This matches IE.
1581 DWORD dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
1583 if (hitScrollbar || !canBeScrolled) {
1584 // The part of the page under the gesture can't be scrolled, or the gesture is on a scrollbar.
1585 // Disallow single-fingered vertical panning in this case, too, so we'll fall back to the default
1586 // behavior (which allows the scrollbar thumb to be dragged, text selections to be made, etc.).
1587 dwPanBlock |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
1589 // The part of the page the gesture is under can be scrolled, and we're not under a scrollbar.
1590 // Allow single-fingered vertical panning in this case, so the user will be able to pan the page
1591 // with one or two fingers.
1592 dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
1595 GESTURECONFIG gc = { GID_PAN, dwPanWant, dwPanBlock };
1596 return SetGestureConfigPtr()(m_viewWindow, 0, 1, &gc, sizeof(GESTURECONFIG));
1599 bool WebView::gesture(WPARAM wParam, LPARAM lParam)
1601 // We want to bail out if we don't have either of these functions
1602 if (!GetGestureInfoPtr() || !CloseGestureInfoHandlePtr())
1605 HGESTUREINFO gestureHandle = reinterpret_cast<HGESTUREINFO>(lParam);
1607 GESTUREINFO gi = {0};
1608 gi.cbSize = sizeof(GESTUREINFO);
1610 if (!GetGestureInfoPtr()(gestureHandle, reinterpret_cast<PGESTUREINFO>(&gi)))
1615 m_lastPanX = gi.ptsLocation.x;
1616 m_lastPanY = gi.ptsLocation.y;
1620 m_gestureTargetNode = 0;
1623 // Where are the fingers currently?
1624 long currentX = gi.ptsLocation.x;
1625 long currentY = gi.ptsLocation.y;
1626 // How far did we pan in each direction?
1627 long deltaX = currentX - m_lastPanX;
1628 long deltaY = currentY - m_lastPanY;
1629 // Calculate the overpan for window bounce
1630 m_yOverpan -= m_lastPanY - currentY;
1631 m_xOverpan -= m_lastPanX - currentX;
1632 // Update our class variables with updated values
1633 m_lastPanX = currentX;
1634 m_lastPanY = currentY;
1636 Frame* coreFrame = core(m_mainFrame);
1638 CloseGestureInfoHandlePtr()(gestureHandle);
1642 if (!m_gestureTargetNode || !m_gestureTargetNode->renderer())
1645 // We negate here since panning up moves the content up, but moves the scrollbar down.
1646 m_gestureTargetNode->renderer()->enclosingLayer()->scrollByRecursively(-deltaX, -deltaY);
1648 if (!(UpdatePanningFeedbackPtr() && BeginPanningFeedbackPtr() && EndPanningFeedbackPtr())) {
1649 CloseGestureInfoHandlePtr()(gestureHandle);
1653 if (gi.dwFlags & GF_BEGIN) {
1654 BeginPanningFeedbackPtr()(m_viewWindow);
1656 } else if (gi.dwFlags & GF_END) {
1657 EndPanningFeedbackPtr()(m_viewWindow, true);
1661 ScrollView* view = coreFrame->view();
1663 CloseGestureInfoHandlePtr()(gestureHandle);
1666 Scrollbar* vertScrollbar = view->verticalScrollbar();
1667 if (!vertScrollbar) {
1668 CloseGestureInfoHandlePtr()(gestureHandle);
1672 // FIXME: Support Horizontal Window Bounce. <https://webkit.org/b/28500>.
1673 // FIXME: If the user starts panning down after a window bounce has started, the window doesn't bounce back
1674 // until they release their finger. <https://webkit.org/b/28501>.
1675 if (vertScrollbar->currentPos() == 0)
1676 UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
1677 else if (vertScrollbar->currentPos() >= vertScrollbar->maximum())
1678 UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
1680 CloseGestureInfoHandlePtr()(gestureHandle);
1687 // If we get to this point, the gesture has not been handled. We forward
1688 // the call to DefWindowProc by returning false, and we don't need to
1689 // to call CloseGestureInfoHandle.
1690 // http://msdn.microsoft.com/en-us/library/dd353228(VS.85).aspx
1694 bool WebView::mouseWheel(WPARAM wParam, LPARAM lParam, bool isMouseHWheel)
1696 // Ctrl+Mouse wheel doesn't ever go into WebCore. It is used to
1697 // zoom instead (Mac zooms the whole Desktop, but Windows browsers trigger their
1698 // own local zoom modes for Ctrl+wheel).
1699 if (wParam & MK_CONTROL) {
1700 short delta = short(HIWORD(wParam));
1708 // FIXME: This doesn't fix https://bugs.webkit.org/show_bug.cgi?id=28217. This only fixes https://bugs.webkit.org/show_bug.cgi?id=28203.
1709 HWND focusedWindow = GetFocus();
1710 if (focusedWindow && focusedWindow != m_viewWindow) {
1711 // Our focus is on a different hwnd, see if it's a PopupMenu and if so, set the focus back on us (which will hide the popup).
1712 WCHAR className[256];
1714 // Make sure truncation won't affect the comparison.
1715 ASSERT(WTF_ARRAY_LENGTH(className) > wcslen(PopupMenuWin::popupClassName()));
1717 if (GetClassNameW(focusedWindow, className, WTF_ARRAY_LENGTH(className)) && !wcscmp(className, PopupMenuWin::popupClassName())) {
1718 // We don't let the WebView scroll here for two reasons - 1) To match Firefox behavior, 2) If we do scroll, we lose the
1719 // focus ring around the select menu.
1720 SetFocus(m_viewWindow);
1725 PlatformWheelEvent wheelEvent(m_viewWindow, wParam, lParam, isMouseHWheel);
1726 Frame* coreFrame = core(m_mainFrame);
1730 return coreFrame->eventHandler()->handleWheelEvent(wheelEvent);
1733 bool WebView::verticalScroll(WPARAM wParam, LPARAM /*lParam*/)
1735 ScrollDirection direction;
1736 ScrollGranularity granularity;
1737 switch (LOWORD(wParam)) {
1739 granularity = ScrollByLine;
1740 direction = ScrollDown;
1743 granularity = ScrollByLine;
1744 direction = ScrollUp;
1747 granularity = ScrollByDocument;
1748 direction = ScrollDown;
1751 granularity = ScrollByDocument;
1752 direction = ScrollUp;
1759 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1760 return frame->eventHandler()->scrollRecursively(direction, granularity);
1763 bool WebView::horizontalScroll(WPARAM wParam, LPARAM /*lParam*/)
1765 ScrollDirection direction;
1766 ScrollGranularity granularity;
1767 switch (LOWORD(wParam)) {
1769 granularity = ScrollByLine;
1770 direction = ScrollLeft;
1773 granularity = ScrollByLine;
1774 direction = ScrollRight;
1777 granularity = ScrollByDocument;
1778 direction = ScrollLeft;
1781 granularity = ScrollByDocument;
1782 direction = ScrollRight;
1788 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1789 return frame->eventHandler()->scrollRecursively(direction, granularity);
1793 bool WebView::execCommand(WPARAM wParam, LPARAM /*lParam*/)
1795 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1796 switch (LOWORD(wParam)) {
1798 return frame->editor()->command("SelectAll").execute();
1800 return frame->editor()->command("Undo").execute();
1802 return frame->editor()->command("Redo").execute();
1807 bool WebView::keyUp(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1809 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::KeyUp, systemKeyDown);
1811 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1812 m_currentCharacterCode = 0;
1814 return frame->eventHandler()->keyEvent(keyEvent);
1817 static const unsigned CtrlKey = 1 << 0;
1818 static const unsigned AltKey = 1 << 1;
1819 static const unsigned ShiftKey = 1 << 2;
1822 struct KeyDownEntry {
1823 unsigned virtualKey;
1828 struct KeyPressEntry {
1834 static const KeyDownEntry keyDownEntries[] = {
1835 { VK_LEFT, 0, "MoveLeft" },
1836 { VK_LEFT, ShiftKey, "MoveLeftAndModifySelection" },
1837 { VK_LEFT, CtrlKey, "MoveWordLeft" },
1838 { VK_LEFT, CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection" },
1839 { VK_RIGHT, 0, "MoveRight" },
1840 { VK_RIGHT, ShiftKey, "MoveRightAndModifySelection" },
1841 { VK_RIGHT, CtrlKey, "MoveWordRight" },
1842 { VK_RIGHT, CtrlKey | ShiftKey, "MoveWordRightAndModifySelection" },
1843 { VK_UP, 0, "MoveUp" },
1844 { VK_UP, ShiftKey, "MoveUpAndModifySelection" },
1845 { VK_PRIOR, ShiftKey, "MovePageUpAndModifySelection" },
1846 { VK_DOWN, 0, "MoveDown" },
1847 { VK_DOWN, ShiftKey, "MoveDownAndModifySelection" },
1848 { VK_NEXT, ShiftKey, "MovePageDownAndModifySelection" },
1849 { VK_PRIOR, 0, "MovePageUp" },
1850 { VK_NEXT, 0, "MovePageDown" },
1851 { VK_HOME, 0, "MoveToBeginningOfLine" },
1852 { VK_HOME, ShiftKey, "MoveToBeginningOfLineAndModifySelection" },
1853 { VK_HOME, CtrlKey, "MoveToBeginningOfDocument" },
1854 { VK_HOME, CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
1856 { VK_END, 0, "MoveToEndOfLine" },
1857 { VK_END, ShiftKey, "MoveToEndOfLineAndModifySelection" },
1858 { VK_END, CtrlKey, "MoveToEndOfDocument" },
1859 { VK_END, CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection" },
1861 { VK_BACK, 0, "DeleteBackward" },
1862 { VK_BACK, ShiftKey, "DeleteBackward" },
1863 { VK_DELETE, 0, "DeleteForward" },
1864 { VK_BACK, CtrlKey, "DeleteWordBackward" },
1865 { VK_DELETE, CtrlKey, "DeleteWordForward" },
1867 { 'B', CtrlKey, "ToggleBold" },
1868 { 'I', CtrlKey, "ToggleItalic" },
1870 { VK_ESCAPE, 0, "Cancel" },
1871 { VK_OEM_PERIOD, CtrlKey, "Cancel" },
1872 { VK_TAB, 0, "InsertTab" },
1873 { VK_TAB, ShiftKey, "InsertBacktab" },
1874 { VK_RETURN, 0, "InsertNewline" },
1875 { VK_RETURN, CtrlKey, "InsertNewline" },
1876 { VK_RETURN, AltKey, "InsertNewline" },
1877 { VK_RETURN, ShiftKey, "InsertNewline" },
1878 { VK_RETURN, AltKey | ShiftKey, "InsertNewline" },
1880 // It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled
1881 // in the application or in WebKit. We chose WebKit.
1882 { 'C', CtrlKey, "Copy" },
1883 { 'V', CtrlKey, "Paste" },
1884 { 'X', CtrlKey, "Cut" },
1885 { 'A', CtrlKey, "SelectAll" },
1886 { VK_INSERT, CtrlKey, "Copy" },
1887 { VK_DELETE, ShiftKey, "Cut" },
1888 { VK_INSERT, ShiftKey, "Paste" },
1889 { 'Z', CtrlKey, "Undo" },
1890 { 'Z', CtrlKey | ShiftKey, "Redo" },
1893 static const KeyPressEntry keyPressEntries[] = {
1894 { '\t', 0, "InsertTab" },
1895 { '\t', ShiftKey, "InsertBacktab" },
1896 { '\r', 0, "InsertNewline" },
1897 { '\r', CtrlKey, "InsertNewline" },
1898 { '\r', AltKey, "InsertNewline" },
1899 { '\r', ShiftKey, "InsertNewline" },
1900 { '\r', AltKey | ShiftKey, "InsertNewline" },
1903 const char* WebView::interpretKeyEvent(const KeyboardEvent* evt)
1905 ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
1907 static HashMap<int, const char*>* keyDownCommandsMap = 0;
1908 static HashMap<int, const char*>* keyPressCommandsMap = 0;
1910 if (!keyDownCommandsMap) {
1911 keyDownCommandsMap = new HashMap<int, const char*>;
1912 keyPressCommandsMap = new HashMap<int, const char*>;
1914 for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyDownEntries); ++i)
1915 keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
1917 for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyPressEntries); ++i)
1918 keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
1921 unsigned modifiers = 0;
1922 if (evt->shiftKey())
1923 modifiers |= ShiftKey;
1925 modifiers |= AltKey;
1927 modifiers |= CtrlKey;
1929 if (evt->type() == eventNames().keydownEvent) {
1930 int mapKey = modifiers << 16 | evt->keyCode();
1931 return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
1934 int mapKey = modifiers << 16 | evt->charCode();
1935 return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
1938 bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
1940 Node* node = evt->target()->toNode();
1942 Frame* frame = node->document()->frame();
1945 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1946 if (!keyEvent || keyEvent->isSystemKey()) // do not treat this as text input if it's a system key event
1949 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1951 if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1952 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1953 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1954 // (e.g. Tab that inserts a Tab character, or Enter).
1955 return !command.isTextInsertion() && command.execute(evt);
1958 if (command.execute(evt))
1961 // Don't insert null or control characters as they can result in unexpected behaviour
1962 if (evt->charCode() < ' ')
1965 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1968 bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1970 #if ENABLE(FULLSCREEN_API)
1971 // Trap the ESC key when in full screen mode.
1972 if (virtualKeyCode == VK_ESCAPE && isFullScreen()) {
1973 m_fullscreenController->exitFullScreen();
1977 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1979 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::RawKeyDown, systemKeyDown);
1980 bool handled = frame->eventHandler()->keyEvent(keyEvent);
1982 // These events cannot be canceled, and we have no default handling for them.
1983 // FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
1984 if (systemKeyDown && virtualKeyCode != VK_RETURN)
1988 // FIXME: remove WM_UNICHAR, too
1990 // WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
1992 ::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
1996 // We need to handle back/forward using either Ctrl+Left/Right Arrow keys.
1997 // FIXME: This logic should probably be in EventHandler::defaultArrowEventHandler().
1998 // FIXME: Should check that other modifiers aren't pressed.
1999 if (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey())
2000 return m_page->goForward();
2001 if (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey())
2002 return m_page->goBack();
2004 // Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
2005 ScrollDirection direction;
2006 ScrollGranularity granularity;
2007 switch (virtualKeyCode) {
2009 granularity = ScrollByLine;
2010 direction = ScrollLeft;
2013 granularity = ScrollByLine;
2014 direction = ScrollRight;
2017 granularity = ScrollByLine;
2018 direction = ScrollUp;
2021 granularity = ScrollByLine;
2022 direction = ScrollDown;
2025 granularity = ScrollByDocument;
2026 direction = ScrollUp;
2029 granularity = ScrollByDocument;
2030 direction = ScrollDown;
2033 granularity = ScrollByPage;
2034 direction = ScrollUp;
2037 granularity = ScrollByPage;
2038 direction = ScrollDown;
2044 return frame->eventHandler()->scrollRecursively(direction, granularity);
2047 bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
2049 Frame* frame = m_page->focusController()->focusedOrMainFrame();
2051 PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformKeyboardEvent::Char, systemKeyDown);
2052 // IE does not dispatch keypress event for WM_SYSCHAR.
2054 return frame->eventHandler()->handleAccessKey(keyEvent);
2055 return frame->eventHandler()->keyEvent(keyEvent);
2058 void WebView::setIsBeingDestroyed()
2060 m_isBeingDestroyed = true;
2062 // Remove our this pointer from the window so we won't try to handle any more window messages.
2063 // See <http://webkit.org/b/55054>.
2064 ::SetWindowLongPtrW(m_viewWindow, 0, 0);
2067 bool WebView::registerWebViewWindowClass()
2069 static bool haveRegisteredWindowClass = false;
2070 if (haveRegisteredWindowClass)
2073 haveRegisteredWindowClass = true;
2077 wcex.cbSize = sizeof(WNDCLASSEX);
2079 wcex.style = CS_DBLCLKS;
2080 wcex.lpfnWndProc = WebViewWndProc;
2081 wcex.cbClsExtra = 0;
2082 wcex.cbWndExtra = 4; // 4 bytes for the IWebView pointer
2083 wcex.hInstance = gInstance;
2085 wcex.hCursor = ::LoadCursor(0, IDC_ARROW);
2086 wcex.hbrBackground = 0;
2087 wcex.lpszMenuName = 0;
2088 wcex.lpszClassName = kWebViewWindowClassName;
2091 return !!RegisterClassEx(&wcex);
2094 static HWND findTopLevelParent(HWND window)
2099 HWND current = window;
2100 for (HWND parent = GetParent(current); current; current = parent, parent = GetParent(parent))
2101 if (!parent || !(GetWindowLongPtr(current, GWL_STYLE) & (WS_POPUP | WS_CHILD)))
2103 ASSERT_NOT_REACHED();
2107 LRESULT CALLBACK WebView::WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
2109 LRESULT lResult = 0;
2110 LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
2111 WebView* webView = reinterpret_cast<WebView*>(longPtr);
2112 WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
2114 return DefWindowProc(hWnd, message, wParam, lParam);
2116 // We shouldn't be trying to handle any window messages after WM_DESTROY.
2117 // See <http://webkit.org/b/55054>.
2118 ASSERT(!webView->isBeingDestroyed());
2120 // hold a ref, since the WebView could go away in an event handler.
2121 COMPtr<WebView> protector(webView);
2124 // Windows Media Player has a modal message loop that will deliver messages
2125 // to us at inappropriate times and we will crash if we handle them when
2126 // they are delivered. We repost paint messages so that we eventually get
2127 // a chance to paint once the modal loop has exited, but other messages
2128 // aren't safe to repost, so we just drop them.
2129 if (PluginView::isCallingPlugin()) {
2130 if (message == WM_PAINT)
2131 PostMessage(hWnd, message, wParam, lParam);
2135 bool handled = true;
2139 webView->paint(0, 0);
2140 if (webView->usesLayeredWindow())
2141 webView->performLayeredWindowUpdate();
2145 if (webView->usesLayeredWindow()) {
2146 // Don't perform a background erase for transparent views.
2151 case WM_PRINTCLIENT:
2152 webView->paint((HDC)wParam, lParam);
2155 webView->setIsBeingDestroyed();
2158 case WM_GESTURENOTIFY:
2159 handled = webView->gestureNotify(wParam, lParam);
2162 handled = webView->gesture(wParam, lParam);
2165 case WM_LBUTTONDOWN:
2166 case WM_MBUTTONDOWN:
2167 case WM_RBUTTONDOWN:
2168 case WM_LBUTTONDBLCLK:
2169 case WM_MBUTTONDBLCLK:
2170 case WM_RBUTTONDBLCLK:
2176 if (Frame* coreFrame = core(mainFrameImpl))
2177 if (coreFrame->view()->didFirstLayout())
2178 handled = webView->handleMouseEvent(message, wParam, lParam);
2181 case WM_VISTA_MOUSEHWHEEL:
2182 if (Frame* coreFrame = core(mainFrameImpl))
2183 if (coreFrame->view()->didFirstLayout())
2184 handled = webView->mouseWheel(wParam, lParam, message == WM_VISTA_MOUSEHWHEEL);
2187 handled = webView->keyDown(wParam, lParam, true);
2190 handled = webView->keyDown(wParam, lParam);
2193 handled = webView->keyUp(wParam, lParam, true);
2196 handled = webView->keyUp(wParam, lParam);
2199 handled = webView->keyPress(wParam, lParam, true);
2202 handled = webView->keyPress(wParam, lParam);
2204 // FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
2207 webView->sizeChanged(IntSize(LOWORD(lParam), HIWORD(lParam)));
2210 lResult = DefWindowProc(hWnd, message, wParam, lParam);
2212 // The window is being hidden (e.g., because we switched tabs).
2213 // Null out our backing store.
2214 webView->deleteBackingStore();
2218 COMPtr<IWebUIDelegate> uiDelegate;
2219 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2220 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2221 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2222 uiDelegatePrivate->webViewReceivedFocus(webView);
2224 FocusController* focusController = webView->page()->focusController();
2225 if (Frame* frame = focusController->focusedFrame()) {
2226 // Send focus events unless the previously focused window is a
2227 // child of ours (for example a plugin).
2228 if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
2229 focusController->setFocused(true);
2231 focusController->setFocused(true);
2234 case WM_KILLFOCUS: {
2235 COMPtr<IWebUIDelegate> uiDelegate;
2236 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2237 HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
2238 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2239 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2240 uiDelegatePrivate->webViewLostFocus(webView, (OLE_HANDLE)(ULONG64)newFocusWnd);
2242 FocusController* focusController = webView->page()->focusController();
2243 Frame* frame = focusController->focusedOrMainFrame();
2244 webView->resetIME(frame);
2245 // Send blur events unless we're losing focus to a child of ours.
2246 if (!IsChild(hWnd, newFocusWnd))
2247 focusController->setFocused(false);
2249 // If we are pan-scrolling when we lose focus, stop the pan scrolling.
2250 frame->eventHandler()->stopAutoscrollTimer();
2254 case WM_WINDOWPOSCHANGED:
2255 if (reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW)
2256 webView->updateActiveStateSoon();
2269 webView->delete_(0);
2273 handled = webView->execCommand(wParam, lParam);
2274 else // If the high word of wParam is 0, the message is from a menu
2275 webView->performContextMenuAction(wParam, lParam, false);
2277 case WM_MENUCOMMAND:
2278 webView->performContextMenuAction(wParam, lParam, true);
2280 case WM_CONTEXTMENU:
2281 handled = webView->handleContextMenuEvent(wParam, lParam);
2283 case WM_INITMENUPOPUP:
2284 handled = webView->onInitMenuPopup(wParam, lParam);
2286 case WM_MEASUREITEM:
2287 handled = webView->onMeasureItem(wParam, lParam);
2290 handled = webView->onDrawItem(wParam, lParam);
2292 case WM_UNINITMENUPOPUP:
2293 handled = webView->onUninitMenuPopup(wParam, lParam);
2295 case WM_XP_THEMECHANGED:
2296 if (Frame* coreFrame = core(mainFrameImpl)) {
2297 webView->deleteBackingStore();
2298 coreFrame->page()->theme()->themeChanged();
2299 ScrollbarTheme::nativeTheme()->themeChanged();
2301 ::GetClientRect(hWnd, &windowRect);
2302 ::InvalidateRect(hWnd, &windowRect, false);
2303 #if USE(ACCELERATED_COMPOSITING)
2304 if (webView->isAcceleratedCompositing())
2305 webView->m_backingLayer->setNeedsDisplay();
2309 case WM_MOUSEACTIVATE:
2310 webView->setMouseActivated(true);
2313 case WM_GETDLGCODE: {
2314 COMPtr<IWebUIDelegate> uiDelegate;
2315 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2316 LONG_PTR dlgCode = 0;
2319 LPMSG lpMsg = (LPMSG)lParam;
2320 if (lpMsg->message == WM_KEYDOWN)
2321 keyCode = (UINT) lpMsg->wParam;
2323 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2324 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate
2325 && SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
2331 handled = webView->onGetObject(wParam, lParam, lResult);
2333 case WM_IME_STARTCOMPOSITION:
2334 handled = webView->onIMEStartComposition();
2336 case WM_IME_REQUEST:
2337 lResult = webView->onIMERequest(wParam, lParam);
2339 case WM_IME_COMPOSITION:
2340 handled = webView->onIMEComposition(lParam);
2342 case WM_IME_ENDCOMPOSITION:
2343 handled = webView->onIMEEndComposition();
2346 handled = webView->onIMEChar(wParam, lParam);
2349 handled = webView->onIMENotify(wParam, lParam, &lResult);
2352 handled = webView->onIMESelect(wParam, lParam);
2354 case WM_IME_SETCONTEXT:
2355 handled = webView->onIMESetContext(wParam, lParam);
2359 case UpdateActiveStateTimer:
2360 KillTimer(hWnd, UpdateActiveStateTimer);
2361 webView->updateActiveState();
2363 case DeleteBackingStoreTimer:
2364 webView->deleteBackingStore();
2369 handled = ::SetCursor(webView->m_lastSetCursor);
2372 handled = webView->verticalScroll(wParam, lParam);
2375 handled = webView->horizontalScroll(wParam, lParam);
2383 lResult = DefWindowProc(hWnd, message, wParam, lParam);
2385 // Let the client know whether we consider this message handled.
2386 return (message == WM_KEYDOWN || message == WM_SYSKEYDOWN || message == WM_KEYUP || message == WM_SYSKEYUP) ? !handled : lResult;
2389 bool WebView::developerExtrasEnabled() const
2391 if (m_preferences->developerExtrasDisabledByOverride())
2396 return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
2402 static String webKitVersionString()
2404 LPWSTR buildNumberStringPtr;
2405 if (!::LoadStringW(gInstance, BUILD_NUMBER, reinterpret_cast<LPWSTR>(&buildNumberStringPtr), 0) || !buildNumberStringPtr)
2408 return buildNumberStringPtr;
2411 const String& WebView::userAgentForKURL(const KURL&)
2413 if (m_userAgentOverridden)
2414 return m_userAgentCustom;
2416 if (!m_userAgentStandard.length())
2417 m_userAgentStandard = WebView::standardUserAgentWithApplicationName(m_applicationName);
2418 return m_userAgentStandard;
2421 // IUnknown -------------------------------------------------------------------
2423 HRESULT STDMETHODCALLTYPE WebView::QueryInterface(REFIID riid, void** ppvObject)
2426 if (IsEqualGUID(riid, CLSID_WebView))
2428 else if (IsEqualGUID(riid, IID_IUnknown))
2429 *ppvObject = static_cast<IWebView*>(this);
2430 else if (IsEqualGUID(riid, IID_IWebView))
2431 *ppvObject = static_cast<IWebView*>(this);
2432 else if (IsEqualGUID(riid, IID_IWebViewPrivate))
2433 *ppvObject = static_cast<IWebViewPrivate*>(this);
2434 else if (IsEqualGUID(riid, IID_IWebIBActions))
2435 *ppvObject = static_cast<IWebIBActions*>(this);
2436 else if (IsEqualGUID(riid, IID_IWebViewCSS))
2437 *ppvObject = static_cast<IWebViewCSS*>(this);
2438 else if (IsEqualGUID(riid, IID_IWebViewEditing))
2439 *ppvObject = static_cast<IWebViewEditing*>(this);
2440 else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
2441 *ppvObject = static_cast<IWebViewUndoableEditing*>(this);
2442 else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
2443 *ppvObject = static_cast<IWebViewEditingActions*>(this);
2444 else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
2445 *ppvObject = static_cast<IWebNotificationObserver*>(this);
2446 else if (IsEqualGUID(riid, IID_IDropTarget))
2447 *ppvObject = static_cast<IDropTarget*>(this);
2449 return E_NOINTERFACE;
2455 ULONG STDMETHODCALLTYPE WebView::AddRef(void)
2457 ASSERT(!m_deletionHasBegun);
2458 return ++m_refCount;
2461 ULONG STDMETHODCALLTYPE WebView::Release(void)
2463 ASSERT(!m_deletionHasBegun);
2465 if (m_refCount == 1) {
2466 // Call close() now so that clients don't have to. (It's harmless to call close() multiple
2467 // times.) We do this here instead of in our destructor because close() can cause AddRef()
2468 // and Release() to be called, and if that happened in our destructor we would be destroyed
2473 ULONG newRef = --m_refCount;
2475 #if !ASSERT_DISABLED
2476 m_deletionHasBegun = true;
2484 // IWebView --------------------------------------------------------------------
2486 HRESULT STDMETHODCALLTYPE WebView::canShowMIMEType(
2487 /* [in] */ BSTR mimeType,
2488 /* [retval][out] */ BOOL* canShow)
2490 String mimeTypeStr(mimeType, SysStringLen(mimeType));
2495 *canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeTypeStr) ||
2496 MIMETypeRegistry::isSupportedNonImageMIMEType(mimeTypeStr) ||
2497 (m_page && m_page->pluginData() && m_page->pluginData()->supportsMimeType(mimeTypeStr)) ||
2498 shouldUseEmbeddedView(mimeTypeStr);
2503 HRESULT STDMETHODCALLTYPE WebView::canShowMIMETypeAsHTML(
2504 /* [in] */ BSTR /*mimeType*/,
2505 /* [retval][out] */ BOOL* canShow)
2512 HRESULT STDMETHODCALLTYPE WebView::MIMETypesShownAsHTML(
2513 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
2515 ASSERT_NOT_REACHED();
2519 HRESULT STDMETHODCALLTYPE WebView::setMIMETypesShownAsHTML(
2520 /* [size_is][in] */ BSTR* /*mimeTypes*/,
2521 /* [in] */ int /*cMimeTypes*/)
2523 ASSERT_NOT_REACHED();
2527 HRESULT STDMETHODCALLTYPE WebView::URLFromPasteboard(
2528 /* [in] */ IDataObject* /*pasteboard*/,
2529 /* [retval][out] */ BSTR* /*url*/)
2531 ASSERT_NOT_REACHED();
2535 HRESULT STDMETHODCALLTYPE WebView::URLTitleFromPasteboard(
2536 /* [in] */ IDataObject* /*pasteboard*/,
2537 /* [retval][out] */ BSTR* /*urlTitle*/)
2539 ASSERT_NOT_REACHED();
2543 static void WebKitSetApplicationCachePathIfNecessary()
2545 static bool initialized = false;
2549 String path = localUserSpecificStorageDirectory();
2551 cacheStorage().setCacheDirectory(path);
2556 bool WebView::shouldInitializeTrackPointHack()
2558 static bool shouldCreateScrollbars;
2559 static bool hasRunTrackPointCheck;
2561 if (hasRunTrackPointCheck)
2562 return shouldCreateScrollbars;
2564 hasRunTrackPointCheck = true;
2565 const WCHAR trackPointKeys[][50] = { L"Software\\Lenovo\\TrackPoint",
2566 L"Software\\Lenovo\\UltraNav",
2567 L"Software\\Alps\\Apoint\\TrackPoint",
2568 L"Software\\Synaptics\\SynTPEnh\\UltraNavUSB",
2569 L"Software\\Synaptics\\SynTPEnh\\UltraNavPS2" };
2571 for (int i = 0; i < 5; ++i) {
2573 int readKeyResult = ::RegOpenKeyExW(HKEY_CURRENT_USER, trackPointKeys[i], 0, KEY_READ, &trackPointKey);
2574 ::RegCloseKey(trackPointKey);
2575 if (readKeyResult == ERROR_SUCCESS) {
2576 shouldCreateScrollbars = true;
2577 return shouldCreateScrollbars;
2581 return shouldCreateScrollbars;
2584 HRESULT STDMETHODCALLTYPE WebView::initWithFrame(
2585 /* [in] */ RECT frame,
2586 /* [in] */ BSTR frameName,
2587 /* [in] */ BSTR groupName)
2594 registerWebViewWindowClass();
2596 m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
2597 frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow ? m_hostWindow : HWND_MESSAGE, 0, gInstance, 0);
2598 ASSERT(::IsWindow(m_viewWindow));
2600 if (shouldInitializeTrackPointHack()) {
2601 // If we detected a registry key belonging to a TrackPoint driver, then create fake trackpoint
2602 // scrollbars, so the WebView will receive WM_VSCROLL and WM_HSCROLL messages. We create one
2603 // vertical scrollbar and one horizontal to allow for receiving both types of messages.
2604 ::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTHSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_HORZ, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
2605 ::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTVSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_VERT, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
2608 hr = registerDragDrop();
2612 WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
2613 sharedPreferences->willAddToWebView();
2614 m_preferences = sharedPreferences;
2616 static bool didOneTimeInitialization;
2617 if (!didOneTimeInitialization) {
2618 InitializeLoggingChannelsIfNecessary();
2619 #if ENABLE(DATABASE)
2620 WebKitInitializeWebDatabasesIfNecessary();
2622 WebKitSetApplicationCachePathIfNecessary();
2623 WebPlatformStrategies::initialize();
2624 Settings::setDefaultMinDOMTimerInterval(0.004);
2626 didOneTimeInitialization = true;
2629 #if USE(SAFARI_THEME)
2630 BOOL shouldPaintNativeControls;
2631 if (SUCCEEDED(m_preferences->shouldPaintNativeControls(&shouldPaintNativeControls)))
2632 Settings::setShouldPaintNativeControls(shouldPaintNativeControls);
2635 BOOL useHighResolutionTimer;
2636 if (SUCCEEDED(m_preferences->shouldUseHighResolutionTimers(&useHighResolutionTimer)))
2637 Settings::setShouldUseHighResolutionTimers(useHighResolutionTimer);
2639 Page::PageClients pageClients;
2640 pageClients.chromeClient = new WebChromeClient(this);
2641 pageClients.contextMenuClient = new WebContextMenuClient(this);
2642 pageClients.editorClient = new WebEditorClient(this);
2643 pageClients.dragClient = new WebDragClient(this);
2644 pageClients.inspectorClient = new WebInspectorClient(this);
2645 pageClients.pluginHalterClient = new WebPluginHalterClient(this);
2646 #if ENABLE(CLIENT_BASED_GEOLOCATION)
2647 pageClients.geolocationClient = new WebGeolocationClient(this);
2649 m_page = new Page(pageClients);
2651 BSTR localStoragePath;
2652 if (SUCCEEDED(m_preferences->localStorageDatabasePath(&localStoragePath))) {
2653 m_page->settings()->setLocalStorageDatabasePath(String(localStoragePath, SysStringLen(localStoragePath)));
2654 SysFreeString(localStoragePath);
2659 if (SUCCEEDED(m_uiDelegate->ftpDirectoryTemplatePath(this, &path))) {
2660 m_page->settings()->setFTPDirectoryTemplatePath(String(path, SysStringLen(path)));
2661 SysFreeString(path);
2665 WebFrame* webFrame = WebFrame::createInstance();
2666 RefPtr<Frame> coreFrame = webFrame->init(this, m_page, 0);
2667 m_mainFrame = webFrame;
2668 webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
2670 coreFrame->tree()->setName(String(frameName, SysStringLen(frameName)));
2672 setGroupName(groupName);
2674 addToAllWebViewsSet();
2676 #pragma warning(suppress: 4244)
2677 SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
2678 ShowWindow(m_viewWindow, SW_SHOW);
2680 initializeToolTipWindow();
2681 windowAncestryDidChange();
2683 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
2684 notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2685 m_preferences->postPreferencesChangesNotification();
2687 setSmartInsertDeleteEnabled(TRUE);
2691 static bool initCommonControls()
2693 static bool haveInitialized = false;
2694 if (haveInitialized)
2697 INITCOMMONCONTROLSEX init;
2698 init.dwSize = sizeof(init);
2699 init.dwICC = ICC_TREEVIEW_CLASSES;
2700 haveInitialized = !!::InitCommonControlsEx(&init);
2701 return haveInitialized;
2704 void WebView::initializeToolTipWindow()
2706 if (!initCommonControls())
2709 m_toolTipHwnd = CreateWindowEx(WS_EX_TRANSPARENT, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
2710 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
2711 m_viewWindow, 0, 0, 0);
2715 TOOLINFO info = {0};
2716 info.cbSize = sizeof(info);
2717 info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
2718 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2720 ::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
2721 ::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, maxToolTipWidth);
2723 ::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
2726 void WebView::setToolTip(const String& toolTip)
2731 if (toolTip == m_toolTip)
2734 m_toolTip = toolTip;
2736 if (!m_toolTip.isEmpty()) {
2737 TOOLINFO info = {0};
2738 info.cbSize = sizeof(info);
2739 info.uFlags = TTF_IDISHWND;
2740 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2741 info.lpszText = const_cast<UChar*>(m_toolTip.charactersWithNullTermination());
2742 ::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
2745 ::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
2748 HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
2750 COMPtr<IPropertyBag> propertyBag;
2751 HRESULT hr = notification->userInfo(&propertyBag);
2757 COMPtr<CFDictionaryPropertyBag> dictionaryPropertyBag;
2758 hr = propertyBag->QueryInterface(&dictionaryPropertyBag);
2762 CFDictionaryRef dictionary = dictionaryPropertyBag->dictionary();
2766 CFTypeRef value = CFDictionaryGetValue(dictionary, WebIconDatabase::iconDatabaseNotificationUserInfoURLKey());
2769 if (CFGetTypeID(value) != CFStringGetTypeID())
2772 String mainFrameURL;
2774 mainFrameURL = m_mainFrame->url().string();
2776 if (!mainFrameURL.isEmpty() && mainFrameURL == String((CFStringRef)value))
2777 dispatchDidReceiveIconFromWebFrame(m_mainFrame);
2782 void WebView::registerForIconNotification(bool listen)
2784 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2786 nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2788 nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2791 void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
2793 registerForIconNotification(false);
2795 if (m_frameLoadDelegate)
2796 // FIXME: <rdar://problem/5491010> - Pass in the right HBITMAP.
2797 m_frameLoadDelegate->didReceiveIcon(this, 0, frame);
2800 HRESULT STDMETHODCALLTYPE WebView::setUIDelegate(
2801 /* [in] */ IWebUIDelegate* d)
2805 if (m_uiDelegatePrivate)
2806 m_uiDelegatePrivate = 0;
2809 if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
2810 m_uiDelegatePrivate = 0;
2816 HRESULT STDMETHODCALLTYPE WebView::uiDelegate(
2817 /* [out][retval] */ IWebUIDelegate** d)
2822 return m_uiDelegate.copyRefTo(d);
2825 HRESULT STDMETHODCALLTYPE WebView::setResourceLoadDelegate(
2826 /* [in] */ IWebResourceLoadDelegate* d)
2828 m_resourceLoadDelegate = d;
2832 HRESULT STDMETHODCALLTYPE WebView::resourceLoadDelegate(
2833 /* [out][retval] */ IWebResourceLoadDelegate** d)
2835 if (!m_resourceLoadDelegate)
2838 return m_resourceLoadDelegate.copyRefTo(d);
2841 HRESULT STDMETHODCALLTYPE WebView::setDownloadDelegate(
2842 /* [in] */ IWebDownloadDelegate* d)
2844 m_downloadDelegate = d;
2848 HRESULT STDMETHODCALLTYPE WebView::downloadDelegate(
2849 /* [out][retval] */ IWebDownloadDelegate** d)
2851 if (!m_downloadDelegate)
2854 return m_downloadDelegate.copyRefTo(d);
2857 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegate(
2858 /* [in] */ IWebFrameLoadDelegate* d)
2860 m_frameLoadDelegate = d;
2864 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegate(
2865 /* [out][retval] */ IWebFrameLoadDelegate** d)
2867 if (!m_frameLoadDelegate)
2870 return m_frameLoadDelegate.copyRefTo(d);
2873 HRESULT STDMETHODCALLTYPE WebView::setPolicyDelegate(
2874 /* [in] */ IWebPolicyDelegate* d)
2876 m_policyDelegate = d;
2880 HRESULT STDMETHODCALLTYPE WebView::policyDelegate(
2881 /* [out][retval] */ IWebPolicyDelegate** d)
2883 if (!m_policyDelegate)
2885 return m_policyDelegate.copyRefTo(d);
2888 HRESULT STDMETHODCALLTYPE WebView::mainFrame(
2889 /* [out][retval] */ IWebFrame** frame)
2892 ASSERT_NOT_REACHED();
2896 *frame = m_mainFrame;
2900 m_mainFrame->AddRef();
2904 HRESULT STDMETHODCALLTYPE WebView::focusedFrame(
2905 /* [out][retval] */ IWebFrame** frame)
2908 ASSERT_NOT_REACHED();
2913 Frame* f = m_page->focusController()->focusedFrame();
2917 WebFrame* webFrame = kit(f);
2921 return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
2924 HRESULT STDMETHODCALLTYPE WebView::backForwardList(
2925 /* [out][retval] */ IWebBackForwardList** list)
2927 if (!m_useBackForwardList)
2930 *list = WebBackForwardList::createInstance(static_cast<WebCore::BackForwardListImpl*>(m_page->backForwardList()));
2935 HRESULT STDMETHODCALLTYPE WebView::setMaintainsBackForwardList(
2936 /* [in] */ BOOL flag)
2938 m_useBackForwardList = !!flag;
2942 HRESULT STDMETHODCALLTYPE WebView::goBack(
2943 /* [retval][out] */ BOOL* succeeded)
2945 *succeeded = m_page->goBack();
2949 HRESULT STDMETHODCALLTYPE WebView::goForward(
2950 /* [retval][out] */ BOOL* succeeded)
2952 *succeeded = m_page->goForward();
2956 HRESULT STDMETHODCALLTYPE WebView::goToBackForwardItem(
2957 /* [in] */ IWebHistoryItem* item,
2958 /* [retval][out] */ BOOL* succeeded)
2962 COMPtr<WebHistoryItem> webHistoryItem;
2963 HRESULT hr = item->QueryInterface(&webHistoryItem);
2967 m_page->goToItem(webHistoryItem->historyItem(), FrameLoadTypeIndexedBackForward);
2973 HRESULT STDMETHODCALLTYPE WebView::setTextSizeMultiplier(
2974 /* [in] */ float multiplier)
2978 setZoomMultiplier(multiplier, true);
2982 HRESULT STDMETHODCALLTYPE WebView::setPageSizeMultiplier(
2983 /* [in] */ float multiplier)
2987 setZoomMultiplier(multiplier, false);
2991 void WebView::setZoomMultiplier(float multiplier, bool isTextOnly)
2993 m_zoomMultiplier = multiplier;
2994 m_zoomsTextOnly = isTextOnly;
2996 if (Frame* coreFrame = core(m_mainFrame)) {
2997 if (m_zoomsTextOnly)
2998 coreFrame->setPageAndTextZoomFactors(1, multiplier);
3000 coreFrame->setPageAndTextZoomFactors(multiplier, 1);
3004 HRESULT STDMETHODCALLTYPE WebView::textSizeMultiplier(
3005 /* [retval][out] */ float* multiplier)
3007 *multiplier = zoomMultiplier(true);
3011 HRESULT STDMETHODCALLTYPE WebView::pageSizeMultiplier(
3012 /* [retval][out] */ float* multiplier)
3014 *multiplier = zoomMultiplier(false);
3018 float WebView::zoomMultiplier(bool isTextOnly)
3020 if (isTextOnly != m_zoomsTextOnly)
3022 return m_zoomMultiplier;
3025 HRESULT STDMETHODCALLTYPE WebView::setApplicationNameForUserAgent(
3026 /* [in] */ BSTR applicationName)
3028 m_applicationName = String(applicationName, SysStringLen(applicationName));
3029 m_userAgentStandard = String();
3033 HRESULT STDMETHODCALLTYPE WebView::applicationNameForUserAgent(
3034 /* [retval][out] */ BSTR* applicationName)
3036 *applicationName = SysAllocStringLen(m_applicationName.characters(), m_applicationName.length());
3037 if (!*applicationName && m_applicationName.length())
3038 return E_OUTOFMEMORY;
3042 HRESULT STDMETHODCALLTYPE WebView::setCustomUserAgent(
3043 /* [in] */ BSTR userAgentString)
3045 m_userAgentOverridden = userAgentString;
3046 m_userAgentCustom = String(userAgentString, SysStringLen(userAgentString));
3050 HRESULT STDMETHODCALLTYPE WebView::customUserAgent(
3051 /* [retval][out] */ BSTR* userAgentString)
3053 *userAgentString = 0;
3054 if (!m_userAgentOverridden)
3056 *userAgentString = SysAllocStringLen(m_userAgentCustom.characters(), m_userAgentCustom.length());
3057 if (!*userAgentString && m_userAgentCustom.length())
3058 return E_OUTOFMEMORY;
3062 HRESULT STDMETHODCALLTYPE WebView::userAgentForURL(
3063 /* [in] */ BSTR url,
3064 /* [retval][out] */ BSTR* userAgent)
3066 String userAgentString = userAgentForKURL(MarshallingHelpers::BSTRToKURL(url));
3067 *userAgent = SysAllocStringLen(userAgentString.characters(), userAgentString.length());
3068 if (!*userAgent && userAgentString.length())
3069 return E_OUTOFMEMORY;
3073 HRESULT STDMETHODCALLTYPE WebView::supportsTextEncoding(
3074 /* [retval][out] */ BOOL* supports)
3080 HRESULT STDMETHODCALLTYPE WebView::setCustomTextEncodingName(
3081 /* [in] */ BSTR encodingName)
3088 hr = customTextEncodingName(&oldEncoding);
3092 if (oldEncoding != encodingName && (!oldEncoding || !encodingName || wcscmp(oldEncoding, encodingName))) {
3093 if (Frame* coreFrame = core(m_mainFrame))
3094 coreFrame->loader()->reloadWithOverrideEncoding(String(encodingName, SysStringLen(encodingName)));
3100 HRESULT STDMETHODCALLTYPE WebView::customTextEncodingName(
3101 /* [retval][out] */ BSTR* encodingName)
3104 COMPtr<IWebDataSource> dataSource;
3105 COMPtr<WebDataSource> dataSourceImpl;
3111 if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
3112 hr = m_mainFrame->dataSource(&dataSource);
3113 if (FAILED(hr) || !dataSource)
3117 hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
3121 BString str = dataSourceImpl->documentLoader()->overrideEncoding();
3126 *encodingName = SysAllocStringLen(m_overrideEncoding.characters(), m_overrideEncoding.length());
3128 if (!*encodingName && m_overrideEncoding.length())
3129 return E_OUTOFMEMORY;
3134 HRESULT STDMETHODCALLTYPE WebView::setMediaStyle(
3135 /* [in] */ BSTR /*media*/)
3137 ASSERT_NOT_REACHED();
3141 HRESULT STDMETHODCALLTYPE WebView::mediaStyle(
3142 /* [retval][out] */ BSTR* /*media*/)
3144 ASSERT_NOT_REACHED();
3148 HRESULT STDMETHODCALLTYPE WebView::stringByEvaluatingJavaScriptFromString(
3149 /* [in] */ BSTR script, // assumes input does not have "JavaScript" at the begining.
3150 /* [retval][out] */ BSTR* result)
3153 ASSERT_NOT_REACHED();
3159 Frame* coreFrame = core(m_mainFrame);
3163 JSC::JSValue scriptExecutionResult = coreFrame->script()->executeScript(WTF::String(script), true).jsValue();
3164 if (!scriptExecutionResult)
3166 else if (scriptExecutionResult.isString()) {
3167 JSLock lock(JSC::SilenceAssertionsOnly);
3168 JSC::ExecState* exec = coreFrame->script()->globalObject(mainThreadNormalWorld())->globalExec();
3169 *result = BString(ustringToString(scriptExecutionResult.getString(exec)));
3175 HRESULT STDMETHODCALLTYPE WebView::windowScriptObject(
3176 /* [retval][out] */ IWebScriptObject** /*webScriptObject*/)
3178 ASSERT_NOT_REACHED();
3182 HRESULT STDMETHODCALLTYPE WebView::setPreferences(
3183 /* [in] */ IWebPreferences* prefs)
3186 prefs = WebPreferences::sharedStandardPreferences();
3188 if (m_preferences == prefs)
3191 COMPtr<WebPreferences> webPrefs(Query, prefs);
3193 return E_NOINTERFACE;
3194 webPrefs->willAddToWebView();
3196 COMPtr<WebPreferences> oldPrefs = m_preferences;
3198 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
3199 nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3201 BSTR identifier = 0;
3202 oldPrefs->identifier(&identifier);
3203 oldPrefs->didRemoveFromWebView();
3204 oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
3206 m_preferences = webPrefs;
3209 WebPreferences::removeReferenceForIdentifier(identifier);
3210 SysFreeString(identifier);
3213 nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3215 m_preferences->postPreferencesChangesNotification();
3220 HRESULT STDMETHODCALLTYPE WebView::preferences(
3221 /* [retval][out] */ IWebPreferences** prefs)
3225 *prefs = m_preferences.get();
3227 m_preferences->AddRef();
3231 HRESULT STDMETHODCALLTYPE WebView::setPreferencesIdentifier(
3232 /* [in] */ BSTR /*anIdentifier*/)
3234 ASSERT_NOT_REACHED();
3238 HRESULT STDMETHODCALLTYPE WebView::preferencesIdentifier(
3239 /* [retval][out] */ BSTR* /*anIdentifier*/)
3241 ASSERT_NOT_REACHED();
3245 static void systemParameterChanged(WPARAM parameter)
3248 if (parameter == SPI_SETFONTSMOOTHING || parameter == SPI_SETFONTSMOOTHINGTYPE || parameter == SPI_SETFONTSMOOTHINGCONTRAST || parameter == SPI_SETFONTSMOOTHINGORIENTATION)
3249 wkSystemFontSmoothingChanged();
3253 void WebView::windowReceivedMessage(HWND, UINT message, WPARAM wParam, LPARAM)
3257 updateActiveStateSoon();
3259 deleteBackingStoreSoon();
3261 case WM_SETTINGCHANGE:
3262 systemParameterChanged(wParam);
3267 void WebView::updateActiveStateSoon() const
3269 // This function is called while processing the WM_NCACTIVATE message.
3270 // While processing WM_NCACTIVATE when we are being deactivated, GetActiveWindow() will
3271 // still return our window. If we were to call updateActiveState() in that case, we would
3272 // wrongly think that we are still the active window. To work around this, we update our
3273 // active state after a 0-delay timer fires, at which point GetActiveWindow() will return
3274 // the newly-activated window.
3276 SetTimer(m_viewWindow, UpdateActiveStateTimer, 0, 0);
3279 void WebView::deleteBackingStoreSoon()
3281 if (pendingDeleteBackingStoreSet.size() > 2) {
3282 Vector<WebView*> views;
3283 HashSet<WebView*>::iterator end = pendingDeleteBackingStoreSet.end();
3284 for (HashSet<WebView*>::iterator it = pendingDeleteBackingStoreSet.begin(); it != end; ++it)
3286 for (int i = 0; i < views.size(); ++i)
3287 views[i]->deleteBackingStore();
3288 ASSERT(pendingDeleteBackingStoreSet.isEmpty());
3291 pendingDeleteBackingStoreSet.add(this);
3292 m_deleteBackingStoreTimerActive = true;
3293 SetTimer(m_viewWindow, DeleteBackingStoreTimer, delayBeforeDeletingBackingStoreMsec, 0);
3296 void WebView::cancelDeleteBackingStoreSoon()
3298 if (!m_deleteBackingStoreTimerActive)
3300 pendingDeleteBackingStoreSet.remove(this);
3301 m_deleteBackingStoreTimerActive = false;
3302 KillTimer(m_viewWindow, DeleteBackingStoreTimer);
3305 HRESULT STDMETHODCALLTYPE WebView::setHostWindow(
3306 /* [in] */ OLE_HANDLE oleWindow)
3308 HWND window = (HWND)(ULONG64)oleWindow;
3311 SetParent(m_viewWindow, window);
3312 else if (!isBeingDestroyed()) {
3313 // Turn the WebView into a message-only window so it will no longer be a child of the
3314 // old host window and will be hidden from screen. We only do this when
3315 // isBeingDestroyed() is false because doing this while handling WM_DESTROY can leave
3316 // m_viewWindow in a weird state (see <http://webkit.org/b/29337>).
3317 SetParent(m_viewWindow, HWND_MESSAGE);
3321 m_hostWindow = window;
3323 windowAncestryDidChange();
3328 HRESULT STDMETHODCALLTYPE WebView::hostWindow(
3329 /* [retval][out] */ OLE_HANDLE* window)
3331 *window = (OLE_HANDLE)(ULONG64)m_hostWindow;
3336 static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
3339 ? curr->tree()->traverseNextWithWrap(wrapFlag)
3340 : curr->tree()->traversePreviousWithWrap(wrapFlag);
3343 HRESULT STDMETHODCALLTYPE WebView::searchFor(
3344 /* [in] */ BSTR str,
3345 /* [in] */ BOOL forward,
3346 /* [in] */ BOOL caseFlag,
3347 /* [in] */ BOOL wrapFlag,
3348 /* [retval][out] */ BOOL* found)
3351 return E_INVALIDARG;
3353 if (!m_page || !m_page->mainFrame())
3354 return E_UNEXPECTED;
3356 if (!str || !SysStringLen(str))
3357 return E_INVALIDARG;
3359 *found = m_page->findString(String(str, SysStringLen(str)), caseFlag ? TextCaseSensitive : TextCaseInsensitive, forward ? FindDirectionForward : FindDirectionBackward, wrapFlag);
3363 bool WebView::active()
3365 HWND activeWindow = GetActiveWindow();
3366 if (usesLayeredWindow() && activeWindow == m_viewWindow)
3369 return (activeWindow && m_topLevelParent == findTopLevelParent(activeWindow));
3372 void WebView::updateActiveState()
3374 m_page->focusController()->setActive(active());
3377 HRESULT STDMETHODCALLTYPE WebView::updateFocusedAndActiveState()
3379 updateActiveState();
3381 bool active = m_page->focusController()->isActive();
3382 Frame* mainFrame = m_page->mainFrame();
3383 Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
3384 mainFrame->selection()->setFocused(active && mainFrame == focusedFrame);
3389 HRESULT STDMETHODCALLTYPE WebView::executeCoreCommandByName(BSTR bName, BSTR bValue)
3391 String name(bName, SysStringLen(bName));
3392 String value(bValue, SysStringLen(bValue));
3394 m_page->focusController()->focusedOrMainFrame()->editor()->command(name).execute(value);
3399 HRESULT STDMETHODCALLTYPE WebView::clearMainFrameName()
3401 m_page->mainFrame()->tree()->clearName();
3406 HRESULT STDMETHODCALLTYPE WebView::markAllMatchesForText(
3407 BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, UINT* matches)
3410 return E_INVALIDARG;
3412 if (!m_page || !m_page->mainFrame())
3413 return E_UNEXPECTED;
3415 if (!str || !SysStringLen(str))
3416 return E_INVALIDARG;
3418 *matches = m_page->markAllMatchesForText(String(str, SysStringLen(str)), caseSensitive ? TextCaseSensitive : TextCaseInsensitive, highlight, limit);
3422 HRESULT STDMETHODCALLTYPE WebView::unmarkAllTextMatches()
3424 if (!m_page || !m_page->mainFrame())
3425 return E_UNEXPECTED;
3427 m_page->unmarkAllTextMatches();
3431 HRESULT STDMETHODCALLTYPE WebView::rectsForTextMatches(
3432 IEnumTextMatches** pmatches)
3434 Vector<IntRect> allRects;
3435 WebCore::Frame* frame = m_page->mainFrame();
3437 if (Document* document = frame->document()) {
3438 IntRect visibleRect = frame->view()->visibleContentRect();
3439 Vector<IntRect> frameRects = document->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
3440 IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
3441 frameOffset = frame->view()->convertToContainingWindow(frameOffset);
3443 Vector<IntRect>::iterator end = frameRects.end();
3444 for (Vector<IntRect>::iterator it = frameRects.begin(); it < end; it++) {
3445 it->intersect(visibleRect);
3446 it->move(frameOffset.x(), frameOffset.y());
3447 allRects.append(*it);
3450 frame = incrementFrame(frame, true, false);
3453 return createMatchEnumerator(&allRects, pmatches);
3456 HRESULT STDMETHODCALLTYPE WebView::generateSelectionImage(BOOL forceWhiteText, OLE_HANDLE* hBitmap)
3460 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
3463 HBITMAP bitmap = imageFromSelection(frame, forceWhiteText ? TRUE : FALSE);
3464 *hBitmap = (OLE_HANDLE)(ULONG64)bitmap;
3470 HRESULT STDMETHODCALLTYPE WebView::selectionRect(RECT* rc)
3472 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
3475 IntRect ir = enclosingIntRect(frame->selection()->bounds());
3476 ir = frame->view()->convertToContainingWindow(ir);
3477 ir.move(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
3480 rc->bottom = rc->top + ir.height();
3481 rc->right = rc->left + ir.width();
3487 HRESULT STDMETHODCALLTYPE WebView::registerViewClass(
3488 /* [in] */ IWebDocumentView* /*view*/,
3489 /* [in] */ IWebDocumentRepresentation* /*representation*/,
3490 /* [in] */ BSTR /*forMIMEType*/)
3492 ASSERT_NOT_REACHED();
3496 HRESULT STDMETHODCALLTYPE WebView::setGroupName(
3497 /* [in] */ BSTR groupName)
3501 m_page->setGroupName(String(groupName, SysStringLen(groupName)));
3505 HRESULT STDMETHODCALLTYPE WebView::groupName(
3506 /* [retval][out] */ BSTR* groupName)
3511 String groupNameString = m_page->groupName();
3512 *groupName = SysAllocStringLen(groupNameString.characters(), groupNameString.length());
3513 if (!*groupName && groupNameString.length())
3514 return E_OUTOFMEMORY;
3518 HRESULT STDMETHODCALLTYPE WebView::estimatedProgress(
3519 /* [retval][out] */ double* estimatedProgress)
3521 *estimatedProgress = m_page->progress()->estimatedProgress();
3525 HRESULT STDMETHODCALLTYPE WebView::isLoading(
3526 /* [retval][out] */ BOOL* isLoading)
3528 COMPtr<IWebDataSource> dataSource;
3529 COMPtr<IWebDataSource> provisionalDataSource;
3539 if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
3540 dataSource->isLoading(isLoading);
3545 if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
3546 provisionalDataSource->isLoading(isLoading);
3550 HRESULT STDMETHODCALLTYPE WebView::elementAtPoint(
3551 /* [in] */ LPPOINT point,
3552 /* [retval][out] */ IPropertyBag** elementDictionary)
3554 if (!elementDictionary) {
3555 ASSERT_NOT_REACHED();
3559 *elementDictionary = 0;
3561 Frame* frame = core(m_mainFrame);
3565 IntPoint webCorePoint = IntPoint(point->x, point->y);
3566 HitTestResult result = HitTestResult(webCorePoint);
3567 if (frame->contentRenderer())
3568 result = frame->eventHandler()->hitTestResultAtPoint(webCorePoint, false);
3569 *elementDictionary = WebElementPropertyBag::createInstance(result);
3573 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForSelection(
3574 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3576 ASSERT_NOT_REACHED();
3580 HRESULT STDMETHODCALLTYPE WebView::writeSelectionWithPasteboardTypes(
3581 /* [size_is][in] */ BSTR* /*types*/,
3582 /* [in] */ int /*cTypes*/,
3583 /* [in] */ IDataObject* /*pasteboard*/)
3585 ASSERT_NOT_REACHED();
3589 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForElement(
3590 /* [in] */ IPropertyBag* /*elementDictionary*/,
3591 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3593 ASSERT_NOT_REACHED();
3597 HRESULT STDMETHODCALLTYPE WebView::writeElement(
3598 /* [in] */ IPropertyBag* /*elementDictionary*/,
3599 /* [size_is][in] */ BSTR* /*withPasteboardTypes*/,
3600 /* [in] */ int /*cWithPasteboardTypes*/,
3601 /* [in] */ IDataObject* /*pasteboard*/)
3603 ASSERT_NOT_REACHED();
3607 HRESULT STDMETHODCALLTYPE WebView::selectedText(
3608 /* [out, retval] */ BSTR* text)
3611 ASSERT_NOT_REACHED();