blob: c18ba7675dec57f8fb887240055e10de4d9f1e4e [file] [log] [blame]
/*
* Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple, Inc. All rights reserved.
* Copyright (C) 2009, 2010, 2011 Appcelerator, Inc. All rights reserved.
* Copyright (C) 2011 Brent Fulgham. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebView.h"
#include "CFDictionaryPropertyBag.h"
#include "DOMCoreClasses.h"
#include "FullscreenVideoController.h"
#include "MarshallingHelpers.h"
#include "SoftLinking.h"
#include "TextIterator.h"
#include "WebBackForwardList.h"
#include "WebChromeClient.h"
#include "WebContextMenuClient.h"
#include "WebCoreTextRenderer.h"
#include "WebDatabaseManager.h"
#include "WebDocumentLoader.h"
#include "WebDownload.h"
#include "WebDragClient.h"
#include "WebEditorClient.h"
#include "WebElementPropertyBag.h"
#include "WebFrame.h"
#include "WebFrameNetworkingContext.h"
#include "WebGeolocationClient.h"
#include "WebGeolocationPosition.h"
#include "WebIconDatabase.h"
#include "WebInspector.h"
#include "WebInspectorClient.h"
#include "WebKit.h"
#include "WebKitDLL.h"
#include "WebKitLogging.h"
#include "WebKitStatisticsPrivate.h"
#include "WebKitSystemBits.h"
#include "WebMutableURLRequest.h"
#include "WebNotificationCenter.h"
#include "WebPlatformStrategies.h"
#include "WebPreferences.h"
#include "WebScriptWorld.h"
#include "resource.h"
#include <JavaScriptCore/APICast.h>
#include <JavaScriptCore/InitializeThreading.h>
#include <JavaScriptCore/JSCJSValue.h>
#include <JavaScriptCore/JSLock.h>
#include <WebCore/AXObjectCache.h>
#include <WebCore/ApplicationCacheStorage.h>
#include <WebCore/BString.h>
#include <WebCore/BackForwardListImpl.h>
#include <WebCore/BitmapInfo.h>
#include <WebCore/Chrome.h>
#include <WebCore/ContextMenu.h>
#include <WebCore/ContextMenuController.h>
#include <WebCore/Cursor.h>
#include <WebCore/DatabaseManager.h>
#include <WebCore/Document.h>
#include <WebCore/DocumentMarkerController.h>
#include <WebCore/DragController.h>
#include <WebCore/DragData.h>
#include <WebCore/DragSession.h>
#include <WebCore/Editor.h>
#include <WebCore/EventHandler.h>
#include <WebCore/EventNames.h>
#include <WebCore/FileSystem.h>
#include <WebCore/FloatQuad.h>
#include <WebCore/FocusController.h>
#include <WebCore/Frame.h>
#include <WebCore/FrameLoader.h>
#include <WebCore/FrameSelection.h>
#include <WebCore/FrameTree.h>
#include <WebCore/FrameView.h>
#include <WebCore/FrameWin.h>
#include <WebCore/GDIObjectCounter.h>
#include <WebCore/GeolocationController.h>
#include <WebCore/GeolocationError.h>
#include <WebCore/GraphicsContext.h>
#include <WebCore/HTMLMediaElement.h>
#include <WebCore/HTMLNames.h>
#include <WebCore/HWndDC.h>
#include <WebCore/HistoryController.h>
#include <WebCore/HistoryItem.h>
#include <WebCore/HitTestRequest.h>
#include <WebCore/HitTestResult.h>
#include <WebCore/InitializeLogging.h>
#include <WebCore/IntRect.h>
#include <WebCore/JSElement.h>
#include <WebCore/KeyboardEvent.h>
#include <WebCore/MIMETypeRegistry.h>
#include <WebCore/MemoryCache.h>
#include <WebCore/Page.h>
#include <WebCore/PageCache.h>
#include <WebCore/PageGroup.h>
#include <WebCore/PlatformKeyboardEvent.h>
#include <WebCore/PlatformMouseEvent.h>
#include <WebCore/PlatformWheelEvent.h>
#include <WebCore/PluginData.h>
#include <WebCore/PluginDatabase.h>
#include <WebCore/PluginView.h>
#include <WebCore/PopupMenu.h>
#include <WebCore/PopupMenuWin.h>
#include <WebCore/ProgressTracker.h>
#include <WebCore/RenderLayer.h>
#include <WebCore/RenderTheme.h>
#include <WebCore/RenderTreeAsText.h>
#include <WebCore/RenderView.h>
#include <WebCore/RenderWidget.h>
#include <WebCore/ResourceHandle.h>
#include <WebCore/ResourceHandleClient.h>
#include <WebCore/ResourceRequest.h>
#include <WebCore/RuntimeEnabledFeatures.h>
#include <WebCore/SchemeRegistry.h>
#include <WebCore/ScriptController.h>
#include <WebCore/ScriptValue.h>
#include <WebCore/Scrollbar.h>
#include <WebCore/ScrollbarTheme.h>
#include <WebCore/SecurityOrigin.h>
#include <WebCore/SecurityPolicy.h>
#include <WebCore/Settings.h>
#include <WebCore/SimpleFontData.h>
#include <WebCore/SystemInfo.h>
#include <WebCore/WindowMessageBroadcaster.h>
#include <WebCore/WindowsTouch.h>
#include <wtf/MainThread.h>
#if USE(CG)
#include <CoreGraphics/CGContext.h>
#endif
#if USE(CF)
#include <CoreFoundation/CoreFoundation.h>
#endif
#if USE(CFNETWORK)
#include <CFNetwork/CFURLCachePriv.h>
#include <CFNetwork/CFURLProtocolPriv.h>
#include <WebKitSystemInterface/WebKitSystemInterface.h>
#endif
#if USE(ACCELERATED_COMPOSITING)
#include <WebCore/CACFLayerTreeHost.h>
#include <WebCore/PlatformCALayer.h>
#endif
#if ENABLE(FULLSCREEN_API)
#include <WebCore/FullScreenController.h>
#endif
#include <ShlObj.h>
#include <comutil.h>
#include <dimm.h>
#include <oleacc.h>
#include <wchar.h>
#include <windowsx.h>
#include <wtf/HashSet.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringConcatenate.h>
// Soft link functions for gestures and panning feedback
SOFT_LINK_LIBRARY(USER32);
SOFT_LINK_OPTIONAL(USER32, GetGestureInfo, BOOL, WINAPI, (HGESTUREINFO, PGESTUREINFO));
SOFT_LINK_OPTIONAL(USER32, SetGestureConfig, BOOL, WINAPI, (HWND, DWORD, UINT, PGESTURECONFIG, UINT));
SOFT_LINK_OPTIONAL(USER32, CloseGestureInfoHandle, BOOL, WINAPI, (HGESTUREINFO));
SOFT_LINK_LIBRARY(Uxtheme);
SOFT_LINK_OPTIONAL(Uxtheme, BeginPanningFeedback, BOOL, WINAPI, (HWND));
SOFT_LINK_OPTIONAL(Uxtheme, EndPanningFeedback, BOOL, WINAPI, (HWND, BOOL));
SOFT_LINK_OPTIONAL(Uxtheme, UpdatePanningFeedback, BOOL, WINAPI, (HWND, LONG, LONG, BOOL));
using namespace WebCore;
using namespace std;
using JSC::JSLock;
static HMODULE accessibilityLib;
static HashSet<WebView*> pendingDeleteBackingStoreSet;
static String webKitVersionString();
WebView* kit(Page* page)
{
return page ? static_cast<WebView*>(static_cast<WebChromeClient*>(page->chrome()->client())->webView()) : 0;
}
static inline AtomicString toAtomicString(BSTR bstr)
{
return AtomicString(bstr, SysStringLen(bstr));
}
static inline String toString(BSTR bstr)
{
return String(bstr, SysStringLen(bstr));
}
static inline KURL toKURL(BSTR bstr)
{
return KURL(KURL(), toString(bstr));
}
class PreferencesChangedOrRemovedObserver : public IWebNotificationObserver {
public:
static PreferencesChangedOrRemovedObserver* sharedInstance();
private:
PreferencesChangedOrRemovedObserver() {}
~PreferencesChangedOrRemovedObserver() {}
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) { return E_FAIL; }
virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; }
virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; }
public:
// IWebNotificationObserver
virtual HRESULT STDMETHODCALLTYPE onNotify(
/* [in] */ IWebNotification* notification);
private:
HRESULT notifyPreferencesChanged(WebCacheModel);
HRESULT notifyPreferencesRemoved(WebCacheModel);
};
PreferencesChangedOrRemovedObserver* PreferencesChangedOrRemovedObserver::sharedInstance()
{
static PreferencesChangedOrRemovedObserver* shared = new PreferencesChangedOrRemovedObserver;
return shared;
}
HRESULT PreferencesChangedOrRemovedObserver::onNotify(IWebNotification* notification)
{
HRESULT hr = S_OK;
COMPtr<IUnknown> unkPrefs;
hr = notification->getObject(&unkPrefs);
if (FAILED(hr))
return hr;
COMPtr<IWebPreferences> preferences(Query, unkPrefs);
if (!preferences)
return E_NOINTERFACE;
WebCacheModel cacheModel;
hr = preferences->cacheModel(&cacheModel);
if (FAILED(hr))
return hr;
BString name;
hr = notification->name(&name);
if (FAILED(hr))
return hr;
if (wcscmp(name, WebPreferences::webPreferencesChangedNotification()) == 0)
return notifyPreferencesChanged(cacheModel);
if (wcscmp(name, WebPreferences::webPreferencesRemovedNotification()) == 0)
return notifyPreferencesRemoved(cacheModel);
ASSERT_NOT_REACHED();
return E_FAIL;
}
HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesChanged(WebCacheModel cacheModel)
{
HRESULT hr = S_OK;
if (!WebView::didSetCacheModel() || cacheModel > WebView::cacheModel())
WebView::setCacheModel(cacheModel);
else if (cacheModel < WebView::cacheModel()) {
WebCacheModel sharedPreferencesCacheModel;
hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
if (FAILED(hr))
return hr;
WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
}
return hr;
}
HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesRemoved(WebCacheModel cacheModel)
{
HRESULT hr = S_OK;
if (cacheModel == WebView::cacheModel()) {
WebCacheModel sharedPreferencesCacheModel;
hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
if (FAILED(hr))
return hr;
WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
}
return hr;
}
const LPCWSTR kWebViewWindowClassName = L"WebViewWindowClass";
const int WM_XP_THEMECHANGED = 0x031A;
const int WM_VISTA_MOUSEHWHEEL = 0x020E;
static const int maxToolTipWidth = 250;
static const int delayBeforeDeletingBackingStoreMsec = 5000;
static ATOM registerWebView();
static void initializeStaticObservers();
static HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences*);
HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches);
static bool continuousSpellCheckingEnabled;
static bool grammarCheckingEnabled;
static bool s_didSetCacheModel;
static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
enum {
UpdateActiveStateTimer = 1,
DeleteBackingStoreTimer = 2,
};
// WebView ----------------------------------------------------------------
bool WebView::s_allowSiteSpecificHacks = false;
WebView::WebView()
: m_refCount(0)
, m_shouldInvertColors(false)
#if !ASSERT_DISABLED
, m_deletionHasBegun(false)
#endif
, m_hostWindow(0)
, m_viewWindow(0)
, m_mainFrame(0)
, m_page(0)
#if ENABLE(INSPECTOR)
, m_inspectorClient(0)
#endif // ENABLE(INSPECTOR)
, m_hasCustomDropTarget(false)
, m_useBackForwardList(true)
, m_userAgentOverridden(false)
, m_zoomMultiplier(1.0f)
, m_zoomsTextOnly(false)
, m_mouseActivated(false)
, m_dragData(0)
, m_currentCharacterCode(0)
, m_isBeingDestroyed(false)
, m_paintCount(0)
, m_hasSpellCheckerDocumentTag(false)
, m_didClose(false)
, m_inIMEComposition(0)
, m_toolTipHwnd(0)
, m_closeWindowTimer(0)
, m_topLevelParent(0)
, m_deleteBackingStoreTimerActive(false)
, m_transparent(false)
, m_lastPanX(0)
, m_lastPanY(0)
, m_xOverpan(0)
, m_yOverpan(0)
#if USE(ACCELERATED_COMPOSITING)
, m_isAcceleratedCompositing(false)
#endif
, m_nextDisplayIsSynchronous(false)
, m_lastSetCursor(0)
, m_usesLayeredWindow(false)
{
JSC::initializeThreading();
WTF::initializeMainThread();
m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper,(void**)&m_dropTargetHelper);
initializeStaticObservers();
WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
BOOL enabled;
if (SUCCEEDED(sharedPreferences->continuousSpellCheckingEnabled(&enabled)))
continuousSpellCheckingEnabled = !!enabled;
if (SUCCEEDED(sharedPreferences->grammarCheckingEnabled(&enabled)))
grammarCheckingEnabled = !!enabled;
WebViewCount++;
gClassCount++;
gClassNameCount.add("WebView");
}
WebView::~WebView()
{
deleteBackingStore();
// the tooltip window needs to be explicitly destroyed since it isn't a WS_CHILD
if (::IsWindow(m_toolTipHwnd))
::DestroyWindow(m_toolTipHwnd);
ASSERT(!m_page);
ASSERT(!m_preferences);
ASSERT(!m_viewWindow);
#if USE(ACCELERATED_COMPOSITING)
ASSERT(!m_layerTreeHost);
ASSERT(!m_backingLayer);
#endif
WebViewCount--;
gClassCount--;
gClassNameCount.remove("WebView");
}
WebView* WebView::createInstance()
{
WebView* instance = new WebView();
instance->AddRef();
return instance;
}
void initializeStaticObservers()
{
static bool initialized;
if (initialized)
return;
initialized = true;
IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesChangedNotification(), 0);
notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesRemovedNotification(), 0);
}
static HashSet<WebView*>& allWebViewsSet()
{
static HashSet<WebView*> allWebViewsSet;
return allWebViewsSet;
}
void WebView::addToAllWebViewsSet()
{
allWebViewsSet().add(this);
}
void WebView::removeFromAllWebViewsSet()
{
allWebViewsSet().remove(this);
}
void WebView::setCacheModel(WebCacheModel cacheModel)
{
#if USE(CFNETWORK)
if (s_didSetCacheModel && cacheModel == s_cacheModel)
return;
RetainPtr<CFURLCacheRef> cfurlCache = adoptCF(CFURLCacheCopySharedURLCache());
RetainPtr<CFStringRef> cfurlCacheDirectory = adoptCF(wkCopyFoundationCacheDirectory(0));
if (!cfurlCacheDirectory)
cfurlCacheDirectory = WebCore::localUserSpecificStorageDirectory().createCFString();
// As a fudge factor, use 1000 instead of 1024, in case the reported byte
// count doesn't align exactly to a megabyte boundary.
unsigned long long memSize = WebMemorySize() / 1024 / 1000;
unsigned long long diskFreeSize = WebVolumeFreeSize(cfurlCacheDirectory.get()) / 1024 / 1000;
unsigned cacheTotalCapacity = 0;
unsigned cacheMinDeadCapacity = 0;
unsigned cacheMaxDeadCapacity = 0;
double deadDecodedDataDeletionInterval = 0;
unsigned pageCacheCapacity = 0;
CFIndex cfurlCacheMemoryCapacity = 0;
CFIndex cfurlCacheDiskCapacity = 0;
switch (cacheModel) {
case WebCacheModelDocumentViewer: {
// Page cache capacity (in pages)
pageCacheCapacity = 0;
// Object cache capacities (in bytes)
if (memSize >= 2048)
cacheTotalCapacity = 96 * 1024 * 1024;
else if (memSize >= 1536)
cacheTotalCapacity = 64 * 1024 * 1024;
else if (memSize >= 1024)
cacheTotalCapacity = 32 * 1024 * 1024;
else if (memSize >= 512)
cacheTotalCapacity = 16 * 1024 * 1024;
cacheMinDeadCapacity = 0;
cacheMaxDeadCapacity = 0;
// Foundation memory cache capacity (in bytes)
cfurlCacheMemoryCapacity = 0;
// Foundation disk cache capacity (in bytes)
cfurlCacheDiskCapacity = CFURLCacheDiskCapacity(cfurlCache.get());
break;
}
case WebCacheModelDocumentBrowser: {
// Page cache capacity (in pages)
if (memSize >= 1024)
pageCacheCapacity = 3;
else if (memSize >= 512)
pageCacheCapacity = 2;
else if (memSize >= 256)
pageCacheCapacity = 1;
else
pageCacheCapacity = 0;
// Object cache capacities (in bytes)
if (memSize >= 2048)
cacheTotalCapacity = 96 * 1024 * 1024;
else if (memSize >= 1536)
cacheTotalCapacity = 64 * 1024 * 1024;
else if (memSize >= 1024)
cacheTotalCapacity = 32 * 1024 * 1024;
else if (memSize >= 512)
cacheTotalCapacity = 16 * 1024 * 1024;
cacheMinDeadCapacity = cacheTotalCapacity / 8;
cacheMaxDeadCapacity = cacheTotalCapacity / 4;
// Foundation memory cache capacity (in bytes)
if (memSize >= 2048)
cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
else if (memSize >= 1024)
cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
else if (memSize >= 512)
cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
else
cfurlCacheMemoryCapacity = 512 * 1024;
// Foundation disk cache capacity (in bytes)
if (diskFreeSize >= 16384)
cfurlCacheDiskCapacity = 50 * 1024 * 1024;
else if (diskFreeSize >= 8192)
cfurlCacheDiskCapacity = 40 * 1024 * 1024;
else if (diskFreeSize >= 4096)
cfurlCacheDiskCapacity = 30 * 1024 * 1024;
else
cfurlCacheDiskCapacity = 20 * 1024 * 1024;
break;
}
case WebCacheModelPrimaryWebBrowser: {
// Page cache capacity (in pages)
// (Research indicates that value / page drops substantially after 3 pages.)
if (memSize >= 2048)
pageCacheCapacity = 5;
else if (memSize >= 1024)
pageCacheCapacity = 4;
else if (memSize >= 512)
pageCacheCapacity = 3;
else if (memSize >= 256)
pageCacheCapacity = 2;
else
pageCacheCapacity = 1;
// Object cache capacities (in bytes)
// (Testing indicates that value / MB depends heavily on content and
// browsing pattern. Even growth above 128MB can have substantial
// value / MB for some content / browsing patterns.)
if (memSize >= 2048)
cacheTotalCapacity = 128 * 1024 * 1024;
else if (memSize >= 1536)
cacheTotalCapacity = 96 * 1024 * 1024;
else if (memSize >= 1024)
cacheTotalCapacity = 64 * 1024 * 1024;
else if (memSize >= 512)
cacheTotalCapacity = 32 * 1024 * 1024;
cacheMinDeadCapacity = cacheTotalCapacity / 4;
cacheMaxDeadCapacity = cacheTotalCapacity / 2;
// This code is here to avoid a PLT regression. We can remove it if we
// can prove that the overall system gain would justify the regression.
cacheMaxDeadCapacity = max(24u, cacheMaxDeadCapacity);
deadDecodedDataDeletionInterval = 60;
// Foundation memory cache capacity (in bytes)
// (These values are small because WebCore does most caching itself.)
if (memSize >= 1024)
cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
else if (memSize >= 512)
cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
else if (memSize >= 256)
cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
else
cfurlCacheMemoryCapacity = 512 * 1024;
// Foundation disk cache capacity (in bytes)
if (diskFreeSize >= 16384)
cfurlCacheDiskCapacity = 175 * 1024 * 1024;
else if (diskFreeSize >= 8192)
cfurlCacheDiskCapacity = 150 * 1024 * 1024;
else if (diskFreeSize >= 4096)
cfurlCacheDiskCapacity = 125 * 1024 * 1024;
else if (diskFreeSize >= 2048)
cfurlCacheDiskCapacity = 100 * 1024 * 1024;
else if (diskFreeSize >= 1024)
cfurlCacheDiskCapacity = 75 * 1024 * 1024;
else
cfurlCacheDiskCapacity = 50 * 1024 * 1024;
break;
}
default:
ASSERT_NOT_REACHED();
}
// Don't shrink a big disk cache, since that would cause churn.
cfurlCacheDiskCapacity = max(cfurlCacheDiskCapacity, CFURLCacheDiskCapacity(cfurlCache.get()));
memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
pageCache()->setCapacity(pageCacheCapacity);
CFURLCacheSetMemoryCapacity(cfurlCache.get(), cfurlCacheMemoryCapacity);
CFURLCacheSetDiskCapacity(cfurlCache.get(), cfurlCacheDiskCapacity);
s_didSetCacheModel = true;
s_cacheModel = cacheModel;
return;
#endif
}
WebCacheModel WebView::cacheModel()
{
return s_cacheModel;
}
bool WebView::didSetCacheModel()
{
return s_didSetCacheModel;
}
WebCacheModel WebView::maxCacheModelInAnyInstance()
{
WebCacheModel cacheModel = WebCacheModelDocumentViewer;
HashSet<WebView*>::iterator end = allWebViewsSet().end();
for (HashSet<WebView*>::iterator it = allWebViewsSet().begin(); it != end; ++it) {
COMPtr<IWebPreferences> pref;
if (FAILED((*it)->preferences(&pref)))
continue;
WebCacheModel prefCacheModel = WebCacheModelDocumentViewer;
if (FAILED(pref->cacheModel(&prefCacheModel)))
continue;
cacheModel = max(cacheModel, prefCacheModel);
}
return cacheModel;
}
HRESULT STDMETHODCALLTYPE WebView::close()
{
if (m_didClose)
return S_OK;
m_didClose = true;
#if USE(ACCELERATED_COMPOSITING)
setAcceleratedCompositing(false);
#endif
WebNotificationCenter::defaultCenterInternal()->postNotificationName(_bstr_t(WebViewWillCloseNotification).GetBSTR(), static_cast<IWebView*>(this), 0);
if (m_uiDelegatePrivate)
m_uiDelegatePrivate->webViewClosing(this);
removeFromAllWebViewsSet();
if (m_page) {
if (Frame* frame = m_page->mainFrame())
frame->loader()->detachFromParent();
}
if (m_mouseOutTracker) {
m_mouseOutTracker->dwFlags = TME_CANCEL;
::TrackMouseEvent(m_mouseOutTracker.get());
m_mouseOutTracker.clear();
}
revokeDragDrop();
if (m_viewWindow) {
// We can't check IsWindow(m_viewWindow) here, because that will return true even while
// we're already handling WM_DESTROY. So we check !isBeingDestroyed() instead.
if (!isBeingDestroyed())
DestroyWindow(m_viewWindow);
// Either we just destroyed m_viewWindow, or it's in the process of being destroyed. Either
// way, we clear it out to make sure we don't try to use it later.
m_viewWindow = 0;
}
setHostWindow(0);
setDownloadDelegate(0);
setEditingDelegate(0);
setFrameLoadDelegate(0);
setFrameLoadDelegatePrivate(0);
setHistoryDelegate(0);
setPolicyDelegate(0);
setResourceLoadDelegate(0);
setUIDelegate(0);
setFormDelegate(0);
#if ENABLE(INSPECTOR)
m_inspectorClient = 0;
if (m_webInspector)
m_webInspector->webViewClosed();
#endif // ENABLE(INSPECTOR)
delete m_page;
m_page = 0;
registerForIconNotification(false);
IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
notifyCenter->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
if (COMPtr<WebPreferences> preferences = m_preferences) {
BString identifier;
preferences->identifier(&identifier);
m_preferences = 0;
preferences->didRemoveFromWebView();
// Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
preferences = 0;
if (identifier)
WebPreferences::removeReferenceForIdentifier(identifier);
}
deleteBackingStore();
return S_OK;
}
void WebView::repaint(const WebCore::IntRect& windowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
{
#if USE(ACCELERATED_COMPOSITING)
if (isAcceleratedCompositing()) {
// The contentChanged, immediate, and repaintContentOnly parameters are all based on a non-
// compositing painting/scrolling model.
addToDirtyRegion(windowRect);
return;
}
#endif
if (!repaintContentOnly) {
RECT rect = windowRect;
::InvalidateRect(m_viewWindow, &rect, false);
}
if (contentChanged)
addToDirtyRegion(windowRect);
if (immediate) {
if (repaintContentOnly)
updateBackingStore(core(topLevelFrame())->view());
else
::UpdateWindow(m_viewWindow);
}
}
void WebView::deleteBackingStore()
{
pendingDeleteBackingStoreSet.remove(this);
if (m_deleteBackingStoreTimerActive) {
KillTimer(m_viewWindow, DeleteBackingStoreTimer);
m_deleteBackingStoreTimerActive = false;
}
m_backingStoreBitmap.clear();
m_backingStoreDirtyRegion.clear();
m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
}
bool WebView::ensureBackingStore()
{
RECT windowRect;
::GetClientRect(m_viewWindow, &windowRect);
LONG width = windowRect.right - windowRect.left;
LONG height = windowRect.bottom - windowRect.top;
if (width > 0 && height > 0 && (width != m_backingStoreSize.cx || height != m_backingStoreSize.cy)) {
deleteBackingStore();
m_backingStoreSize.cx = width;
m_backingStoreSize.cy = height;
BitmapInfo bitmapInfo = BitmapInfo::createBottomUp(IntSize(m_backingStoreSize));
void* pixels = NULL;
m_backingStoreBitmap = RefCountedHBITMAP::create(::CreateDIBSection(0, &bitmapInfo, DIB_RGB_COLORS, &pixels, 0, 0));
return true;
}
return false;
}
void WebView::addToDirtyRegion(const IntRect& dirtyRect)
{
// FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
// but it was being hit during our layout tests, and is being investigated in
// http://webkit.org/b/29350.
#if USE(ACCELERATED_COMPOSITING)
if (isAcceleratedCompositing()) {
m_backingLayer->setNeedsDisplayInRect(dirtyRect);
return;
}
#endif
HRGN newRegion = ::CreateRectRgn(dirtyRect.x(), dirtyRect.y(),
dirtyRect.maxX(), dirtyRect.maxY());
addToDirtyRegion(newRegion);
}
void WebView::addToDirtyRegion(HRGN newRegion)
{
#if USE(ACCELERATED_COMPOSITING)
ASSERT(!isAcceleratedCompositing());
#endif
LOCAL_GDI_COUNTER(0, __FUNCTION__);
if (m_backingStoreDirtyRegion) {
HRGN combinedRegion = ::CreateRectRgn(0,0,0,0);
::CombineRgn(combinedRegion, m_backingStoreDirtyRegion->handle(), newRegion, RGN_OR);
::DeleteObject(newRegion);
m_backingStoreDirtyRegion = RefCountedHRGN::create(combinedRegion);
} else
m_backingStoreDirtyRegion = RefCountedHRGN::create(newRegion);
if (m_uiDelegatePrivate)
m_uiDelegatePrivate->webViewDidInvalidate(this);
}
void WebView::scrollBackingStore(FrameView* frameView, int dx, int dy, const IntRect& scrollViewRect, const IntRect& clipRect)
{
#if USE(ACCELERATED_COMPOSITING)
if (isAcceleratedCompositing()) {
// FIXME: We should be doing something smarter here, like moving tiles around and painting
// any newly-exposed tiles. <http://webkit.org/b/52714>
m_backingLayer->setNeedsDisplayInRect(scrollViewRect);
return;
}
#endif
LOCAL_GDI_COUNTER(0, __FUNCTION__);
// If there's no backing store we don't need to update it
if (!m_backingStoreBitmap) {
if (m_uiDelegatePrivate)
m_uiDelegatePrivate->webViewScrolled(this);
return;
}
// Make a region to hold the invalidated scroll area.
HRGN updateRegion = ::CreateRectRgn(0, 0, 0, 0);
// Collect our device context info and select the bitmap to scroll.
HWndDC windowDC(m_viewWindow);
HDC bitmapDC = ::CreateCompatibleDC(windowDC);
HGDIOBJ oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
// Scroll the bitmap.
RECT scrollRectWin(scrollViewRect);
RECT clipRectWin(clipRect);
::ScrollDC(bitmapDC, dx, dy, &scrollRectWin, &clipRectWin, updateRegion, 0);
RECT regionBox;
::GetRgnBox(updateRegion, &regionBox);
// Flush.
GdiFlush();
// Add the dirty region to the backing store's dirty region.
addToDirtyRegion(updateRegion);
if (m_uiDelegatePrivate)
m_uiDelegatePrivate->webViewScrolled(this);
// Update the backing store.
updateBackingStore(frameView, bitmapDC, false);
// Clean up.
::SelectObject(bitmapDC, oldBitmap);
::DeleteDC(bitmapDC);
}
void WebView::sizeChanged(const IntSize& newSize)
{
deleteBackingStore();
if (Frame* coreFrame = core(topLevelFrame()))
coreFrame->view()->resize(newSize);
#if USE(ACCELERATED_COMPOSITING)
if (m_layerTreeHost)
m_layerTreeHost->resize();
if (m_backingLayer) {
m_backingLayer->setSize(newSize);
m_backingLayer->setNeedsDisplay();
}
#endif
}
// This emulates the Mac smarts for painting rects intelligently. This is very
// important for us, since we double buffer based off dirty rects.
static void getUpdateRects(HRGN region, const IntRect& dirtyRect, Vector<IntRect>& rects)
{
ASSERT_ARG(region, region);
const int cRectThreshold = 10;
const float cWastedSpaceThreshold = 0.75f;
rects.clear();
DWORD regionDataSize = GetRegionData(region, sizeof(RGNDATA), NULL);
if (!regionDataSize) {
rects.append(dirtyRect);
return;
}
Vector<unsigned char> buffer(regionDataSize);
RGNDATA* regionData = reinterpret_cast<RGNDATA*>(buffer.data());
GetRegionData(region, regionDataSize, regionData);
if (regionData->rdh.nCount > cRectThreshold) {
rects.append(dirtyRect);
return;
}
double singlePixels = 0.0;
unsigned i;
RECT* rect;
for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
singlePixels += (rect->right - rect->left) * (rect->bottom - rect->top);
double unionPixels = dirtyRect.width() * dirtyRect.height();
double wastedSpace = 1.0 - (singlePixels / unionPixels);
if (wastedSpace <= cWastedSpaceThreshold) {
rects.append(dirtyRect);
return;
}
for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
rects.append(*rect);
}
void WebView::updateBackingStore(FrameView* frameView, HDC dc, bool backingStoreCompletelyDirty, WindowsToPaint windowsToPaint)
{
#if USE(ACCELERATED_COMPOSITING)
ASSERT(!isAcceleratedCompositing());
#endif
LOCAL_GDI_COUNTER(0, __FUNCTION__);
HDC bitmapDC = dc;
HGDIOBJ oldBitmap = 0;
if (!dc) {
HWndDC windowDC(m_viewWindow);
bitmapDC = ::CreateCompatibleDC(windowDC);
oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
}
if (m_backingStoreBitmap && (m_backingStoreDirtyRegion || backingStoreCompletelyDirty)) {
// Do a layout first so that everything we render to the backing store is always current.
if (Frame* coreFrame = core(m_mainFrame))
if (FrameView* view = coreFrame->view())
view->updateLayoutAndStyleIfNeededRecursive();
Vector<IntRect> paintRects;
if (!backingStoreCompletelyDirty && m_backingStoreDirtyRegion) {
RECT regionBox;
::GetRgnBox(m_backingStoreDirtyRegion->handle(), &regionBox);
getUpdateRects(m_backingStoreDirtyRegion->handle(), regionBox, paintRects);
} else {
RECT clientRect;
::GetClientRect(m_viewWindow, &clientRect);
paintRects.append(clientRect);
}
for (unsigned i = 0; i < paintRects.size(); ++i)
paintIntoBackingStore(frameView, bitmapDC, paintRects[i], windowsToPaint);
if (m_uiDelegatePrivate)
m_uiDelegatePrivate->webViewPainted(this);
m_backingStoreDirtyRegion.clear();
}
if (!dc) {
::SelectObject(bitmapDC, oldBitmap);
::DeleteDC(bitmapDC);
}
GdiFlush();
}
void WebView::performLayeredWindowUpdate()
{
// The backing store may have been destroyed if the window rect was set to zero height or zero width.
if (!m_backingStoreBitmap)
return;
HWndDC hdcScreen(m_viewWindow);
OwnPtr<HDC> hdcMem = adoptPtr(::CreateCompatibleDC(hdcScreen));
HBITMAP hbmOld = static_cast<HBITMAP>(::SelectObject(hdcMem.get(), m_backingStoreBitmap->handle()));
BITMAP bmpInfo;
::GetObject(m_backingStoreBitmap->handle(), sizeof(bmpInfo), &bmpInfo);
SIZE windowSize = { bmpInfo.bmWidth, bmpInfo.bmHeight };
BLENDFUNCTION blendFunction;
blendFunction.BlendOp = AC_SRC_OVER;
blendFunction.BlendFlags = 0;
blendFunction.SourceConstantAlpha = 0xFF;
blendFunction.AlphaFormat = AC_SRC_ALPHA;
POINT layerPos = { 0, 0 };
::UpdateLayeredWindow(m_viewWindow, hdcScreen, 0, &windowSize, hdcMem.get(), &layerPos, 0, &blendFunction, ULW_ALPHA);
::SelectObject(hdcMem.get(), hbmOld);
}
void WebView::paint(HDC dc, LPARAM options)
{
LOCAL_GDI_COUNTER(0, __FUNCTION__);
#if USE(ACCELERATED_COMPOSITING)
if (isAcceleratedCompositing() && !usesLayeredWindow()) {
m_layerTreeHost->flushPendingLayerChangesNow();
// Flushing might have taken us out of compositing mode.
if (isAcceleratedCompositing()) {
// FIXME: We need to paint into dc (if provided). <http://webkit.org/b/52578>
m_layerTreeHost->paint();
::ValidateRect(m_viewWindow, 0);
return;
}
}
#endif
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame)
return;
FrameView* frameView = coreFrame->view();
RECT rcPaint;
HDC hdc;
OwnPtr<HRGN> region;
int regionType = NULLREGION;
PAINTSTRUCT ps;
WindowsToPaint windowsToPaint;
if (!dc) {
region = adoptPtr(CreateRectRgn(0,0,0,0));
regionType = GetUpdateRgn(m_viewWindow, region.get(), false);
hdc = BeginPaint(m_viewWindow, &ps);
rcPaint = ps.rcPaint;
// We're painting to the screen, and our child windows can handle
// painting themselves to the screen.
windowsToPaint = PaintWebViewOnly;
} else {
hdc = dc;
::GetClientRect(m_viewWindow, &rcPaint);
if (options & PRF_ERASEBKGND)
::FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
// Since we aren't painting to the screen, we want to paint all our
// children into the HDC.
windowsToPaint = PaintWebViewAndChildren;
}
bool backingStoreCompletelyDirty = ensureBackingStore();
if (!m_backingStoreBitmap) {
if (!dc)
EndPaint(m_viewWindow, &ps);
return;
}
m_paintCount++;
HDC bitmapDC = ::CreateCompatibleDC(hdc);
HGDIOBJ oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
// Update our backing store if needed.
updateBackingStore(frameView, bitmapDC, backingStoreCompletelyDirty, windowsToPaint);
// Now we blit the updated backing store
IntRect windowDirtyRect = rcPaint;
// Apply the same heuristic for this update region too.
Vector<IntRect> blitRects;
if (region && regionType == COMPLEXREGION)
getUpdateRects(region.get(), windowDirtyRect, blitRects);
else
blitRects.append(windowDirtyRect);
for (unsigned i = 0; i < blitRects.size(); ++i)
paintIntoWindow(bitmapDC, hdc, blitRects[i]);
::SelectObject(bitmapDC, oldBitmap);
::DeleteDC(bitmapDC);
if (!dc)
EndPaint(m_viewWindow, &ps);
m_paintCount--;
if (active())
cancelDeleteBackingStoreSoon();
else
deleteBackingStoreSoon();
}
void WebView::paintIntoBackingStore(FrameView* frameView, HDC bitmapDC, const IntRect& dirtyRect, WindowsToPaint windowsToPaint)
{
// FIXME: This function should never be called in accelerated compositing mode, and we should
// assert as such. But currently it *is* sometimes called, so we can't assert yet. See
// <http://webkit.org/b/58539>.
LOCAL_GDI_COUNTER(0, __FUNCTION__);
// FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
// but it was being hit during our layout tests, and is being investigated in
// http://webkit.org/b/29350.
RECT rect = dirtyRect;
#if FLASH_BACKING_STORE_REDRAW
{
HWndDC dc(m_viewWindow);
OwnPtr<HBRUSH> yellowBrush(CreateSolidBrush(RGB(255, 255, 0)));
FillRect(dc, &rect, yellowBrush.get());
GdiFlush();
Sleep(50);
paintIntoWindow(bitmapDC, dc, dirtyRect);
}
#endif
GraphicsContext gc(bitmapDC, m_transparent);
gc.setShouldIncludeChildWindows(windowsToPaint == PaintWebViewAndChildren);
gc.save();
if (m_transparent)
gc.clearRect(dirtyRect);
else
FillRect(bitmapDC, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
COMPtr<IWebUIDelegatePrivate2> uiPrivate(Query, m_uiDelegate);
if (uiPrivate)
uiPrivate->drawBackground(this, reinterpret_cast<OLE_HANDLE>(bitmapDC), &rect);
if (frameView && frameView->frame() && frameView->frame()->contentRenderer()) {
gc.clip(dirtyRect);
frameView->paint(&gc, dirtyRect);
if (m_shouldInvertColors)
gc.fillRect(dirtyRect, Color::white, ColorSpaceDeviceRGB, CompositeDifference);
}
gc.restore();
}
void WebView::paintIntoWindow(HDC bitmapDC, HDC windowDC, const IntRect& dirtyRect)
{
// FIXME: This function should never be called in accelerated compositing mode, and we should
// assert as such. But currently it *is* sometimes called, so we can't assert yet. See
// <http://webkit.org/b/58539>.
LOCAL_GDI_COUNTER(0, __FUNCTION__);
#if FLASH_WINDOW_REDRAW
OwnPtr<HBRUSH> greenBrush = CreateSolidBrush(RGB(0, 255, 0));
RECT rect = dirtyRect;
FillRect(windowDC, &rect, greenBrush.get());
GdiFlush();
Sleep(50);
#endif
// Blit the dirty rect from the backing store into the same position
// in the destination DC.
BitBlt(windowDC, dirtyRect.x(), dirtyRect.y(), dirtyRect.width(), dirtyRect.height(), bitmapDC,
dirtyRect.x(), dirtyRect.y(), SRCCOPY);
}
void WebView::frameRect(RECT* rect)
{
::GetWindowRect(m_viewWindow, rect);
}
class WindowCloseTimer : public WebCore::SuspendableTimer {
public:
static WindowCloseTimer* create(WebView*);
private:
WindowCloseTimer(ScriptExecutionContext*, WebView*);
virtual void contextDestroyed();
virtual void fired();
WebView* m_webView;
};
WindowCloseTimer* WindowCloseTimer::create(WebView* webView)
{
ASSERT_ARG(webView, webView);
Frame* frame = core(webView->topLevelFrame());
ASSERT(frame);
if (!frame)
return 0;
Document* document = frame->document();
ASSERT(document);
if (!document)
return 0;
return new WindowCloseTimer(document, webView);
}
WindowCloseTimer::WindowCloseTimer(ScriptExecutionContext* context, WebView* webView)
: SuspendableTimer(context)
, m_webView(webView)
{
ASSERT_ARG(context, context);
ASSERT_ARG(webView, webView);
}
void WindowCloseTimer::contextDestroyed()
{
SuspendableTimer::contextDestroyed();
delete this;
}
void WindowCloseTimer::fired()
{
m_webView->closeWindowTimerFired();
}
void WebView::closeWindowSoon()
{
if (m_closeWindowTimer)
return;
m_closeWindowTimer = WindowCloseTimer::create(this);
if (!m_closeWindowTimer)
return;
m_closeWindowTimer->startOneShot(0);
AddRef();
}
void WebView::closeWindowTimerFired()
{
closeWindow();
Release();
}
void WebView::closeWindow()
{
if (m_hasSpellCheckerDocumentTag) {
if (m_editingDelegate)
m_editingDelegate->closeSpellDocument(this);
m_hasSpellCheckerDocumentTag = false;
}
COMPtr<IWebUIDelegate> ui;
if (SUCCEEDED(uiDelegate(&ui)))
ui->webViewClose(this);
}
bool WebView::canHandleRequest(const WebCore::ResourceRequest& request)
{
// On the mac there's an about url protocol implementation but CFNetwork doesn't have that.
if (equalIgnoringCase(String(request.url().protocol()), "about"))
return true;
#if USE(CFNETWORK)
if (CFURLProtocolCanHandleRequest(request.cfURLRequest(UpdateHTTPBody)))
return true;
// FIXME: Mac WebKit calls _representationExistsForURLScheme here
return false;
#else
return true;
#endif
}
String WebView::standardUserAgentWithApplicationName(const String& applicationName)
{
DEFINE_STATIC_LOCAL(String, osVersion, (windowsVersionForUAString()));
DEFINE_STATIC_LOCAL(String, webKitVersion, (webKitVersionString()));
return makeString("Mozilla/5.0 (", osVersion, ") AppleWebKit/", webKitVersion, " (KHTML, like Gecko)", applicationName.isEmpty() ? "" : " ", applicationName);
}
Page* WebView::page()
{
return m_page;
}
bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam)
{
// Translate the screen coordinates into window coordinates
POINT coords = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
if (coords.x == -1 || coords.y == -1) {
// The contextMenuController() holds onto the last context menu that was popped up on the
// page until a new one is created. We need to clear this menu before propagating the event
// through the DOM so that we can detect if we create a new menu for this event, since we
// won't create a new menu if the DOM swallows the event and the defaultEventHandler does
// not run.
m_page->contextMenuController()->clearContextMenu();
Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
return focusedFrame->eventHandler()->sendContextMenuEventForKey();
} else {
if (!::ScreenToClient(m_viewWindow, &coords))
return false;
}
lParam = MAKELPARAM(coords.x, coords.y);
m_page->contextMenuController()->clearContextMenu();
IntPoint documentPoint(m_page->mainFrame()->view()->windowToContents(coords));
HitTestResult result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(documentPoint);
Frame* targetFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : m_page->focusController()->focusedOrMainFrame();
targetFrame->view()->setCursor(pointerCursor());
PlatformMouseEvent mouseEvent(m_viewWindow, WM_RBUTTONUP, wParam, lParam);
bool handledEvent = targetFrame->eventHandler()->sendContextMenuEvent(mouseEvent);
if (!handledEvent)
return false;
ContextMenuController* contextMenuController = m_page->contextMenuController();
// Show the menu
ContextMenu* coreMenu = contextMenuController->contextMenu();
if (!coreMenu)
return false;
Frame* frame = contextMenuController->hitTestResult().innerNodeFrame();
if (!frame)
return false;
FrameView* view = frame->view();
if (!view)
return false;
POINT point(view->contentsToWindow(contextMenuController->hitTestResult().roundedPointInInnerNodeFrame()));
// Translate the point to screen coordinates
if (!::ClientToScreen(m_viewWindow, &point))
return false;
BOOL hasCustomMenus = false;
if (m_uiDelegate)
m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
if (hasCustomMenus)
m_uiDelegate->trackCustomPopupMenu((IWebView*)this, (OLE_HANDLE)(ULONG64)coreMenu->platformContextMenu(), &point);
else {
// Surprisingly, TPM_RIGHTBUTTON means that items are selectable with either the right OR left mouse button
UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL
| TPM_LEFTALIGN | TPM_HORPOSANIMATION;
::TrackPopupMenuEx(coreMenu->platformContextMenu(), flags, point.x, point.y, m_viewWindow, 0);
}
return true;
}
bool WebView::onMeasureItem(WPARAM /*wParam*/, LPARAM lParam)
{
if (!m_uiDelegate)
return false;
BOOL hasCustomMenus = false;
m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
if (!hasCustomMenus)
return false;
m_uiDelegate->measureCustomMenuItem((IWebView*)this, (void*)lParam);
return true;
}
bool WebView::onDrawItem(WPARAM /*wParam*/, LPARAM lParam)
{
if (!m_uiDelegate)
return false;
BOOL hasCustomMenus = false;
m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
if (!hasCustomMenus)
return false;
m_uiDelegate->drawCustomMenuItem((IWebView*)this, (void*)lParam);
return true;
}
bool WebView::onInitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
{
if (!m_uiDelegate)
return false;
HMENU menu = (HMENU)wParam;
if (!menu)
return false;
BOOL hasCustomMenus = false;
m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
if (!hasCustomMenus)
return false;
m_uiDelegate->addCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
return true;
}
bool WebView::onUninitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
{
if (!m_uiDelegate)
return false;
HMENU menu = (HMENU)wParam;
if (!menu)
return false;
BOOL hasCustomMenus = false;
m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
if (!hasCustomMenus)
return false;
m_uiDelegate->cleanUpCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
return true;
}
void WebView::performContextMenuAction(WPARAM wParam, LPARAM lParam, bool byPosition)
{
ContextMenu* menu = m_page->contextMenuController()->contextMenu();
ASSERT(menu);
ContextMenuItem* item = byPosition ? menu->itemAtIndex((unsigned)wParam) : menu->itemWithAction((ContextMenuAction)wParam);
if (!item)
return;
m_page->contextMenuController()->contextMenuItemSelected(item);
}
bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
{
static LONG globalClickCount;
static IntPoint globalPrevPoint;
static MouseButton globalPrevButton;
static LONG globalPrevMouseDownTime;
if (message == WM_CANCELMODE) {
m_page->mainFrame()->eventHandler()->lostMouseCapture();
return true;
}
// Create our event.
// On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
// of the event to be at (MINSHORT, MINSHORT).
LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
setMouseActivated(false);
bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.position().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
abs(globalPrevPoint.y() - mouseEvent.position().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
LONG messageTime = ::GetMessageTime();
bool handled = false;
if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
// FIXME: I'm not sure if this is the "right" way to do this
// but without this call, we never become focused since we don't allow
// the default handling of mouse events.
SetFocus(m_viewWindow);
// Always start capturing events when the mouse goes down in our HWND.
::SetCapture(m_viewWindow);
if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) &&
insideThreshold &&
mouseEvent.button() == globalPrevButton)
globalClickCount++;
else
// Reset the click count.
globalClickCount = 1;
globalPrevMouseDownTime = messageTime;
globalPrevButton = mouseEvent.button();
globalPrevPoint = mouseEvent.position();
mouseEvent.setClickCount(globalClickCount);
handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
} else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
globalClickCount++;
mouseEvent.setClickCount(globalClickCount);
handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
} else if (message == WM_LBUTTONUP || message == WM_MBUTTONUP || message == WM_RBUTTONUP) {
// Record the global position and the button of the up.
globalPrevButton = mouseEvent.button();
globalPrevPoint = mouseEvent.position();
mouseEvent.setClickCount(globalClickCount);
m_page->mainFrame()->eventHandler()->handleMouseReleaseEvent(mouseEvent);
::ReleaseCapture();
} else if (message == WM_MOUSELEAVE && m_mouseOutTracker) {
// Once WM_MOUSELEAVE is fired windows clears this tracker
// so there is no need to disable it ourselves.
m_mouseOutTracker.clear();
m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
handled = true;
} else if (message == WM_MOUSEMOVE) {
if (!insideThreshold)
globalClickCount = 0;
mouseEvent.setClickCount(globalClickCount);
handled = m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
if (!m_mouseOutTracker) {
m_mouseOutTracker = adoptPtr(new TRACKMOUSEEVENT);
m_mouseOutTracker->cbSize = sizeof(TRACKMOUSEEVENT);
m_mouseOutTracker->dwFlags = TME_LEAVE;
m_mouseOutTracker->hwndTrack = m_viewWindow;
::TrackMouseEvent(m_mouseOutTracker.get());
}
}
return handled;
}
bool WebView::gestureNotify(WPARAM wParam, LPARAM lParam)
{
GESTURENOTIFYSTRUCT* gn = reinterpret_cast<GESTURENOTIFYSTRUCT*>(lParam);
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame)
return false;
ScrollView* view = coreFrame->view();
if (!view)
return false;
// If we don't have this function, we shouldn't be receiving this message
ASSERT(SetGestureConfigPtr());
bool hitScrollbar = false;
POINT gestureBeginPoint = {gn->ptsLocation.x, gn->ptsLocation.y};
HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
for (Frame* childFrame = m_page->mainFrame(); childFrame; childFrame = EventHandler::subframeForTargetNode(m_gestureTargetNode.get())) {
FrameView* frameView = childFrame->view();
if (!frameView)
break;
RenderView* renderView = childFrame->document()->renderView();
if (!renderView)
break;
RenderLayer* layer = renderView->layer();
if (!layer)
break;
HitTestResult result(frameView->screenToContents(gestureBeginPoint));
layer->hitTest(request, result);
m_gestureTargetNode = result.innerNode();
if (!hitScrollbar)
hitScrollbar = result.scrollbar();
}
if (!hitScrollbar) {
// The hit testing above won't detect if we've hit the main frame's vertical scrollbar. Check that manually now.
RECT webViewRect;
GetWindowRect(m_viewWindow, &webViewRect);
hitScrollbar = view->verticalScrollbar() && (gestureBeginPoint.x > (webViewRect.right - view->verticalScrollbar()->theme()->scrollbarThickness()));
}
bool canBeScrolled = false;
if (m_gestureTargetNode) {
for (RenderObject* renderer = m_gestureTargetNode->renderer(); renderer; renderer = renderer->parent()) {
if (renderer->isBox() && toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()) {
canBeScrolled = true;
break;
}
}
}
// We always allow two-fingered panning with inertia and a gutter (which limits movement to one
// direction in most cases).
DWORD dwPanWant = GC_PAN | GC_PAN_WITH_INERTIA | GC_PAN_WITH_GUTTER;
// We never allow single-fingered horizontal panning. That gesture is reserved for creating text
// selections. This matches IE.
DWORD dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
if (hitScrollbar || !canBeScrolled) {
// The part of the page under the gesture can't be scrolled, or the gesture is on a scrollbar.
// Disallow single-fingered vertical panning in this case, too, so we'll fall back to the default
// behavior (which allows the scrollbar thumb to be dragged, text selections to be made, etc.).
dwPanBlock |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
} else {
// The part of the page the gesture is under can be scrolled, and we're not under a scrollbar.
// Allow single-fingered vertical panning in this case, so the user will be able to pan the page
// with one or two fingers.
dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
}
GESTURECONFIG gc = { GID_PAN, dwPanWant, dwPanBlock };
return SetGestureConfigPtr()(m_viewWindow, 0, 1, &gc, sizeof(GESTURECONFIG));
}
bool WebView::gesture(WPARAM wParam, LPARAM lParam)
{
// We want to bail out if we don't have either of these functions
if (!GetGestureInfoPtr() || !CloseGestureInfoHandlePtr())
return false;
HGESTUREINFO gestureHandle = reinterpret_cast<HGESTUREINFO>(lParam);
GESTUREINFO gi = {0};
gi.cbSize = sizeof(GESTUREINFO);
if (!GetGestureInfoPtr()(gestureHandle, reinterpret_cast<PGESTUREINFO>(&gi)))
return false;
switch (gi.dwID) {
case GID_BEGIN:
m_lastPanX = gi.ptsLocation.x;
m_lastPanY = gi.ptsLocation.y;
break;
case GID_END:
m_gestureTargetNode = 0;
break;
case GID_PAN: {
// Where are the fingers currently?
long currentX = gi.ptsLocation.x;
long currentY = gi.ptsLocation.y;
// How far did we pan in each direction?
long deltaX = currentX - m_lastPanX;
long deltaY = currentY - m_lastPanY;
// Calculate the overpan for window bounce
m_yOverpan -= m_lastPanY - currentY;
m_xOverpan -= m_lastPanX - currentX;
// Update our class variables with updated values
m_lastPanX = currentX;
m_lastPanY = currentY;
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame) {
CloseGestureInfoHandlePtr()(gestureHandle);
return false;
}
if (!m_gestureTargetNode || !m_gestureTargetNode->renderer())
return false;
// We negate here since panning up moves the content up, but moves the scrollbar down.
m_gestureTargetNode->renderer()->enclosingLayer()->scrollByRecursively(IntSize(-deltaX, -deltaY));
if (!(UpdatePanningFeedbackPtr() && BeginPanningFeedbackPtr() && EndPanningFeedbackPtr())) {
CloseGestureInfoHandlePtr()(gestureHandle);
return true;
}
if (gi.dwFlags & GF_BEGIN) {
BeginPanningFeedbackPtr()(m_viewWindow);
m_yOverpan = 0;
} else if (gi.dwFlags & GF_END) {
EndPanningFeedbackPtr()(m_viewWindow, true);
m_yOverpan = 0;
}
ScrollView* view = coreFrame->view();
if (!view) {
CloseGestureInfoHandlePtr()(gestureHandle);
return true;
}
Scrollbar* vertScrollbar = view->verticalScrollbar();
if (!vertScrollbar) {
CloseGestureInfoHandlePtr()(gestureHandle);
return true;
}
// FIXME: Support Horizontal Window Bounce. <https://webkit.org/b/28500>.
// FIXME: If the user starts panning down after a window bounce has started, the window doesn't bounce back
// until they release their finger. <https://webkit.org/b/28501>.
if (vertScrollbar->currentPos() == 0)
UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
else if (vertScrollbar->currentPos() >= vertScrollbar->maximum())
UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
CloseGestureInfoHandlePtr()(gestureHandle);
return true;
}
default:
break;
}
// If we get to this point, the gesture has not been handled. We forward
// the call to DefWindowProc by returning false, and we don't need to
// to call CloseGestureInfoHandle.
// http://msdn.microsoft.com/en-us/library/dd353228(VS.85).aspx
return false;
}
bool WebView::mouseWheel(WPARAM wParam, LPARAM lParam, bool isMouseHWheel)
{
// Ctrl+Mouse wheel doesn't ever go into WebCore. It is used to
// zoom instead (Mac zooms the whole Desktop, but Windows browsers trigger their
// own local zoom modes for Ctrl+wheel).
if (wParam & MK_CONTROL) {
short delta = short(HIWORD(wParam));
if (delta < 0)
makeTextSmaller(0);
else
makeTextLarger(0);
return true;
}
// 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.
HWND focusedWindow = GetFocus();
if (focusedWindow && focusedWindow != m_viewWindow) {
// 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).
WCHAR className[256];
// Make sure truncation won't affect the comparison.
ASSERT(WTF_ARRAY_LENGTH(className) > wcslen(PopupMenuWin::popupClassName()));
if (GetClassNameW(focusedWindow, className, WTF_ARRAY_LENGTH(className)) && !wcscmp(className, PopupMenuWin::popupClassName())) {
// We don't let the WebView scroll here for two reasons - 1) To match Firefox behavior, 2) If we do scroll, we lose the
// focus ring around the select menu.
SetFocus(m_viewWindow);
return true;
}
}
PlatformWheelEvent wheelEvent(m_viewWindow, wParam, lParam, isMouseHWheel);
Frame* coreFrame = core(m_mainFrame);
if (!coreFrame)
return false;
return coreFrame->eventHandler()->handleWheelEvent(wheelEvent);
}
bool WebView::verticalScroll(WPARAM wParam, LPARAM /*lParam*/)
{
ScrollDirection direction;
ScrollGranularity granularity;
switch (LOWORD(wParam)) {
case SB_LINEDOWN:
granularity = ScrollByLine;
direction = ScrollDown;
break;
case SB_LINEUP:
granularity = ScrollByLine;
direction = ScrollUp;
break;
case SB_PAGEDOWN:
granularity = ScrollByDocument;
direction = ScrollDown;
break;
case SB_PAGEUP:
granularity = ScrollByDocument;
direction = ScrollUp;
break;
default:
return false;
break;
}
Frame* frame = m_page->focusController()->focusedOrMainFrame();
return frame->eventHandler()->scrollRecursively(direction, granularity);
}
bool WebView::horizontalScroll(WPARAM wParam, LPARAM /*lParam*/)
{
ScrollDirection direction;
ScrollGranularity granularity;
switch (LOWORD(wParam)) {
case SB_LINELEFT:
granularity = ScrollByLine;
direction = ScrollLeft;
break;
case SB_LINERIGHT:
granularity = ScrollByLine;
direction = ScrollRight;
break;
case SB_PAGELEFT:
granularity = ScrollByDocument;
direction = ScrollLeft;
break;
case SB_PAGERIGHT:
granularity = ScrollByDocument;
direction = ScrollRight;
break;
default:
return false;
}
Frame* frame = m_page->focusController()->focusedOrMainFrame();
return frame->eventHandler()->scrollRecursively(direction, granularity);
}
bool WebView::execCommand(WPARAM wParam, LPARAM /*lParam*/)
{
Frame* frame = m_page->focusController()->focusedOrMainFrame();
switch (LOWORD(wParam)) {
case SelectAll:
return frame->editor().command("SelectAll").execute();
case Undo:
return frame->editor().command("Undo").execute();
case Redo:
return frame->editor().command("Redo").execute();
}
return false;
}
bool WebView::keyUp(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
{
PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformEvent::KeyUp, systemKeyDown);
Frame* frame = m_page->focusController()->focusedOrMainFrame();
m_currentCharacterCode = 0;
return frame->eventHandler()->keyEvent(keyEvent);
}
static const unsigned CtrlKey = 1 << 0;
static const unsigned AltKey = 1 << 1;
static const unsigned ShiftKey = 1 << 2;
struct KeyDownEntry {
unsigned virtualKey;
unsigned modifiers;
const char* name;
};
struct KeyPressEntry {
unsigned charCode;
unsigned modifiers;
const char* name;
};
static const KeyDownEntry keyDownEntries[] = {
{ VK_LEFT, 0, "MoveLeft" },
{ VK_LEFT, ShiftKey, "MoveLeftAndModifySelection" },
{ VK_LEFT, CtrlKey, "MoveWordLeft" },
{ VK_LEFT, CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection" },
{ VK_RIGHT, 0, "MoveRight" },
{ VK_RIGHT, ShiftKey, "MoveRightAndModifySelection" },
{ VK_RIGHT, CtrlKey, "MoveWordRight" },
{ VK_RIGHT, CtrlKey | ShiftKey, "MoveWordRightAndModifySelection" },
{ VK_UP, 0, "MoveUp" },
{ VK_UP, ShiftKey, "MoveUpAndModifySelection" },
{ VK_PRIOR, ShiftKey, "MovePageUpAndModifySelection" },
{ VK_DOWN, 0, "MoveDown" },
{ VK_DOWN, ShiftKey, "MoveDownAndModifySelection" },
{ VK_NEXT, ShiftKey, "MovePageDownAndModifySelection" },
{ VK_PRIOR, 0, "MovePageUp" },
{ VK_NEXT, 0, "MovePageDown" },
{ VK_HOME, 0, "MoveToBeginningOfLine" },
{ VK_HOME, ShiftKey, "MoveToBeginningOfLineAndModifySelection" },
{ VK_HOME, CtrlKey, "MoveToBeginningOfDocument" },
{ VK_HOME, CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
{ VK_END, 0, "MoveToEndOfLine" },
{ VK_END, ShiftKey, "MoveToEndOfLineAndModifySelection" },
{ VK_END, CtrlKey, "MoveToEndOfDocument" },
{ VK_END, CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection" },
{ VK_BACK, 0, "DeleteBackward" },
{ VK_BACK, ShiftKey, "DeleteBackward" },
{ VK_DELETE, 0, "DeleteForward" },
{ VK_BACK, CtrlKey, "DeleteWordBackward" },
{ VK_DELETE, CtrlKey, "DeleteWordForward" },
{ 'B', CtrlKey, "ToggleBold" },
{ 'I', CtrlKey, "ToggleItalic" },
{ VK_ESCAPE, 0, "Cancel" },
{ VK_OEM_PERIOD, CtrlKey, "Cancel" },
{ VK_TAB, 0, "InsertTab" },
{ VK_TAB, ShiftKey, "InsertBacktab" },
{ VK_RETURN, 0, "InsertNewline" },
{ VK_RETURN, CtrlKey, "InsertNewline" },
{ VK_RETURN, AltKey, "InsertNewline" },
{ VK_RETURN, ShiftKey, "InsertNewline" },
{ VK_RETURN, AltKey | ShiftKey, "InsertNewline" },
// It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled
// in the application or in WebKit. We chose WebKit.
{ 'C', CtrlKey, "Copy" },
{ 'V', CtrlKey, "Paste" },
{ 'X', CtrlKey, "Cut" },
{ 'A', CtrlKey, "SelectAll" },
{ VK_INSERT, CtrlKey, "Copy" },
{ VK_DELETE, ShiftKey, "Cut" },
{ VK_INSERT, ShiftKey, "Paste" },
{ 'Z', CtrlKey, "Undo" },
{ 'Z', CtrlKey | ShiftKey, "Redo" },
};
static const KeyPressEntry keyPressEntries[] = {
{ '\t', 0, "InsertTab" },
{ '\t', ShiftKey, "InsertBacktab" },
{ '\r', 0, "InsertNewline" },
{ '\r', CtrlKey, "InsertNewline" },
{ '\r', AltKey, "InsertNewline" },
{ '\r', ShiftKey, "InsertNewline" },
{ '\r', AltKey | ShiftKey, "InsertNewline" },
};
const char* WebView::interpretKeyEvent(const KeyboardEvent* evt)
{
ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
static HashMap<int, const char*>* keyDownCommandsMap = 0;
static HashMap<int, const char*>* keyPressCommandsMap = 0;
if (!keyDownCommandsMap) {
keyDownCommandsMap = new HashMap<int, const char*>;
keyPressCommandsMap = new HashMap<int, const char*>;
for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyDownEntries); ++i)
keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyPressEntries); ++i)
keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
}
unsigned modifiers = 0;
if (evt->shiftKey())
modifiers |= ShiftKey;
if (evt->altKey())
modifiers |= AltKey;
if (evt->ctrlKey())
modifiers |= CtrlKey;
if (evt->type() == eventNames().keydownEvent) {
int mapKey = modifiers << 16 | evt->keyCode();
return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
}
int mapKey = modifiers << 16 | evt->charCode();
return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
}
bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
{
Node* node = evt->target()->toNode();
ASSERT(node);
Frame* frame = node->document()->frame();
ASSERT(frame);
const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
if (!keyEvent || keyEvent->isSystemKey()) // do not treat this as text input if it's a system key event
return false;
Editor::Command command = frame->editor().command(interpretKeyEvent(evt));
if (keyEvent->type() == PlatformEvent::RawKeyDown) {
// WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
// so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
// (e.g. Tab that inserts a Tab character, or Enter).
return !command.isTextInsertion() && command.execute(evt);
}
if (command.execute(evt))
return true;
// Don't insert null or control characters as they can result in unexpected behaviour
if (evt->charCode() < ' ')
return false;
return frame->editor().insertText(evt->keyEvent()->text(), evt);
}
bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
{
#if ENABLE(FULLSCREEN_API)
// Trap the ESC key when in full screen mode.
if (virtualKeyCode == VK_ESCAPE && isFullScreen()) {
m_fullscreenController->exitFullScreen();
return false;
}
#endif
Frame* frame = m_page->focusController()->focusedOrMainFrame();
PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformEvent::RawKeyDown, systemKeyDown);
bool handled = frame->eventHandler()->keyEvent(keyEvent);
// These events cannot be canceled, and we have no default handling for them.
// FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
if (systemKeyDown && virtualKeyCode != VK_RETURN)
return false;
if (handled) {
// FIXME: remove WM_UNICHAR, too
MSG msg;
// WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
if (!systemKeyDown)
::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
return true;
}
// We need to handle back/forward using either Ctrl+Left/Right Arrow keys.
// FIXME: This logic should probably be in EventHandler::defaultArrowEventHandler().
// FIXME: Should check that other modifiers aren't pressed.
if (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey())
return m_page->goForward();
if (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey())
return m_page->goBack();
// Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
ScrollDirection direction;
ScrollGranularity granularity;
switch (virtualKeyCode) {
case VK_LEFT:
granularity = ScrollByLine;
direction = ScrollLeft;
break;
case VK_RIGHT:
granularity = ScrollByLine;
direction = ScrollRight;
break;
case VK_UP:
granularity = ScrollByLine;
direction = ScrollUp;
break;
case VK_DOWN:
granularity = ScrollByLine;
direction = ScrollDown;
break;
case VK_HOME:
granularity = ScrollByDocument;
direction = ScrollUp;
break;
case VK_END:
granularity = ScrollByDocument;
direction = ScrollDown;
break;
case VK_PRIOR:
granularity = ScrollByPage;
direction = ScrollUp;
break;
case VK_NEXT:
granularity = ScrollByPage;
direction = ScrollDown;
break;
default:
return false;
}
return frame->eventHandler()->scrollRecursively(direction, granularity);
}
bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
{
Frame* frame = m_page->focusController()->focusedOrMainFrame();
PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformEvent::Char, systemKeyDown);
// IE does not dispatch keypress event for WM_SYSCHAR.
if (systemKeyDown)
return frame->eventHandler()->handleAccessKey(keyEvent);
return frame->eventHandler()->keyEvent(keyEvent);
}
void WebView::setIsBeingDestroyed()
{
m_isBeingDestroyed = true;
// Remove our this pointer from the window so we won't try to handle any more window messages.
// See <http://webkit.org/b/55054>.
::SetWindowLongPtrW(m_viewWindow, 0, 0);
}
void WebView::setShouldInvertColors(bool shouldInvertColors)
{
if (m_shouldInvertColors == shouldInvertColors)
return;
m_shouldInvertColors = shouldInvertColors;
#if USE(ACCELERATED_COMPOSITING)
if (m_layerTreeHost)
m_layerTreeHost->setShouldInvertColors(shouldInvertColors);
#endif
RECT windowRect = {0};
frameRect(&windowRect);
repaint(windowRect, true, true);
}
bool WebView::registerWebViewWindowClass()
{
static bool haveRegisteredWindowClass = false;
if (haveRegisteredWindowClass)
return true;
haveRegisteredWindowClass = true;
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_DBLCLKS;
wcex.lpfnWndProc = WebViewWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = sizeof(WebView*);
wcex.hInstance = gInstance;
wcex.hIcon = 0;
wcex.hCursor = ::LoadCursor(0, IDC_ARROW);
wcex.hbrBackground = 0;
wcex.lpszMenuName = 0;
wcex.lpszClassName = kWebViewWindowClassName;
wcex.hIconSm = 0;
return !!RegisterClassEx(&wcex);
}
static HWND findTopLevelParent(HWND window)
{
if (!window)
return 0;
HWND current = window;
for (HWND parent = GetParent(current); current; current = parent, parent = GetParent(parent))
if (!parent || !(GetWindowLongPtr(current, GWL_STYLE) & (WS_POPUP | WS_CHILD)))
return current;
ASSERT_NOT_REACHED();
return 0;
}
LRESULT CALLBACK WebView::WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT lResult = 0;
LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
WebView* webView = reinterpret_cast<WebView*>(longPtr);
WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
if (!mainFrameImpl)
return DefWindowProc(hWnd, message, wParam, lParam);
// We shouldn't be trying to handle any window messages after WM_DESTROY.
// See <http://webkit.org/b/55054>.
ASSERT(!webView->isBeingDestroyed());
// hold a ref, since the WebView could go away in an event handler.
COMPtr<WebView> protector(webView);
ASSERT(webView);
// Windows Media Player has a modal message loop that will deliver messages
// to us at inappropriate times and we will crash if we handle them when
// they are delivered. We repost paint messages so that we eventually get
// a chance to paint once the modal loop has exited, but other messages
// aren't safe to repost, so we just drop them.
if (PluginView::isCallingPlugin()) {
if (message == WM_PAINT)
PostMessage(hWnd, message, wParam, lParam);
return 0;
}
bool handled = true;
switch (message) {
case WM_PAINT: {
webView->paint(0, 0);
if (webView->usesLayeredWindow())
webView->performLayeredWindowUpdate();
break;
}
case WM_ERASEBKGND:
if (webView->usesLayeredWindow()) {
// Don't perform a background erase for transparent views.
handled = true;
lResult = 1;
}
break;
case WM_PRINTCLIENT:
webView->paint((HDC)wParam, lParam);
break;
case WM_DESTROY:
webView->setIsBeingDestroyed();
webView->close();
break;
case WM_GESTURENOTIFY:
handled = webView->gestureNotify(wParam, lParam);
break;
case WM_GESTURE:
handled = webView->gesture(wParam, lParam);
break;
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_LBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
case WM_MOUSELEAVE:
case WM_CANCELMODE:
if (Frame* coreFrame = core(mainFrameImpl))
if (coreFrame->view()->didFirstLayout())
handled = webView->handleMouseEvent(message, wParam, lParam);
break;
case WM_MOUSEWHEEL:
case WM_VISTA_MOUSEHWHEEL:
if (Frame* coreFrame = core(mainFrameImpl))
if (coreFrame->view()->didFirstLayout())
handled = webView->mouseWheel(wParam, lParam, message == WM_VISTA_MOUSEHWHEEL);
break;
case WM_SYSKEYDOWN:
handled = webView->keyDown(wParam, lParam, true);
break;
case WM_KEYDOWN:
handled = webView->keyDown(wParam, lParam);
break;
case WM_SYSKEYUP:
handled = webView->keyUp(wParam, lParam, true);
break;
case WM_KEYUP:
handled = webView->keyUp(wParam, lParam);
break;
case WM_SYSCHAR:
handled = webView->keyPress(wParam, lParam, true);
break;
case WM_CHAR:
handled = webView->keyPress(wParam, lParam);
break;
// FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
case WM_SIZE:
if (lParam != 0)
webView->sizeChanged(IntSize(LOWORD(lParam), HIWORD(lParam)));
break;
case WM_SHOWWINDOW:
lResult = DefWindowProc(hWnd, message, wParam, lParam);
if (wParam == 0) {
// The window is being hidden (e.g., because we switched tabs).
// Null out our backing store.
webView->deleteBackingStore();
}
break;
case WM_SETFOCUS: {
COMPtr<IWebUIDelegate> uiDelegate;
COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
&& SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
uiDelegatePrivate->webViewReceivedFocus(webView);
FocusController* focusController = webView->page()->focusController();
if (Frame* frame = focusController->focusedFrame()) {
// Send focus events unless the previously focused window is a
// child of ours (for example a plugin).
if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
focusController->setFocused(true);
} else
focusController->setFocused(true);
break;
}
case WM_KILLFOCUS: {
COMPtr<IWebUIDelegate> uiDelegate;
COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
&& SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
uiDelegatePrivate->webViewLostFocus(webView, (OLE_HANDLE)(ULONG64)newFocusWnd);
FocusController* focusController = webView->page()->focusController();
Frame* frame = focusController->focusedOrMainFrame();
webView->resetIME(frame);
// Send blur events unless we're losing focus to a child of ours.
if (!IsChild(hWnd, newFocusWnd))
focusController->setFocused(false);
// If we are pan-scrolling when we lose focus, stop the pan scrolling.
frame->eventHandler()->stopAutoscrollTimer();
break;
}
case WM_WINDOWPOSCHANGED:
if (reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW)
webView->updateActiveStateSoon();
handled = false;
break;
case WM_CUT:
webView->cut(0);
break;
case WM_COPY:
webView->copy(0);
break;
case WM_PASTE:
webView->paste(0);
break;
case WM_CLEAR:
webView->delete_(0);
break;
case WM_COMMAND:
if (HIWORD(wParam))
handled = webView->execCommand(wParam, lParam);
else // If the high word of wParam is 0, the message is from a menu
webView->performContextMenuAction(wParam, lParam, false);
break;
case WM_MENUCOMMAND:
webView->performContextMenuAction(wParam, lParam, true);
break;
case WM_CONTEXTMENU:
handled = webView->handleContextMenuEvent(wParam, lParam);
break;
case WM_INITMENUPOPUP:
handled = webView->onInitMenuPopup(wParam, lParam);
break;
case WM_MEASUREITEM:
handled = webView->onMeasureItem(wParam, lParam);
break;
case WM_DRAWITEM:
handled = webView->onDrawItem(wParam, lParam);
break;
case WM_UNINITMENUPOPUP:
handled = webView->onUninitMenuPopup(wParam, lParam);
break;
case WM_XP_THEMECHANGED:
if (Frame* coreFrame = core(mainFrameImpl)) {
webView->deleteBackingStore();
coreFrame->page()->theme()->themeChanged();
ScrollbarTheme::theme()->themeChanged();
RECT windowRect;
::GetClientRect(hWnd, &windowRect);
::InvalidateRect(hWnd, &windowRect, false);
#if USE(ACCELERATED_COMPOSITING)
if (webView->isAcceleratedCompositing())
webView->m_backingLayer->setNeedsDisplay();
#endif
}
break;
case WM_MOUSEACTIVATE:
webView->setMouseActivated(true);
handled = false;
break;
case WM_GETDLGCODE: {
COMPtr<IWebUIDelegate> uiDelegate;
COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
LONG_PTR dlgCode = 0;
UINT keyCode = 0;
if (lParam) {
LPMSG lpMsg = (LPMSG)lParam;
if (lpMsg->message == WM_KEYDOWN)
keyCode = (UINT) lpMsg->wParam;
}
if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
&& SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate
&& SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
return dlgCode;
handled = false;
break;
}
case WM_GETOBJECT:
handled = webView->onGetObject(wParam, lParam, lResult);
break;
case WM_IME_STARTCOMPOSITION:
handled = webView->onIMEStartComposition();
break;
case WM_IME_REQUEST:
lResult = webView->onIMERequest(wParam, lParam);
break;
case WM_IME_COMPOSITION:
handled = webView->onIMEComposition(lParam);
break;
case WM_IME_ENDCOMPOSITION:
handled = webView->onIMEEndComposition();
break;
case WM_IME_CHAR:
handled = webView->onIMEChar(wParam, lParam);
break;
case WM_IME_NOTIFY:
handled = webView->onIMENotify(wParam, lParam, &lResult);
break;
case WM_IME_SELECT:
handled = webView->onIMESelect(wParam, lParam);
break;
case WM_IME_SETCONTEXT:
handled = webView->onIMESetContext(wParam, lParam);
break;
case WM_TIMER:
switch (wParam) {
case UpdateActiveStateTimer:
KillTimer(hWnd, UpdateActiveStateTimer);
webView->updateActiveState();
break;
case DeleteBackingStoreTimer:
webView->deleteBackingStore();
break;
}
break;
case WM_SETCURSOR:
handled = ::SetCursor(webView->m_lastSetCursor);
break;
case WM_VSCROLL:
handled = webView->verticalScroll(wParam, lParam);
break;
case WM_HSCROLL:
handled = webView->horizontalScroll(wParam, lParam);
break;
default:
handled = false;
break;
}
if (!handled)
lResult = DefWindowProc(hWnd, message, wParam, lParam);
// Let the client know whether we consider this message handled.
return (message == WM_KEYDOWN || message == WM_SYSKEYDOWN || message == WM_KEYUP || message == WM_SYSKEYUP) ? !handled : lResult;
}
bool WebView::developerExtrasEnabled() const
{
if (m_preferences->developerExtrasDisabledByOverride())
return false;
#ifdef NDEBUG
BOOL enabled;
return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
#else
return true;
#endif
}
static String webKitVersionString()
{
LPWSTR buildNumberStringPtr;
if (!::LoadStringW(gInstance, BUILD_NUMBER, reinterpret_cast<LPWSTR>(&buildNumberStringPtr), 0) || !buildNumberStringPtr)
return "534+";
return buildNumberStringPtr;
}
const String& WebView::userAgentForKURL(const KURL&)
{
if (m_userAgentOverridden)
return m_userAgentCustom;
if (!m_userAgentStandard.length())
m_userAgentStandard = WebView::standardUserAgentWithApplicationName(m_applicationName);
return m_userAgentStandard;
}
// IUnknown -------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::QueryInterface(REFIID riid, void** ppvObject)
{
*ppvObject = 0;
if (IsEqualGUID(riid, CLSID_WebView))
*ppvObject = this;
else if (IsEqualGUID(riid, IID_IUnknown))
*ppvObject = static_cast<IWebView*>(this);
else if (IsEqualGUID(riid, IID_IWebView))
*ppvObject = static_cast<IWebView*>(this);
else if (IsEqualGUID(riid, IID_IWebViewPrivate))
*ppvObject = static_cast<IWebViewPrivate*>(this);
else if (IsEqualGUID(riid, IID_IWebIBActions))
*ppvObject = static_cast<IWebIBActions*>(this);
else if (IsEqualGUID(riid, IID_IWebViewCSS))
*ppvObject = static_cast<IWebViewCSS*>(this);
else if (IsEqualGUID(riid, IID_IWebViewEditing))
*ppvObject = static_cast<IWebViewEditing*>(this);
else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
*ppvObject = static_cast<IWebViewUndoableEditing*>(this);
else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
*ppvObject = static_cast<IWebViewEditingActions*>(this);
else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
*ppvObject = static_cast<IWebNotificationObserver*>(this);
else if (IsEqualGUID(riid, IID_IDropTarget))
*ppvObject = static_cast<IDropTarget*>(this);
else
return E_NOINTERFACE;
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE WebView::AddRef(void)
{
ASSERT(!m_deletionHasBegun);
return ++m_refCount;
}
ULONG STDMETHODCALLTYPE WebView::Release(void)
{
ASSERT(!m_deletionHasBegun);
if (m_refCount == 1) {
// Call close() now so that clients don't have to. (It's harmless to call close() multiple
// times.) We do this here instead of in our destructor because close() can cause AddRef()
// and Release() to be called, and if that happened in our destructor we would be destroyed
// more than once.
close();
}
ULONG newRef = --m_refCount;
if (!newRef) {
#if !ASSERT_DISABLED
m_deletionHasBegun = true;
#endif
delete(this);
}
return newRef;
}
// IWebView --------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE WebView::canShowMIMEType(
/* [in] */ BSTR mimeType,
/* [retval][out] */ BOOL* canShow)
{
String mimeTypeStr = toString(mimeType);
if (!canShow)
return E_POINTER;
*canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeTypeStr) ||
MIMETypeRegistry::isSupportedNonImageMIMEType(mimeTypeStr) ||
(m_page && m_page->pluginData() && m_page->pluginData()->supportsMimeType(mimeTypeStr)) ||
shouldUseEmbeddedView(mimeTypeStr);
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::canShowMIMETypeAsHTML(
/* [in] */ BSTR /*mimeType*/,
/* [retval][out] */ BOOL* canShow)
{
// FIXME
*canShow = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE WebView::MIMETypesShownAsHTML(
/* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::setMIMETypesShownAsHTML(
/* [size_is][in] */ BSTR* /*mimeTypes*/,
/* [in] */ int /*cMimeTypes*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::URLFromPasteboard(
/* [in] */ IDataObject* /*pasteboard*/,
/* [retval][out] */ BSTR* /*url*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE WebView::URLTitleFromPasteboard(
/* [in] */ IDataObject* /*pasteboard*/,
/* [retval][out] */ BSTR* /*urlTitle*/)
{
ASSERT_NOT_REACHED();
return E_NOTIMPL;
}
static void WebKitSetApplicationCachePathIfNecessary()
{
static bool initialized = false;
if (initialized)
return;
String path = localUserSpecificStorageDirectory();
if (!path.isNull())
cacheStorage().setCacheDirectory(path);
initialized = true;
}
bool WebView::shouldInitializeTrackPointHack()
{
static bool shouldCreateScrollbars;
static bool hasRunTrackPointCheck;
if (hasRunTrackPointCheck)
return shouldCreateScrollbars;
hasRunTrackPointCheck = true;
const WCHAR trackPointKeys[][50] = { L"Software\\Lenovo\\TrackPoint",
L"Software\\Lenovo\\UltraNav",
L"Software\\Alps\\Apoint\\TrackPoint",
L"Software\\Synaptics\\SynTPEnh\\UltraNavUSB",
L"Software\\Synaptics\\SynTPEnh\\UltraNavPS2" };
for (int i = 0; i < 5; ++i) {
HKEY trackPointKey;
int readKeyResult = ::RegOpenKeyExW(HKEY_CURRENT_USER, trackPointKeys[i], 0, KEY_READ, &trackPointKey);
::RegCloseKey(trackPointKey);
if (readKeyResult == ERROR_SUCCESS) {
shouldCreateScrollbars = true;
return shouldCreateScrollbars;
}
}
return shouldCreateScrollbars;
}
HRESULT STDMETHODCALLTYPE WebView::initWithFrame(
/* [in] */ RECT frame,
/* [in] */ BSTR frameName,
/* [in] */ BSTR groupName)
{
HRESULT hr = S_OK;
if (m_viewWindow)
return E_FAIL;
registerWebViewWindowClass();
m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow ? m_hostWindow : HWND_MESSAGE, 0, gInstance, 0);
ASSERT(::IsWindow(m_viewWindow));
if (shouldInitializeTrackPointHack()) {
// If we detected a registry key belonging to a TrackPoint driver, then create fake trackpoint
// scrollbars, so the WebView will receive WM_VSCROLL and WM_HSCROLL messages. We create one
// vertical scrollbar and one horizontal to allow for receiving both types of messages.
::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTHSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_HORZ, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTVSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_VERT, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
}
hr = registerDragDrop();
if (FAILED(hr))
return hr;
WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
sharedPreferences->willAddToWebView();
m_preferences = sharedPreferences;
static bool didOneTimeInitialization;
if (!didOneTimeInitialization) {
#if !LOG_DISABLED
initializeLoggingChannelsIfNecessary();
#endif // !LOG_DISABLED
// Initialize our platform strategies first before invoking the rest
// of the initialization code which may depend on the strategies.
WebPlatformStrategies::initialize();