2 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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 "WebPreferences.h"
61 #include "WebScriptWorld.h"
63 #include <JavaScriptCore/APICast.h>
64 #include <JavaScriptCore/InitializeThreading.h>
65 #include <JavaScriptCore/JSLock.h>
66 #include <JavaScriptCore/JSValue.h>
67 #include <WebCore/AXObjectCache.h>
68 #include <WebCore/AbstractDatabase.h>
69 #include <WebCore/ApplicationCacheStorage.h>
70 #include <WebCore/BString.h>
71 #include <WebCore/BackForwardListImpl.h>
72 #include <WebCore/BitmapInfo.h>
73 #include <WebCore/Chrome.h>
74 #include <WebCore/ContextMenu.h>
75 #include <WebCore/ContextMenuController.h>
76 #include <WebCore/Cursor.h>
77 #include <WebCore/Document.h>
78 #include <WebCore/DocumentMarkerController.h>
79 #include <WebCore/DragController.h>
80 #include <WebCore/DragData.h>
81 #include <WebCore/Editor.h>
82 #include <WebCore/EventHandler.h>
83 #include <WebCore/EventNames.h>
84 #include <WebCore/FileSystem.h>
85 #include <WebCore/FloatQuad.h>
86 #include <WebCore/FocusController.h>
87 #include <WebCore/Frame.h>
88 #include <WebCore/FrameLoader.h>
89 #include <WebCore/FrameSelection.h>
90 #include <WebCore/FrameTree.h>
91 #include <WebCore/FrameView.h>
92 #include <WebCore/FrameWin.h>
93 #include <WebCore/GDIObjectCounter.h>
94 #include <WebCore/GraphicsContext.h>
95 #include <WebCore/HTMLMediaElement.h>
96 #include <WebCore/HTMLNames.h>
97 #include <WebCore/HistoryItem.h>
98 #include <WebCore/HitTestRequest.h>
99 #include <WebCore/HitTestResult.h>
100 #include <WebCore/IntRect.h>
101 #include <WebCore/JSElement.h>
102 #include <WebCore/KeyboardEvent.h>
103 #include <WebCore/Logging.h>
104 #include <WebCore/MIMETypeRegistry.h>
105 #include <WebCore/MemoryCache.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/MainThread.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);
712 m_webInspector->webViewClosed();
717 registerForIconNotification(false);
718 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
719 notifyCenter->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
721 if (COMPtr<WebPreferences> preferences = m_preferences) {
723 preferences->identifier(&identifier);
726 preferences->didRemoveFromWebView();
727 // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
730 WebPreferences::removeReferenceForIdentifier(identifier);
731 SysFreeString(identifier);
735 deleteBackingStore();
739 void WebView::repaint(const WebCore::IntRect& windowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
741 #if USE(ACCELERATED_COMPOSITING)
742 if (isAcceleratedCompositing()) {
743 // The contentChanged, immediate, and repaintContentOnly parameters are all based on a non-
744 // compositing painting/scrolling model.
745 addToDirtyRegion(windowRect);
750 if (!repaintContentOnly) {
751 RECT rect = windowRect;
752 ::InvalidateRect(m_viewWindow, &rect, false);
755 addToDirtyRegion(windowRect);
757 if (repaintContentOnly)
758 updateBackingStore(core(topLevelFrame())->view());
760 ::UpdateWindow(m_viewWindow);
764 void WebView::deleteBackingStore()
766 pendingDeleteBackingStoreSet.remove(this);
768 if (m_deleteBackingStoreTimerActive) {
769 KillTimer(m_viewWindow, DeleteBackingStoreTimer);
770 m_deleteBackingStoreTimerActive = false;
772 m_backingStoreBitmap.clear();
773 m_backingStoreDirtyRegion.clear();
774 m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
777 bool WebView::ensureBackingStore()
780 ::GetClientRect(m_viewWindow, &windowRect);
781 LONG width = windowRect.right - windowRect.left;
782 LONG height = windowRect.bottom - windowRect.top;
783 if (width > 0 && height > 0 && (width != m_backingStoreSize.cx || height != m_backingStoreSize.cy)) {
784 deleteBackingStore();
786 m_backingStoreSize.cx = width;
787 m_backingStoreSize.cy = height;
788 BitmapInfo bitmapInfo = BitmapInfo::createBottomUp(IntSize(m_backingStoreSize));
791 m_backingStoreBitmap = RefCountedHBITMAP::create(::CreateDIBSection(0, &bitmapInfo, DIB_RGB_COLORS, &pixels, 0, 0));
798 void WebView::addToDirtyRegion(const IntRect& dirtyRect)
800 // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
801 // but it was being hit during our layout tests, and is being investigated in
802 // http://webkit.org/b/29350.
804 #if USE(ACCELERATED_COMPOSITING)
805 if (isAcceleratedCompositing()) {
806 m_backingLayer->setNeedsDisplayInRect(dirtyRect);
811 HRGN newRegion = ::CreateRectRgn(dirtyRect.x(), dirtyRect.y(),
812 dirtyRect.maxX(), dirtyRect.maxY());
813 addToDirtyRegion(newRegion);
816 void WebView::addToDirtyRegion(HRGN newRegion)
818 #if USE(ACCELERATED_COMPOSITING)
819 ASSERT(!isAcceleratedCompositing());
822 LOCAL_GDI_COUNTER(0, __FUNCTION__);
824 if (m_backingStoreDirtyRegion) {
825 HRGN combinedRegion = ::CreateRectRgn(0,0,0,0);
826 ::CombineRgn(combinedRegion, m_backingStoreDirtyRegion->handle(), newRegion, RGN_OR);
827 ::DeleteObject(newRegion);
828 m_backingStoreDirtyRegion = RefCountedHRGN::create(combinedRegion);
830 m_backingStoreDirtyRegion = RefCountedHRGN::create(newRegion);
832 if (m_uiDelegatePrivate)
833 m_uiDelegatePrivate->webViewDidInvalidate(this);
836 void WebView::scrollBackingStore(FrameView* frameView, int dx, int dy, const IntRect& scrollViewRect, const IntRect& clipRect)
838 #if USE(ACCELERATED_COMPOSITING)
839 if (isAcceleratedCompositing()) {
840 // FIXME: We should be doing something smarter here, like moving tiles around and painting
841 // any newly-exposed tiles. <http://webkit.org/b/52714>
842 m_backingLayer->setNeedsDisplayInRect(scrollViewRect);
847 LOCAL_GDI_COUNTER(0, __FUNCTION__);
849 // If there's no backing store we don't need to update it
850 if (!m_backingStoreBitmap) {
851 if (m_uiDelegatePrivate)
852 m_uiDelegatePrivate->webViewScrolled(this);
857 // Make a region to hold the invalidated scroll area.
858 HRGN updateRegion = ::CreateRectRgn(0, 0, 0, 0);
860 // Collect our device context info and select the bitmap to scroll.
861 HDC windowDC = ::GetDC(m_viewWindow);
862 HDC bitmapDC = ::CreateCompatibleDC(windowDC);
863 HGDIOBJ oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
865 // Scroll the bitmap.
866 RECT scrollRectWin(scrollViewRect);
867 RECT clipRectWin(clipRect);
868 ::ScrollDC(bitmapDC, dx, dy, &scrollRectWin, &clipRectWin, updateRegion, 0);
870 ::GetRgnBox(updateRegion, ®ionBox);
875 // Add the dirty region to the backing store's dirty region.
876 addToDirtyRegion(updateRegion);
878 if (m_uiDelegatePrivate)
879 m_uiDelegatePrivate->webViewScrolled(this);
881 // Update the backing store.
882 updateBackingStore(frameView, bitmapDC, false);
885 ::SelectObject(bitmapDC, oldBitmap);
886 ::DeleteDC(bitmapDC);
887 ::ReleaseDC(m_viewWindow, windowDC);
890 void WebView::sizeChanged(const IntSize& newSize)
892 deleteBackingStore();
894 if (Frame* coreFrame = core(topLevelFrame()))
895 coreFrame->view()->resize(newSize);
897 #if USE(ACCELERATED_COMPOSITING)
899 m_layerTreeHost->resize();
900 if (m_backingLayer) {
901 m_backingLayer->setSize(newSize);
902 m_backingLayer->setNeedsDisplay();
907 // This emulates the Mac smarts for painting rects intelligently. This is very
908 // important for us, since we double buffer based off dirty rects.
909 static void getUpdateRects(HRGN region, const IntRect& dirtyRect, Vector<IntRect>& rects)
911 ASSERT_ARG(region, region);
913 const int cRectThreshold = 10;
914 const float cWastedSpaceThreshold = 0.75f;
918 DWORD regionDataSize = GetRegionData(region, sizeof(RGNDATA), NULL);
919 if (!regionDataSize) {
920 rects.append(dirtyRect);
924 Vector<unsigned char> buffer(regionDataSize);
925 RGNDATA* regionData = reinterpret_cast<RGNDATA*>(buffer.data());
926 GetRegionData(region, regionDataSize, regionData);
927 if (regionData->rdh.nCount > cRectThreshold) {
928 rects.append(dirtyRect);
932 double singlePixels = 0.0;
935 for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
936 singlePixels += (rect->right - rect->left) * (rect->bottom - rect->top);
938 double unionPixels = dirtyRect.width() * dirtyRect.height();
939 double wastedSpace = 1.0 - (singlePixels / unionPixels);
940 if (wastedSpace <= cWastedSpaceThreshold) {
941 rects.append(dirtyRect);
945 for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
949 void WebView::updateBackingStore(FrameView* frameView, HDC dc, bool backingStoreCompletelyDirty, WindowsToPaint windowsToPaint)
951 #if USE(ACCELERATED_COMPOSITING)
952 ASSERT(!isAcceleratedCompositing());
955 LOCAL_GDI_COUNTER(0, __FUNCTION__);
959 HGDIOBJ oldBitmap = 0;
961 windowDC = ::GetDC(m_viewWindow);
962 bitmapDC = ::CreateCompatibleDC(windowDC);
963 oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
966 if (m_backingStoreBitmap && (m_backingStoreDirtyRegion || backingStoreCompletelyDirty)) {
967 // Do a layout first so that everything we render to the backing store is always current.
968 if (Frame* coreFrame = core(m_mainFrame))
969 if (FrameView* view = coreFrame->view())
970 view->updateLayoutAndStyleIfNeededRecursive();
972 Vector<IntRect> paintRects;
973 if (!backingStoreCompletelyDirty && m_backingStoreDirtyRegion) {
975 ::GetRgnBox(m_backingStoreDirtyRegion->handle(), ®ionBox);
976 getUpdateRects(m_backingStoreDirtyRegion->handle(), regionBox, paintRects);
979 ::GetClientRect(m_viewWindow, &clientRect);
980 paintRects.append(clientRect);
983 for (unsigned i = 0; i < paintRects.size(); ++i)
984 paintIntoBackingStore(frameView, bitmapDC, paintRects[i], windowsToPaint);
986 if (m_uiDelegatePrivate)
987 m_uiDelegatePrivate->webViewPainted(this);
989 m_backingStoreDirtyRegion.clear();
993 ::SelectObject(bitmapDC, oldBitmap);
994 ::DeleteDC(bitmapDC);
995 ::ReleaseDC(m_viewWindow, windowDC);
1001 void WebView::performLayeredWindowUpdate()
1003 // The backing store may have been destroyed if the window rect was set to zero height or zero width.
1004 if (!m_backingStoreBitmap)
1007 HDC hdcScreen = ::GetDC(m_viewWindow);
1008 OwnPtr<HDC> hdcMem = adoptPtr(::CreateCompatibleDC(hdcScreen));
1009 HBITMAP hbmOld = static_cast<HBITMAP>(::SelectObject(hdcMem.get(), m_backingStoreBitmap->handle()));
1012 ::GetObject(m_backingStoreBitmap->handle(), sizeof(bmpInfo), &bmpInfo);
1013 SIZE windowSize = { bmpInfo.bmWidth, bmpInfo.bmHeight };
1015 BLENDFUNCTION blendFunction;
1016 blendFunction.BlendOp = AC_SRC_OVER;
1017 blendFunction.BlendFlags = 0;
1018 blendFunction.SourceConstantAlpha = 0xFF;
1019 blendFunction.AlphaFormat = AC_SRC_ALPHA;
1021 POINT layerPos = { 0, 0 };
1022 ::UpdateLayeredWindow(m_viewWindow, hdcScreen, 0, &windowSize, hdcMem.get(), &layerPos, 0, &blendFunction, ULW_ALPHA);
1024 ::SelectObject(hdcMem.get(), hbmOld);
1025 ::ReleaseDC(0, hdcScreen);
1028 void WebView::paint(HDC dc, LPARAM options)
1030 LOCAL_GDI_COUNTER(0, __FUNCTION__);
1032 #if USE(ACCELERATED_COMPOSITING)
1033 if (isAcceleratedCompositing() && !usesLayeredWindow()) {
1034 m_layerTreeHost->flushPendingLayerChangesNow();
1035 // Flushing might have taken us out of compositing mode.
1036 if (isAcceleratedCompositing()) {
1037 // FIXME: We need to paint into dc (if provided). <http://webkit.org/b/52578>
1038 m_layerTreeHost->paint();
1039 ::ValidateRect(m_viewWindow, 0);
1045 Frame* coreFrame = core(m_mainFrame);
1048 FrameView* frameView = coreFrame->view();
1052 OwnPtr<HRGN> region;
1053 int regionType = NULLREGION;
1055 WindowsToPaint windowsToPaint;
1057 region = adoptPtr(CreateRectRgn(0,0,0,0));
1058 regionType = GetUpdateRgn(m_viewWindow, region.get(), false);
1059 hdc = BeginPaint(m_viewWindow, &ps);
1060 rcPaint = ps.rcPaint;
1061 // We're painting to the screen, and our child windows can handle
1062 // painting themselves to the screen.
1063 windowsToPaint = PaintWebViewOnly;
1066 ::GetClientRect(m_viewWindow, &rcPaint);
1067 if (options & PRF_ERASEBKGND)
1068 ::FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
1069 // Since we aren't painting to the screen, we want to paint all our
1070 // children into the HDC.
1071 windowsToPaint = PaintWebViewAndChildren;
1074 bool backingStoreCompletelyDirty = ensureBackingStore();
1075 if (!m_backingStoreBitmap) {
1077 EndPaint(m_viewWindow, &ps);
1083 HDC bitmapDC = ::CreateCompatibleDC(hdc);
1084 HGDIOBJ oldBitmap = ::SelectObject(bitmapDC, m_backingStoreBitmap->handle());
1086 // Update our backing store if needed.
1087 updateBackingStore(frameView, bitmapDC, backingStoreCompletelyDirty, windowsToPaint);
1089 // Now we blit the updated backing store
1090 IntRect windowDirtyRect = rcPaint;
1092 // Apply the same heuristic for this update region too.
1093 Vector<IntRect> blitRects;
1094 if (region && regionType == COMPLEXREGION)
1095 getUpdateRects(region.get(), windowDirtyRect, blitRects);
1097 blitRects.append(windowDirtyRect);
1099 for (unsigned i = 0; i < blitRects.size(); ++i)
1100 paintIntoWindow(bitmapDC, hdc, blitRects[i]);
1102 ::SelectObject(bitmapDC, oldBitmap);
1103 ::DeleteDC(bitmapDC);
1106 EndPaint(m_viewWindow, &ps);
1111 cancelDeleteBackingStoreSoon();
1113 deleteBackingStoreSoon();
1116 void WebView::paintIntoBackingStore(FrameView* frameView, HDC bitmapDC, const IntRect& dirtyRect, WindowsToPaint windowsToPaint)
1118 // FIXME: This function should never be called in accelerated compositing mode, and we should
1119 // assert as such. But currently it *is* sometimes called, so we can't assert yet. See
1120 // <http://webkit.org/b/58539>.
1122 LOCAL_GDI_COUNTER(0, __FUNCTION__);
1124 // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
1125 // but it was being hit during our layout tests, and is being investigated in
1126 // http://webkit.org/b/29350.
1128 RECT rect = dirtyRect;
1130 #if FLASH_BACKING_STORE_REDRAW
1131 HDC dc = ::GetDC(m_viewWindow);
1132 OwnPtr<HBRUSH> yellowBrush(CreateSolidBrush(RGB(255, 255, 0)));
1133 FillRect(dc, &rect, yellowBrush.get());
1136 paintIntoWindow(bitmapDC, dc, dirtyRect);
1137 ::ReleaseDC(m_viewWindow, dc);
1140 GraphicsContext gc(bitmapDC, m_transparent);
1141 gc.setShouldIncludeChildWindows(windowsToPaint == PaintWebViewAndChildren);
1144 gc.clearRect(dirtyRect);
1146 FillRect(bitmapDC, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
1148 COMPtr<IWebUIDelegatePrivate2> uiPrivate(Query, m_uiDelegate);
1150 uiPrivate->drawBackground(this, reinterpret_cast<OLE_HANDLE>(bitmapDC), &rect);
1152 if (frameView && frameView->frame() && frameView->frame()->contentRenderer()) {
1154 frameView->paint(&gc, dirtyRect);
1159 void WebView::paintIntoWindow(HDC bitmapDC, HDC windowDC, const IntRect& dirtyRect)
1161 // FIXME: This function should never be called in accelerated compositing mode, and we should
1162 // assert as such. But currently it *is* sometimes called, so we can't assert yet. See
1163 // <http://webkit.org/b/58539>.
1165 LOCAL_GDI_COUNTER(0, __FUNCTION__);
1166 #if FLASH_WINDOW_REDRAW
1167 OwnPtr<HBRUSH> greenBrush = CreateSolidBrush(RGB(0, 255, 0));
1168 RECT rect = dirtyRect;
1169 FillRect(windowDC, &rect, greenBrush.get());
1174 // Blit the dirty rect from the backing store into the same position
1175 // in the destination DC.
1176 BitBlt(windowDC, dirtyRect.x(), dirtyRect.y(), dirtyRect.width(), dirtyRect.height(), bitmapDC,
1177 dirtyRect.x(), dirtyRect.y(), SRCCOPY);
1180 void WebView::frameRect(RECT* rect)
1182 ::GetWindowRect(m_viewWindow, rect);
1185 class WindowCloseTimer : public WebCore::SuspendableTimer {
1187 static WindowCloseTimer* create(WebView*);
1190 WindowCloseTimer(ScriptExecutionContext*, WebView*);
1191 virtual void contextDestroyed();
1192 virtual void fired();
1197 WindowCloseTimer* WindowCloseTimer::create(WebView* webView)
1199 ASSERT_ARG(webView, webView);
1200 Frame* frame = core(webView->topLevelFrame());
1205 Document* document = frame->document();
1210 return new WindowCloseTimer(document, webView);
1213 WindowCloseTimer::WindowCloseTimer(ScriptExecutionContext* context, WebView* webView)
1214 : SuspendableTimer(context)
1215 , m_webView(webView)
1217 ASSERT_ARG(context, context);
1218 ASSERT_ARG(webView, webView);
1221 void WindowCloseTimer::contextDestroyed()
1223 SuspendableTimer::contextDestroyed();
1227 void WindowCloseTimer::fired()
1229 m_webView->closeWindowTimerFired();
1232 void WebView::closeWindowSoon()
1234 if (m_closeWindowTimer)
1237 m_closeWindowTimer = WindowCloseTimer::create(this);
1238 if (!m_closeWindowTimer)
1240 m_closeWindowTimer->startOneShot(0);
1245 void WebView::closeWindowTimerFired()
1251 void WebView::closeWindow()
1253 if (m_hasSpellCheckerDocumentTag) {
1254 if (m_editingDelegate)
1255 m_editingDelegate->closeSpellDocument(this);
1256 m_hasSpellCheckerDocumentTag = false;
1259 COMPtr<IWebUIDelegate> ui;
1260 if (SUCCEEDED(uiDelegate(&ui)))
1261 ui->webViewClose(this);
1264 bool WebView::canHandleRequest(const WebCore::ResourceRequest& request)
1266 // On the mac there's an about url protocol implementation but CFNetwork doesn't have that.
1267 if (equalIgnoringCase(String(request.url().protocol()), "about"))
1271 if (CFURLProtocolCanHandleRequest(request.cfURLRequest()))
1274 // FIXME: Mac WebKit calls _representationExistsForURLScheme here
1281 String WebView::standardUserAgentWithApplicationName(const String& applicationName)
1283 DEFINE_STATIC_LOCAL(String, osVersion, (windowsVersionForUAString()));
1284 DEFINE_STATIC_LOCAL(String, webKitVersion, (webKitVersionString()));
1286 return makeString("Mozilla/5.0 (", osVersion, ") AppleWebKit/", webKitVersion, " (KHTML, like Gecko)", applicationName.isEmpty() ? "" : " ", applicationName);
1289 Page* WebView::page()
1294 bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam)
1296 // Translate the screen coordinates into window coordinates
1297 POINT coords = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
1298 if (coords.x == -1 || coords.y == -1) {
1299 // The contextMenuController() holds onto the last context menu that was popped up on the
1300 // page until a new one is created. We need to clear this menu before propagating the event
1301 // through the DOM so that we can detect if we create a new menu for this event, since we
1302 // won't create a new menu if the DOM swallows the event and the defaultEventHandler does
1304 m_page->contextMenuController()->clearContextMenu();
1306 Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
1307 return focusedFrame->eventHandler()->sendContextMenuEventForKey();
1310 if (!::ScreenToClient(m_viewWindow, &coords))
1314 lParam = MAKELPARAM(coords.x, coords.y);
1316 m_page->contextMenuController()->clearContextMenu();
1318 IntPoint documentPoint(m_page->mainFrame()->view()->windowToContents(coords));
1319 HitTestResult result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(documentPoint, false);
1320 Frame* targetFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : m_page->focusController()->focusedOrMainFrame();
1322 targetFrame->view()->setCursor(pointerCursor());
1323 PlatformMouseEvent mouseEvent(m_viewWindow, WM_RBUTTONUP, wParam, lParam);
1324 bool handledEvent = targetFrame->eventHandler()->sendContextMenuEvent(mouseEvent);
1328 ContextMenuController* contextMenuController = m_page->contextMenuController();
1331 ContextMenu* coreMenu = contextMenuController->contextMenu();
1335 Node* node = contextMenuController->hitTestResult().innerNonSharedNode();
1339 Frame* frame = node->document()->frame();
1343 FrameView* view = frame->view();
1347 POINT point(view->contentsToWindow(contextMenuController->hitTestResult().point()));
1349 // Translate the point to screen coordinates
1350 if (!::ClientToScreen(m_viewWindow, &point))
1353 BOOL hasCustomMenus = false;
1355 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1358 m_uiDelegate->trackCustomPopupMenu((IWebView*)this, (OLE_HANDLE)(ULONG64)coreMenu->nativeMenu(), &point);
1360 // Surprisingly, TPM_RIGHTBUTTON means that items are selectable with either the right OR left mouse button
1361 UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL
1362 | TPM_LEFTALIGN | TPM_HORPOSANIMATION;
1363 ::TrackPopupMenuEx(coreMenu->nativeMenu(), flags, point.x, point.y, m_viewWindow, 0);
1369 bool WebView::onMeasureItem(WPARAM /*wParam*/, LPARAM lParam)
1374 BOOL hasCustomMenus = false;
1375 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1376 if (!hasCustomMenus)
1379 m_uiDelegate->measureCustomMenuItem((IWebView*)this, (void*)lParam);
1383 bool WebView::onDrawItem(WPARAM /*wParam*/, LPARAM lParam)
1388 BOOL hasCustomMenus = false;
1389 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1390 if (!hasCustomMenus)
1393 m_uiDelegate->drawCustomMenuItem((IWebView*)this, (void*)lParam);
1397 bool WebView::onInitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1402 HMENU menu = (HMENU)wParam;
1406 BOOL hasCustomMenus = false;
1407 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1408 if (!hasCustomMenus)
1411 m_uiDelegate->addCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1415 bool WebView::onUninitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1420 HMENU menu = (HMENU)wParam;
1424 BOOL hasCustomMenus = false;
1425 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1426 if (!hasCustomMenus)
1429 m_uiDelegate->cleanUpCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1433 void WebView::performContextMenuAction(WPARAM wParam, LPARAM lParam, bool byPosition)
1435 ContextMenu* menu = m_page->contextMenuController()->contextMenu();
1438 ContextMenuItem* item = byPosition ? menu->itemAtIndex((unsigned)wParam) : menu->itemWithAction((ContextMenuAction)wParam);
1441 m_page->contextMenuController()->contextMenuItemSelected(item);
1444 bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
1446 static LONG globalClickCount;
1447 static IntPoint globalPrevPoint;
1448 static MouseButton globalPrevButton;
1449 static LONG globalPrevMouseDownTime;
1451 if (message == WM_CANCELMODE) {
1452 m_page->mainFrame()->eventHandler()->lostMouseCapture();
1456 // Create our event.
1457 // On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
1458 // of the event to be at (MINSHORT, MINSHORT).
1459 LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
1460 PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
1462 setMouseActivated(false);
1464 bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.pos().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
1465 abs(globalPrevPoint.y() - mouseEvent.pos().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
1466 LONG messageTime = ::GetMessageTime();
1468 bool handled = false;
1470 if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
1471 // FIXME: I'm not sure if this is the "right" way to do this
1472 // but without this call, we never become focused since we don't allow
1473 // the default handling of mouse events.
1474 SetFocus(m_viewWindow);
1476 // Always start capturing events when the mouse goes down in our HWND.
1477 ::SetCapture(m_viewWindow);
1479 if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) &&
1481 mouseEvent.button() == globalPrevButton)
1484 // Reset the click count.
1485 globalClickCount = 1;
1486 globalPrevMouseDownTime = messageTime;
1487 globalPrevButton = mouseEvent.button();
1488 globalPrevPoint = mouseEvent.pos();
1490 mouseEvent.setClickCount(globalClickCount);
1491 handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1492 } else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
1494 mouseEvent.setClickCount(globalClickCount);
1495 handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1496 } else if (message == WM_LBUTTONUP || message == WM_MBUTTONUP || message == WM_RBUTTONUP) {
1497 // Record the global position and the button of the up.
1498 globalPrevButton = mouseEvent.button();
1499 globalPrevPoint = mouseEvent.pos();
1500 mouseEvent.setClickCount(globalClickCount);
1501 m_page->mainFrame()->eventHandler()->handleMouseReleaseEvent(mouseEvent);
1503 } else if (message == WM_MOUSELEAVE && m_mouseOutTracker) {
1504 // Once WM_MOUSELEAVE is fired windows clears this tracker
1505 // so there is no need to disable it ourselves.
1506 m_mouseOutTracker.clear();
1507 m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1509 } else if (message == WM_MOUSEMOVE) {
1510 if (!insideThreshold)
1511 globalClickCount = 0;
1512 mouseEvent.setClickCount(globalClickCount);
1513 handled = m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1514 if (!m_mouseOutTracker) {
1515 m_mouseOutTracker = adoptPtr(new TRACKMOUSEEVENT);
1516 m_mouseOutTracker->cbSize = sizeof(TRACKMOUSEEVENT);
1517 m_mouseOutTracker->dwFlags = TME_LEAVE;
1518 m_mouseOutTracker->hwndTrack = m_viewWindow;
1519 ::TrackMouseEvent(m_mouseOutTracker.get());
1525 bool WebView::gestureNotify(WPARAM wParam, LPARAM lParam)
1527 GESTURENOTIFYSTRUCT* gn = reinterpret_cast<GESTURENOTIFYSTRUCT*>(lParam);
1529 Frame* coreFrame = core(m_mainFrame);
1533 ScrollView* view = coreFrame->view();
1537 // If we don't have this function, we shouldn't be receiving this message
1538 ASSERT(SetGestureConfigPtr());
1540 bool hitScrollbar = false;
1541 POINT gestureBeginPoint = {gn->ptsLocation.x, gn->ptsLocation.y};
1542 HitTestRequest request(HitTestRequest::ReadOnly);
1543 for (Frame* childFrame = m_page->mainFrame(); childFrame; childFrame = EventHandler::subframeForTargetNode(m_gestureTargetNode.get())) {
1544 FrameView* frameView = childFrame->view();
1547 RenderView* renderView = childFrame->document()->renderView();
1550 RenderLayer* layer = renderView->layer();
1554 HitTestResult result(frameView->screenToContents(gestureBeginPoint));
1555 layer->hitTest(request, result);
1556 m_gestureTargetNode = result.innerNode();
1559 hitScrollbar = result.scrollbar();
1562 if (!hitScrollbar) {
1563 // The hit testing above won't detect if we've hit the main frame's vertical scrollbar. Check that manually now.
1565 GetWindowRect(m_viewWindow, &webViewRect);
1566 hitScrollbar = view->verticalScrollbar() && (gestureBeginPoint.x > (webViewRect.right - view->verticalScrollbar()->theme()->scrollbarThickness()));
1569 bool canBeScrolled = false;
1570 if (m_gestureTargetNode) {
1571 for (RenderObject* renderer = m_gestureTargetNode->renderer(); renderer; renderer = renderer->parent()) {
1572 if (renderer->isBox() && toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()) {
1573 canBeScrolled = true;
1579 // We always allow two-fingered panning with inertia and a gutter (which limits movement to one
1580 // direction in most cases).
1581 DWORD dwPanWant = GC_PAN | GC_PAN_WITH_INERTIA | GC_PAN_WITH_GUTTER;
1582 // We never allow single-fingered horizontal panning. That gesture is reserved for creating text
1583 // selections. This matches IE.
1584 DWORD dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
1586 if (hitScrollbar || !canBeScrolled) {
1587 // The part of the page under the gesture can't be scrolled, or the gesture is on a scrollbar.
1588 // Disallow single-fingered vertical panning in this case, too, so we'll fall back to the default
1589 // behavior (which allows the scrollbar thumb to be dragged, text selections to be made, etc.).
1590 dwPanBlock |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
1592 // The part of the page the gesture is under can be scrolled, and we're not under a scrollbar.
1593 // Allow single-fingered vertical panning in this case, so the user will be able to pan the page
1594 // with one or two fingers.
1595 dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
1598 GESTURECONFIG gc = { GID_PAN, dwPanWant, dwPanBlock };
1599 return SetGestureConfigPtr()(m_viewWindow, 0, 1, &gc, sizeof(GESTURECONFIG));
1602 bool WebView::gesture(WPARAM wParam, LPARAM lParam)
1604 // We want to bail out if we don't have either of these functions
1605 if (!GetGestureInfoPtr() || !CloseGestureInfoHandlePtr())
1608 HGESTUREINFO gestureHandle = reinterpret_cast<HGESTUREINFO>(lParam);
1610 GESTUREINFO gi = {0};
1611 gi.cbSize = sizeof(GESTUREINFO);
1613 if (!GetGestureInfoPtr()(gestureHandle, reinterpret_cast<PGESTUREINFO>(&gi)))
1618 m_lastPanX = gi.ptsLocation.x;
1619 m_lastPanY = gi.ptsLocation.y;
1623 m_gestureTargetNode = 0;
1626 // Where are the fingers currently?
1627 long currentX = gi.ptsLocation.x;
1628 long currentY = gi.ptsLocation.y;
1629 // How far did we pan in each direction?
1630 long deltaX = currentX - m_lastPanX;
1631 long deltaY = currentY - m_lastPanY;
1632 // Calculate the overpan for window bounce
1633 m_yOverpan -= m_lastPanY - currentY;
1634 m_xOverpan -= m_lastPanX - currentX;
1635 // Update our class variables with updated values
1636 m_lastPanX = currentX;
1637 m_lastPanY = currentY;
1639 Frame* coreFrame = core(m_mainFrame);
1641 CloseGestureInfoHandlePtr()(gestureHandle);
1645 if (!m_gestureTargetNode || !m_gestureTargetNode->renderer())
1648 // We negate here since panning up moves the content up, but moves the scrollbar down.
1649 m_gestureTargetNode->renderer()->enclosingLayer()->scrollByRecursively(-deltaX, -deltaY);
1651 if (!(UpdatePanningFeedbackPtr() && BeginPanningFeedbackPtr() && EndPanningFeedbackPtr())) {
1652 CloseGestureInfoHandlePtr()(gestureHandle);
1656 if (gi.dwFlags & GF_BEGIN) {
1657 BeginPanningFeedbackPtr()(m_viewWindow);
1659 } else if (gi.dwFlags & GF_END) {
1660 EndPanningFeedbackPtr()(m_viewWindow, true);
1664 ScrollView* view = coreFrame->view();
1666 CloseGestureInfoHandlePtr()(gestureHandle);
1669 Scrollbar* vertScrollbar = view->verticalScrollbar();
1670 if (!vertScrollbar) {
1671 CloseGestureInfoHandlePtr()(gestureHandle);
1675 // FIXME: Support Horizontal Window Bounce. <https://webkit.org/b/28500>.
1676 // FIXME: If the user starts panning down after a window bounce has started, the window doesn't bounce back
1677 // until they release their finger. <https://webkit.org/b/28501>.
1678 if (vertScrollbar->currentPos() == 0)
1679 UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
1680 else if (vertScrollbar->currentPos() >= vertScrollbar->maximum())
1681 UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
1683 CloseGestureInfoHandlePtr()(gestureHandle);
1690 // If we get to this point, the gesture has not been handled. We forward
1691 // the call to DefWindowProc by returning false, and we don't need to
1692 // to call CloseGestureInfoHandle.
1693 // http://msdn.microsoft.com/en-us/library/dd353228(VS.85).aspx
1697 bool WebView::mouseWheel(WPARAM wParam, LPARAM lParam, bool isMouseHWheel)
1699 // Ctrl+Mouse wheel doesn't ever go into WebCore. It is used to
1700 // zoom instead (Mac zooms the whole Desktop, but Windows browsers trigger their
1701 // own local zoom modes for Ctrl+wheel).
1702 if (wParam & MK_CONTROL) {
1703 short delta = short(HIWORD(wParam));
1711 // 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.
1712 HWND focusedWindow = GetFocus();
1713 if (focusedWindow && focusedWindow != m_viewWindow) {
1714 // 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).
1715 WCHAR className[256];
1717 // Make sure truncation won't affect the comparison.
1718 ASSERT(WTF_ARRAY_LENGTH(className) > wcslen(PopupMenuWin::popupClassName()));
1720 if (GetClassNameW(focusedWindow, className, WTF_ARRAY_LENGTH(className)) && !wcscmp(className, PopupMenuWin::popupClassName())) {
1721 // We don't let the WebView scroll here for two reasons - 1) To match Firefox behavior, 2) If we do scroll, we lose the
1722 // focus ring around the select menu.
1723 SetFocus(m_viewWindow);
1728 PlatformWheelEvent wheelEvent(m_viewWindow, wParam, lParam, isMouseHWheel);
1729 Frame* coreFrame = core(m_mainFrame);
1733 return coreFrame->eventHandler()->handleWheelEvent(wheelEvent);
1736 bool WebView::verticalScroll(WPARAM wParam, LPARAM /*lParam*/)
1738 ScrollDirection direction;
1739 ScrollGranularity granularity;
1740 switch (LOWORD(wParam)) {
1742 granularity = ScrollByLine;
1743 direction = ScrollDown;
1746 granularity = ScrollByLine;
1747 direction = ScrollUp;
1750 granularity = ScrollByDocument;
1751 direction = ScrollDown;
1754 granularity = ScrollByDocument;
1755 direction = ScrollUp;
1762 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1763 return frame->eventHandler()->scrollRecursively(direction, granularity);
1766 bool WebView::horizontalScroll(WPARAM wParam, LPARAM /*lParam*/)
1768 ScrollDirection direction;
1769 ScrollGranularity granularity;
1770 switch (LOWORD(wParam)) {
1772 granularity = ScrollByLine;
1773 direction = ScrollLeft;
1776 granularity = ScrollByLine;
1777 direction = ScrollRight;
1780 granularity = ScrollByDocument;
1781 direction = ScrollLeft;
1784 granularity = ScrollByDocument;
1785 direction = ScrollRight;
1791 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1792 return frame->eventHandler()->scrollRecursively(direction, granularity);
1796 bool WebView::execCommand(WPARAM wParam, LPARAM /*lParam*/)
1798 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1799 switch (LOWORD(wParam)) {
1801 return frame->editor()->command("SelectAll").execute();
1803 return frame->editor()->command("Undo").execute();
1805 return frame->editor()->command("Redo").execute();
1810 bool WebView::keyUp(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1812 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::KeyUp, systemKeyDown);
1814 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1815 m_currentCharacterCode = 0;
1817 return frame->eventHandler()->keyEvent(keyEvent);
1820 static const unsigned CtrlKey = 1 << 0;
1821 static const unsigned AltKey = 1 << 1;
1822 static const unsigned ShiftKey = 1 << 2;
1825 struct KeyDownEntry {
1826 unsigned virtualKey;
1831 struct KeyPressEntry {
1837 static const KeyDownEntry keyDownEntries[] = {
1838 { VK_LEFT, 0, "MoveLeft" },
1839 { VK_LEFT, ShiftKey, "MoveLeftAndModifySelection" },
1840 { VK_LEFT, CtrlKey, "MoveWordLeft" },
1841 { VK_LEFT, CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection" },
1842 { VK_RIGHT, 0, "MoveRight" },
1843 { VK_RIGHT, ShiftKey, "MoveRightAndModifySelection" },
1844 { VK_RIGHT, CtrlKey, "MoveWordRight" },
1845 { VK_RIGHT, CtrlKey | ShiftKey, "MoveWordRightAndModifySelection" },
1846 { VK_UP, 0, "MoveUp" },
1847 { VK_UP, ShiftKey, "MoveUpAndModifySelection" },
1848 { VK_PRIOR, ShiftKey, "MovePageUpAndModifySelection" },
1849 { VK_DOWN, 0, "MoveDown" },
1850 { VK_DOWN, ShiftKey, "MoveDownAndModifySelection" },
1851 { VK_NEXT, ShiftKey, "MovePageDownAndModifySelection" },
1852 { VK_PRIOR, 0, "MovePageUp" },
1853 { VK_NEXT, 0, "MovePageDown" },
1854 { VK_HOME, 0, "MoveToBeginningOfLine" },
1855 { VK_HOME, ShiftKey, "MoveToBeginningOfLineAndModifySelection" },
1856 { VK_HOME, CtrlKey, "MoveToBeginningOfDocument" },
1857 { VK_HOME, CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
1859 { VK_END, 0, "MoveToEndOfLine" },
1860 { VK_END, ShiftKey, "MoveToEndOfLineAndModifySelection" },
1861 { VK_END, CtrlKey, "MoveToEndOfDocument" },
1862 { VK_END, CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection" },
1864 { VK_BACK, 0, "DeleteBackward" },
1865 { VK_BACK, ShiftKey, "DeleteBackward" },
1866 { VK_DELETE, 0, "DeleteForward" },
1867 { VK_BACK, CtrlKey, "DeleteWordBackward" },
1868 { VK_DELETE, CtrlKey, "DeleteWordForward" },
1870 { 'B', CtrlKey, "ToggleBold" },
1871 { 'I', CtrlKey, "ToggleItalic" },
1873 { VK_ESCAPE, 0, "Cancel" },
1874 { VK_OEM_PERIOD, CtrlKey, "Cancel" },
1875 { VK_TAB, 0, "InsertTab" },
1876 { VK_TAB, ShiftKey, "InsertBacktab" },
1877 { VK_RETURN, 0, "InsertNewline" },
1878 { VK_RETURN, CtrlKey, "InsertNewline" },
1879 { VK_RETURN, AltKey, "InsertNewline" },
1880 { VK_RETURN, ShiftKey, "InsertNewline" },
1881 { VK_RETURN, AltKey | ShiftKey, "InsertNewline" },
1883 // It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled
1884 // in the application or in WebKit. We chose WebKit.
1885 { 'C', CtrlKey, "Copy" },
1886 { 'V', CtrlKey, "Paste" },
1887 { 'X', CtrlKey, "Cut" },
1888 { 'A', CtrlKey, "SelectAll" },
1889 { VK_INSERT, CtrlKey, "Copy" },
1890 { VK_DELETE, ShiftKey, "Cut" },
1891 { VK_INSERT, ShiftKey, "Paste" },
1892 { 'Z', CtrlKey, "Undo" },
1893 { 'Z', CtrlKey | ShiftKey, "Redo" },
1896 static const KeyPressEntry keyPressEntries[] = {
1897 { '\t', 0, "InsertTab" },
1898 { '\t', ShiftKey, "InsertBacktab" },
1899 { '\r', 0, "InsertNewline" },
1900 { '\r', CtrlKey, "InsertNewline" },
1901 { '\r', AltKey, "InsertNewline" },
1902 { '\r', ShiftKey, "InsertNewline" },
1903 { '\r', AltKey | ShiftKey, "InsertNewline" },
1906 const char* WebView::interpretKeyEvent(const KeyboardEvent* evt)
1908 ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
1910 static HashMap<int, const char*>* keyDownCommandsMap = 0;
1911 static HashMap<int, const char*>* keyPressCommandsMap = 0;
1913 if (!keyDownCommandsMap) {
1914 keyDownCommandsMap = new HashMap<int, const char*>;
1915 keyPressCommandsMap = new HashMap<int, const char*>;
1917 for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyDownEntries); ++i)
1918 keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
1920 for (size_t i = 0; i < WTF_ARRAY_LENGTH(keyPressEntries); ++i)
1921 keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
1924 unsigned modifiers = 0;
1925 if (evt->shiftKey())
1926 modifiers |= ShiftKey;
1928 modifiers |= AltKey;
1930 modifiers |= CtrlKey;
1932 if (evt->type() == eventNames().keydownEvent) {
1933 int mapKey = modifiers << 16 | evt->keyCode();
1934 return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
1937 int mapKey = modifiers << 16 | evt->charCode();
1938 return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
1941 bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
1943 Node* node = evt->target()->toNode();
1945 Frame* frame = node->document()->frame();
1948 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1949 if (!keyEvent || keyEvent->isSystemKey()) // do not treat this as text input if it's a system key event
1952 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1954 if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1955 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1956 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1957 // (e.g. Tab that inserts a Tab character, or Enter).
1958 return !command.isTextInsertion() && command.execute(evt);
1961 if (command.execute(evt))
1964 // Don't insert null or control characters as they can result in unexpected behaviour
1965 if (evt->charCode() < ' ')
1968 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1971 bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1973 #if ENABLE(FULLSCREEN_API)
1974 // Trap the ESC key when in full screen mode.
1975 if (virtualKeyCode == VK_ESCAPE && isFullScreen()) {
1976 m_fullscreenController->exitFullScreen();
1980 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1982 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::RawKeyDown, systemKeyDown);
1983 bool handled = frame->eventHandler()->keyEvent(keyEvent);
1985 // These events cannot be canceled, and we have no default handling for them.
1986 // FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
1987 if (systemKeyDown && virtualKeyCode != VK_RETURN)
1991 // FIXME: remove WM_UNICHAR, too
1993 // WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
1995 ::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
1999 // We need to handle back/forward using either Ctrl+Left/Right Arrow keys.
2000 // FIXME: This logic should probably be in EventHandler::defaultArrowEventHandler().
2001 // FIXME: Should check that other modifiers aren't pressed.
2002 if (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey())
2003 return m_page->goForward();
2004 if (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey())
2005 return m_page->goBack();
2007 // Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
2008 ScrollDirection direction;
2009 ScrollGranularity granularity;
2010 switch (virtualKeyCode) {
2012 granularity = ScrollByLine;
2013 direction = ScrollLeft;
2016 granularity = ScrollByLine;
2017 direction = ScrollRight;
2020 granularity = ScrollByLine;
2021 direction = ScrollUp;
2024 granularity = ScrollByLine;
2025 direction = ScrollDown;
2028 granularity = ScrollByDocument;
2029 direction = ScrollUp;
2032 granularity = ScrollByDocument;
2033 direction = ScrollDown;
2036 granularity = ScrollByPage;
2037 direction = ScrollUp;
2040 granularity = ScrollByPage;
2041 direction = ScrollDown;
2047 return frame->eventHandler()->scrollRecursively(direction, granularity);
2050 bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
2052 Frame* frame = m_page->focusController()->focusedOrMainFrame();
2054 PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformKeyboardEvent::Char, systemKeyDown);
2055 // IE does not dispatch keypress event for WM_SYSCHAR.
2057 return frame->eventHandler()->handleAccessKey(keyEvent);
2058 return frame->eventHandler()->keyEvent(keyEvent);
2061 void WebView::setIsBeingDestroyed()
2063 m_isBeingDestroyed = true;
2065 // Remove our this pointer from the window so we won't try to handle any more window messages.
2066 // See <http://webkit.org/b/55054>.
2067 ::SetWindowLongPtrW(m_viewWindow, 0, 0);
2070 bool WebView::registerWebViewWindowClass()
2072 static bool haveRegisteredWindowClass = false;
2073 if (haveRegisteredWindowClass)
2076 haveRegisteredWindowClass = true;
2080 wcex.cbSize = sizeof(WNDCLASSEX);
2082 wcex.style = CS_DBLCLKS;
2083 wcex.lpfnWndProc = WebViewWndProc;
2084 wcex.cbClsExtra = 0;
2085 wcex.cbWndExtra = 4; // 4 bytes for the IWebView pointer
2086 wcex.hInstance = gInstance;
2088 wcex.hCursor = ::LoadCursor(0, IDC_ARROW);
2089 wcex.hbrBackground = 0;
2090 wcex.lpszMenuName = 0;
2091 wcex.lpszClassName = kWebViewWindowClassName;
2094 return !!RegisterClassEx(&wcex);
2097 static HWND findTopLevelParent(HWND window)
2102 HWND current = window;
2103 for (HWND parent = GetParent(current); current; current = parent, parent = GetParent(parent))
2104 if (!parent || !(GetWindowLongPtr(current, GWL_STYLE) & (WS_POPUP | WS_CHILD)))
2106 ASSERT_NOT_REACHED();
2110 LRESULT CALLBACK WebView::WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
2112 LRESULT lResult = 0;
2113 LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
2114 WebView* webView = reinterpret_cast<WebView*>(longPtr);
2115 WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
2117 return DefWindowProc(hWnd, message, wParam, lParam);
2119 // We shouldn't be trying to handle any window messages after WM_DESTROY.
2120 // See <http://webkit.org/b/55054>.
2121 ASSERT(!webView->isBeingDestroyed());
2123 // hold a ref, since the WebView could go away in an event handler.
2124 COMPtr<WebView> protector(webView);
2127 // Windows Media Player has a modal message loop that will deliver messages
2128 // to us at inappropriate times and we will crash if we handle them when
2129 // they are delivered. We repost paint messages so that we eventually get
2130 // a chance to paint once the modal loop has exited, but other messages
2131 // aren't safe to repost, so we just drop them.
2132 if (PluginView::isCallingPlugin()) {
2133 if (message == WM_PAINT)
2134 PostMessage(hWnd, message, wParam, lParam);
2138 bool handled = true;
2142 webView->paint(0, 0);
2143 if (webView->usesLayeredWindow())
2144 webView->performLayeredWindowUpdate();
2148 if (webView->usesLayeredWindow()) {
2149 // Don't perform a background erase for transparent views.
2154 case WM_PRINTCLIENT:
2155 webView->paint((HDC)wParam, lParam);
2158 webView->setIsBeingDestroyed();
2161 case WM_GESTURENOTIFY:
2162 handled = webView->gestureNotify(wParam, lParam);
2165 handled = webView->gesture(wParam, lParam);
2168 case WM_LBUTTONDOWN:
2169 case WM_MBUTTONDOWN:
2170 case WM_RBUTTONDOWN:
2171 case WM_LBUTTONDBLCLK:
2172 case WM_MBUTTONDBLCLK:
2173 case WM_RBUTTONDBLCLK:
2179 if (Frame* coreFrame = core(mainFrameImpl))
2180 if (coreFrame->view()->didFirstLayout())
2181 handled = webView->handleMouseEvent(message, wParam, lParam);
2184 case WM_VISTA_MOUSEHWHEEL:
2185 if (Frame* coreFrame = core(mainFrameImpl))
2186 if (coreFrame->view()->didFirstLayout())
2187 handled = webView->mouseWheel(wParam, lParam, message == WM_VISTA_MOUSEHWHEEL);
2190 handled = webView->keyDown(wParam, lParam, true);
2193 handled = webView->keyDown(wParam, lParam);
2196 handled = webView->keyUp(wParam, lParam, true);
2199 handled = webView->keyUp(wParam, lParam);
2202 handled = webView->keyPress(wParam, lParam, true);
2205 handled = webView->keyPress(wParam, lParam);
2207 // FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
2210 webView->sizeChanged(IntSize(LOWORD(lParam), HIWORD(lParam)));
2213 lResult = DefWindowProc(hWnd, message, wParam, lParam);
2215 // The window is being hidden (e.g., because we switched tabs).
2216 // Null out our backing store.
2217 webView->deleteBackingStore();
2221 COMPtr<IWebUIDelegate> uiDelegate;
2222 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2223 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2224 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2225 uiDelegatePrivate->webViewReceivedFocus(webView);
2227 FocusController* focusController = webView->page()->focusController();
2228 if (Frame* frame = focusController->focusedFrame()) {
2229 // Send focus events unless the previously focused window is a
2230 // child of ours (for example a plugin).
2231 if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
2232 focusController->setFocused(true);
2234 focusController->setFocused(true);
2237 case WM_KILLFOCUS: {
2238 COMPtr<IWebUIDelegate> uiDelegate;
2239 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2240 HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
2241 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2242 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2243 uiDelegatePrivate->webViewLostFocus(webView, (OLE_HANDLE)(ULONG64)newFocusWnd);
2245 FocusController* focusController = webView->page()->focusController();
2246 Frame* frame = focusController->focusedOrMainFrame();
2247 webView->resetIME(frame);
2248 // Send blur events unless we're losing focus to a child of ours.
2249 if (!IsChild(hWnd, newFocusWnd))
2250 focusController->setFocused(false);
2252 // If we are pan-scrolling when we lose focus, stop the pan scrolling.
2253 frame->eventHandler()->stopAutoscrollTimer();
2257 case WM_WINDOWPOSCHANGED:
2258 if (reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW)
2259 webView->updateActiveStateSoon();
2272 webView->delete_(0);
2276 handled = webView->execCommand(wParam, lParam);
2277 else // If the high word of wParam is 0, the message is from a menu
2278 webView->performContextMenuAction(wParam, lParam, false);
2280 case WM_MENUCOMMAND:
2281 webView->performContextMenuAction(wParam, lParam, true);
2283 case WM_CONTEXTMENU:
2284 handled = webView->handleContextMenuEvent(wParam, lParam);
2286 case WM_INITMENUPOPUP:
2287 handled = webView->onInitMenuPopup(wParam, lParam);
2289 case WM_MEASUREITEM:
2290 handled = webView->onMeasureItem(wParam, lParam);
2293 handled = webView->onDrawItem(wParam, lParam);
2295 case WM_UNINITMENUPOPUP:
2296 handled = webView->onUninitMenuPopup(wParam, lParam);
2298 case WM_XP_THEMECHANGED:
2299 if (Frame* coreFrame = core(mainFrameImpl)) {
2300 webView->deleteBackingStore();
2301 coreFrame->page()->theme()->themeChanged();
2302 ScrollbarTheme::nativeTheme()->themeChanged();
2304 ::GetClientRect(hWnd, &windowRect);
2305 ::InvalidateRect(hWnd, &windowRect, false);
2306 #if USE(ACCELERATED_COMPOSITING)
2307 if (webView->isAcceleratedCompositing())
2308 webView->m_backingLayer->setNeedsDisplay();
2312 case WM_MOUSEACTIVATE:
2313 webView->setMouseActivated(true);
2316 case WM_GETDLGCODE: {
2317 COMPtr<IWebUIDelegate> uiDelegate;
2318 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2319 LONG_PTR dlgCode = 0;
2322 LPMSG lpMsg = (LPMSG)lParam;
2323 if (lpMsg->message == WM_KEYDOWN)
2324 keyCode = (UINT) lpMsg->wParam;
2326 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate
2327 && SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate
2328 && SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
2334 handled = webView->onGetObject(wParam, lParam, lResult);
2336 case WM_IME_STARTCOMPOSITION:
2337 handled = webView->onIMEStartComposition();
2339 case WM_IME_REQUEST:
2340 lResult = webView->onIMERequest(wParam, lParam);
2342 case WM_IME_COMPOSITION:
2343 handled = webView->onIMEComposition(lParam);
2345 case WM_IME_ENDCOMPOSITION:
2346 handled = webView->onIMEEndComposition();
2349 handled = webView->onIMEChar(wParam, lParam);
2352 handled = webView->onIMENotify(wParam, lParam, &lResult);
2355 handled = webView->onIMESelect(wParam, lParam);
2357 case WM_IME_SETCONTEXT:
2358 handled = webView->onIMESetContext(wParam, lParam);
2362 case UpdateActiveStateTimer:
2363 KillTimer(hWnd, UpdateActiveStateTimer);
2364 webView->updateActiveState();
2366 case DeleteBackingStoreTimer:
2367 webView->deleteBackingStore();
2372 handled = ::SetCursor(webView->m_lastSetCursor);
2375 handled = webView->verticalScroll(wParam, lParam);
2378 handled = webView->horizontalScroll(wParam, lParam);
2386 lResult = DefWindowProc(hWnd, message, wParam, lParam);
2388 // Let the client know whether we consider this message handled.
2389 return (message == WM_KEYDOWN || message == WM_SYSKEYDOWN || message == WM_KEYUP || message == WM_SYSKEYUP) ? !handled : lResult;
2392 bool WebView::developerExtrasEnabled() const
2394 if (m_preferences->developerExtrasDisabledByOverride())
2399 return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
2405 static String webKitVersionString()
2407 LPWSTR buildNumberStringPtr;
2408 if (!::LoadStringW(gInstance, BUILD_NUMBER, reinterpret_cast<LPWSTR>(&buildNumberStringPtr), 0) || !buildNumberStringPtr)
2411 return buildNumberStringPtr;
2414 const String& WebView::userAgentForKURL(const KURL&)
2416 if (m_userAgentOverridden)
2417 return m_userAgentCustom;
2419 if (!m_userAgentStandard.length())
2420 m_userAgentStandard = WebView::standardUserAgentWithApplicationName(m_applicationName);
2421 return m_userAgentStandard;
2424 // IUnknown -------------------------------------------------------------------
2426 HRESULT STDMETHODCALLTYPE WebView::QueryInterface(REFIID riid, void** ppvObject)
2429 if (IsEqualGUID(riid, CLSID_WebView))
2431 else if (IsEqualGUID(riid, IID_IUnknown))
2432 *ppvObject = static_cast<IWebView*>(this);
2433 else if (IsEqualGUID(riid, IID_IWebView))
2434 *ppvObject = static_cast<IWebView*>(this);
2435 else if (IsEqualGUID(riid, IID_IWebViewPrivate))
2436 *ppvObject = static_cast<IWebViewPrivate*>(this);
2437 else if (IsEqualGUID(riid, IID_IWebIBActions))
2438 *ppvObject = static_cast<IWebIBActions*>(this);
2439 else if (IsEqualGUID(riid, IID_IWebViewCSS))
2440 *ppvObject = static_cast<IWebViewCSS*>(this);
2441 else if (IsEqualGUID(riid, IID_IWebViewEditing))
2442 *ppvObject = static_cast<IWebViewEditing*>(this);
2443 else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
2444 *ppvObject = static_cast<IWebViewUndoableEditing*>(this);
2445 else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
2446 *ppvObject = static_cast<IWebViewEditingActions*>(this);
2447 else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
2448 *ppvObject = static_cast<IWebNotificationObserver*>(this);
2449 else if (IsEqualGUID(riid, IID_IDropTarget))
2450 *ppvObject = static_cast<IDropTarget*>(this);
2452 return E_NOINTERFACE;
2458 ULONG STDMETHODCALLTYPE WebView::AddRef(void)
2460 ASSERT(!m_deletionHasBegun);
2461 return ++m_refCount;
2464 ULONG STDMETHODCALLTYPE WebView::Release(void)
2466 ASSERT(!m_deletionHasBegun);
2468 if (m_refCount == 1) {
2469 // Call close() now so that clients don't have to. (It's harmless to call close() multiple
2470 // times.) We do this here instead of in our destructor because close() can cause AddRef()
2471 // and Release() to be called, and if that happened in our destructor we would be destroyed
2476 ULONG newRef = --m_refCount;
2478 #if !ASSERT_DISABLED
2479 m_deletionHasBegun = true;
2487 // IWebView --------------------------------------------------------------------
2489 HRESULT STDMETHODCALLTYPE WebView::canShowMIMEType(
2490 /* [in] */ BSTR mimeType,
2491 /* [retval][out] */ BOOL* canShow)
2493 String mimeTypeStr(mimeType, SysStringLen(mimeType));
2498 *canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeTypeStr) ||
2499 MIMETypeRegistry::isSupportedNonImageMIMEType(mimeTypeStr) ||
2500 (m_page && m_page->pluginData() && m_page->pluginData()->supportsMimeType(mimeTypeStr)) ||
2501 shouldUseEmbeddedView(mimeTypeStr);
2506 HRESULT STDMETHODCALLTYPE WebView::canShowMIMETypeAsHTML(
2507 /* [in] */ BSTR /*mimeType*/,
2508 /* [retval][out] */ BOOL* canShow)
2515 HRESULT STDMETHODCALLTYPE WebView::MIMETypesShownAsHTML(
2516 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
2518 ASSERT_NOT_REACHED();
2522 HRESULT STDMETHODCALLTYPE WebView::setMIMETypesShownAsHTML(
2523 /* [size_is][in] */ BSTR* /*mimeTypes*/,
2524 /* [in] */ int /*cMimeTypes*/)
2526 ASSERT_NOT_REACHED();
2530 HRESULT STDMETHODCALLTYPE WebView::URLFromPasteboard(
2531 /* [in] */ IDataObject* /*pasteboard*/,
2532 /* [retval][out] */ BSTR* /*url*/)
2534 ASSERT_NOT_REACHED();
2538 HRESULT STDMETHODCALLTYPE WebView::URLTitleFromPasteboard(
2539 /* [in] */ IDataObject* /*pasteboard*/,
2540 /* [retval][out] */ BSTR* /*urlTitle*/)
2542 ASSERT_NOT_REACHED();
2546 static void WebKitSetApplicationCachePathIfNecessary()
2548 static bool initialized = false;
2552 String path = localUserSpecificStorageDirectory();
2554 cacheStorage().setCacheDirectory(path);
2559 bool WebView::shouldInitializeTrackPointHack()
2561 static bool shouldCreateScrollbars;
2562 static bool hasRunTrackPointCheck;
2564 if (hasRunTrackPointCheck)
2565 return shouldCreateScrollbars;
2567 hasRunTrackPointCheck = true;
2568 const WCHAR trackPointKeys[][50] = { L"Software\\Lenovo\\TrackPoint",
2569 L"Software\\Lenovo\\UltraNav",
2570 L"Software\\Alps\\Apoint\\TrackPoint",
2571 L"Software\\Synaptics\\SynTPEnh\\UltraNavUSB",
2572 L"Software\\Synaptics\\SynTPEnh\\UltraNavPS2" };
2574 for (int i = 0; i < 5; ++i) {
2576 int readKeyResult = ::RegOpenKeyExW(HKEY_CURRENT_USER, trackPointKeys[i], 0, KEY_READ, &trackPointKey);
2577 ::RegCloseKey(trackPointKey);
2578 if (readKeyResult == ERROR_SUCCESS) {
2579 shouldCreateScrollbars = true;
2580 return shouldCreateScrollbars;
2584 return shouldCreateScrollbars;
2587 HRESULT STDMETHODCALLTYPE WebView::initWithFrame(
2588 /* [in] */ RECT frame,
2589 /* [in] */ BSTR frameName,
2590 /* [in] */ BSTR groupName)
2597 registerWebViewWindowClass();
2599 m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
2600 frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow ? m_hostWindow : HWND_MESSAGE, 0, gInstance, 0);
2601 ASSERT(::IsWindow(m_viewWindow));
2603 if (shouldInitializeTrackPointHack()) {
2604 // If we detected a registry key belonging to a TrackPoint driver, then create fake trackpoint
2605 // scrollbars, so the WebView will receive WM_VSCROLL and WM_HSCROLL messages. We create one
2606 // vertical scrollbar and one horizontal to allow for receiving both types of messages.
2607 ::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTHSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_HORZ, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
2608 ::CreateWindowW(L"SCROLLBAR", L"FAKETRACKPOINTVSCROLLBAR", WS_CHILD | WS_VISIBLE | SBS_VERT, 0, 0, 0, 0, m_viewWindow, 0, gInstance, 0);
2611 hr = registerDragDrop();
2615 WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
2616 sharedPreferences->willAddToWebView();
2617 m_preferences = sharedPreferences;
2619 static bool didOneTimeInitialization;
2620 if (!didOneTimeInitialization) {
2621 InitializeLoggingChannelsIfNecessary();
2622 #if ENABLE(SQL_DATABASE)
2623 WebKitInitializeWebDatabasesIfNecessary();
2625 WebKitSetApplicationCachePathIfNecessary();
2626 WebPlatformStrategies::initialize();
2627 Settings::setDefaultMinDOMTimerInterval(0.004);
2629 didOneTimeInitialization = true;
2632 #if USE(SAFARI_THEME)
2633 BOOL shouldPaintNativeControls;
2634 if (SUCCEEDED(m_preferences->shouldPaintNativeControls(&shouldPaintNativeControls)))
2635 Settings::setShouldPaintNativeControls(shouldPaintNativeControls);
2638 BOOL useHighResolutionTimer;
2639 if (SUCCEEDED(m_preferences->shouldUseHighResolutionTimers(&useHighResolutionTimer)))
2640 Settings::setShouldUseHighResolutionTimers(useHighResolutionTimer);
2642 Page::PageClients pageClients;
2643 pageClients.chromeClient = new WebChromeClient(this);
2644 pageClients.contextMenuClient = new WebContextMenuClient(this);
2645 pageClients.editorClient = new WebEditorClient(this);
2646 pageClients.dragClient = new WebDragClient(this);
2647 pageClients.inspectorClient = new WebInspectorClient(this);
2648 #if ENABLE(CLIENT_BASED_GEOLOCATION)
2649 pageClients.geolocationClient = new WebGeolocationClient(this);
2651 m_page = new Page(pageClients);
2653 BSTR localStoragePath;
2654 if (SUCCEEDED(m_preferences->localStorageDatabasePath(&localStoragePath))) {
2655 m_page->settings()->setLocalStorageDatabasePath(String(localStoragePath, SysStringLen(localStoragePath)));
2656 SysFreeString(localStoragePath);
2661 if (SUCCEEDED(m_uiDelegate->ftpDirectoryTemplatePath(this, &path))) {
2662 m_page->settings()->setFTPDirectoryTemplatePath(String(path, SysStringLen(path)));
2663 SysFreeString(path);
2667 WebFrame* webFrame = WebFrame::createInstance();
2668 RefPtr<Frame> coreFrame = webFrame->init(this, m_page, 0);
2669 m_mainFrame = webFrame;
2670 webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
2672 coreFrame->tree()->setName(String(frameName, SysStringLen(frameName)));
2674 setGroupName(groupName);
2676 addToAllWebViewsSet();
2678 #pragma warning(suppress: 4244)
2679 SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
2680 ShowWindow(m_viewWindow, SW_SHOW);
2682 initializeToolTipWindow();
2683 windowAncestryDidChange();
2685 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
2686 notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2687 m_preferences->postPreferencesChangesNotification();
2689 setSmartInsertDeleteEnabled(TRUE);
2693 static bool initCommonControls()
2695 static bool haveInitialized = false;
2696 if (haveInitialized)
2699 INITCOMMONCONTROLSEX init;
2700 init.dwSize = sizeof(init);
2701 init.dwICC = ICC_TREEVIEW_CLASSES;
2702 haveInitialized = !!::InitCommonControlsEx(&init);
2703 return haveInitialized;
2706 void WebView::initializeToolTipWindow()
2708 if (!initCommonControls())
2711 m_toolTipHwnd = CreateWindowEx(WS_EX_TRANSPARENT, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
2712 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
2713 m_viewWindow, 0, 0, 0);
2717 TOOLINFO info = {0};
2718 info.cbSize = sizeof(info);
2719 info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
2720 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2722 ::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
2723 ::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, maxToolTipWidth);
2725 ::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
2728 void WebView::setToolTip(const String& toolTip)
2733 if (toolTip == m_toolTip)
2736 m_toolTip = toolTip;
2738 if (!m_toolTip.isEmpty()) {
2739 TOOLINFO info = {0};
2740 info.cbSize = sizeof(info);
2741 info.uFlags = TTF_IDISHWND;
2742 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2743 info.lpszText = const_cast<UChar*>(m_toolTip.charactersWithNullTermination());
2744 ::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
2747 ::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
2750 HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
2752 COMPtr<IPropertyBag> propertyBag;
2753 HRESULT hr = notification->userInfo(&propertyBag);
2759 COMPtr<CFDictionaryPropertyBag> dictionaryPropertyBag;
2760 hr = propertyBag->QueryInterface(&dictionaryPropertyBag);
2764 CFDictionaryRef dictionary = dictionaryPropertyBag->dictionary();
2768 CFTypeRef value = CFDictionaryGetValue(dictionary, WebIconDatabase::iconDatabaseNotificationUserInfoURLKey());
2771 if (CFGetTypeID(value) != CFStringGetTypeID())
2774 String mainFrameURL;
2776 mainFrameURL = m_mainFrame->url().string();
2778 if (!mainFrameURL.isEmpty() && mainFrameURL == String((CFStringRef)value))
2779 dispatchDidReceiveIconFromWebFrame(m_mainFrame);
2784 void WebView::registerForIconNotification(bool listen)
2786 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2788 nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2790 nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2793 void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
2795 registerForIconNotification(false);
2797 if (m_frameLoadDelegate)
2798 // FIXME: <rdar://problem/5491010> - Pass in the right HBITMAP.
2799 m_frameLoadDelegate->didReceiveIcon(this, 0, frame);
2802 HRESULT STDMETHODCALLTYPE WebView::setUIDelegate(
2803 /* [in] */ IWebUIDelegate* d)
2807 if (m_uiDelegatePrivate)
2808 m_uiDelegatePrivate = 0;
2811 if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
2812 m_uiDelegatePrivate = 0;
2818 HRESULT STDMETHODCALLTYPE WebView::uiDelegate(
2819 /* [out][retval] */ IWebUIDelegate** d)
2824 return m_uiDelegate.copyRefTo(d);
2827 HRESULT STDMETHODCALLTYPE WebView::setResourceLoadDelegate(
2828 /* [in] */ IWebResourceLoadDelegate* d)
2830 m_resourceLoadDelegate = d;
2834 HRESULT STDMETHODCALLTYPE WebView::resourceLoadDelegate(
2835 /* [out][retval] */ IWebResourceLoadDelegate** d)
2837 if (!m_resourceLoadDelegate)
2840 return m_resourceLoadDelegate.copyRefTo(d);
2843 HRESULT STDMETHODCALLTYPE WebView::setDownloadDelegate(
2844 /* [in] */ IWebDownloadDelegate* d)
2846 m_downloadDelegate = d;
2850 HRESULT STDMETHODCALLTYPE WebView::downloadDelegate(
2851 /* [out][retval] */ IWebDownloadDelegate** d)
2853 if (!m_downloadDelegate)
2856 return m_downloadDelegate.copyRefTo(d);
2859 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegate(
2860 /* [in] */ IWebFrameLoadDelegate* d)
2862 m_frameLoadDelegate = d;
2866 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegate(
2867 /* [out][retval] */ IWebFrameLoadDelegate** d)
2869 if (!m_frameLoadDelegate)
2872 return m_frameLoadDelegate.copyRefTo(d);
2875 HRESULT STDMETHODCALLTYPE WebView::setPolicyDelegate(
2876 /* [in] */ IWebPolicyDelegate* d)
2878 m_policyDelegate = d;
2882 HRESULT STDMETHODCALLTYPE WebView::policyDelegate(
2883 /* [out][retval] */ IWebPolicyDelegate** d)
2885 if (!m_policyDelegate)
2887 return m_policyDelegate.copyRefTo(d);
2890 HRESULT STDMETHODCALLTYPE WebView::mainFrame(
2891 /* [out][retval] */ IWebFrame** frame)
2894 ASSERT_NOT_REACHED();
2898 *frame = m_mainFrame;
2902 m_mainFrame->AddRef();
2906 HRESULT STDMETHODCALLTYPE WebView::focusedFrame(
2907 /* [out][retval] */ IWebFrame** frame)
2910 ASSERT_NOT_REACHED();
2915 Frame* f = m_page->focusController()->focusedFrame();
2919 WebFrame* webFrame = kit(f);
2923 return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
2926 HRESULT STDMETHODCALLTYPE WebView::backForwardList(
2927 /* [out][retval] */ IWebBackForwardList** list)
2929 if (!m_useBackForwardList)
2932 *list = WebBackForwardList::createInstance(static_cast<WebCore::BackForwardListImpl*>(m_page->backForwardList()));
2937 HRESULT STDMETHODCALLTYPE WebView::setMaintainsBackForwardList(
2938 /* [in] */ BOOL flag)
2940 m_useBackForwardList = !!flag;
2944 HRESULT STDMETHODCALLTYPE WebView::goBack(
2945 /* [retval][out] */ BOOL* succeeded)
2947 *succeeded = m_page->goBack();
2951 HRESULT STDMETHODCALLTYPE WebView::goForward(
2952 /* [retval][out] */ BOOL* succeeded)
2954 *succeeded = m_page->goForward();
2958 HRESULT STDMETHODCALLTYPE WebView::goToBackForwardItem(
2959 /* [in] */ IWebHistoryItem* item,
2960 /* [retval][out] */ BOOL* succeeded)
2964 COMPtr<WebHistoryItem> webHistoryItem;
2965 HRESULT hr = item->QueryInterface(&webHistoryItem);
2969 m_page->goToItem(webHistoryItem->historyItem(), FrameLoadTypeIndexedBackForward);
2975 HRESULT STDMETHODCALLTYPE WebView::setTextSizeMultiplier(
2976 /* [in] */ float multiplier)
2980 setZoomMultiplier(multiplier, true);
2984 HRESULT STDMETHODCALLTYPE WebView::setPageSizeMultiplier(
2985 /* [in] */ float multiplier)
2989 setZoomMultiplier(multiplier, false);
2993 void WebView::setZoomMultiplier(float multiplier, bool isTextOnly)
2995 m_zoomMultiplier = multiplier;
2996 m_zoomsTextOnly = isTextOnly;
2998 if (Frame* coreFrame = core(m_mainFrame)) {
2999 if (m_zoomsTextOnly)
3000 coreFrame->setPageAndTextZoomFactors(1, multiplier);
3002 coreFrame->setPageAndTextZoomFactors(multiplier, 1);
3006 HRESULT STDMETHODCALLTYPE WebView::textSizeMultiplier(
3007 /* [retval][out] */ float* multiplier)
3009 *multiplier = zoomMultiplier(true);
3013 HRESULT STDMETHODCALLTYPE WebView::pageSizeMultiplier(
3014 /* [retval][out] */ float* multiplier)
3016 *multiplier = zoomMultiplier(false);
3020 float WebView::zoomMultiplier(bool isTextOnly)
3022 if (isTextOnly != m_zoomsTextOnly)
3024 return m_zoomMultiplier;
3027 HRESULT STDMETHODCALLTYPE WebView::setApplicationNameForUserAgent(
3028 /* [in] */ BSTR applicationName)
3030 m_applicationName = String(applicationName, SysStringLen(applicationName));
3031 m_userAgentStandard = String();
3035 HRESULT STDMETHODCALLTYPE WebView::applicationNameForUserAgent(
3036 /* [retval][out] */ BSTR* applicationName)
3038 *applicationName = SysAllocStringLen(m_applicationName.characters(), m_applicationName.length());
3039 if (!*applicationName && m_applicationName.length())
3040 return E_OUTOFMEMORY;
3044 HRESULT STDMETHODCALLTYPE WebView::setCustomUserAgent(
3045 /* [in] */ BSTR userAgentString)
3047 m_userAgentOverridden = userAgentString;
3048 m_userAgentCustom = String(userAgentString, SysStringLen(userAgentString));
3052 HRESULT STDMETHODCALLTYPE WebView::customUserAgent(
3053 /* [retval][out] */ BSTR* userAgentString)
3055 *userAgentString = 0;
3056 if (!m_userAgentOverridden)
3058 *userAgentString = SysAllocStringLen(m_userAgentCustom.characters(), m_userAgentCustom.length());
3059 if (!*userAgentString && m_userAgentCustom.length())
3060 return E_OUTOFMEMORY;
3064 HRESULT STDMETHODCALLTYPE WebView::userAgentForURL(
3065 /* [in] */ BSTR url,
3066 /* [retval][out] */ BSTR* userAgent)
3068 String userAgentString = userAgentForKURL(MarshallingHelpers::BSTRToKURL(url));
3069 *userAgent = SysAllocStringLen(userAgentString.characters(), userAgentString.length());
3070 if (!*userAgent && userAgentString.length())
3071 return E_OUTOFMEMORY;
3075 HRESULT STDMETHODCALLTYPE WebView::supportsTextEncoding(
3076 /* [retval][out] */ BOOL* supports)
3082 HRESULT STDMETHODCALLTYPE WebView::setCustomTextEncodingName(
3083 /* [in] */ BSTR encodingName)
3090 hr = customTextEncodingName(&oldEncoding);
3094 if (oldEncoding != encodingName && (!oldEncoding || !encodingName || wcscmp(oldEncoding, encodingName))) {
3095 if (Frame* coreFrame = core(m_mainFrame))
3096 coreFrame->loader()->reloadWithOverrideEncoding(String(encodingName, SysStringLen(encodingName)));
3102 HRESULT STDMETHODCALLTYPE WebView::customTextEncodingName(
3103 /* [retval][out] */ BSTR* encodingName)
3106 COMPtr<IWebDataSource> dataSource;
3107 COMPtr<WebDataSource> dataSourceImpl;
3113 if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
3114 hr = m_mainFrame->dataSource(&dataSource);
3115 if (FAILED(hr) || !dataSource)
3119 hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
3123 BString str = dataSourceImpl->documentLoader()->overrideEncoding();
3128 *encodingName = SysAllocStringLen(m_overrideEncoding.characters(), m_overrideEncoding.length());
3130 if (!*encodingName && m_overrideEncoding.length())
3131 return E_OUTOFMEMORY;
3136 HRESULT STDMETHODCALLTYPE WebView::setMediaStyle(
3137 /* [in] */ BSTR /*media*/)
3139 ASSERT_NOT_REACHED();
3143 HRESULT STDMETHODCALLTYPE WebView::mediaStyle(
3144 /* [retval][out] */ BSTR* /*media*/)
3146 ASSERT_NOT_REACHED();
3150 HRESULT STDMETHODCALLTYPE WebView::stringByEvaluatingJavaScriptFromString(
3151 /* [in] */ BSTR script, // assumes input does not have "JavaScript" at the begining.
3152 /* [retval][out] */ BSTR* result)
3155 ASSERT_NOT_REACHED();
3161 Frame* coreFrame = core(m_mainFrame);
3165 JSC::JSValue scriptExecutionResult = coreFrame->script()->executeScript(WTF::String(script), true).jsValue();
3166 if (!scriptExecutionResult)
3168 else if (scriptExecutionResult.isString()) {
3169 JSLock lock(JSC::SilenceAssertionsOnly);
3170 JSC::ExecState* exec = coreFrame->script()->globalObject(mainThreadNormalWorld())->globalExec();
3171 *result = BString(ustringToString(scriptExecutionResult.getString(exec)));
3177 HRESULT STDMETHODCALLTYPE WebView::windowScriptObject(
3178 /* [retval][out] */ IWebScriptObject** /*webScriptObject*/)
3180 ASSERT_NOT_REACHED();
3184 HRESULT STDMETHODCALLTYPE WebView::setPreferences(
3185 /* [in] */ IWebPreferences* prefs)
3188 prefs = WebPreferences::sharedStandardPreferences();
3190 if (m_preferences == prefs)
3193 COMPtr<WebPreferences> webPrefs(Query, prefs);
3195 return E_NOINTERFACE;
3196 webPrefs->willAddToWebView();
3198 COMPtr<WebPreferences> oldPrefs = m_preferences;
3200 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
3201 nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3203 BSTR identifier = 0;
3204 oldPrefs->identifier(&identifier);
3205 oldPrefs->didRemoveFromWebView();
3206 oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
3208 m_preferences = webPrefs;
3211 WebPreferences::removeReferenceForIdentifier(identifier);
3212 SysFreeString(identifier);
3215 nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
3217 m_preferences->postPreferencesChangesNotification();
3222 HRESULT STDMETHODCALLTYPE WebView::preferences(
3223 /* [retval][out] */ IWebPreferences** prefs)
3227 *prefs = m_preferences.get();
3229 m_preferences->AddRef();
3233 HRESULT STDMETHODCALLTYPE WebView::setPreferencesIdentifier(
3234 /* [in] */ BSTR /*anIdentifier*/)
3236 ASSERT_NOT_REACHED();
3240 HRESULT STDMETHODCALLTYPE WebView::preferencesIdentifier(
3241 /* [retval][out] */ BSTR* /*anIdentifier*/)
3243 ASSERT_NOT_REACHED();
3247 static void systemParameterChanged(WPARAM parameter)
3250 if (parameter == SPI_SETFONTSMOOTHING || parameter == SPI_SETFONTSMOOTHINGTYPE || parameter == SPI_SETFONTSMOOTHINGCONTRAST || parameter == SPI_SETFONTSMOOTHINGORIENTATION)
3251 wkSystemFontSmoothingChanged();
3255 void WebView::windowReceivedMessage(HWND, UINT message, WPARAM wParam, LPARAM)
3259 updateActiveStateSoon();
3261 deleteBackingStoreSoon();
3263 case WM_SETTINGCHANGE:
3264 systemParameterChanged(wParam);
3269 void WebView::updateActiveStateSoon() const
3271 // This function is called while processing the WM_NCACTIVATE message.
3272 // While processing WM_NCACTIVATE when we are being deactivated, GetActiveWindow() will
3273 // still return our window. If we were to call updateActiveState() in that case, we would
3274 // wrongly think that we are still the active window. To work around this, we update our
3275 // active state after a 0-delay timer fires, at which point GetActiveWindow() will return
3276 // the newly-activated window.
3278 SetTimer(m_viewWindow, UpdateActiveStateTimer, 0, 0);
3281 void WebView::deleteBackingStoreSoon()
3283 if (pendingDeleteBackingStoreSet.size() > 2) {
3284 Vector<WebView*> views;
3285 HashSet<WebView*>::iterator end = pendingDeleteBackingStoreSet.end();
3286 for (HashSet<WebView*>::iterator it = pendingDeleteBackingStoreSet.begin(); it != end; ++it)
3288 for (int i = 0; i < views.size(); ++i)
3289 views[i]->deleteBackingStore();
3290 ASSERT(pendingDeleteBackingStoreSet.isEmpty());
3293 pendingDeleteBackingStoreSet.add(this);
3294 m_deleteBackingStoreTimerActive = true;
3295 SetTimer(m_viewWindow, DeleteBackingStoreTimer, delayBeforeDeletingBackingStoreMsec, 0);
3298 void WebView::cancelDeleteBackingStoreSoon()
3300 if (!m_deleteBackingStoreTimerActive)
3302 pendingDeleteBackingStoreSet.remove(this);
3303 m_deleteBackingStoreTimerActive = false;
3304 KillTimer(m_viewWindow, DeleteBackingStoreTimer);
3307 HRESULT STDMETHODCALLTYPE WebView::setHostWindow(
3308 /* [in] */ OLE_HANDLE oleWindow)
3310 HWND window = (HWND)(ULONG64)oleWindow;
3313 SetParent(m_viewWindow, window);
3314 else if (!isBeingDestroyed()) {
3315 // Turn the WebView into a message-only window so it will no longer be a child of the
3316 // old host window and will be hidden from screen. We only do this when
3317 // isBeingDestroyed() is false because doing this while handling WM_DESTROY can leave
3318 // m_viewWindow in a weird state (see <http://webkit.org/b/29337>).
3319 SetParent(m_viewWindow, HWND_MESSAGE);
3323 m_hostWindow = window;
3325 windowAncestryDidChange();
3330 HRESULT STDMETHODCALLTYPE WebView::hostWindow(
3331 /* [retval][out] */ OLE_HANDLE* window)
3333 *window = (OLE_HANDLE)(ULONG64)m_hostWindow;
3338 static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
3341 ? curr->tree()->traverseNextWithWrap(wrapFlag)
3342 : curr->tree()->traversePreviousWithWrap(wrapFlag);
3345 HRESULT STDMETHODCALLTYPE WebView::searchFor(
3346 /* [in] */ BSTR str,
3347 /* [in] */ BOOL forward,
3348 /* [in] */ BOOL caseFlag,
3349 /* [in] */ BOOL wrapFlag,
3350 /* [retval][out] */ BOOL* found)
3353 return E_INVALIDARG;
3355 if (!m_page || !m_page->mainFrame())
3356 return E_UNEXPECTED;
3358 if (!str || !SysStringLen(str))
3359 return E_INVALIDARG;
3361 *found = m_page->findString(String(str, SysStringLen(str)), caseFlag ? TextCaseSensitive : TextCaseInsensitive, forward ? FindDirectionForward : FindDirectionBackward, wrapFlag);
3365 bool WebView::active()
3367 HWND activeWindow = GetActiveWindow();
3368 if (usesLayeredWindow() && activeWindow == m_viewWindow)
3371 return (activeWindow && m_topLevelParent == findTopLevelParent(activeWindow));
3374 void WebView::updateActiveState()
3376 m_page->focusController()->setActive(active());
3379 HRESULT STDMETHODCALLTYPE WebView::updateFocusedAndActiveState()
3381 updateActiveState();
3383 bool active = m_page->focusController()->isActive();
3384 Frame* mainFrame = m_page->mainFrame();
3385 Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
3386 mainFrame->selection()->setFocused(active && mainFrame == focusedFrame);
3391 HRESULT STDMETHODCALLTYPE WebView::executeCoreCommandByName(BSTR bName, BSTR bValue)
3393 String name(bName, SysStringLen(bName));
3394 String value(bValue, SysStringLen(bValue));
3396 m_page->focusController()->focusedOrMainFrame()->editor()->command(name).execute(value);
3401 HRESULT STDMETHODCALLTYPE WebView::clearMainFrameName()
3403 m_page->mainFrame()->tree()->clearName();
3408 HRESULT STDMETHODCALLTYPE WebView::markAllMatchesForText(
3409 BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, UINT* matches)
3412 return E_INVALIDARG;
3414 if (!m_page || !m_page->mainFrame())
3415 return E_UNEXPECTED;
3417 if (!str || !SysStringLen(str))
3418 return E_INVALIDARG;
3420 *matches = m_page->markAllMatchesForText(String(str, SysStringLen(str)), caseSensitive ? TextCaseSensitive : TextCaseInsensitive, highlight, limit);
3424 HRESULT STDMETHODCALLTYPE WebView::unmarkAllTextMatches()
3426 if (!m_page || !m_page->mainFrame())
3427 return E_UNEXPECTED;
3429 m_page->unmarkAllTextMatches();
3433 HRESULT STDMETHODCALLTYPE WebView::rectsForTextMatches(
3434 IEnumTextMatches** pmatches)
3436 Vector<IntRect> allRects;
3437 WebCore::Frame* frame = m_page->mainFrame();
3439 if (Document* document = frame->document()) {
3440 IntRect visibleRect = frame->view()->visibleContentRect();
3441 Vector<IntRect> frameRects = document->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
3442 IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
3443 frameOffset = frame->view()->convertToContainingWindow(frameOffset);
3445 Vector<IntRect>::iterator end = frameRects.end();
3446 for (Vector<IntRect>::iterator it = frameRects.begin(); it < end; it++) {
3447 it->intersect(visibleRect);
3448 it->move(frameOffset.x(), frameOffset.y());
3449 allRects.append(*it);
3452 frame = incrementFrame(frame, true, false);
3455 return createMatchEnumerator(&allRects, pmatches);
3458 HRESULT STDMETHODCALLTYPE WebView::generateSelectionImage(BOOL forceWhiteText, OLE_HANDLE* hBitmap)
3462 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
3465 HBITMAP bitmap = imageFromSelection(frame, forceWhiteText ? TRUE : FALSE);
3466 *hBitmap = (OLE_HANDLE)(ULONG64)bitmap;
3472 HRESULT STDMETHODCALLTYPE WebView::selectionRect(RECT* rc)
3474 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
3477 IntRect ir = enclosingIntRect(frame->selection()->bounds());
3478 ir = frame->view()->convertToContainingWindow(ir);
3479 ir.move(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
3482 rc->bottom = rc->top + ir.height();
3483 rc->right = rc->left + ir.width();
3489 HRESULT STDMETHODCALLTYPE WebView::registerViewClass(
3490 /* [in] */ IWebDocumentView* /*view*/,
3491 /* [in] */ IWebDocumentRepresentation* /*representation*/,
3492 /* [in] */ BSTR /*forMIMEType*/)
3494 ASSERT_NOT_REACHED();
3498 HRESULT STDMETHODCALLTYPE WebView::setGroupName(
3499 /* [in] */ BSTR groupName)
3503 m_page->setGroupName(String(groupName, SysStringLen(groupName)));
3507 HRESULT STDMETHODCALLTYPE WebView::groupName(
3508 /* [retval][out] */ BSTR* groupName)
3513 String groupNameString = m_page->groupName();
3514 *groupName = SysAllocStringLen(groupNameString.characters(), groupNameString.length());
3515 if (!*groupName && groupNameString.length())
3516 return E_OUTOFMEMORY;
3520 HRESULT STDMETHODCALLTYPE WebView::estimatedProgress(
3521 /* [retval][out] */ double* estimatedProgress)
3523 *estimatedProgress = m_page->progress()->estimatedProgress();
3527 HRESULT STDMETHODCALLTYPE WebView::isLoading(
3528 /* [retval][out] */ BOOL* isLoading)
3530 COMPtr<IWebDataSource> dataSource;
3531 COMPtr<IWebDataSource> provisionalDataSource;
3541 if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
3542 dataSource->isLoading(isLoading);
3547 if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
3548 provisionalDataSource->isLoading(isLoading);
3552 HRESULT STDMETHODCALLTYPE WebView::elementAtPoint(
3553 /* [in] */ LPPOINT point,
3554 /* [retval][out] */ IPropertyBag** elementDictionary)
3556 if (!elementDictionary) {
3557 ASSERT_NOT_REACHED();
3561 *elementDictionary = 0;
3563 Frame* frame = core(m_mainFrame);
3567 IntPoint webCorePoint = IntPoint(point->x, point->y);
3568 HitTestResult result = HitTestResult(webCorePoint);
3569 if (frame->contentRenderer())
3570 result = frame->eventHandler()->hitTestResultAtPoint(webCorePoint, false);
3571 *elementDictionary = WebElementPropertyBag::createInstance(result);
3575 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForSelection(
3576 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3578 ASSERT_NOT_REACHED();
3582 HRESULT STDMETHODCALLTYPE WebView::writeSelectionWithPasteboardTypes(
3583 /* [size_is][in] */ BSTR* /*types*/,
3584 /* [in] */ int /*cTypes*/,
3585 /* [in] */ IDataObject* /*pasteboard*/)
3587 ASSERT_NOT_REACHED();
3591 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForElement(
3592 /* [in] */ IPropertyBag* /*elementDictionary*/,
3593 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3595 ASSERT_NOT_REACHED();
3599 HRESULT STDMETHODCALLTYPE WebView::writeElement(
3600 /* [in] */ IPropertyBag* /*elementDictionary*/,
3601 /* [size_is][in] */ BSTR* /*withPasteboardTypes*/,
3602 /* [in] */ int /*cWithPasteboardTypes*/,
3603 /* [in] */ IDataObject* /*pasteboard*/)
3605 ASSERT_NOT_REACHED();
3609 HRESULT STDMETHODCALLTYPE WebView::selectedText(
3610 /* [out, retval] */ BSTR* text)
3613 ASSERT_NOT_REACHED();
3619 Frame* focusedFrame = (m_page && m_page->focusController()) ? m_page->focusController()->focusedOrMainFrame() : 0;
3623 String frameSelectedText = focusedFrame->editor()->selectedText();
3624 *text = SysAllocStringLen(frameSelectedText.characters(), frameSelectedText.length());
3625 if (!*text && frameSelectedText.length())
3626 return E_OUTOFMEMORY;
3630 HRESULT STDMETHODCALLTYPE WebView::centerSelectionInVisibleArea(
3631 /* [in] */ IUnknown* /* sender */)
3633 Frame* coreFrame = core(m_mainFrame);
3637 coreFrame->selection()->revealSelection(ScrollAlignment::alignCenterAlways);
3642 HRESULT STDMETHODCALLTYPE WebView::moveDragCaretToPoint(
3643 /* [in] */ LPPOINT /*point*/)
3645 ASSERT_NOT_REACHED();
3649 HRESULT STDMETHODCALLTYPE WebView::removeDragCaret( void)
3651 ASSERT_NOT_REACHED();
3655 HRESULT STDMETHODCALLTYPE WebView::setDrawsBackground(
3656 /* [in] */ BOOL /*drawsBackground*/)
3658 ASSERT_NOT_REACHED();
3662 HRESULT STDMETHODCALLTYPE WebView::drawsBackground(
3663 /* [retval][out] */ BOOL* /*drawsBackground*/)
3665 ASSERT_NOT_REACHED();
3669 HRESULT STDMETHODCALLTYPE WebView::setMainFrameURL(
3670 /* [in] */ BSTR /*urlString*/)
3672 ASSERT_NOT_REACHED();
3676 HRESULT STDMETHODCALLTYPE WebView::mainFrameURL(
3677 /* [retval][out] */ BSTR* urlString)
3685 COMPtr<IWebDataSource> dataSource;
3687 if (FAILED(m_mainFrame->provisionalDataSource(&dataSource))) {
3688 if (FAILED(m_mainFrame->dataSource(&dataSource)))
3697 COMPtr<IWebMutableURLRequest> request;
3698 if (FAILED(dataSource->request(&request)) || !request)
3701 if (FAILED(request->URL(urlString)))
3707 HRESULT STDMETHODCALLTYPE WebView::mainFrameDocument(
3708 /* [retval][out] */ IDOMDocument** document)
3714 return m_mainFrame->DOMDocument(document);
3717 HRESULT STDMETHODCALLTYPE WebView::mainFrameTitle(
3718 /* [retval][out] */ BSTR* /*title*/)
3720 ASSERT_NOT_REACHED();
3724 HRESULT STDMETHODCALLTYPE WebView::mainFrameIcon(
3725 /* [retval][out] */ OLE_HANDLE* /*hBitmap*/)
3727 ASSERT_NOT_REACHED();
3731 HRESULT STDMETHODCALLTYPE WebView::registerURLSchemeAsLocal(
3732 /* [in] */ BSTR scheme)
3737 SchemeRegistry::registerURLSchemeAsLocal(String(scheme, ::SysStringLen(scheme)));
3742 // IWebIBActions ---------------------------------------------------------------
3744 HRESULT STDMETHODCALLTYPE WebView::takeStringURLFrom(
3745 /* [in] */ IUnknown* /*sender*/)
3747 ASSERT_NOT_REACHED();
3751 HRESULT STDMETHODCALLTYPE WebView::stopLoading(
3752 /* [in] */ IUnknown* /*sender*/)
3757 return m_mainFrame->stopLoading();
3760 HRESULT STDMETHODCALLTYPE WebView::reload(
3761 /* [in] */ IUnknown* /*sender*/)
3766 return m_mainFrame->reload();
3769 HRESULT STDMETHODCALLTYPE WebView::canGoBack(
3770 /* [in] */ IUnknown* /*sender*/,
3771 /* [retval][out] */ BOOL* result)
3773 *result = !!(m_page->backForwardList()->backItem() && !m_page->defersLoading());
3777 HRESULT STDMETHODCALLTYPE WebView::goBack(
3778 /* [in] */ IUnknown* /*sender*/)
3780 ASSERT_NOT_REACHED();
3784 HRESULT STDMETHODCALLTYPE WebView::canGoForward(
3785 /* [in] */ IUnknown* /*sender*/,
3786 /* [retval][out] */ BOOL* result)
3788 *result = !!(m_page->backForwardList()->forwardItem() && !m_page->defersLoading());
3792 HRESULT STDMETHODCALLTYPE WebView::goForward(
3793 /* [in] */ IUnknown* /*sender*/)
3795 ASSERT_NOT_REACHED();
3799 // FIXME: This code should move into WebCore so it can be shared by all the WebKits.
3800 #define MinimumZoomMultiplier 0.5f
3801 #define MaximumZoomMultiplier 3.0f
3802 #define ZoomMultiplierRatio 1.2f
3804 HRESULT STDMETHODCALLTYPE WebView::canMakeTextLarger(
3805 /* [in] */ IUnknown* /*sender*/,
3806 /* [retval][out] */ BOOL* result)
3808 bool canGrowMore = canZoomIn(m_zoomsTextOnly);
3809 *result = canGrowMore ? TRUE : FALSE;
3813 HRESULT STDMETHODCALLTYPE WebView::canZoomPageIn(
3814 /* [in] */ IUnknown* /*sender*/,
3815 /* [retval][out] */ BOOL* result)
3817 bool canGrowMore = canZoomIn(false);
3818 *result = canGrowMore ? TRUE : FALSE;
3822 bool WebView::canZoomIn(bool isTextOnly)
3824 return zoomMultiplier(isTextOnly) * ZoomMultiplierRatio < MaximumZoomMultiplier;
3827 HRESULT STDMETHODCALLTYPE WebView::makeTextLarger(
3828 /* [in] */ IUnknown* /*sender*/)
3830 return zoomIn(m_zoomsTextOnly);
3833 HRESULT STDMETHODCALLTYPE WebView::zoomPageIn(
3834 /* [in] */ IUnknown* /*sender*/)
3836 return zoomIn(false);
3839 HRESULT WebView::zoomIn(bool isTextOnly)
3841 if (!canZoomIn(isTextOnly))
3843 setZoomMultiplier(zoomMultiplier(isTextOnly) * ZoomMultiplierRatio, isTextOnly);
3847 HRESULT STDMETHODCALLTYPE WebView::canMakeTextSmaller(
3848 /* [in] */ IUnknown* /*sender*/,
3849 /* [retval][out] */ BOOL* result)
3851 bool canShrinkMore = canZoomOut(m_zoomsTextOnly);
3852 *result = canShrinkMore ? TRUE : FALSE;
3856 HRESULT STDMETHODCALLTYPE WebView::canZoomPageOut(
3857 /* [in] */ IUnknown* /*sender*/,
3858 /* [retval][out] */ BOOL* result)
3860 bool canShrinkMore = canZoomOut(false);
3861 *result = canShrinkMore ? TRUE : FALSE;
3865 bool WebView::canZoomOut(bool isTextOnly)
3867 return zoomMultiplier(isTextOnly) / ZoomMultiplierRatio > MinimumZoomMultiplier;
3870 HRESULT STDMETHODCALLTYPE WebView::makeTextSmaller(
3871 /* [in] */ IUnknown* /*sender*/)
3873 return zoomOut(m_zoomsTextOnly);
3876 HRESULT STDMETHODCALLTYPE WebView::zoomPageOut(
3877 /* [in] */ IUnknown* /*sender*/)
3879 return zoomOut(false);
3882 HRESULT WebView::zoomOut(bool isTextOnly)
3884 if (!canZoomOut(isTextOnly))
3886 setZoomMultiplier(zoomMultiplier(isTextOnly) / ZoomMultiplierRatio, isTextOnly);
3890 HRESULT STDMETHODCALLTYPE WebView::canMakeTextStandardSize(
3891 /* [in] */ IUnknown* /*sender*/,
3892 /* [retval][out] */ BOOL* result)
3894 // Since we always reset text zoom and page zoom together, this should continue to return an answer about text zoom even if its not enabled.
3895 bool notAlreadyStandard = canResetZoom(true);
3896 *result = notAlreadyStandard ? TRUE : FALSE;
3900 HRESULT STDMETHODCALLTYPE WebView::canResetPageZoom(
3901 /* [in] */ IUnknown* /*sender*/,
3902 /* [retval][out] */ BOOL* result)
3904 bool notAlreadyStandard = canResetZoom(false);
3905 *result = notAlreadyStandard ? TRUE : FALSE;
3909 bool WebView::canResetZoom(bool isTextOnly)
3911 return zoomMultiplier(isTextOnly) != 1.0f;
3914 HRESULT STDMETHODCALLTYPE WebView::makeTextStandardSize(
3915 /* [in] */ IUnknown* /*sender*/)
3917 return resetZoom(true);
3920 HRESULT STDMETHODCALLTYPE WebView::resetPageZoom(
3921 /* [in] */ IUnknown* /*sender*/)
3923 return resetZoom(false);
3926 HRESULT WebView::resetZoom(bool isTextOnly)
3928 if (!canResetZoom(isTextOnly))
3930 setZoomMultiplier(1.0f, isTextOnly);
3934 HRESULT STDMETHODCALLTYPE WebView::toggleContinuousSpellChecking(
3935 /* [in] */ IUnknown* /*sender*/)
3939 if (FAILED(hr = isContinuousSpellCheckingEnabled(&enabled)))
3941 return setContinuousSpellCheckingEnabled(enabled ? FALSE : TRUE);
3944 HRESULT STDMETHODCALLTYPE WebView::toggleSmartInsertDelete(
3945 /* [in] */ IUnknown* /*sender*/)
3947 BOOL enabled = FALSE;
3948 HRESULT hr = smartInsertDeleteEnabled(&enabled);
3952 return setSmartInsertDeleteEnabled(enabled ? FALSE : TRUE);
3955 HRESULT STDMETHODCALLTYPE WebView::toggleGrammarChecking(
3956 /* [in] */ IUnknown* /*sender*/)
3959 HRESULT hr = isGrammarCheckingEnabled(&enabled);
3963 return setGrammarCheckingEnabled(enabled ? FALSE : TRUE);
3966 HRESULT STDMETHODCALLTYPE WebView::reloadFromOrigin(
3967 /* [in] */ IUnknown* /*sender*/)
3972 return m_mainFrame->reloadFromOrigin();
3975 // IWebViewCSS -----------------------------------------------------------------
3977 HRESULT STDMETHODCALLTYPE WebView::computedStyleForElement(
3978 /* [in] */ IDOMElement* /*element*/,
3979 /* [in] */ BSTR /*pseudoElement*/,
3980 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3982 ASSERT_NOT_REACHED();
3986 // IWebViewEditing -------------------------------------------------------------
3988 HRESULT STDMETHODCALLTYPE WebView::editableDOMRangeForPoint(
3989 /* [in] */ LPPOINT /*point*/,
3990 /* [retval][out] */ IDOMRange** /*range*/)
3992 ASSERT_NOT_REACHED();
3996 HRESULT STDMETHODCALLTYPE WebView::setSelectedDOMRange(
3997 /* [in] */ IDOMRange* /*range*/,
3998 /* [in] */ WebSelectionAffinity /*affinity*/)
4000 ASSERT_NOT_REACHED();
4004 HRESULT STDMETHODCALLTYPE WebView::selectedDOMRange(
4005 /* [retval][out] */ IDOMRange** /*range*/)
4007 ASSERT_NOT_REACHED();
4011 HRESULT STDMETHODCALLTYPE WebView::selectionAffinity(
4012 /* [retval][out][retval][out] */ WebSelectionAffinity* /*affinity*/)
4014 ASSERT_NOT_REACHED();
4018 HRESULT STDMETHODCALLTYPE WebView::setEditable(
4019 /* [in] */ BOOL /*flag*/)
4021 ASSERT_NOT_REACHED();
4025 HRESULT STDMETHODCALLTYPE WebView::isEditable(
4026 /* [retval][out] */ BOOL* /*isEditable*/)
4028 ASSERT_NOT_REACHED();
4032 HRESULT STDMETHODCALLTYPE WebView::setTypingStyle(
4033 /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
4035 ASSERT_NOT_REACHED();
4039 HRESULT STDMETHODCALLTYPE WebView::typingStyle(
4040 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
4042 ASSERT_NOT_REACHED();
4046 HRESULT STDMETHODCALLTYPE WebView::setSmartInsertDeleteEnabled(
4047 /* [in] */ BOOL flag)
4049 m_smartInsertDeleteEnabled = !!flag;
4050 if (m_smartInsertDeleteEnabled)
4051 setSelectTrailingWhitespaceEnabled(false);
4055 HRESULT STDMETHODCALLTYPE WebView::smartInsertDeleteEnabled(
4056 /* [retval][out] */ BOOL* enabled)
4058 *enabled = m_smartInsertDeleteEnabled ? TRUE : FALSE;
4062 HRESULT STDMETHODCALLTYPE WebView::setSelectTrailingWhitespaceEnabled(
4063 /* [in] */ BOOL flag)
4065 m_selectTrailingWhitespaceEnabled = !!flag;
4066 if (m_selectTrailingWhitespaceEnabled)
4067 setSmartInsertDeleteEnabled(false);
4071 HRESULT STDMETHODCALLTYPE WebView::isSelectTrailingWhitespaceEnabled(
4072 /* [retval][out] */ BOOL* enabled)
4074 *enabled = m_selectTrailingWhitespaceEnabled ? TRUE : FALSE;
4078 HRESULT STDMETHODCALLTYPE WebView::setContinuousSpellCheckingEnabled(
4079 /* [in] */ BOOL flag)
4081 if (continuousSpellCheckingEnabled != !!flag) {
4082 continuousSpellCheckingEnabled = !!flag;
4083 COMPtr<IWebPreferences> prefs;
4084 if (SUCCEEDED(preferences(&prefs)))
4085 prefs->setContinuousSpellCheckingEnabled(flag);
4088 BOOL spellCheckingEnabled;
4089 if (SUCCEEDED(isContinuousSpellCheckingEnabled(&spellCheckingEnabled)) && spellCheckingEnabled)
4090 preflightSpellChecker();
4092 m_mainFrame->unmarkAllMisspellings();
4097 HRESULT STDMETHODCALLTYPE WebView::isContinuousSpellCheckingEnabled(
4098 /* [retval][out] */ BOOL* enabled)
4100 *enabled = (continuousSpellCheckingEnabled && continuousCheckingAllowed()) ? TRUE : FALSE;
4104 HRESULT STDMETHODCALLTYPE WebView::spellCheckerDocumentTag(
4105 /* [retval][out] */ int* tag)
4107 // we just use this as a flag to indicate that we've spell checked the document
4108 // and need to close the spell checker out when the view closes.
4110 m_hasSpellCheckerDocumentTag = true;
4114 static COMPtr<IWebEditingDelegate> spellingDelegateForTimer;
4116 static void preflightSpellCheckerNow()
4118 spellingDelegateForTimer->preflightChosenSpellServer();
4119 spellingDelegateForTimer = 0;
4122 static void CALLBACK preflightSpellCheckerTimerCallback(HWND, UINT, UINT_PTR id, DWORD)
4125 preflightSpellCheckerNow();
4128 void WebView::preflightSpellChecker()
4130 // As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
4131 if (!m_editingDelegate)
4135 spellingDelegateForTimer = m_editingDelegate;
4136 if (SUCCEEDED(m_editingDelegate->sharedSpellCheckerExists(&exists)) && exists)
4137 preflightSpellCheckerNow();
4139 ::SetTimer(0, 0, 2000, preflightSpellCheckerTimerCallback);
4142 bool WebView::continuousCheckingAllowed()
4144 static bool allowContinuousSpellChecking = true;
4145 static bool readAllowContinuousSpellCheckingDefault = false;
4146 if (!readAllowContinuousSpellCheckingDefault) {
4147 COMPtr<IWebPreferences> prefs;
4148 if (SUCCEEDED(preferences(&prefs))) {
4150 prefs->allowContinuousSpellChecking(&allowed);
4151 allowContinuousSpellChecking = !!allowed;
4153 readAllowContinuousSpellCheckingDefault = true;
4155 return allowContinuousSpellChecking;
4158 HRESULT STDMETHODCALLTYPE WebView::undoManager(
4159 /* [retval][out] */ IWebUndoManager** /*manager*/)
4161 ASSERT_NOT_REACHED();
4165 HRESULT STDMETHODCALLTYPE WebView::setEditingDelegate(
4166 /* [in] */ IWebEditingDelegate* d)
4168 m_editingDelegate = d;
4172 HRESULT STDMETHODCALLTYPE WebView::editingDelegate(
4173 /* [retval][out] */ IWebEditingDelegate** d)
4176 ASSERT_NOT_REACHED();
4180 *d = m_editingDelegate.get();
4188 HRESULT STDMETHODCALLTYPE WebView::styleDeclarationWithText(
4189 /* [in] */ BSTR /*text*/,
4190 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
4192 ASSERT_NOT_REACHED();
4196 HRESULT STDMETHODCALLTYPE WebView::hasSelectedRange(
4197 /* [retval][out] */ BOOL* hasSelectedRange)
4199 *hasSelectedRange = m_page->mainFrame()->selection()->isRange();
4203 HRESULT STDMETHODCALLTYPE WebView::cutEnabled(
4204 /* [retval][out] */ BOOL* enabled)
4206 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
4207 *enabled = editor->canCut() || editor->canDHTMLCut();
4211 HRESULT STDMETHODCALLTYPE WebView::copyEnabled(
4212 /* [retval][out] */ BOOL* enabled)
4214 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
4215 *enabled = editor->canCopy() || editor->canDHTMLCopy();
4219 HRESULT STDMETHODCALLTYPE WebView::pasteEnabled(
4220 /* [retval][out] */ BOOL* enabled)
4222 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
4223 *enabled = editor->canPaste() || editor->canDHTMLPaste();
4227 HRESULT STDMETHODCALLTYPE WebView::deleteEnabled(
4228 /* [retval][out] */ BOOL* enabled)
4230 *enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canDelete();
4234 HRESULT STDMETHODCALLTYPE WebView::editingEnabled(
4235 /* [retval][out] */ BOOL* enabled)
4237 *enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canEdit();
4241 HRESULT STDMETHODCALLTYPE WebView::isGrammarCheckingEnabled(
4242 /* [retval][out] */ BOOL* enabled)
4244 *enabled = grammarCheckingEnabled ? TRUE : FALSE;
4248 HRESULT STDMETHODCALLTYPE WebView::setGrammarCheckingEnabled(
4251 if (!m_editingDelegate) {
4252 LOG_ERROR("No NSSpellChecker");
4256 if (grammarCheckingEnabled == !!enabled)
4259 grammarCheckingEnabled = !!enabled;
4260 COMPtr<IWebPreferences> prefs;
4261 if (SUCCEEDED(preferences(&prefs)))
4262 prefs->setGrammarCheckingEnabled(enabled);
4264 m_editingDelegate->updateGrammar();
4266 // We call _preflightSpellChecker when turning continuous spell checking on, but we don't need to do that here
4267 // because grammar checking only occurs on code paths that already preflight spell checking appropriately.
4269 BOOL grammarEnabled;
4270 if (SUCCEEDED(isGrammarCheckingEnabled(&grammarEnabled)) && !grammarEnabled)
4271 m_mainFrame->unmarkAllBadGrammar();
4276 // IWebViewUndoableEditing -----------------------------------------------------
4278 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithNode(
4279 /* [in] */ IDOMNode* /*node*/)
4281 ASSERT_NOT_REACHED();
4285 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithText(
4286 /* [in] */ BSTR text)
4288 String textString(text, ::SysStringLen(text));
4289 Position start = m_page->mainFrame()->selection()->selection().start();
4290 m_page->focusController()->focusedOrMainFrame()->editor()->insertText(textString, 0);
4291 m_page->mainFrame()->selection()->setBase(start);
4295 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithMarkupString(
4296 /* [in] */ BSTR /*markupString*/)
4298 ASSERT_NOT_REACHED();
4302 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithArchive(
4303 /* [in] */ IWebArchive* /*archive*/)
4305 ASSERT_NOT_REACHED();
4309 HRESULT STDMETHODCALLTYPE WebView::deleteSelection( void)
4311 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
4312 editor->deleteSelectionWithSmartDelete(editor->canSmartCopyOrDelete());
4316 HRESULT STDMETHODCALLTYPE WebView::clearSelection( void)
4318 m_page->focusController()->focusedOrMainFrame()->selection()->clear();
4322 HRESULT STDMETHODCALLTYPE WebView::applyStyle(
4323 /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
4325 ASSERT_NOT_REACHED();
4329 // IWebViewEditingActions ------------------------------------------------------
4331 HRESULT STDMETHODCALLTYPE WebView::copy(
4332 /* [in] */ IUnknown* /*sender*/)
4334 m_page->focusController()->focusedOrMainFrame()->editor()->command("Copy").execute();
4338 HRESULT STDMETHODCALLTYPE WebView::cut(
4339 /* [in] */ IUnknown* /*sender*/)
4341 m_page->focusController()->focusedOrMainFrame()->editor()->command("Cut").execute();
4345 HRESULT STDMETHODCALLTYPE WebView::paste(
4346 /* [in] */ IUnknown* /*sender*/)
4348 m_page->focusController()->focusedOrMainFrame()->editor()->command("Paste").execute();
4352 HRESULT STDMETHODCALLTYPE WebView::copyURL(
4353 /* [in] */ BSTR url)
4355 m_page->focusController()->focusedOrMainFrame()->editor()->copyURL(MarshallingHelpers::BSTRToKURL(url), "");
4360 HRESULT STDMETHODCALLTYPE WebView::copyFont(
4361 /* [in] */ IUnknown* /*sender*/)
4363 ASSERT_NOT_REACHED();
4367 HRESULT STDMETHODCALLTYPE WebView::pasteFont(
4368 /* [in] */ IUnknown* /*sender*/)
4370 ASSERT_NOT_REACHED();
4374 HRESULT STDMETHODCALLTYPE WebView::delete_(
4375 /* [in] */ IUnknown* /*sender*/)
4377 m_page->focusController()->focusedOrMainFrame()->editor()->command("Delete").execute();
4381 HRESULT STDMETHODCALLTYPE WebView::pasteAsPlainText(
4382 /* [in] */ IUnknown* /*sender*/)
4384 ASSERT_NOT_REACHED();
4388 HRESULT STDMETHODCALLTYPE WebView::pasteAsRichText(
4389 /* [in] */ IUnknown* /*sender*/)
4391 ASSERT_NOT_REACHED();
4395 HRESULT STDMETHODCALLTYPE WebView::changeFont(
4396 /* [in] */ IUnknown* /*sender*/)
4398 ASSERT_NOT_REACHED();
4402 HRESULT STDMETHODCALLTYPE WebView::changeAttributes(
4403 /* [in] */ IUnknown* /*sender*/)
4405 ASSERT_NOT_REACHED();
4409 HRESULT STDMETHODCALLTYPE WebView::changeDocumentBackgroundColor(
4410 /* [in] */ IUnknown* /*sender*/)
4412 ASSERT_NOT_REACHED();
4416 HRESULT STDMETHODCALLTYPE WebView::changeColor(
4417 /* [in] */ IUnknown* /*sender*/)
4419 ASSERT_NOT_REACHED();
4423 HRESULT STDMETHODCALLTYPE WebView::alignCenter(
4424 /* [in] */ IUnknown* /*sender*/)
4426 ASSERT_NOT_REACHED();
4430 HRESULT STDMETHODCALLTYPE WebView::alignJustified(
4431 /* [in] */ IUnknown* /*sender*/)
4433 ASSERT_NOT_REACHED();
4437 HRESULT STDMETHODCALLTYPE WebView::alignLeft(
4438 /* [in] */ IUnknown* /*sender*/)
4440 ASSERT_NOT_REACHED();
4444 HRESULT STDMETHODCALLTYPE WebView::alignRight(
4445 /* [in] */ IUnknown* /*sender*/)
4447 ASSERT_NOT_REACHED();
4451 HRESULT STDMETHODCALLTYPE WebView::checkSpelling(
4452 /* [in] */ IUnknown* /*sender*/)
4454 if (!m_editingDelegate) {
4455 LOG_ERROR("No NSSpellChecker");
4459 core(m_mainFrame)->editor()->advanceToNextMisspelling();
4463 HRESULT STDMETHODCALLTYPE WebView::showGuessPanel(
4464 /* [in] */ IUnknown* /*sender*/)
4466 if (!m_editingDelegate) {
4467 LOG_ERROR("No NSSpellChecker");
4471 // Post-Tiger, this menu item is a show/hide toggle, to match AppKit. Leave Tiger behavior alone
4472 // to match rest of OS X.
4474 if (SUCCEEDED(m_editingDelegate->spellingUIIsShowing(&showing)) && showing) {
4475 m_editingDelegate->showSpellingUI(FALSE);
4478 core(m_mainFrame)->editor()->advanceToNextMisspelling(true);
4479 m_editingDelegate->showSpellingUI(TRUE);
4483 HRESULT STDMETHODCALLTYPE WebView::performFindPanelAction(
4484 /* [in] */ IUnknown* /*sender*/)
4486 ASSERT_NOT_REACHED();
4490 HRESULT STDMETHODCALLTYPE WebView::startSpeaking(
4491 /* [in] */ IUnknown* /*sender*/)
4493 ASSERT_NOT_REACHED();
4497 HRESULT STDMETHODCALLTYPE WebView::stopSpeaking(
4498 /* [in] */ IUnknown* /*sender*/)
4500 ASSERT_NOT_REACHED();
4504 // IWebNotificationObserver -----------------------------------------------------------------
4506 HRESULT STDMETHODCALLTYPE WebView::onNotify(
4507 /* [in] */ IWebNotification* notification)
4510 HRESULT hr = notification->name(&nameBSTR);
4515 name.adoptBSTR(nameBSTR);
4517 if (!wcscmp(name, WebIconDatabase::iconDatabaseDidAddIconNotification()))
4518 return notifyDidAddIcon(notification);
4520 if (!wcscmp(name, WebPreferences::webPreferencesChangedNotification()))
4521 return notifyPreferencesChanged(notification);
4526 HRESULT WebView::notifyPreferencesChanged(IWebNotification* notification)
4530 COMPtr<IUnknown> unkPrefs;
4531 hr = notification->getObject(&unkPrefs);
4535 COMPtr<IWebPreferences> preferences(Query, unkPrefs);
4537 return E_NOINTERFACE;
4539 ASSERT(preferences == m_preferences);
4545 Settings* settings = m_page->settings();
4547 hr = preferences->cursiveFontFamily(&str);
4550 settings->setCursiveFontFamily(AtomicString(str, SysStringLen(str)));
4553 hr = preferences->defaultFixedFontSize(&size);
4556 settings->setDefaultFixedFontSize(size);
4558 hr = preferences->defaultFontSize(&size);
4561 settings->setDefaultFontSize(size);
4563 hr = preferences->defaultTextEncodingName(&str);
4566 settings->setDefaultTextEncodingName(String(str, SysStringLen(str)));
4569 hr = preferences->fantasyFontFamily(&str);
4572 settings->setFantasyFontFamily(AtomicString(str, SysStringLen(str)));
4575 hr = preferences->fixedFontFamily(&str);
4578 settings->setFixedFontFamily(AtomicString(str, SysStringLen(str)));
4581 hr = preferences->pictographFontFamily(&str);
4584 settings->setPictographFontFamily(AtomicString(str, SysStringLen(str)));
4587 hr = preferences->isJavaEnabled(&enabled);
4590 settings->setJavaEnabled(!!enabled);
4592 hr = preferences->isJavaScriptEnabled(&enabled);
4595 settings->setJavaScriptEnabled(!!enabled);
4597 hr = preferences->javaScriptCanOpenWindowsAutomatically(&enabled);
4600 settings->setJavaScriptCanOpenWindowsAutomatically(!!enabled);
4602 hr = preferences->minimumFontSize(&size);
4605 settings->setMinimumFontSize(size);
4607 hr = preferences->minimumLogicalFontSize(&size);
4610 settings->setMinimumLogicalFontSize(size);
4612 hr = preferences->arePlugInsEnabled(&enabled);
4615 settings->setPluginsEnabled(!!enabled);
4617 hr = preferences->privateBrowsingEnabled(&enabled);
4620 settings->setPrivateBrowsingEnabled(!!enabled);
4622 hr = preferences->sansSerifFontFamily(&str);
4625 settings->setSansSerifFontFamily(AtomicString(str, SysStringLen(str)));
4628 hr = preferences->serifFontFamily(&str);
4631 settings->setSerifFontFamily(AtomicString(str, SysStringLen(str)));
4634 hr = preferences->standardFontFamily(&str);
4637 settings->setStandardFontFamily(AtomicString(str, SysStringLen(str)));
4640 hr = preferences->loadsImagesAutomatically(&enabled);
4643 settings->setLoadsImagesAutomatically(!!enabled);
4645 hr = preferences->userStyleSheetEnabled(&enabled);
4649 hr = preferences->userStyleSheetLocation(&str);
4653 RetainPtr<CFStringRef> urlString(AdoptCF, String(str, SysStringLen(str)).createCFString());
4654 RetainPtr<CFURLRef> url(AdoptCF, CFURLCreateWithString(kCFAllocatorDefault, urlString.get(), 0));
4656 // Check if the passed in string is a path and convert it to a URL.
4657 // FIXME: This is a workaround for nightly builds until we can get Safari to pass
4658 // in an URL here. See <rdar://problem/5478378>
4660 DWORD len = SysStringLen(str) + 1;
4662 int result = WideCharToMultiByte(CP_UTF8, 0, str, len, 0, 0, 0, 0);
4663 Vector<UInt8> utf8Path(result);
4664 if (!WideCharToMultiByte(CP_UTF8, 0, str, len, (LPSTR)utf8Path.data(), result, 0, 0))
4667 url.adoptCF(CFURLCreateFromFileSystemRepresentation(0, utf8Path.data(), result - 1, false));
4670 settings->setUserStyleSheetLocation(url.get());
4673 settings->setUserStyleSheetLocation(KURL());
4676 hr = preferences->shouldPrintBackgrounds(&enabled);
4679 settings->setShouldPrintBackgrounds(!!enabled);
4681 hr = preferences->textAreasAreResizable(&enabled);
4684 settings->setTextAreasAreResizable(!!enabled);
4686 WebKitEditableLinkBehavior behavior;
4687 hr = preferences->editableLinkBehavior(&behavior);
4690 settings->setEditableLinkBehavior((EditableLinkBehavior)behavior);
4692 WebKitEditingBehavior editingBehavior;
4693 hr = preferences->editingBehavior(&editingBehavior);
4696 settings->setEditingBehaviorType((EditingBehaviorType)editingBehavior);
4698 hr = preferences->usesPageCache(&enabled);
4701 settings->setUsesPageCache(!!enabled);
4703 hr = preferences->isDOMPasteAllowed(&enabled);
4706 settings->setDOMPasteAllowed(!!enabled);
4708 hr = preferences->shouldPaintCustomScrollbars(&enabled);
4711 settings->setShouldPaintCustomScrollbars(!!enabled);
4713 hr = preferences->zoomsTextOnly(&enabled);
4717 if (m_zoomsTextOnly != !!enabled)
4718 setZoomMultiplier(m_zoomMultiplier, enabled);
4720 settings->setShowsURLsInToolTips(false);
4722 settings->setForceFTPDirectoryListings(true);
4723 settings->setDeveloperExtrasEnabled(developerExtrasEnabled());
4724 settings->setNeedsSiteSpecificQuirks(s_allowSiteSpecificHacks);
4726 FontSmoothingType smoothingType;
4727 hr = preferences->fontSmoothing(&smoothingType);
4730 settings->setFontRenderingMode(smoothingType != FontSmoothingTypeWindows ? NormalRenderingMode : AlternateRenderingMode);
4732 #if USE(AVFOUNDATION)
4733 hr = preferences->avFoundationEnabled(&enabled);
4736 settings->setAVFoundationEnabled(enabled);
4739 COMPtr<IWebPreferencesPrivate> prefsPrivate(Query, preferences);
4741 hr = prefsPrivate->authorAndUserStylesEnabled(&enabled);
4744 settings->setAuthorAndUserStylesEnabled(enabled);
4747 hr = prefsPrivate->inApplicationChromeMode(&enabled);
4750 settings->setApplicationChromeMode(enabled);
4752 hr = prefsPrivate->offlineWebApplicationCacheEnabled(&enabled);
4755 settings->setOfflineWebApplicationCacheEnabled(enabled);
4757 #if ENABLE(SQL_DATABASE)
4758 hr = prefsPrivate->databasesEnabled(&enabled);
4761 AbstractDatabase::setIsAvailable(enabled);
4764 hr = prefsPrivate->localStorageEnabled(&enabled);
4767 settings->setLocalStorageEnabled(enabled);
4769 hr = prefsPrivate->experimentalNotificationsEnabled(&enabled);
4772 settings->setExperimentalNotificationsEnabled(enabled);
4774 hr = prefsPrivate->isWebSecurityEnabled(&enabled);
4777 settings->setWebSecurityEnabled(!!enabled);
4779 hr = prefsPrivate->allowUniversalAccessFromFileURLs(&enabled);
4782 settings->setAllowUniversalAccessFromFileURLs(!!enabled);
4784 hr = prefsPrivate->allowFileAccessFromFileURLs(&enabled);
4787 settings->setAllowFileAccessFromFileURLs(!!enabled);
4789 hr = prefsPrivate->javaScriptCanAccessClipboard(&enabled);
4792 settings->setJavaScriptCanAccessClipboard(!!enabled);
4794 hr = prefsPrivate->isXSSAuditorEnabled(&enabled);
4797 settings->setXSSAuditorEnabled(!!enabled);
4799 #if USE(SAFARI_THEME)
4800 hr = prefsPrivate->shouldPaintNativeControls(&enabled);
4803 settings->setShouldPaintNativeControls(!!enabled);
4806 hr = prefsPrivate->shouldUseHighResolutionTimers(&enabled);
4809 settings->setShouldUseHighResolutionTimers(enabled);
4811 hr = prefsPrivate->isFrameFlatteningEnabled(&enabled);
4814 settings->setFrameFlatteningEnabled(enabled);
4816 #if USE(ACCELERATED_COMPOSITING)
4817 hr = prefsPrivate->acceleratedCompositingEnabled(&enabled);
4820 settings->setAcceleratedCompositingEnabled(enabled);
4823 hr = prefsPrivate->showDebugBorders(&enabled);
4826 settings->setShowDebugBorders(enabled);
4828 hr = prefsPrivate->showRepaintCounter(&enabled);
4831 settings->setShowRepaintCounter(enabled);
4833 #if ENABLE(WEB_AUDIO)
4834 settings->setWebAudioEnabled(true);
4835 #endif // ENABLE(WEB_AUDIO)
4838 settings->setWebGLEnabled(true);
4839 #endif // ENABLE(WEBGL)
4841 hr = prefsPrivate->isDNSPrefetchingEnabled(&enabled);
4844 settings->setDNSPrefetchingEnabled(enabled);
4846 hr = prefsPrivate->memoryInfoEnabled(&enabled);
4849 settings->setMemoryInfoEnabled(enabled);
4851 hr = prefsPrivate->hyperlinkAuditingEnabled(&enabled);
4854 settings->setHyperlinkAuditingEnabled(enabled);
4856 hr = prefsPrivate->loadsSiteIconsIgnoringImageLoadingPreference(&enabled);
4859 settings->setLoadsSiteIconsIgnoringImageLoadingSetting(!!enabled);
4861 #if ENABLE(WEB_SOCKETS)
4862 hr = prefsPrivate->hixie76WebSocketProtocolEnabled(&enabled);
4865 settings->setUseHixie76WebSocketProtocol(enabled);
4868 hr = prefsPrivate->showsToolTipOverTruncatedText(&enabled);
4872 settings->setShowsToolTipOverTruncatedText(enabled);
4874 if (!m_closeWindowTimer)
4875 m_mainFrame->invalidate(); // FIXME
4877 hr = updateSharedSettingsFromPreferencesIfNeeded(preferences.get());
4881 #if ENABLE(FULLSCREEN_API)
4882 hr = prefsPrivate->isFullScreenEnabled(&enabled);
4885 settings->setFullScreenEnabled(enabled);
4888 hr = prefsPrivate->mediaPlaybackRequiresUserGesture(&enabled);
4891 settings->setMediaPlaybackRequiresUserGesture(enabled);
4893 hr = prefsPrivate->mediaPlaybackAllowsInline(&enabled);
4896 settings->setMediaPlaybackAllowsInline(enabled);
4901 HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences* preferences)
4903 if (preferences != WebPreferences::sharedStandardPreferences())
4906 WebKitCookieStorageAcceptPolicy acceptPolicy;
4907 HRESULT hr = preferences->cookieStorageAcceptPolicy(&acceptPolicy);
4912 // Set cookie storage accept policy
4913 if (RetainPtr<CFHTTPCookieStorageRef> cookieStorage = currentCFHTTPCookieStorage())
4914 CFHTTPCookieStorageSetCookieAcceptPolicy(cookieStorage.get(), acceptPolicy);
4920 // IWebViewPrivate ------------------------------------------------------------
4922 HRESULT STDMETHODCALLTYPE WebView::MIMETypeForExtension(
4923 /* [in] */ BSTR extension,
4924 /* [retval][out] */ BSTR* mimeType)
4929 String extensionStr(extension, SysStringLen(extension));
4931 *mimeType = BString(MIMETypeRegistry::getMIMETypeForExtension(extensionStr)).release();
4936 HRESULT STDMETHODCALLTYPE WebView::setCustomDropTarget(
4937 /* [in] */ IDropTarget* dt)
4939 ASSERT(::IsWindow(m_viewWindow));
4942 m_hasCustomDropTarget = true;
4944 return ::RegisterDragDrop(m_viewWindow,dt);
4947 HRESULT STDMETHODCALLTYPE WebView::removeCustomDropTarget()
4949 if (!m_hasCustomDropTarget)
4951 m_hasCustomDropTarget = false;
4953 return registerDragDrop();
4956 HRESULT STDMETHODCALLTYPE WebView::setInViewSourceMode(
4957 /* [in] */ BOOL flag)
4962 return m_mainFrame->setInViewSourceMode(flag);
4965 HRESULT STDMETHODCALLTYPE WebView::inViewSourceMode(
4966 /* [retval][out] */ BOOL* flag)
4971 return m_mainFrame->inViewSourceMode(flag);
4974 HRESULT STDMETHODCALLTYPE WebView::viewWindow(
4975 /* [retval][out] */ OLE_HANDLE *window)
4977 *window = (OLE_HANDLE)(ULONG64)m_viewWindow;
4981 HRESULT STDMETHODCALLTYPE WebView::setFormDelegate(
4982 /* [in] */ IWebFormDelegate *formDelegate)
4984 m_formDelegate = formDelegate;
4988 HRESULT STDMETHODCALLTYPE WebView::formDelegate(
4989 /* [retval][out] */ IWebFormDelegate **formDelegate)
4991 if (!m_formDelegate)
4994 return m_formDelegate.copyRefTo(formDelegate);
4997 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegatePrivate(
4998 /* [in] */ IWebFrameLoadDelegatePrivate* d)
5000 m_frameLoadDelegatePrivate = d;
5004 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegatePrivate(
5005 /* [out][retval] */ IWebFrameLoadDelegatePrivate** d)
5007 if (!m_frameLoadDelegatePrivate)
5010 return m_frameLoadDelegatePrivate.copyRefTo(d);
5013 HRESULT STDMETHODCALLTYPE WebView::scrollOffset(
5014 /* [retval][out] */ LPPOINT offset)
5018 IntSize offsetIntSize = m_page->mainFrame()->view()->scrollOffset();
5019 offset->x = offsetIntSize.width();
5020 offset->y = offsetIntSize.height();
5024 HRESULT STDMETHODCALLTYPE WebView::scrollBy(
5025 /* [in] */ LPPOINT offset)
5029 m_page->mainFrame()->view()->scrollBy(IntSize(offset->x, offset->y));
5033 HRESULT STDMETHODCALLTYPE WebView::visibleContentRect(
5034 /* [retval][out] */ LPRECT rect)
5038 FloatRect visibleContent = m_page->mainFrame()->view()->visibleContentRect();
5039 rect->left = (LONG) visibleContent.x();
5040 rect->top = (LONG) visibleContent.y();
5041 rect->right = (LONG) visibleContent.maxX();
5042 rect->bottom = (LONG) visibleContent.maxY();
5046 static DWORD dragOperationToDragCursor(DragOperation op) {
5047 DWORD res = DROPEFFECT_NONE;
5048 if (op & DragOperationCopy)
5049 res = DROPEFFECT_COPY;
5050 else if (op & DragOperationLink)
5051 res = DROPEFFECT_LINK;
5052 else if (op & DragOperationMove)
5053 res = DROPEFFECT_MOVE;
5054 else if (op & DragOperationGeneric)
5055 res = DROPEFFECT_MOVE; //This appears to be the Firefox behaviour
5059 DragOperation WebView::keyStateToDragOperation(DWORD grfKeyState) const
5062 return DragOperationNone;
5064 // Conforms to Microsoft's key combinations as documented for
5065 // IDropTarget::DragOver. Note, grfKeyState is the current
5066 // state of the keyboard modifier keys on the keyboard. See:
5067 // <http://msdn.microsoft.com/en-us/library/ms680129(VS.85).aspx>.
5068 DragOperation operation = m_page->dragController()->sourceDragOperation();
5070 if ((grfKeyState & (MK_CONTROL | MK_SHIFT)) == (MK_CONTROL | MK_SHIFT))
5071 operation = DragOperationLink;
5072 else if ((grfKeyState & MK_CONTROL) == MK_CONTROL)
5073 operation = DragOperationCopy;
5074 else if ((grfKeyState & MK_SHIFT) == MK_SHIFT)
5075 operation = DragOperationGeneric;
5080 HRESULT STDMETHODCALLTYPE WebView::DragEnter(
5081 IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
5085 if (m_dropTargetHelper)
5086 m_dropTargetHelper->DragEnter(m_viewWindow, pDataObject, (POINT*)&pt, *pdwEffect);
5088 POINTL localpt = pt;
5089 ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
5090 DragData data(pDataObject, IntPoint(localpt.x, localpt.y),
5091 IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
5092 *pdwEffect = dragOperationToDragCursor(m_page->dragController()->dragEntered(&data));
5094 m_lastDropEffect = *pdwEffect;
5095 m_dragData = pDataObject;
5100 HRESULT STDMETHODCALLTYPE WebView::DragOver(
5101 DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
5103 if (m_dropTargetHelper)
5104 m_dropTargetHelper->DragOver((POINT*)&pt, *pdwEffect);
5107 POINTL localpt = pt;
5108 ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
5109 DragData data(m_dragData.get(), IntPoint(localpt.x, localpt.y),
5110 IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
5111 *pdwEffect = dragOperationToDragCursor(m_page->dragController()->dragUpdated(&data));
5113 *pdwEffect = DROPEFFECT_NONE;
5115 m_lastDropEffect = *pdwEffect;
5119 HRESULT STDMETHODCALLTYPE WebView::DragLeave()
5121 if (m_dropTargetHelper)
5122 m_dropTargetHelper->DragLeave();
5125 DragData data(m_dragData.get(), IntPoint(), IntPoint(),
5127 m_page->dragController()->dragExited(&data);
5133 HRESULT STDMETHODCALLTYPE WebView::Drop(
5134 IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
5136 if (m_dropTargetHelper)
5137 m_dropTargetHelper->Drop(pDataObject, (POINT*)&pt, *pdwEffect);
5140 *pdwEffect = m_lastDropEffect;
5141 POINTL localpt = pt;
5142 ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
5143 DragData data(pDataObject, IntPoint(localpt.x, localpt.y),
5144 IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
5145 m_page->dragController()->performDrag(&data);
5149 HRESULT STDMETHODCALLTYPE WebView::canHandleRequest(
5150 IWebURLRequest *request,
5153 COMPtr<WebMutableURLRequest> requestImpl;
5155 HRESULT hr = request->QueryInterface(&requestImpl);
5159 *result = !!canHandleRequest(requestImpl->resourceRequest());
5163 HRESULT STDMETHODCALLTYPE WebView::standardUserAgentWithApplicationName(
5164 BSTR applicationName,
5168 ASSERT_NOT_REACHED();
5174 if (!applicationName) {
5175 ASSERT_NOT_REACHED();
5179 BString applicationNameBString(applicationName);
5180 *groupName = BString(standardUserAgentWithApplicationName(String(applicationNameBString, SysStringLen(applicationNameBString)))).release();
5184 HRESULT STDMETHODCALLTYPE WebView::clearFocusNode()
5186 if (m_page && m_page->focusController())
5187 m_page->focusController()->setFocusedNode(0, 0);
5191 HRESULT STDMETHODCALLTYPE WebView::setInitialFocus(
5192 /* [in] */ BOOL forward)
5194 if (m_page && m_page->focusController()) {
5195 Frame* frame = m_page->focusController()->focusedOrMainFrame();
5196 frame->document()->setFocusedNode(0);
5197 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
5202 HRESULT STDMETHODCALLTYPE WebView::setTabKeyCyclesThroughElements(
5203 /* [in] */ BOOL cycles)
5206 m_page->setTabKeyCyclesThroughElements(!!cycles);
5211 HRESULT STDMETHODCALLTYPE WebView::tabKeyCyclesThroughElements(
5212 /* [retval][out] */ BOOL* result)
5215 ASSERT_NOT_REACHED();
5219 *result = m_page && m_page->tabKeyCyclesThroughElements() ? TRUE : FALSE;
5223 HRESULT STDMETHODCALLTYPE WebView::setAllowSiteSpecificHacks(
5224 /* [in] */ BOOL allow)
5226 s_allowSiteSpecificHacks = !!allow;
5227 // FIXME: This sets a global so it needs to call notifyPreferencesChanged
5228 // on all WebView objects (not just itself).
5232 HRESULT STDMETHODCALLTYPE WebView::addAdditionalPluginDirectory(
5233 /* [in] */ BSTR directory)
5235 PluginDatabase::installedPlugins()->addExtraPluginDirectory(String(directory, SysStringLen(directory)));
5239 HRESULT STDMETHODCALLTYPE WebView::loadBackForwardListFromOtherView(
5240 /* [in] */ IWebView* otherView)
5245 // It turns out the right combination of behavior is done with the back/forward load
5246 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
5247 // in the back forward list, and go to the current one.
5248 BackForwardList* backForwardList = m_page->backForwardList();
5249 ASSERT(!backForwardList->currentItem()); // destination list should be empty
5251 COMPtr<WebView> otherWebView;
5252 if (FAILED(otherView->QueryInterface(&otherWebView)))
5254 BackForwardList* otherBackForwardList = otherWebView->m_page->backForwardList();
5255 if (!otherBackForwardList->currentItem())
5256 return S_OK; // empty back forward list, bail
5258 HistoryItem* newItemToGoTo = 0;
5260 int lastItemIndex = otherBackForwardList->forwardListCount();
5261 for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
5263 // If this item is showing , save away its current scroll and form state,
5264 // since that might have changed since loading and it is normally not saved
5265 // until we leave that page.
5266 otherWebView->m_page->mainFrame()->loader()->history()->saveDocumentAndScrollState();
5268 RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
5270 newItemToGoTo = newItem.get();
5271 backForwardList->addItem(newItem.release());
5274 ASSERT(newItemToGoTo);
5275 m_page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
5279 HRESULT STDMETHODCALLTYPE WebView::clearUndoRedoOperations()
5281 if (Frame* frame = m_page->focusController()->focusedOrMainFrame())
5282 frame->editor()->clearUndoRedoOperations();
5286 HRESULT STDMETHODCALLTYPE WebView::shouldClose(
5287 /* [retval][out] */ BOOL* result)
5290 ASSERT_NOT_REACHED();
5295 if (Frame* frame = m_page->mainFrame())
5296 *result = frame->loader()->shouldClose();
5300 HRESULT WebView::registerDragDrop()
5302 ASSERT(::IsWindow(m_viewWindow));
5303 return ::RegisterDragDrop(m_viewWindow, this);
5306 HRESULT WebView::revokeDragDrop()
5311 return ::RevokeDragDrop(m_viewWindow);
5314 HRESULT WebView::setProhibitsMainFrameScrolling(BOOL b)
5319 m_page->mainFrame()->view()->setProhibitsScrolling(b);
5323 HRESULT WebView::setShouldApplyMacFontAscentHack(BOOL b)
5325 SimpleFontData::setShouldApplyMacAscentHack(b);
5330 typedef HIMC (CALLBACK *getContextPtr)(HWND);
5331 typedef BOOL (CALLBACK *releaseContextPtr)(HWND, HIMC);
5332 typedef LONG (CALLBACK *getCompositionStringPtr)(HIMC, DWORD, LPVOID, DWORD);
5333 typedef BOOL (CALLBACK *setCandidateWindowPtr)(HIMC, LPCANDIDATEFORM);
5334 typedef BOOL (CALLBACK *setOpenStatusPtr)(HIMC, BOOL);
5335 typedef BOOL (CALLBACK *notifyIMEPtr)(HIMC, DWORD, DWORD, DWORD);
5336 typedef BOOL (CALLBACK *associateContextExPtr)(HWND, HIMC, DWORD);
5339 getContextPtr getContext;
5340 releaseContextPtr releaseContext;
5341 getCompositionStringPtr getCompositionString;
5342 setCandidateWindowPtr setCandidateWindow;
5343 setOpenStatusPtr setOpenStatus;
5344 notifyIMEPtr notifyIME;
5345 associateContextExPtr associateContextEx;
5347 static const IMMDict& dict();
5353 const IMMDict& IMMDict::dict()
5355 static IMMDict instance;
5361 m_instance = ::LoadLibraryW(L"IMM32.DLL");
5362 getContext = reinterpret_cast<getContextPtr>(::GetProcAddress(m_instance, "ImmGetContext"));
5364 releaseContext = reinterpret_cast<releaseContextPtr>(::GetProcAddress(m_instance, "ImmReleaseContext"));
5365 ASSERT(releaseContext);
5366 getCompositionString = reinterpret_cast<getCompositionStringPtr>(::GetProcAddress(m_instance, "ImmGetCompositionStringW"));
5367 ASSERT(getCompositionString);
5368 setCandidateWindow = reinterpret_cast<setCandidateWindowPtr>(::GetProcAddress(m_instance, "ImmSetCandidateWindow"));
5369 ASSERT(setCandidateWindow);
5370 setOpenStatus = reinterpret_cast<setOpenStatusPtr>(::GetProcAddress(m_instance, "ImmSetOpenStatus"));
5371 ASSERT(setOpenStatus);
5372 notifyIME = reinterpret_cast<notifyIMEPtr>(::GetProcAddress(m_instance, "ImmNotifyIME"));
5374 associateContextEx = reinterpret_cast<associateContextExPtr>(::GetProcAddress(m_instance, "ImmAssociateContextEx"));
5375 ASSERT(associateContextEx);
5378 HIMC WebView::getIMMContext()
5380 HIMC context = IMMDict::dict().getContext(m_viewWindow);
5384 void WebView::releaseIMMContext(HIMC hIMC)
5388 IMMDict::dict().releaseContext(m_viewWindow, hIMC);
5391 void WebView::prepareCandidateWindow(Frame* targetFrame, HIMC hInputContext)
5394 if (RefPtr<Range> range = targetFrame->selection()->selection().toNormalizedRange()) {
5395 ExceptionCode ec = 0;
5396 RefPtr<Range> tempRange = range->cloneRange(ec);
5397 caret = targetFrame->editor()->firstRectForRange(tempRange.get());
5399 caret = targetFrame->view()->contentsToWindow(caret);
5402 form.dwStyle = CFS_EXCLUDE;
5403 form.ptCurrentPos.x = caret.x();
5404 form.ptCurrentPos.y = caret.y() + caret.height();
5405 form.rcArea.top = caret.y();
5406 form.rcArea.bottom = caret.maxY();
5407 form.rcArea.left = caret.x();
5408 form.rcArea.right = caret.maxX();
5409 IMMDict::dict().setCandidateWindow(hInputContext, &form);
5412 void WebView::resetIME(Frame* targetFrame)
5415 targetFrame->editor()->cancelComposition();
5417 if (HIMC hInputContext = getIMMContext()) {
5418 IMMDict::dict().notifyIME(hInputContext, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
5419 releaseIMMContext(hInputContext);
5423 void WebView::updateSelectionForIME()
5425 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
5426 if (!targetFrame || !targetFrame->editor()->hasComposition())
5429 if (targetFrame->editor()->ignoreCompositionSelectionChange())
5434 if (!targetFrame->editor()->getCompositionSelection(start, end))
5435 resetIME(targetFrame);
5438 void WebView::setInputMethodState(bool enabled)
5440 IMMDict::dict().associateContextEx(m_viewWindow, 0, enabled ? IACE_DEFAULT : 0);
5443 void WebView::selectionChanged()
5445 updateSelectionForIME();
5448 bool WebView::onIMEStartComposition()
5450 LOG(TextInput, "onIMEStartComposition");
5451 m_inIMEComposition++;
5452 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
5456 HIMC hInputContext = getIMMContext();
5457 prepareCandidateWindow(targetFrame, hInputContext);
5458 releaseIMMContext(hInputContext);
5462 static bool getCompositionString(HIMC hInputContext, DWORD type, String& result)
5464 int compositionLength = IMMDict::dict().getCompositionString(hInputContext, type, 0, 0);
5465 if (compositionLength <= 0)
5467 Vector<UChar> compositionBuffer(compositionLength / 2);
5468 compositionLength = IMMDict::dict().getCompositionString(hInputContext, type, (LPVOID)compositionBuffer.data(), compositionLength);
5469 result = String(compositionBuffer.data(), compositionLength / 2);
5470 ASSERT(!compositionLength || compositionBuffer[0]);
5471 ASSERT(!compositionLength || compositionBuffer[compositionLength / 2 - 1]);
5475 static void compositionToUnderlines(const Vector<DWORD>& clauses, const Vector<BYTE>& attributes, Vector<CompositionUnderline>& underlines)
5477 if (clauses.isEmpty()) {
5482 const size_t numBoundaries = clauses.size() - 1;
5483 underlines.resize(numBoundaries);
5484 for (unsigned i = 0; i < numBoundaries; i++) {
5485 underlines[i].startOffset = clauses[i];
5486 underlines[i].endOffset = clauses[i + 1];
5487 BYTE attribute = attributes[clauses[i]];
5488 underlines[i].thick = attribute == ATTR_TARGET_CONVERTED || attribute == ATTR_TARGET_NOTCONVERTED;
5489 underlines[i].color = Color(0,0,0);
5494 #define APPEND_ARGUMENT_NAME(name) \
5495 if (lparam & name) { \
5499 needsComma = true; \
5502 static String imeCompositionArgumentNames(LPARAM lparam)
5505 bool needsComma = false;
5506 if (lparam & GCS_COMPATTR) {
5507 result = "GCS_COMPATTR";
5510 APPEND_ARGUMENT_NAME(GCS_COMPCLAUSE);
5511 APPEND_ARGUMENT_NAME(GCS_COMPREADSTR);
5512 APPEND_ARGUMENT_NAME(GCS_COMPREADATTR);
5513 APPEND_ARGUMENT_NAME(GCS_COMPREADCLAUSE);
5514 APPEND_ARGUMENT_NAME(GCS_COMPSTR);
5515 APPEND_ARGUMENT_NAME(GCS_CURSORPOS);
5516 APPEND_ARGUMENT_NAME(GCS_DELTASTART);
5517 APPEND_ARGUMENT_NAME(GCS_RESULTCLAUSE);
5518 APPEND_ARGUMENT_NAME(GCS_RESULTREADCLAUSE);
5519 APPEND_ARGUMENT_NAME(GCS_RESULTREADSTR);
5520 APPEND_ARGUMENT_NAME(GCS_RESULTSTR);
5521 APPEND_ARGUMENT_NAME(CS_INSERTCHAR);
5522 APPEND_ARGUMENT_NAME(CS_NOMOVECARET);
5527 static String imeNotificationName(WPARAM wparam)
5530 case IMN_CHANGECANDIDATE:
5531 return "IMN_CHANGECANDIDATE";
5532 case IMN_CLOSECANDIDATE:
5533 return "IMN_CLOSECANDIDATE";
5534 case IMN_CLOSESTATUSWINDOW:
5535 return "IMN_CLOSESTATUSWINDOW";
5537 return "IMN_GUIDELINE";
5538 case IMN_OPENCANDIDATE:
5539 return "IMN_OPENCANDIDATE";
5540 case IMN_OPENSTATUSWINDOW:
5541 return "IMN_OPENSTATUSWINDOW";
5542 case IMN_SETCANDIDATEPOS:
5543 return "IMN_SETCANDIDATEPOS";
5544 case IMN_SETCOMPOSITIONFONT:
5545 return "IMN_SETCOMPOSITIONFONT";
5546 case IMN_SETCOMPOSITIONWINDOW:
5547 return "IMN_SETCOMPOSITIONWINDOW";
5548 case IMN_SETCONVERSIONMODE:
5549 return "IMN_SETCONVERSIONMODE";
5550 case IMN_SETOPENSTATUS:
5551 return "IMN_SETOPENSTATUS";
5552 case IMN_SETSENTENCEMODE:
5553 return "IMN_SETSENTENCEMODE";
5554 case IMN_SETSTATUSWINDOWPOS:
5555 return "IMN_SETSTATUSWINDOWPOS";
5557 return "Unknown (" + String::number(wparam) + ")";
5561 static String imeRequestName(WPARAM wparam)
5564 case IMR_CANDIDATEWINDOW:
5565 return "IMR_CANDIDATEWINDOW";
5566 case IMR_COMPOSITIONFONT:
5567 return "IMR_COMPOSITIONFONT";
5568 case IMR_COMPOSITIONWINDOW:
5569 return "IMR_COMPOSITIONWINDOW";
5570 case IMR_CONFIRMRECONVERTSTRING:
5571 return "IMR_CONFIRMRECONVERTSTRING";
5572 case IMR_DOCUMENTFEED:
5573 return "IMR_DOCUMENTFEED";
5574 case IMR_QUERYCHARPOSITION:
5575 return "IMR_QUERYCHARPOSITION";
5576 case IMR_RECONVERTSTRING:
5577 return "IMR_RECONVERTSTRING";
5579 return "Unknown (" + String::number(wparam) + ")";
5584 bool WebView::onIMEComposition(LPARAM lparam)
5586 LOG(TextInput, "onIMEComposition %s", imeCompositionArgumentNames(lparam).latin1().data());
5587 HIMC hInputContext = getIMMContext();
5591 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
5592 if (!targetFrame || !targetFrame->editor()->canEdit())
5595 prepareCandidateWindow(targetFrame, hInputContext);
5597 if (lparam & GCS_RESULTSTR || !lparam) {
5598 String compositionString;
5599 if (!getCompositionString(hInputContext, GCS_RESULTSTR, compositionString) && lparam)
5602 targetFrame->editor()->confirmComposition(compositionString);
5604 String compositionString;
5605 if (!getCompositionString(hInputContext, GCS_COMPSTR, compositionString))
5608 // Composition string attributes
5609 int numAttributes = IMMDict::dict().getCompositionString(hInputContext, GCS_COMPATTR, 0, 0);
5610 Vector<BYTE> attributes(numAttributes);
5611 IMMDict::dict().getCompositionString(hInputContext, GCS_COMPATTR, attributes.data(), numAttributes);
5614 int numClauses = IMMDict::dict().getCompositionString(hInputContext, GCS_COMPCLAUSE, 0, 0);
5615 Vector<DWORD> clauses(numClauses / sizeof(DWORD));
5616 IMMDict::dict().getCompositionString(hInputContext, GCS_COMPCLAUSE, clauses.data(), numClauses);
5618 Vector<CompositionUnderline> underlines;
5619 compositionToUnderlines(clauses, attributes, underlines);
5621 int cursorPosition = LOWORD(IMMDict::dict().getCompositionString(hInputContext, GCS_CURSORPOS, 0, 0));
5623 targetFrame->editor()->setComposition(compositionString, underlines, cursorPosition, 0);
5629 bool WebView::onIMEEndComposition()
5631 LOG(TextInput, "onIMEEndComposition");
5632 // If the composition hasn't been confirmed yet, it needs to be cancelled.
5633 // This happens after deleting the last character from inline input hole.
5634 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
5635 if (targetFrame && targetFrame->editor()->hasComposition())
5636 targetFrame->editor()->confirmComposition(String());
5638 if (m_inIMEComposition)
5639 m_inIMEComposition--;
5644 bool WebView::onIMEChar(WPARAM wparam, LPARAM lparam)
5646 UNUSED_PARAM(wparam);
5647 UNUSED_PARAM(lparam);
5648 LOG(TextInput, "onIMEChar U+%04X %08X", wparam, lparam);
5652 bool WebView::onIMENotify(WPARAM wparam, LPARAM, LRESULT*)
5654 UNUSED_PARAM(wparam);
5655 LOG(TextInput, "onIMENotify %s", imeNotificationName(wparam).latin1().data());
5659 LRESULT WebView::onIMERequestCharPosition(Frame* targetFrame, IMECHARPOSITION* charPos)
5661 if (charPos->dwCharPos && !targetFrame->editor()->hasComposition())
5664 if (RefPtr<Range> range = targetFrame->editor()->hasComposition() ? targetFrame->editor()->compositionRange() : targetFrame->selection()->selection().toNormalizedRange()) {
5665 ExceptionCode ec = 0;
5666 RefPtr<Range> tempRange = range->cloneRange(ec);
5667 tempRange->setStart(tempRange->startContainer(ec), tempRange->startOffset(ec) + charPos->dwCharPos, ec);
5668 caret = targetFrame->editor()->firstRectForRange(tempRange.get());
5670 caret = targetFrame->view()->contentsToWindow(caret);
5671 charPos->pt.x = caret.x();
5672 charPos->pt.y = caret.y();
5673 ::ClientToScreen(m_viewWindow, &charPos->pt);
5674 charPos->cLineHeight = caret.height();
5675 ::GetWindowRect(m_viewWindow, &charPos->rcDocument);
5679 LRESULT WebView::onIMERequestReconvertString(Frame* targetFrame, RECONVERTSTRING* reconvertString)
5681 RefPtr<Range> selectedRange = targetFrame->selection()->toNormalizedRange();
5682 String text = selectedRange->text();
5683 if (!reconvertString)
5684 return sizeof(RECONVERTSTRING) + text.length() * sizeof(UChar);
5686 unsigned totalSize = sizeof(RECONVERTSTRING) + text.length() * sizeof(UChar);
5687 if (totalSize > reconvertString->dwSize)
5689 reconvertString->dwCompStrLen = text.length();
5690 reconvertString->dwStrLen = text.length();
5691 reconvertString->dwTargetStrLen = text.length();
5692 reconvertString->dwStrOffset = sizeof(RECONVERTSTRING);
5693 memcpy(reconvertString + 1, text.characters(), text.length() * sizeof(UChar));
5697 LRESULT WebView::onIMERequest(WPARAM request, LPARAM data)
5699 LOG(TextInput, "onIMERequest %s", imeRequestName(request).latin1().data());
5700 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
5701 if (!targetFrame || !targetFrame->editor()->canEdit())
5705 case IMR_RECONVERTSTRING:
5706 return onIMERequestReconvertString(targetFrame, (RECONVERTSTRING*)data);
5708 case IMR_QUERYCHARPOSITION:
5709 return onIMERequestCharPosition(targetFrame, (IMECHARPOSITION*)data);
5714 bool WebView::onIMESelect(WPARAM wparam, LPARAM lparam)
5716 UNUSED_PARAM(wparam);
5717 UNUSED_PARAM(lparam);
5718 LOG(TextInput, "onIMESelect locale %ld %s", lparam, wparam ? "select" : "deselect");
5722 bool WebView::onIMESetContext(WPARAM wparam, LPARAM)
5724 LOG(TextInput, "onIMESetContext %s", wparam ? "active" : "inactive");
5728 HRESULT STDMETHODCALLTYPE WebView::inspector(IWebInspector** inspector)
5730 if (!m_webInspector)
5731 m_webInspector.adoptRef(WebInspector::createInstance(this));
5733 return m_webInspector.copyRefTo(inspector);
5736 HRESULT STDMETHODCALLTYPE WebView::windowAncestryDidChange()
5740 newParent = findTopLevelParent(m_hostWindow);
5742 // There's no point in tracking active state changes of our parent window if we don't have
5743 // a window ourselves.
5747 if (newParent == m_topLevelParent)
5750 if (m_topLevelParent)
5751 WindowMessageBroadcaster::removeListener(m_topLevelParent, this);
5753 m_topLevelParent = newParent;
5755 if (m_topLevelParent)
5756 WindowMessageBroadcaster::addListener(m_topLevelParent, this);
5758 updateActiveState();
5763 HRESULT STDMETHODCALLTYPE WebView::paintDocumentRectToContext(
5764 /* [in] */ RECT rect,
5765 /* [in] */ OLE_HANDLE deviceContext)
5773 return m_mainFrame->paintDocumentRectToContext(rect, deviceContext);
5776 HRESULT STDMETHODCALLTYPE WebView::paintScrollViewRectToContextAtPoint(
5777 /* [in] */ RECT rect,
5778 /* [in] */ POINT pt,
5779 /* [in] */ OLE_HANDLE deviceContext)
5787 return m_mainFrame->paintScrollViewRectToContextAtPoint(rect, pt, deviceContext);
5790 HRESULT STDMETHODCALLTYPE WebView::reportException(
5791 /* [in] */ JSContextRef context,
5792 /* [in] */ JSValueRef exception)
5794 if (!context || !exception)
5797 JSLock lock(JSC::SilenceAssertionsOnly);
5798 JSC::ExecState* execState = toJS(context);
5800 // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
5801 if (!toJSDOMWindow(execState->lexicalGlobalObject()))
5804 WebCore::reportException(execState, toJS(execState, exception));
5808 HRESULT STDMETHODCALLTYPE WebView::elementFromJS(
5809 /* [in] */ JSContextRef context,
5810 /* [in] */ JSValueRef nodeObject,
5811 /* [retval][out] */ IDOMElement **element)
5824 JSLock lock(JSC::SilenceAssertionsOnly);
5825 Element* elt = toElement(toJS(toJS(context), nodeObject));
5829 *element = DOMElement::createInstance(elt);
5833 HRESULT STDMETHODCALLTYPE WebView::setCustomHTMLTokenizerTimeDelay(
5834 /* [in] */ double timeDelay)
5839 m_page->setCustomHTMLTokenizerTimeDelay(timeDelay);
5843 HRESULT STDMETHODCALLTYPE WebView::setCustomHTMLTokenizerChunkSize(
5844 /* [in] */ int chunkSize)
5849 m_page->setCustomHTMLTokenizerChunkSize(chunkSize);
5853 HRESULT STDMETHODCALLTYPE WebView::backingStore(
5854 /* [out, retval] */ OLE_HANDLE* hBitmap)
5858 if (!m_backingStoreBitmap)
5860 *hBitmap = reinterpret_cast<OLE_HANDLE>(m_backingStoreBitmap->handle());
5864 HRESULT STDMETHODCALLTYPE WebView::setTransparent(BOOL transparent)
5866 if (m_transparent == !!transparent)
5869 m_transparent = transparent;
5870 m_mainFrame->updateBackground();
5874 HRESULT STDMETHODCALLTYPE WebView::transparent(BOOL* transparent)
5879 *transparent = this->transparent() ? TRUE : FALSE;
5883 static bool setWindowStyle(HWND window, int index, LONG_PTR newValue)
5885 // According to MSDN, if the last value of the flag we are setting was zero,
5886 // then SetWindowLongPtr returns zero, even though the call succeeded. So,
5887 // we have to clear the error state, then check the last error after
5888 // setting the value to see if it actually was a failure.
5890 return ::SetWindowLongPtr(window, index, newValue) || !::GetLastError();
5893 HRESULT WebView::setUsesLayeredWindow(BOOL usesLayeredWindow)
5895 if (m_usesLayeredWindow == !!usesLayeredWindow)
5902 ::GetWindowRect(m_viewWindow, &rect);
5904 LONG_PTR origExStyle = ::GetWindowLongPtr(m_viewWindow, GWL_EXSTYLE);
5905 LONG_PTR origStyle = ::GetWindowLongPtr(m_viewWindow, GWL_STYLE);
5907 // The logic here has to account for the way SetParent works.
5908 // According to MSDN, to go from a child window to a popup window,
5909 // you must clear the child bit after setting the parent to 0.
5910 // On the other hand, to go from a popup window to a child, you
5911 // must clear the popup state before setting the parent.
5912 if (usesLayeredWindow) {
5913 LONG_PTR newExStyle = origExStyle | WS_EX_LAYERED;
5914 LONG_PTR newStyle = (origStyle & ~(WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN)) | WS_POPUP;
5916 HWND origParent = ::SetParent(m_viewWindow, 0);
5918 if (!setWindowStyle(m_viewWindow, GWL_STYLE, newStyle)) {
5919 ::SetParent(m_viewWindow, origParent);
5923 if (!setWindowStyle(m_viewWindow, GWL_EXSTYLE, newExStyle)) {
5924 setWindowStyle(m_viewWindow, GWL_STYLE, origStyle);
5925 ::SetParent(m_viewWindow, origParent);
5929 LONG_PTR newExStyle = origExStyle & ~WS_EX_LAYERED;
5930 LONG_PTR newStyle = (origStyle & ~WS_POPUP) | WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
5932 if (!setWindowStyle(m_viewWindow, GWL_EXSTYLE, newExStyle))
5935 if (!setWindowStyle(m_viewWindow, GWL_STYLE, newStyle)) {
5936 setWindowStyle(m_viewWindow, GWL_EXSTYLE, origExStyle);
5940 ::SetParent(m_viewWindow, m_hostWindow ? m_hostWindow : HWND_MESSAGE);
5943 // MSDN indicates that SetWindowLongPtr doesn't take effect for some settings until a
5944 // SetWindowPos is called.
5945 ::SetWindowPos(m_viewWindow, 0, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
5946 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
5948 m_usesLayeredWindow = usesLayeredWindow;
5952 HRESULT WebView::usesLayeredWindow(BOOL* usesLayeredWindow)
5954 if (!usesLayeredWindow)
5957 *usesLayeredWindow = this->usesLayeredWindow() ? TRUE : FALSE;
5961 HRESULT STDMETHODCALLTYPE WebView::setCookieEnabled(BOOL enable)
5966 m_page->setCookieEnabled(enable);
5970 HRESULT STDMETHODCALLTYPE WebView::cookieEnabled(BOOL* enabled)
5978 *enabled = m_page->cookieEnabled();
5982 HRESULT STDMETHODCALLTYPE WebView::setMediaVolume(float volume)
5987 m_page->setMediaVolume(volume);
5991 HRESULT STDMETHODCALLTYPE WebView::mediaVolume(float* volume)
5999 *volume = m_page->mediaVolume();
6003 HRESULT STDMETHODCALLTYPE WebView::setDefersCallbacks(BOOL defersCallbacks)
6008 m_page->setDefersLoading(defersCallbacks);
6012 HRESULT STDMETHODCALLTYPE WebView::defersCallbacks(BOOL* defersCallbacks)
6014 if (!defersCallbacks)
6020 *defersCallbacks = m_page->defersLoading();
6024 HRESULT STDMETHODCALLTYPE WebView::globalHistoryItem(IWebHistoryItem** item)
6032 if (!m_globalHistoryItem) {
6037 *item = WebHistoryItem::createInstance(m_globalHistoryItem);
6041 HRESULT STDMETHODCALLTYPE WebView::setAlwaysUsesComplexTextCodePath(BOOL complex)
6043 WebCoreSetAlwaysUsesComplexTextCodePath(complex);
6048 HRESULT STDMETHODCALLTYPE WebView::alwaysUsesComplexTextCodePath(BOOL* complex)
6053 *complex = WebCoreAlwaysUsesComplexTextCodePath();
6057 HRESULT STDMETHODCALLTYPE WebView::registerEmbeddedViewMIMEType(BSTR mimeType)
6062 if (!m_embeddedViewMIMETypes)
6063 m_embeddedViewMIMETypes = adoptPtr(new HashSet<String>);
6065 m_embeddedViewMIMETypes->add(String(mimeType, ::SysStringLen(mimeType)));
6069 bool WebView::shouldUseEmbeddedView(const WTF::String& mimeType) const
6071 if (!m_embeddedViewMIMETypes)
6074 return m_embeddedViewMIMETypes->contains(mimeType);
6077 bool WebView::onGetObject(WPARAM wParam, LPARAM lParam, LRESULT& lResult) const
6081 if (lParam != OBJID_CLIENT)
6084 AXObjectCache::enableAccessibility();
6086 // Get the accessible object for the top-level frame.
6087 WebFrame* mainFrameImpl = topLevelFrame();
6091 COMPtr<IAccessible> accessible = mainFrameImpl->accessible();
6095 if (!accessibilityLib) {
6096 if (!(accessibilityLib = ::LoadLibraryW(L"oleacc.dll")))
6100 static LPFNLRESULTFROMOBJECT procPtr = reinterpret_cast<LPFNLRESULTFROMOBJECT>(::GetProcAddress(accessibilityLib, "LresultFromObject"));
6104 // LresultFromObject returns a reference to the accessible object, stored
6105 // in an LRESULT. If this call is not successful, Windows will handle the
6106 // request through DefWindowProc.
6107 return SUCCEEDED(lResult = procPtr(__uuidof(IAccessible), wParam, accessible.get()));
6110 STDMETHODIMP WebView::AccessibleObjectFromWindow(HWND hwnd, DWORD objectID, REFIID riid, void** ppObject)
6112 ASSERT(accessibilityLib);
6113 static LPFNACCESSIBLEOBJECTFROMWINDOW procPtr = reinterpret_cast<LPFNACCESSIBLEOBJECTFROMWINDOW>(::GetProcAddress(accessibilityLib, "AccessibleObjectFromWindow"));
6116 return procPtr(hwnd, objectID, riid, ppObject);
6119 HRESULT WebView::setMemoryCacheDelegateCallsEnabled(BOOL enabled)
6121 m_page->setMemoryCacheClientCallsEnabled(enabled);
6125 HRESULT WebView::setJavaScriptURLsAreAllowed(BOOL areAllowed)
6127 m_page->setJavaScriptURLsAreAllowed(areAllowed);
6131 HRESULT WebView::setCanStartPlugins(BOOL canStartPlugins)
6133 m_page->setCanStartMedia(canStartPlugins);
6137 static String toString(BSTR bstr)
6139 return String(bstr, SysStringLen(bstr));
6142 static KURL toKURL(BSTR bstr)
6144 return KURL(KURL(), toString(bstr));
6147 void WebView::enterFullscreenForNode(Node* node)
6149 if (!node->hasTagName(HTMLNames::videoTag) || !node->isElementNode())
6153 if (!static_cast<Element*>(node)->isMediaElement())
6155 HTMLMediaElement* videoElement = static_cast<HTMLMediaElement*>(node);
6157 if (m_fullScreenVideoController) {
6158 if (m_fullScreenVideoController->mediaElement() == videoElement) {
6159 // The backend may just warn us that the underlaying plaftormMovie()
6160 // has changed. Just force an update.
6161 m_fullScreenVideoController->setMediaElement(videoElement);
6162 return; // No more to do.
6165 // First exit Fullscreen for the old mediaElement.
6166 m_fullScreenVideoController->mediaElement()->exitFullscreen();
6167 // This previous call has to trigger exitFullscreen,
6168 // which has to clear m_fullScreenVideoController.
6169 ASSERT(!m_fullScreenVideoController);
6172 m_fullScreenVideoController = adoptPtr(new FullscreenVideoController);
6173 m_fullScreenVideoController->setMediaElement(videoElement);
6174 m_fullScreenVideoController->enterFullscreen();
6178 void WebView::exitFullscreen()
6181 if (m_fullScreenVideoController)
6182 m_fullScreenVideoController->exitFullscreen();
6187 static PassOwnPtr<Vector<String> > toStringVector(unsigned patternsCount, BSTR* patterns)
6189 // Convert the patterns into a Vector.
6190 if (patternsCount == 0)
6192 OwnPtr<Vector<String> > patternsVector = adoptPtr(new Vector<String>);
6193 for (unsigned i = 0; i < patternsCount; ++i)
6194 patternsVector->append(toString(patterns[i]));
6195 return patternsVector.release();
6198 HRESULT WebView::addUserScriptToGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR source, BSTR url,
6199 unsigned whitelistCount, BSTR* whitelist,
6200 unsigned blacklistCount, BSTR* blacklist,
6201 WebUserScriptInjectionTime injectionTime)
6203 COMPtr<WebScriptWorld> world(Query, iWorld);
6207 String group = toString(groupName);
6208 if (group.isEmpty())
6209 return E_INVALIDARG;
6211 PageGroup* pageGroup = PageGroup::pageGroup(group);
6216 pageGroup->addUserScriptToWorld(world->world(), toString(source), toKURL(url),
6217 toStringVector(whitelistCount, whitelist), toStringVector(blacklistCount, blacklist),
6218 injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd,
6224 HRESULT WebView::addUserStyleSheetToGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR source, BSTR url,
6225 unsigned whitelistCount, BSTR* whitelist,
6226 unsigned blacklistCount, BSTR* blacklist)
6228 COMPtr<WebScriptWorld> world(Query, iWorld);
6232 String group = toString(groupName);
6233 if (group.isEmpty())
6234 return E_INVALIDARG;
6236 PageGroup* pageGroup = PageGroup::pageGroup(group);
6241 pageGroup->addUserStyleSheetToWorld(world->world(), toString(source), toKURL(url),
6242 toStringVector(whitelistCount, whitelist), toStringVector(blacklistCount, blacklist),
6248 HRESULT WebView::removeUserScriptFromGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR url)
6250 COMPtr<WebScriptWorld> world(Query, iWorld);
6254 String group = toString(groupName);
6255 if (group.isEmpty())
6256 return E_INVALIDARG;
6258 PageGroup* pageGroup = PageGroup::pageGroup(group);
6263 pageGroup->removeUserScriptFromWorld(world->world(), toKURL(url));
6268 HRESULT WebView::removeUserStyleSheetFromGroup(BSTR groupName, IWebScriptWorld* iWorld, BSTR url)
6270 COMPtr<WebScriptWorld> world(Query, iWorld);
6274 String group = toString(groupName);
6275 if (group.isEmpty())
6276 return E_INVALIDARG;
6278 PageGroup* pageGroup = PageGroup::pageGroup(group);
6283 pageGroup->removeUserStyleSheetFromWorld(world->world(), toKURL(url));
6288 HRESULT WebView::removeUserScriptsFromGroup(BSTR groupName, IWebScriptWorld* iWorld)
6290 COMPtr<WebScriptWorld> world(Query, iWorld);
6294 String group = toString(groupName);
6295 if (group.isEmpty())
6296 return E_INVALIDARG;
6298 PageGroup* pageGroup = PageGroup::pageGroup(group);
6303 pageGroup->removeUserScriptsFromWorld(world->world());
6307 HRESULT WebView::removeUserStyleSheetsFromGroup(BSTR groupName, IWebScriptWorld* iWorld)
6309 COMPtr<WebScriptWorld> world(Query, iWorld);
6313 String group = toString(groupName);
6314 if (group.isEmpty())
6315 return E_INVALIDARG;
6317 PageGroup* pageGroup = PageGroup::pageGroup(group);
6322 pageGroup->removeUserStyleSheetsFromWorld(world->world());
6326 HRESULT WebView::removeAllUserContentFromGroup(BSTR groupName)
6328 String group = toString(groupName);
6329 if (group.isEmpty())
6330 return E_INVALIDARG;
6332 PageGroup* pageGroup = PageGroup::pageGroup(group);
6337 pageGroup->removeAllUserContent();
6341 HRESULT WebView::invalidateBackingStore(const RECT* rect)
6343 if (!IsWindow(m_viewWindow))
6347 if (!GetClientRect(m_viewWindow, &clientRect))
6350 RECT rectToInvalidate;
6352 rectToInvalidate = clientRect;
6353 else if (!IntersectRect(&rectToInvalidate, &clientRect, rect))
6356 repaint(rectToInvalidate, true);
6360 HRESULT WebView::addOriginAccessWhitelistEntry(BSTR sourceOrigin, BSTR destinationProtocol, BSTR destinationHost, BOOL allowDestinationSubdomains)
6362 SecurityOrigin::addOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(String(sourceOrigin, SysStringLen(sourceOrigin))), String(destinationProtocol, SysStringLen(destinationProtocol)), String(destinationHost, SysStringLen(destinationHost)), allowDestinationSubdomains);
6366 HRESULT WebView::removeOriginAccessWhitelistEntry(BSTR sourceOrigin, BSTR destinationProtocol, BSTR destinationHost, BOOL allowDestinationSubdomains)
6368 SecurityOrigin::removeOriginAccessWhitelistEntry(*SecurityOrigin::createFromString(String(sourceOrigin, SysStringLen(sourceOrigin))), String(destinationProtocol, SysStringLen(destinationProtocol)), String(destinationHost, SysStringLen(destinationHost)), allowDestinationSubdomains);
6372 HRESULT WebView::resetOriginAccessWhitelists()
6374 SecurityOrigin::resetOriginAccessWhitelists();
6378 HRESULT WebView::setHistoryDelegate(IWebHistoryDelegate* historyDelegate)
6380 m_historyDelegate = historyDelegate;
6384 HRESULT WebView::historyDelegate(IWebHistoryDelegate** historyDelegate)
6386 if (!historyDelegate)
6389 return m_historyDelegate.copyRefTo(historyDelegate);
6392 HRESULT WebView::addVisitedLinks(BSTR* visitedURLs, unsigned visitedURLCount)
6394 PageGroup& group = core(this)->group();
6396 for (unsigned i = 0; i < visitedURLCount; ++i) {
6397 BSTR url = visitedURLs[i];
6398 unsigned length = SysStringLen(url);
6399 group.addVisitedLink(url, length);
6405 void WebView::downloadURL(const KURL& url)
6407 // It's the delegate's job to ref the WebDownload to keep it alive - otherwise it will be
6408 // destroyed when this function returns.
6409 COMPtr<WebDownload> download(AdoptCOM, WebDownload::createInstance(url, m_downloadDelegate.get()));
6413 #if USE(ACCELERATED_COMPOSITING)
6414 void WebView::setRootChildLayer(GraphicsLayer* layer)
6416 setAcceleratedCompositing(layer ? true : false);
6417 if (!m_backingLayer)
6419 m_backingLayer->addChild(layer);
6422 void WebView::flushPendingGraphicsLayerChangesSoon()
6424 if (!m_layerTreeHost)
6426 m_layerTreeHost->flushPendingGraphicsLayerChangesSoon();
6429 void WebView::setAcceleratedCompositing(bool accelerated)
6431 if (m_isAcceleratedCompositing == accelerated || !CACFLayerTreeHost::acceleratedCompositingAvailable())
6435 m_layerTreeHost = CACFLayerTreeHost::create();
6436 if (m_layerTreeHost) {
6437 m_isAcceleratedCompositing = true;
6439 m_layerTreeHost->setClient(this);
6440 ASSERT(m_viewWindow);
6441 m_layerTreeHost->setWindow(m_viewWindow);
6443 // FIXME: We could perhaps get better performance by never allowing this layer to
6444 // become tiled (or choosing a higher-than-normal tiling threshold).
6445 // <http://webkit.org/b/52603>
6446 m_backingLayer = GraphicsLayer::create(this);
6447 m_backingLayer->setDrawsContent(true);
6448 m_backingLayer->setContentsOpaque(true);
6450 ::GetClientRect(m_viewWindow, &clientRect);
6451 m_backingLayer->setSize(IntRect(clientRect).size());
6452 m_backingLayer->setNeedsDisplay();
6454 m_layerTreeHost->setRootChildLayer(PlatformCALayer::platformCALayer(m_backingLayer->platformLayer()));
6456 // We aren't going to be using our backing store while we're in accelerated compositing
6457 // mode. But don't delete it immediately, in case we switch out of accelerated
6458 // compositing mode soon (e.g., if we're only compositing for a :hover animation).
6459 deleteBackingStoreSoon();
6462 ASSERT(m_layerTreeHost);
6463 m_layerTreeHost->setClient(0);
6464 m_layerTreeHost->setWindow(0);
6465 m_layerTreeHost = 0;
6466 m_backingLayer = nullptr;
6467 m_isAcceleratedCompositing = false;
6472 HRESULT WebView::unused1()
6474 ASSERT_NOT_REACHED();
6478 HRESULT WebView::unused2()
6480 ASSERT_NOT_REACHED();
6484 HRESULT WebView::unused3()
6486 ASSERT_NOT_REACHED();
6490 HRESULT WebView::unused4()
6492 ASSERT_NOT_REACHED();
6496 HRESULT WebView::unused5()
6498 ASSERT_NOT_REACHED();
6502 HRESULT WebView::setGeolocationProvider(IWebGeolocationProvider* locationProvider)
6504 m_geolocationProvider = locationProvider;
6508 HRESULT WebView::geolocationProvider(IWebGeolocationProvider** locationProvider)
6510 if (!locationProvider)
6513 if (!m_geolocationProvider)
6516 return m_geolocationProvider.copyRefTo(locationProvider);
6519 HRESULT WebView::geolocationDidChangePosition(IWebGeolocationPosition* position)
6521 #if ENABLE(CLIENT_BASED_GEOLOCATION)
6524 m_page->geolocationController()->positionChanged(core(position));
6531 HRESULT WebView::geolocationDidFailWithError(IWebError* error)
6533 #if ENABLE(CLIENT_BASED_GEOLOCATION)
6539 BSTR descriptionBSTR;
6540 if (FAILED(error->localizedDescription(&descriptionBSTR)))
6542 String descriptionString(descriptionBSTR, SysStringLen(descriptionBSTR));
6543 SysFreeString(descriptionBSTR);
6545 RefPtr<GeolocationError> geolocationError = GeolocationError::create(GeolocationError::PositionUnavailable, descriptionString);
6546 m_page->geolocationController()->errorOccurred(geolocationError.get());
6553 HRESULT WebView::setDomainRelaxationForbiddenForURLScheme(BOOL forbidden, BSTR scheme)
6555 SecurityOrigin::setDomainRelaxationForbiddenForURLScheme(forbidden, String(scheme, SysStringLen(scheme)));
6559 HRESULT WebView::registerURLSchemeAsSecure(BSTR scheme)
6561 SchemeRegistry::registerURLSchemeAsSecure(toString(scheme));
6565 HRESULT WebView::nextDisplayIsSynchronous()
6567 m_nextDisplayIsSynchronous = true;
6571 #if USE(ACCELERATED_COMPOSITING)
6572 void WebView::notifyAnimationStarted(const GraphicsLayer*, double)
6574 // We never set any animations on our backing layer.
6575 ASSERT_NOT_REACHED();
6578 void WebView::notifySyncRequired(const GraphicsLayer*)
6580 flushPendingGraphicsLayerChangesSoon();
6583 void WebView::paintContents(const GraphicsLayer*, GraphicsContext& context, GraphicsLayerPaintingPhase, const IntRect& inClip)
6585 Frame* frame = core(m_mainFrame);
6590 context.clip(inClip);
6591 frame->view()->paint(&context, inClip);
6595 bool WebView::showDebugBorders() const
6597 return m_page->settings()->showDebugBorders();
6600 bool WebView::showRepaintCounter() const
6602 return m_page->settings()->showRepaintCounter();
6605 void WebView::flushPendingGraphicsLayerChanges()
6607 Frame* coreFrame = core(m_mainFrame);
6610 FrameView* view = coreFrame->view();
6613 if (!m_backingLayer)
6616 view->updateLayoutAndStyleIfNeededRecursive();
6618 // Updating layout might have taken us out of compositing mode.
6620 m_backingLayer->syncCompositingStateForThisLayerOnly();
6622 view->syncCompositingStateIncludingSubframes();
6627 class EnumTextMatches : public IEnumTextMatches
6631 Vector<IntRect> m_rects;
6633 EnumTextMatches(Vector<IntRect>* rects) : m_index(0), m_ref(1)
6638 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv)
6640 if (IsEqualGUID(riid, IID_IUnknown) || IsEqualGUID(riid, IID_IEnumTextMatches)) {
6645 return *ppv?S_OK:E_NOINTERFACE;
6648 virtual ULONG STDMETHODCALLTYPE AddRef()
6653 virtual ULONG STDMETHODCALLTYPE Release()
6663 virtual HRESULT STDMETHODCALLTYPE Next(ULONG, RECT* rect, ULONG* pceltFetched)
6665 if (m_index < m_rects.size()) {
6668 *rect = m_rects[m_index];
6678 virtual HRESULT STDMETHODCALLTYPE Skip(ULONG celt)
6683 virtual HRESULT STDMETHODCALLTYPE Reset(void)
6688 virtual HRESULT STDMETHODCALLTYPE Clone(IEnumTextMatches**)
6694 HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches)
6696 *matches = new EnumTextMatches(rects);
6697 return (*matches)?S_OK:E_OUTOFMEMORY;
6700 Page* core(IWebView* iWebView)
6704 COMPtr<WebView> webView;
6705 if (SUCCEEDED(iWebView->QueryInterface(&webView)) && webView)
6706 page = webView->page();
6711 HRESULT WebView::defaultMinimumTimerInterval(double* interval)
6715 *interval = Settings::defaultMinDOMTimerInterval();
6719 HRESULT WebView::setMinimumTimerInterval(double interval)
6721 page()->settings()->setMinDOMTimerInterval(interval);
6725 HRESULT WebView::httpPipeliningEnabled(BOOL* enabled)
6729 *enabled = ResourceRequest::httpPipeliningEnabled();
6733 HRESULT WebView::setHTTPPipeliningEnabled(BOOL enabled)
6735 ResourceRequest::setHTTPPipeliningEnabled(enabled);
6739 void WebView::setGlobalHistoryItem(HistoryItem* historyItem)
6741 m_globalHistoryItem = historyItem;
6744 #if ENABLE(FULLSCREEN_API)
6745 bool WebView::supportsFullScreenForElement(const WebCore::Element*, bool withKeyboard) const
6750 BOOL enabled = FALSE;
6751 if (!m_preferences || FAILED(m_preferences->isFullScreenEnabled(&enabled)))
6757 bool WebView::isFullScreen() const
6759 return m_fullscreenController && m_fullscreenController->isFullScreen();
6762 FullScreenController* WebView::fullScreenController()
6764 if (!m_fullscreenController)
6765 m_fullscreenController = adoptPtr(new FullScreenController(this));
6766 return m_fullscreenController.get();
6769 void WebView::setFullScreenElement(PassRefPtr<Element> element)
6771 m_fullScreenElement = element;
6774 HWND WebView::fullScreenClientWindow() const
6776 return m_viewWindow;
6779 HWND WebView::fullScreenClientParentWindow() const
6781 return m_hostWindow;
6784 void WebView::fullScreenClientSetParentWindow(HWND hostWindow)
6786 setHostWindow(reinterpret_cast<OLE_HANDLE>(hostWindow));
6789 void WebView::fullScreenClientWillEnterFullScreen()
6791 ASSERT(m_fullScreenElement);
6792 m_fullScreenElement->document()->webkitWillEnterFullScreenForElement(m_fullScreenElement.get());
6795 void WebView::fullScreenClientDidEnterFullScreen()
6797 ASSERT(m_fullScreenElement);
6798 m_fullScreenElement->document()->webkitDidEnterFullScreenForElement(m_fullScreenElement.get());
6801 void WebView::fullScreenClientWillExitFullScreen()
6803 ASSERT(m_fullScreenElement);
6804 m_fullScreenElement->document()->webkitWillExitFullScreenForElement(m_fullScreenElement.get());
6807 void WebView::fullScreenClientDidExitFullScreen()
6809 ASSERT(m_fullScreenElement);
6810 m_fullScreenElement->document()->webkitDidExitFullScreenForElement(m_fullScreenElement.get());
6811 m_fullScreenElement = nullptr;
6814 void WebView::fullScreenClientForceRepaint()
6816 ASSERT(m_fullScreenElement);
6817 RECT windowRect = {0};
6818 frameRect(&windowRect);
6819 repaint(windowRect, true /*contentChanged*/, true /*immediate*/, false /*contentOnly*/);
6820 m_fullscreenController->repaintCompleted();