2 * Copyright (C) 2006, 2007, 2008 Apple, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "WebKitDLL.h"
30 #include "CFDictionaryPropertyBag.h"
31 #include "DOMCoreClasses.h"
32 #include "MarshallingHelpers.h"
33 #include "SoftLinking.h"
34 #include "WebBackForwardList.h"
35 #include "WebChromeClient.h"
36 #include "WebContextMenuClient.h"
37 #include "WebCoreTextRenderer.h"
38 #include "WebDatabaseManager.h"
39 #include "WebDocumentLoader.h"
40 #include "WebDownload.h"
41 #include "WebDragClient.h"
42 #include "WebEditorClient.h"
43 #include "WebElementPropertyBag.h"
45 #include "WebIconDatabase.h"
46 #include "WebInspector.h"
47 #include "WebInspectorClient.h"
49 #include "WebKitStatisticsPrivate.h"
50 #include "WebKitSystemBits.h"
51 #include "WebMutableURLRequest.h"
52 #include "WebNotificationCenter.h"
53 #include "WebPluginHalterClient.h"
54 #include "WebPreferences.h"
55 #include "WebScriptWorld.h"
56 #include "WindowsTouch.h"
57 #pragma warning( push, 0 )
58 #include <WebCore/ApplicationCacheStorage.h>
59 #include <WebCore/AXObjectCache.h>
60 #include <WebCore/BitmapInfo.h>
61 #include <WebCore/BString.h>
62 #include <WebCore/Cache.h>
63 #include <WebCore/ContextMenu.h>
64 #include <WebCore/ContextMenuController.h>
65 #include <WebCore/CookieStorageWin.h>
66 #include <WebCore/CString.h>
67 #include <WebCore/Cursor.h>
68 #include <WebCore/Document.h>
69 #include <WebCore/DragController.h>
70 #include <WebCore/DragData.h>
71 #include <WebCore/Editor.h>
72 #include <WebCore/EventHandler.h>
73 #include <WebCore/EventNames.h>
74 #include <WebCore/FileSystem.h>
75 #include <WebCore/FocusController.h>
76 #include <WebCore/FloatQuad.h>
77 #include <WebCore/FrameLoader.h>
78 #include <WebCore/FrameTree.h>
79 #include <WebCore/FrameView.h>
80 #include <WebCore/FrameWin.h>
81 #include <WebCore/GDIObjectCounter.h>
82 #include <WebCore/GraphicsContext.h>
83 #include <WebCore/HistoryItem.h>
84 #include <WebCore/HitTestRequest.h>
85 #include <WebCore/HitTestResult.h>
86 #include <WebCore/IntRect.h>
87 #include <WebCore/KeyboardEvent.h>
88 #include <WebCore/Language.h>
89 #include <WebCore/Logging.h>
90 #include <WebCore/MIMETypeRegistry.h>
91 #include <WebCore/Page.h>
92 #include <WebCore/PageCache.h>
93 #include <WebCore/PageGroup.h>
94 #include <WebCore/PlatformKeyboardEvent.h>
95 #include <WebCore/PlatformMouseEvent.h>
96 #include <WebCore/PlatformWheelEvent.h>
97 #include <WebCore/PluginDatabase.h>
98 #include <WebCore/PluginInfoStore.h>
99 #include <WebCore/PluginView.h>
100 #include <WebCore/PopupMenu.h>
101 #include <WebCore/ProgressTracker.h>
102 #include <WebCore/RenderTheme.h>
103 #include <WebCore/RenderView.h>
104 #include <WebCore/RenderWidget.h>
105 #include <WebCore/ResourceHandle.h>
106 #include <WebCore/ResourceHandleClient.h>
107 #include <WebCore/ScriptValue.h>
108 #include <WebCore/Scrollbar.h>
109 #include <WebCore/ScrollbarTheme.h>
110 #include <WebCore/SecurityOrigin.h>
111 #include <WebCore/SelectionController.h>
112 #include <WebCore/Settings.h>
113 #include <WebCore/SimpleFontData.h>
114 #include <WebCore/TypingCommand.h>
115 #include <WebCore/WindowMessageBroadcaster.h>
117 #include <JavaScriptCore/InitializeThreading.h>
118 #include <JavaScriptCore/JSLock.h>
119 #include <JavaScriptCore/JSValue.h>
122 #include <CoreGraphics/CGContext.h>
126 #include <CoreFoundation/CoreFoundation.h>
130 #include <CFNetwork/CFURLCachePriv.h>
131 #include <CFNetwork/CFURLProtocolPriv.h>
132 #include <WebKitSystemInterface/WebKitSystemInterface.h>
135 #include <wtf/HashSet.h>
141 #include <windowsx.h>
143 // Soft link functions for gestures and panning feedback
144 SOFT_LINK_LIBRARY(USER32);
145 SOFT_LINK_OPTIONAL(USER32, GetGestureInfo, BOOL, WINAPI, (HGESTUREINFO, PGESTUREINFO));
146 SOFT_LINK_OPTIONAL(USER32, SetGestureConfig, BOOL, WINAPI, (HWND, DWORD, UINT, PGESTURECONFIG, UINT));
147 SOFT_LINK_OPTIONAL(USER32, CloseGestureInfoHandle, BOOL, WINAPI, (HGESTUREINFO));
148 SOFT_LINK_LIBRARY(Uxtheme);
149 SOFT_LINK_OPTIONAL(Uxtheme, BeginPanningFeedback, BOOL, WINAPI, (HWND));
150 SOFT_LINK_OPTIONAL(Uxtheme, EndPanningFeedback, BOOL, WINAPI, (HWND, BOOL));
151 SOFT_LINK_OPTIONAL(Uxtheme, UpdatePanningFeedback, BOOL, WINAPI, (HWND, LONG, LONG, BOOL));
153 using namespace WebCore;
157 static HMODULE accessibilityLib;
158 static HashSet<WebView*> pendingDeleteBackingStoreSet;
160 static String osVersion();
161 static String webKitVersion();
163 WebView* kit(Page* page)
165 return page ? static_cast<WebChromeClient*>(page->chrome()->client())->webView() : 0;
168 class PreferencesChangedOrRemovedObserver : public IWebNotificationObserver {
170 static PreferencesChangedOrRemovedObserver* sharedInstance();
173 PreferencesChangedOrRemovedObserver() {}
174 ~PreferencesChangedOrRemovedObserver() {}
176 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) { return E_FAIL; }
177 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; }
178 virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; }
181 // IWebNotificationObserver
182 virtual HRESULT STDMETHODCALLTYPE onNotify(
183 /* [in] */ IWebNotification* notification);
186 HRESULT notifyPreferencesChanged(WebCacheModel);
187 HRESULT notifyPreferencesRemoved(WebCacheModel);
190 PreferencesChangedOrRemovedObserver* PreferencesChangedOrRemovedObserver::sharedInstance()
192 static PreferencesChangedOrRemovedObserver* shared = new PreferencesChangedOrRemovedObserver;
196 HRESULT PreferencesChangedOrRemovedObserver::onNotify(IWebNotification* notification)
200 COMPtr<IUnknown> unkPrefs;
201 hr = notification->getObject(&unkPrefs);
205 COMPtr<IWebPreferences> preferences(Query, unkPrefs);
207 return E_NOINTERFACE;
209 WebCacheModel cacheModel;
210 hr = preferences->cacheModel(&cacheModel);
215 hr = notification->name(&nameBSTR);
219 name.adoptBSTR(nameBSTR);
221 if (wcscmp(name, WebPreferences::webPreferencesChangedNotification()) == 0)
222 return notifyPreferencesChanged(cacheModel);
224 if (wcscmp(name, WebPreferences::webPreferencesRemovedNotification()) == 0)
225 return notifyPreferencesRemoved(cacheModel);
227 ASSERT_NOT_REACHED();
231 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesChanged(WebCacheModel cacheModel)
235 if (!WebView::didSetCacheModel() || cacheModel > WebView::cacheModel())
236 WebView::setCacheModel(cacheModel);
237 else if (cacheModel < WebView::cacheModel()) {
238 WebCacheModel sharedPreferencesCacheModel;
239 hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
242 WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
248 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesRemoved(WebCacheModel cacheModel)
252 if (cacheModel == WebView::cacheModel()) {
253 WebCacheModel sharedPreferencesCacheModel;
254 hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
257 WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
264 const LPCWSTR kWebViewWindowClassName = L"WebViewWindowClass";
266 const int WM_XP_THEMECHANGED = 0x031A;
267 const int WM_VISTA_MOUSEHWHEEL = 0x020E;
269 static const int maxToolTipWidth = 250;
271 static const int delayBeforeDeletingBackingStoreMsec = 5000;
273 static ATOM registerWebView();
274 static LRESULT CALLBACK WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
276 static void initializeStaticObservers();
278 static HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences*);
280 HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches);
282 static bool continuousSpellCheckingEnabled;
283 static bool grammarCheckingEnabled;
285 static bool s_didSetCacheModel;
286 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
289 UpdateActiveStateTimer = 1,
290 DeleteBackingStoreTimer = 2,
293 // WebView ----------------------------------------------------------------
295 bool WebView::s_allowSiteSpecificHacks = false;
303 , m_hasCustomDropTarget(false)
304 , m_useBackForwardList(true)
305 , m_userAgentOverridden(false)
306 , m_zoomMultiplier(1.0f)
307 , m_mouseActivated(false)
309 , m_currentCharacterCode(0)
310 , m_isBeingDestroyed(false)
312 , m_hasSpellCheckerDocumentTag(false)
313 , m_smartInsertDeleteEnabled(false)
315 , m_inIMEComposition(0)
317 , m_closeWindowTimer(this, &WebView::closeWindowTimerFired)
318 , m_topLevelParent(0)
319 , m_deleteBackingStoreTimerActive(false)
320 , m_transparent(false)
321 , m_selectTrailingWhitespaceEnabled(false)
326 #if USE(ACCELERATED_COMPOSITING)
327 , m_isAcceleratedCompositing(false)
330 JSC::initializeThreading();
332 m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
334 CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper,(void**)&m_dropTargetHelper);
336 initializeStaticObservers();
338 WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
340 if (SUCCEEDED(sharedPreferences->continuousSpellCheckingEnabled(&enabled)))
341 continuousSpellCheckingEnabled = !!enabled;
342 if (SUCCEEDED(sharedPreferences->grammarCheckingEnabled(&enabled)))
343 grammarCheckingEnabled = !!enabled;
347 gClassNameCount.add("WebView");
352 deleteBackingStore();
354 // <rdar://4958382> m_viewWindow will be destroyed when m_hostWindow is destroyed, but if
355 // setHostWindow was never called we will leak our HWND. If we still have a valid HWND at
356 // this point, we should just destroy it ourselves.
357 if (!isBeingDestroyed() && ::IsWindow(m_viewWindow))
358 ::DestroyWindow(m_viewWindow);
360 // the tooltip window needs to be explicitly destroyed since it isn't a WS_CHILD
361 if (::IsWindow(m_toolTipHwnd))
362 ::DestroyWindow(m_toolTipHwnd);
365 ASSERT(!m_preferences);
369 gClassNameCount.remove("WebView");
372 WebView* WebView::createInstance()
374 WebView* instance = new WebView();
379 void initializeStaticObservers()
381 static bool initialized;
386 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
387 notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesChangedNotification(), 0);
388 notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesRemovedNotification(), 0);
391 static HashSet<WebView*>& allWebViewsSet()
393 static HashSet<WebView*> allWebViewsSet;
394 return allWebViewsSet;
397 void WebView::addToAllWebViewsSet()
399 allWebViewsSet().add(this);
402 void WebView::removeFromAllWebViewsSet()
404 allWebViewsSet().remove(this);
407 void WebView::setCacheModel(WebCacheModel cacheModel)
410 if (s_didSetCacheModel && cacheModel == s_cacheModel)
413 RetainPtr<CFURLCacheRef> cfurlCache(AdoptCF, CFURLCacheCopySharedURLCache());
414 RetainPtr<CFStringRef> cfurlCacheDirectory(AdoptCF, wkCopyFoundationCacheDirectory());
415 if (!cfurlCacheDirectory)
416 cfurlCacheDirectory.adoptCF(WebCore::localUserSpecificStorageDirectory().createCFString());
418 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
419 // count doesn't align exactly to a megabyte boundary.
420 unsigned long long memSize = WebMemorySize() / 1024 / 1000;
421 unsigned long long diskFreeSize = WebVolumeFreeSize(cfurlCacheDirectory.get()) / 1024 / 1000;
423 unsigned cacheTotalCapacity = 0;
424 unsigned cacheMinDeadCapacity = 0;
425 unsigned cacheMaxDeadCapacity = 0;
426 double deadDecodedDataDeletionInterval = 0;
428 unsigned pageCacheCapacity = 0;
430 CFIndex cfurlCacheMemoryCapacity = 0;
431 CFIndex cfurlCacheDiskCapacity = 0;
433 switch (cacheModel) {
434 case WebCacheModelDocumentViewer: {
435 // Page cache capacity (in pages)
436 pageCacheCapacity = 0;
438 // Object cache capacities (in bytes)
440 cacheTotalCapacity = 96 * 1024 * 1024;
441 else if (memSize >= 1536)
442 cacheTotalCapacity = 64 * 1024 * 1024;
443 else if (memSize >= 1024)
444 cacheTotalCapacity = 32 * 1024 * 1024;
445 else if (memSize >= 512)
446 cacheTotalCapacity = 16 * 1024 * 1024;
448 cacheMinDeadCapacity = 0;
449 cacheMaxDeadCapacity = 0;
451 // Foundation memory cache capacity (in bytes)
452 cfurlCacheMemoryCapacity = 0;
454 // Foundation disk cache capacity (in bytes)
455 cfurlCacheDiskCapacity = CFURLCacheDiskCapacity(cfurlCache.get());
459 case WebCacheModelDocumentBrowser: {
460 // Page cache capacity (in pages)
462 pageCacheCapacity = 3;
463 else if (memSize >= 512)
464 pageCacheCapacity = 2;
465 else if (memSize >= 256)
466 pageCacheCapacity = 1;
468 pageCacheCapacity = 0;
470 // Object cache capacities (in bytes)
472 cacheTotalCapacity = 96 * 1024 * 1024;
473 else if (memSize >= 1536)
474 cacheTotalCapacity = 64 * 1024 * 1024;
475 else if (memSize >= 1024)
476 cacheTotalCapacity = 32 * 1024 * 1024;
477 else if (memSize >= 512)
478 cacheTotalCapacity = 16 * 1024 * 1024;
480 cacheMinDeadCapacity = cacheTotalCapacity / 8;
481 cacheMaxDeadCapacity = cacheTotalCapacity / 4;
483 // Foundation memory cache capacity (in bytes)
485 cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
486 else if (memSize >= 1024)
487 cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
488 else if (memSize >= 512)
489 cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
491 cfurlCacheMemoryCapacity = 512 * 1024;
493 // Foundation disk cache capacity (in bytes)
494 if (diskFreeSize >= 16384)
495 cfurlCacheDiskCapacity = 50 * 1024 * 1024;
496 else if (diskFreeSize >= 8192)
497 cfurlCacheDiskCapacity = 40 * 1024 * 1024;
498 else if (diskFreeSize >= 4096)
499 cfurlCacheDiskCapacity = 30 * 1024 * 1024;
501 cfurlCacheDiskCapacity = 20 * 1024 * 1024;
505 case WebCacheModelPrimaryWebBrowser: {
506 // Page cache capacity (in pages)
507 // (Research indicates that value / page drops substantially after 3 pages.)
509 pageCacheCapacity = 5;
510 else if (memSize >= 1024)
511 pageCacheCapacity = 4;
512 else if (memSize >= 512)
513 pageCacheCapacity = 3;
514 else if (memSize >= 256)
515 pageCacheCapacity = 2;
517 pageCacheCapacity = 1;
519 // Object cache capacities (in bytes)
520 // (Testing indicates that value / MB depends heavily on content and
521 // browsing pattern. Even growth above 128MB can have substantial
522 // value / MB for some content / browsing patterns.)
524 cacheTotalCapacity = 128 * 1024 * 1024;
525 else if (memSize >= 1536)
526 cacheTotalCapacity = 96 * 1024 * 1024;
527 else if (memSize >= 1024)
528 cacheTotalCapacity = 64 * 1024 * 1024;
529 else if (memSize >= 512)
530 cacheTotalCapacity = 32 * 1024 * 1024;
532 cacheMinDeadCapacity = cacheTotalCapacity / 4;
533 cacheMaxDeadCapacity = cacheTotalCapacity / 2;
535 // This code is here to avoid a PLT regression. We can remove it if we
536 // can prove that the overall system gain would justify the regression.
537 cacheMaxDeadCapacity = max(24u, cacheMaxDeadCapacity);
539 deadDecodedDataDeletionInterval = 60;
541 // Foundation memory cache capacity (in bytes)
542 // (These values are small because WebCore does most caching itself.)
544 cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
545 else if (memSize >= 512)
546 cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
547 else if (memSize >= 256)
548 cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
550 cfurlCacheMemoryCapacity = 512 * 1024;
552 // Foundation disk cache capacity (in bytes)
553 if (diskFreeSize >= 16384)
554 cfurlCacheDiskCapacity = 175 * 1024 * 1024;
555 else if (diskFreeSize >= 8192)
556 cfurlCacheDiskCapacity = 150 * 1024 * 1024;
557 else if (diskFreeSize >= 4096)
558 cfurlCacheDiskCapacity = 125 * 1024 * 1024;
559 else if (diskFreeSize >= 2048)
560 cfurlCacheDiskCapacity = 100 * 1024 * 1024;
561 else if (diskFreeSize >= 1024)
562 cfurlCacheDiskCapacity = 75 * 1024 * 1024;
564 cfurlCacheDiskCapacity = 50 * 1024 * 1024;
569 ASSERT_NOT_REACHED();
572 // Don't shrink a big disk cache, since that would cause churn.
573 cfurlCacheDiskCapacity = max(cfurlCacheDiskCapacity, CFURLCacheDiskCapacity(cfurlCache.get()));
575 cache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
576 cache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
577 pageCache()->setCapacity(pageCacheCapacity);
579 CFURLCacheSetMemoryCapacity(cfurlCache.get(), cfurlCacheMemoryCapacity);
580 CFURLCacheSetDiskCapacity(cfurlCache.get(), cfurlCacheDiskCapacity);
582 s_didSetCacheModel = true;
583 s_cacheModel = cacheModel;
588 WebCacheModel WebView::cacheModel()
593 bool WebView::didSetCacheModel()
595 return s_didSetCacheModel;
598 WebCacheModel WebView::maxCacheModelInAnyInstance()
600 WebCacheModel cacheModel = WebCacheModelDocumentViewer;
602 HashSet<WebView*>::iterator end = allWebViewsSet().end();
603 for (HashSet<WebView*>::iterator it = allWebViewsSet().begin(); it != end; ++it) {
604 COMPtr<IWebPreferences> pref;
605 if (FAILED((*it)->preferences(&pref)))
607 WebCacheModel prefCacheModel = WebCacheModelDocumentViewer;
608 if (FAILED(pref->cacheModel(&prefCacheModel)))
611 cacheModel = max(cacheModel, prefCacheModel);
617 HRESULT STDMETHODCALLTYPE WebView::close()
624 #if USE(ACCELERATED_COMPOSITING)
625 setAcceleratedCompositing(false);
628 WebNotificationCenter::defaultCenterInternal()->postNotificationName(_bstr_t(WebViewWillCloseNotification).GetBSTR(), static_cast<IWebView*>(this), 0);
630 if (m_uiDelegatePrivate)
631 m_uiDelegatePrivate->webViewClosing(this);
633 removeFromAllWebViewsSet();
635 Frame* frame = m_page->mainFrame();
637 frame->loader()->detachFromParent();
639 if (m_mouseOutTracker) {
640 m_mouseOutTracker->dwFlags = TME_CANCEL;
641 ::TrackMouseEvent(m_mouseOutTracker.get());
642 m_mouseOutTracker.set(0);
647 setDownloadDelegate(0);
648 setEditingDelegate(0);
649 setFrameLoadDelegate(0);
650 setFrameLoadDelegatePrivate(0);
651 setHistoryDelegate(0);
652 setPolicyDelegate(0);
653 setResourceLoadDelegate(0);
656 setPluginHalterDelegate(0);
659 m_webInspector->webViewClosed();
664 registerForIconNotification(false);
665 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
666 notifyCenter->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
669 m_preferences->identifier(&identifier);
671 COMPtr<WebPreferences> preferences = m_preferences;
673 preferences->didRemoveFromWebView();
674 // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
677 WebPreferences::removeReferenceForIdentifier(identifier);
678 SysFreeString(identifier);
681 deleteBackingStore();
685 void WebView::repaint(const WebCore::IntRect& windowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
687 #if USE(ACCELERATED_COMPOSITING)
688 if (isAcceleratedCompositing())
689 setRootLayerNeedsDisplay();
692 if (!repaintContentOnly) {
693 RECT rect = windowRect;
694 ::InvalidateRect(m_viewWindow, &rect, false);
697 addToDirtyRegion(windowRect);
699 if (repaintContentOnly)
700 updateBackingStore(core(topLevelFrame())->view());
702 ::UpdateWindow(m_viewWindow);
706 void WebView::deleteBackingStore()
708 pendingDeleteBackingStoreSet.remove(this);
710 if (m_deleteBackingStoreTimerActive) {
711 KillTimer(m_viewWindow, DeleteBackingStoreTimer);
712 m_deleteBackingStoreTimerActive = false;
714 m_backingStoreBitmap.clear();
715 m_backingStoreDirtyRegion.clear();
717 m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
720 bool WebView::ensureBackingStore()
723 ::GetClientRect(m_viewWindow, &windowRect);
724 LONG width = windowRect.right - windowRect.left;
725 LONG height = windowRect.bottom - windowRect.top;
726 if (width > 0 && height > 0 && (width != m_backingStoreSize.cx || height != m_backingStoreSize.cy)) {
727 deleteBackingStore();
729 m_backingStoreSize.cx = width;
730 m_backingStoreSize.cy = height;
731 BitmapInfo bitmapInfo = BitmapInfo::createBottomUp(IntSize(m_backingStoreSize));
734 m_backingStoreBitmap.set(::CreateDIBSection(NULL, &bitmapInfo, DIB_RGB_COLORS, &pixels, NULL, 0));
741 void WebView::addToDirtyRegion(const IntRect& dirtyRect)
743 // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
744 // but it was being hit during our layout tests, and is being investigated in
745 // http://webkit.org/b/29350.
747 HRGN newRegion = ::CreateRectRgn(dirtyRect.x(), dirtyRect.y(),
748 dirtyRect.right(), dirtyRect.bottom());
749 addToDirtyRegion(newRegion);
752 void WebView::addToDirtyRegion(HRGN newRegion)
754 LOCAL_GDI_COUNTER(0, __FUNCTION__);
756 if (m_backingStoreDirtyRegion) {
757 HRGN combinedRegion = ::CreateRectRgn(0,0,0,0);
758 ::CombineRgn(combinedRegion, m_backingStoreDirtyRegion.get(), newRegion, RGN_OR);
759 ::DeleteObject(newRegion);
760 m_backingStoreDirtyRegion.set(combinedRegion);
762 m_backingStoreDirtyRegion.set(newRegion);
764 if (m_uiDelegatePrivate)
765 m_uiDelegatePrivate->webViewDidInvalidate(this);
768 void WebView::scrollBackingStore(FrameView* frameView, int dx, int dy, const IntRect& scrollViewRect, const IntRect& clipRect)
770 LOCAL_GDI_COUNTER(0, __FUNCTION__);
772 // If there's no backing store we don't need to update it
773 if (!m_backingStoreBitmap) {
774 if (m_uiDelegatePrivate)
775 m_uiDelegatePrivate->webViewScrolled(this);
780 // Make a region to hold the invalidated scroll area.
781 HRGN updateRegion = ::CreateRectRgn(0, 0, 0, 0);
783 // Collect our device context info and select the bitmap to scroll.
784 HDC windowDC = ::GetDC(m_viewWindow);
785 HDC bitmapDC = ::CreateCompatibleDC(windowDC);
786 ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
788 // Scroll the bitmap.
789 RECT scrollRectWin(scrollViewRect);
790 RECT clipRectWin(clipRect);
791 ::ScrollDC(bitmapDC, dx, dy, &scrollRectWin, &clipRectWin, updateRegion, 0);
793 ::GetRgnBox(updateRegion, ®ionBox);
798 // Add the dirty region to the backing store's dirty region.
799 addToDirtyRegion(updateRegion);
801 if (m_uiDelegatePrivate)
802 m_uiDelegatePrivate->webViewScrolled(this);
804 // Update the backing store.
805 updateBackingStore(frameView, bitmapDC, false);
808 ::DeleteDC(bitmapDC);
809 ::ReleaseDC(m_viewWindow, windowDC);
812 // This emulates the Mac smarts for painting rects intelligently. This is very
813 // important for us, since we double buffer based off dirty rects.
814 static void getUpdateRects(HRGN region, const IntRect& dirtyRect, Vector<IntRect>& rects)
816 ASSERT_ARG(region, region);
818 const int cRectThreshold = 10;
819 const float cWastedSpaceThreshold = 0.75f;
823 DWORD regionDataSize = GetRegionData(region, sizeof(RGNDATA), NULL);
824 if (!regionDataSize) {
825 rects.append(dirtyRect);
829 Vector<unsigned char> buffer(regionDataSize);
830 RGNDATA* regionData = reinterpret_cast<RGNDATA*>(buffer.data());
831 GetRegionData(region, regionDataSize, regionData);
832 if (regionData->rdh.nCount > cRectThreshold) {
833 rects.append(dirtyRect);
837 double singlePixels = 0.0;
840 for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
841 singlePixels += (rect->right - rect->left) * (rect->bottom - rect->top);
843 double unionPixels = dirtyRect.width() * dirtyRect.height();
844 double wastedSpace = 1.0 - (singlePixels / unionPixels);
845 if (wastedSpace <= cWastedSpaceThreshold) {
846 rects.append(dirtyRect);
850 for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
854 void WebView::updateBackingStore(FrameView* frameView, HDC dc, bool backingStoreCompletelyDirty, WindowsToPaint windowsToPaint)
856 LOCAL_GDI_COUNTER(0, __FUNCTION__);
861 windowDC = ::GetDC(m_viewWindow);
862 bitmapDC = ::CreateCompatibleDC(windowDC);
863 ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
866 if (m_backingStoreBitmap && (m_backingStoreDirtyRegion || backingStoreCompletelyDirty)) {
867 // Do a layout first so that everything we render to the backing store is always current.
868 if (Frame* coreFrame = core(m_mainFrame))
869 if (FrameView* view = coreFrame->view())
870 view->layoutIfNeededRecursive();
872 Vector<IntRect> paintRects;
873 if (!backingStoreCompletelyDirty) {
875 ::GetRgnBox(m_backingStoreDirtyRegion.get(), ®ionBox);
876 getUpdateRects(m_backingStoreDirtyRegion.get(), regionBox, paintRects);
879 ::GetClientRect(m_viewWindow, &clientRect);
880 paintRects.append(clientRect);
883 for (unsigned i = 0; i < paintRects.size(); ++i)
884 paintIntoBackingStore(frameView, bitmapDC, paintRects[i], windowsToPaint);
886 if (m_uiDelegatePrivate)
887 m_uiDelegatePrivate->webViewPainted(this);
889 m_backingStoreDirtyRegion.clear();
893 ::DeleteDC(bitmapDC);
894 ::ReleaseDC(m_viewWindow, windowDC);
900 void WebView::paint(HDC dc, LPARAM options)
902 LOCAL_GDI_COUNTER(0, __FUNCTION__);
904 Frame* coreFrame = core(m_mainFrame);
907 FrameView* frameView = coreFrame->view();
914 int regionType = NULLREGION;
916 WindowsToPaint windowsToPaint;
918 region.set(CreateRectRgn(0,0,0,0));
919 regionType = GetUpdateRgn(m_viewWindow, region.get(), false);
920 hdc = BeginPaint(m_viewWindow, &ps);
921 rcPaint = ps.rcPaint;
922 // We're painting to the screen, and our child windows can handle
923 // painting themselves to the screen.
924 windowsToPaint = PaintWebViewOnly;
927 ::GetClientRect(m_viewWindow, &rcPaint);
928 if (options & PRF_ERASEBKGND)
929 ::FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
930 // Since we aren't painting to the screen, we want to paint all our
931 // children into the HDC.
932 windowsToPaint = PaintWebViewAndChildren;
935 HDC bitmapDC = ::CreateCompatibleDC(hdc);
936 bool backingStoreCompletelyDirty = ensureBackingStore();
937 ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
939 // Update our backing store if needed.
940 updateBackingStore(frameView, bitmapDC, backingStoreCompletelyDirty, windowsToPaint);
942 #if USE(ACCELERATED_COMPOSITING)
943 if (!isAcceleratedCompositing()) {
945 // Now we blit the updated backing store
946 IntRect windowDirtyRect = rcPaint;
948 // Apply the same heuristic for this update region too.
949 Vector<IntRect> blitRects;
950 if (region && regionType == COMPLEXREGION)
951 getUpdateRects(region.get(), windowDirtyRect, blitRects);
953 blitRects.append(windowDirtyRect);
955 for (unsigned i = 0; i < blitRects.size(); ++i)
956 paintIntoWindow(bitmapDC, hdc, blitRects[i]);
957 #if USE(ACCELERATED_COMPOSITING)
959 updateRootLayerContents();
962 ::DeleteDC(bitmapDC);
965 EndPaint(m_viewWindow, &ps);
970 cancelDeleteBackingStoreSoon();
972 deleteBackingStoreSoon();
975 void WebView::paintIntoBackingStore(FrameView* frameView, HDC bitmapDC, const IntRect& dirtyRect, WindowsToPaint windowsToPaint)
977 LOCAL_GDI_COUNTER(0, __FUNCTION__);
979 // FIXME: We want an assert here saying that the dirtyRect is inside the clienRect,
980 // but it was being hit during our layout tests, and is being investigated in
981 // http://webkit.org/b/29350.
983 RECT rect = dirtyRect;
985 #if FLASH_BACKING_STORE_REDRAW
986 HDC dc = ::GetDC(m_viewWindow);
987 OwnPtr<HBRUSH> yellowBrush = CreateSolidBrush(RGB(255, 255, 0));
988 FillRect(dc, &rect, yellowBrush.get());
991 paintIntoWindow(bitmapDC, dc, dirtyRect);
992 ::ReleaseDC(m_viewWindow, dc);
995 GraphicsContext gc(bitmapDC, m_transparent);
996 gc.setShouldIncludeChildWindows(windowsToPaint == PaintWebViewAndChildren);
999 gc.clearRect(dirtyRect);
1001 FillRect(bitmapDC, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
1003 COMPtr<IWebUIDelegatePrivate2> uiPrivate(Query, m_uiDelegate);
1005 uiPrivate->drawBackground(this, reinterpret_cast<OLE_HANDLE>(bitmapDC), &rect);
1007 if (frameView && frameView->frame() && frameView->frame()->contentRenderer()) {
1009 frameView->paint(&gc, dirtyRect);
1014 void WebView::paintIntoWindow(HDC bitmapDC, HDC windowDC, const IntRect& dirtyRect)
1016 LOCAL_GDI_COUNTER(0, __FUNCTION__);
1017 #if FLASH_WINDOW_REDRAW
1018 OwnPtr<HBRUSH> greenBrush = CreateSolidBrush(RGB(0, 255, 0));
1019 RECT rect = dirtyRect;
1020 FillRect(windowDC, &rect, greenBrush.get());
1025 // Blit the dirty rect from the backing store into the same position
1026 // in the destination DC.
1027 BitBlt(windowDC, dirtyRect.x(), dirtyRect.y(), dirtyRect.width(), dirtyRect.height(), bitmapDC,
1028 dirtyRect.x(), dirtyRect.y(), SRCCOPY);
1031 void WebView::frameRect(RECT* rect)
1033 ::GetWindowRect(m_viewWindow, rect);
1036 void WebView::closeWindowSoon()
1038 m_closeWindowTimer.startOneShot(0);
1042 void WebView::closeWindowTimerFired(WebCore::Timer<WebView>*)
1048 void WebView::closeWindow()
1050 if (m_hasSpellCheckerDocumentTag) {
1051 if (m_editingDelegate)
1052 m_editingDelegate->closeSpellDocument(this);
1053 m_hasSpellCheckerDocumentTag = false;
1056 COMPtr<IWebUIDelegate> ui;
1057 if (SUCCEEDED(uiDelegate(&ui)))
1058 ui->webViewClose(this);
1061 bool WebView::canHandleRequest(const WebCore::ResourceRequest& request)
1063 // On the mac there's an about url protocol implementation but CFNetwork doesn't have that.
1064 if (equalIgnoringCase(String(request.url().protocol()), "about"))
1068 if (CFURLProtocolCanHandleRequest(request.cfURLRequest()))
1071 // FIXME: Mac WebKit calls _representationExistsForURLScheme here
1078 String WebView::standardUserAgentWithApplicationName(const String& applicationName)
1080 return String::format("Mozilla/5.0 (Windows; U; %s; %s) AppleWebKit/%s (KHTML, like Gecko)%s%s", osVersion().latin1().data(), defaultLanguage().latin1().data(), webKitVersion().latin1().data(), (applicationName.length() ? " " : ""), applicationName.latin1().data());
1083 Page* WebView::page()
1088 bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam)
1090 static const int contextMenuMargin = 1;
1092 // Translate the screen coordinates into window coordinates
1093 POINT coords = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
1094 if (coords.x == -1 || coords.y == -1) {
1095 FrameView* view = m_page->mainFrame()->view();
1099 int rightAligned = ::GetSystemMetrics(SM_MENUDROPALIGNMENT);
1102 // The context menu event was generated from the keyboard, so show the context menu by the current selection.
1103 Position start = m_page->mainFrame()->selection()->selection().start();
1104 Position end = m_page->mainFrame()->selection()->selection().end();
1106 if (!start.node() || !end.node())
1107 location = IntPoint(rightAligned ? view->contentsWidth() - contextMenuMargin : contextMenuMargin, contextMenuMargin);
1109 RenderObject* renderer = start.node()->renderer();
1113 // Calculate the rect of the first line of the selection (cribbed from -[WebCoreFrameBridge firstRectForDOMRange:],
1114 // now Frame::firstRectForRange(), which perhaps this should call).
1115 int extraWidthToEndOfLine = 0;
1117 InlineBox* startInlineBox;
1118 int startCaretOffset;
1119 start.getInlineBoxAndOffset(DOWNSTREAM, startInlineBox, startCaretOffset);
1120 IntRect startCaretRect = renderer->localCaretRect(startInlineBox, startCaretOffset, &extraWidthToEndOfLine);
1121 if (startCaretRect != IntRect())
1122 startCaretRect = renderer->localToAbsoluteQuad(FloatRect(startCaretRect)).enclosingBoundingBox();
1124 InlineBox* endInlineBox;
1126 end.getInlineBoxAndOffset(UPSTREAM, endInlineBox, endCaretOffset);
1127 IntRect endCaretRect = renderer->localCaretRect(endInlineBox, endCaretOffset);
1128 if (endCaretRect != IntRect())
1129 endCaretRect = renderer->localToAbsoluteQuad(FloatRect(endCaretRect)).enclosingBoundingBox();
1132 if (startCaretRect.y() == endCaretRect.y())
1133 firstRect = IntRect(min(startCaretRect.x(), endCaretRect.x()), startCaretRect.y(), abs(endCaretRect.x() - startCaretRect.x()), max(startCaretRect.height(), endCaretRect.height()));
1135 firstRect = IntRect(startCaretRect.x(), startCaretRect.y(), startCaretRect.width() + extraWidthToEndOfLine, startCaretRect.height());
1137 location = IntPoint(rightAligned ? firstRect.right() : firstRect.x(), firstRect.bottom());
1140 location = view->contentsToWindow(location);
1141 // FIXME: The IntSize(0, -1) is a hack to get the hit-testing to result in the selected element.
1142 // Ideally we'd have the position of a context menu event be separate from its target node.
1143 coords = location + IntSize(0, -1);
1145 if (!::ScreenToClient(m_viewWindow, &coords))
1149 lParam = MAKELPARAM(coords.x, coords.y);
1151 // The contextMenuController() holds onto the last context menu that was popped up on the
1152 // page until a new one is created. We need to clear this menu before propagating the event
1153 // through the DOM so that we can detect if we create a new menu for this event, since we
1154 // won't create a new menu if the DOM swallows the event and the defaultEventHandler does
1156 m_page->contextMenuController()->clearContextMenu();
1158 IntPoint documentPoint(m_page->mainFrame()->view()->windowToContents(coords));
1159 HitTestResult result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(documentPoint, false);
1160 Frame* targetFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : m_page->focusController()->focusedOrMainFrame();
1162 targetFrame->view()->setCursor(pointerCursor());
1163 PlatformMouseEvent mouseEvent(m_viewWindow, WM_RBUTTONUP, wParam, lParam);
1164 bool handledEvent = targetFrame->eventHandler()->sendContextMenuEvent(mouseEvent);
1169 ContextMenu* coreMenu = m_page->contextMenuController()->contextMenu();
1173 Node* node = coreMenu->hitTestResult().innerNonSharedNode();
1177 Frame* frame = node->document()->frame();
1181 FrameView* view = frame->view();
1185 POINT point(view->contentsToWindow(coreMenu->hitTestResult().point()));
1187 // Translate the point to screen coordinates
1188 if (!::ClientToScreen(m_viewWindow, &point))
1191 BOOL hasCustomMenus = false;
1193 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1196 m_uiDelegate->trackCustomPopupMenu((IWebView*)this, (OLE_HANDLE)(ULONG64)coreMenu->platformDescription(), &point);
1198 // Surprisingly, TPM_RIGHTBUTTON means that items are selectable with either the right OR left mouse button
1199 UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL
1200 | TPM_LEFTALIGN | TPM_HORPOSANIMATION;
1201 ::TrackPopupMenuEx(coreMenu->platformDescription(), flags, point.x, point.y, m_viewWindow, 0);
1207 bool WebView::onMeasureItem(WPARAM /*wParam*/, LPARAM lParam)
1212 BOOL hasCustomMenus = false;
1213 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1214 if (!hasCustomMenus)
1217 m_uiDelegate->measureCustomMenuItem((IWebView*)this, (void*)lParam);
1221 bool WebView::onDrawItem(WPARAM /*wParam*/, LPARAM lParam)
1226 BOOL hasCustomMenus = false;
1227 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1228 if (!hasCustomMenus)
1231 m_uiDelegate->drawCustomMenuItem((IWebView*)this, (void*)lParam);
1235 bool WebView::onInitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1240 HMENU menu = (HMENU)wParam;
1244 BOOL hasCustomMenus = false;
1245 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1246 if (!hasCustomMenus)
1249 m_uiDelegate->addCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1253 bool WebView::onUninitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1258 HMENU menu = (HMENU)wParam;
1262 BOOL hasCustomMenus = false;
1263 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1264 if (!hasCustomMenus)
1267 m_uiDelegate->cleanUpCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1271 void WebView::performContextMenuAction(WPARAM wParam, LPARAM lParam, bool byPosition)
1273 ContextMenu* menu = m_page->contextMenuController()->contextMenu();
1276 ContextMenuItem* item = byPosition ? menu->itemAtIndex((unsigned)wParam, (HMENU)lParam) : menu->itemWithAction((ContextMenuAction)wParam);
1279 m_page->contextMenuController()->contextMenuItemSelected(item);
1283 bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
1285 static LONG globalClickCount;
1286 static IntPoint globalPrevPoint;
1287 static MouseButton globalPrevButton;
1288 static LONG globalPrevMouseDownTime;
1290 // Create our event.
1291 // On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
1292 // of the event to be at (MINSHORT, MINSHORT).
1293 LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
1294 PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
1296 bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.pos().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
1297 abs(globalPrevPoint.y() - mouseEvent.pos().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
1298 LONG messageTime = ::GetMessageTime();
1300 bool handled = false;
1302 if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
1303 // FIXME: I'm not sure if this is the "right" way to do this
1304 // but without this call, we never become focused since we don't allow
1305 // the default handling of mouse events.
1306 SetFocus(m_viewWindow);
1308 // Always start capturing events when the mouse goes down in our HWND.
1309 ::SetCapture(m_viewWindow);
1311 if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) &&
1313 mouseEvent.button() == globalPrevButton)
1316 // Reset the click count.
1317 globalClickCount = 1;
1318 globalPrevMouseDownTime = messageTime;
1319 globalPrevButton = mouseEvent.button();
1320 globalPrevPoint = mouseEvent.pos();
1322 mouseEvent.setClickCount(globalClickCount);
1323 handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1324 } else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
1326 mouseEvent.setClickCount(globalClickCount);
1327 handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1328 } else if (message == WM_LBUTTONUP || message == WM_MBUTTONUP || message == WM_RBUTTONUP) {
1329 // Record the global position and the button of the up.
1330 globalPrevButton = mouseEvent.button();
1331 globalPrevPoint = mouseEvent.pos();
1332 mouseEvent.setClickCount(globalClickCount);
1333 m_page->mainFrame()->eventHandler()->handleMouseReleaseEvent(mouseEvent);
1335 } else if (message == WM_MOUSELEAVE && m_mouseOutTracker) {
1336 // Once WM_MOUSELEAVE is fired windows clears this tracker
1337 // so there is no need to disable it ourselves.
1338 m_mouseOutTracker.set(0);
1339 m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1341 } else if (message == WM_MOUSEMOVE) {
1342 if (!insideThreshold)
1343 globalClickCount = 0;
1344 mouseEvent.setClickCount(globalClickCount);
1345 handled = m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1346 if (!m_mouseOutTracker) {
1347 m_mouseOutTracker.set(new TRACKMOUSEEVENT);
1348 m_mouseOutTracker->cbSize = sizeof(TRACKMOUSEEVENT);
1349 m_mouseOutTracker->dwFlags = TME_LEAVE;
1350 m_mouseOutTracker->hwndTrack = m_viewWindow;
1351 ::TrackMouseEvent(m_mouseOutTracker.get());
1354 setMouseActivated(false);
1358 bool WebView::gestureNotify(WPARAM wParam, LPARAM lParam)
1360 GESTURENOTIFYSTRUCT* gn = reinterpret_cast<GESTURENOTIFYSTRUCT*>(lParam);
1362 Frame* coreFrame = core(m_mainFrame);
1366 ScrollView* view = coreFrame->view();
1370 // If we don't have this function, we shouldn't be receiving this message
1371 ASSERT(SetGestureConfigPtr());
1373 bool hitScrollbar = false;
1374 POINT gestureBeginPoint = {gn->ptsLocation.x, gn->ptsLocation.y};
1375 HitTestRequest request(HitTestRequest::ReadOnly);
1376 for (Frame* childFrame = m_page->mainFrame(); childFrame; childFrame = EventHandler::subframeForTargetNode(m_gestureTargetNode.get())) {
1377 FrameView* frameView = childFrame->view();
1380 RenderView* renderView = childFrame->document()->renderView();
1383 RenderLayer* layer = renderView->layer();
1387 HitTestResult result(frameView->screenToContents(gestureBeginPoint));
1388 layer->hitTest(request, result);
1389 m_gestureTargetNode = result.innerNode();
1392 hitScrollbar = result.scrollbar();
1395 if (!hitScrollbar) {
1396 // The hit testing above won't detect if we've hit the main frame's vertical scrollbar. Check that manually now.
1398 GetWindowRect(m_viewWindow, &webViewRect);
1399 hitScrollbar = view->verticalScrollbar() && (gestureBeginPoint.x > (webViewRect.right - view->verticalScrollbar()->theme()->scrollbarThickness()));
1402 bool canBeScrolled = false;
1403 if (m_gestureTargetNode) {
1404 for (RenderObject* renderer = m_gestureTargetNode->renderer(); renderer; renderer = renderer->parent()) {
1405 if (renderer->isBox() && toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()) {
1406 canBeScrolled = true;
1412 // We always allow two-fingered panning with inertia and a gutter (which limits movement to one
1413 // direction in most cases).
1414 DWORD dwPanWant = GC_PAN | GC_PAN_WITH_INERTIA | GC_PAN_WITH_GUTTER;
1415 // We never allow single-fingered horizontal panning. That gesture is reserved for creating text
1416 // selections. This matches IE.
1417 DWORD dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
1419 if (hitScrollbar || !canBeScrolled) {
1420 // The part of the page under the gesture can't be scrolled, or the gesture is on a scrollbar.
1421 // Disallow single-fingered vertical panning in this case, too, so we'll fall back to the default
1422 // behavior (which allows the scrollbar thumb to be dragged, text selections to be made, etc.).
1423 dwPanBlock |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
1425 // The part of the page the gesture is under can be scrolled, and we're not under a scrollbar.
1426 // Allow single-fingered vertical panning in this case, so the user will be able to pan the page
1427 // with one or two fingers.
1428 dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
1431 GESTURECONFIG gc = { GID_PAN, dwPanWant, dwPanBlock };
1432 return SetGestureConfigPtr()(m_viewWindow, 0, 1, &gc, sizeof(GESTURECONFIG));
1435 bool WebView::gesture(WPARAM wParam, LPARAM lParam)
1437 // We want to bail out if we don't have either of these functions
1438 if (!GetGestureInfoPtr() || !CloseGestureInfoHandlePtr())
1441 HGESTUREINFO gestureHandle = reinterpret_cast<HGESTUREINFO>(lParam);
1443 GESTUREINFO gi = {0};
1444 gi.cbSize = sizeof(GESTUREINFO);
1446 if (!GetGestureInfoPtr()(gestureHandle, reinterpret_cast<PGESTUREINFO>(&gi)))
1451 m_lastPanX = gi.ptsLocation.x;
1452 m_lastPanY = gi.ptsLocation.y;
1456 m_gestureTargetNode = 0;
1459 // Where are the fingers currently?
1460 long currentX = gi.ptsLocation.x;
1461 long currentY = gi.ptsLocation.y;
1462 // How far did we pan in each direction?
1463 long deltaX = currentX - m_lastPanX;
1464 long deltaY = currentY - m_lastPanY;
1465 // Calculate the overpan for window bounce
1466 m_yOverpan -= m_lastPanY - currentY;
1467 m_xOverpan -= m_lastPanX - currentX;
1468 // Update our class variables with updated values
1469 m_lastPanX = currentX;
1470 m_lastPanY = currentY;
1472 Frame* coreFrame = core(m_mainFrame);
1474 CloseGestureInfoHandlePtr()(gestureHandle);
1478 if (!m_gestureTargetNode || !m_gestureTargetNode->renderer())
1481 // We negate here since panning up moves the content up, but moves the scrollbar down.
1482 m_gestureTargetNode->renderer()->enclosingLayer()->scrollByRecursively(-deltaX, -deltaY);
1484 if (!(UpdatePanningFeedbackPtr() && BeginPanningFeedbackPtr() && EndPanningFeedbackPtr())) {
1485 CloseGestureInfoHandlePtr()(gestureHandle);
1489 if (gi.dwFlags & GF_BEGIN) {
1490 BeginPanningFeedbackPtr()(m_viewWindow);
1492 } else if (gi.dwFlags & GF_END) {
1493 EndPanningFeedbackPtr()(m_viewWindow, true);
1497 ScrollView* view = coreFrame->view();
1499 CloseGestureInfoHandlePtr()(gestureHandle);
1502 Scrollbar* vertScrollbar = view->verticalScrollbar();
1503 if (!vertScrollbar) {
1504 CloseGestureInfoHandlePtr()(gestureHandle);
1508 // FIXME: Support Horizontal Window Bounce. <https://webkit.org/b/28500>.
1509 // FIXME: If the user starts panning down after a window bounce has started, the window doesn't bounce back
1510 // until they release their finger. <https://webkit.org/b/28501>.
1511 if (vertScrollbar->currentPos() == 0)
1512 UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
1513 else if (vertScrollbar->currentPos() >= vertScrollbar->maximum())
1514 UpdatePanningFeedbackPtr()(m_viewWindow, 0, m_yOverpan, gi.dwFlags & GF_INERTIA);
1516 CloseGestureInfoHandlePtr()(gestureHandle);
1523 // If we get to this point, the gesture has not been handled. We forward
1524 // the call to DefWindowProc by returning false, and we don't need to
1525 // to call CloseGestureInfoHandle.
1526 // http://msdn.microsoft.com/en-us/library/dd353228(VS.85).aspx
1530 bool WebView::mouseWheel(WPARAM wParam, LPARAM lParam, bool isMouseHWheel)
1532 // Ctrl+Mouse wheel doesn't ever go into WebCore. It is used to
1533 // zoom instead (Mac zooms the whole Desktop, but Windows browsers trigger their
1534 // own local zoom modes for Ctrl+wheel).
1535 if (wParam & MK_CONTROL) {
1536 short delta = short(HIWORD(wParam));
1544 // 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.
1545 HWND focusedWindow = GetFocus();
1546 if (focusedWindow && focusedWindow != m_viewWindow) {
1547 // 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).
1548 TCHAR className[256];
1550 // Make sure truncation won't affect the comparison.
1551 ASSERT(ARRAYSIZE(className) > _tcslen(PopupMenu::popupClassName()));
1553 if (GetClassName(focusedWindow, className, ARRAYSIZE(className)) && !_tcscmp(className, PopupMenu::popupClassName())) {
1554 // We don't let the WebView scroll here for two reasons - 1) To match Firefox behavior, 2) If we do scroll, we lose the
1555 // focus ring around the select menu.
1556 SetFocus(m_viewWindow);
1561 PlatformWheelEvent wheelEvent(m_viewWindow, wParam, lParam, isMouseHWheel);
1562 Frame* coreFrame = core(m_mainFrame);
1566 return coreFrame->eventHandler()->handleWheelEvent(wheelEvent);
1569 bool WebView::execCommand(WPARAM wParam, LPARAM /*lParam*/)
1571 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1572 switch (LOWORD(wParam)) {
1574 return frame->editor()->command("SelectAll").execute();
1576 return frame->editor()->command("Undo").execute();
1578 return frame->editor()->command("Redo").execute();
1583 bool WebView::keyUp(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1585 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::KeyUp, systemKeyDown);
1587 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1588 m_currentCharacterCode = 0;
1590 return frame->eventHandler()->keyEvent(keyEvent);
1593 static const unsigned CtrlKey = 1 << 0;
1594 static const unsigned AltKey = 1 << 1;
1595 static const unsigned ShiftKey = 1 << 2;
1598 struct KeyDownEntry {
1599 unsigned virtualKey;
1604 struct KeyPressEntry {
1610 static const KeyDownEntry keyDownEntries[] = {
1611 { VK_LEFT, 0, "MoveLeft" },
1612 { VK_LEFT, ShiftKey, "MoveLeftAndModifySelection" },
1613 { VK_LEFT, CtrlKey, "MoveWordLeft" },
1614 { VK_LEFT, CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection" },
1615 { VK_RIGHT, 0, "MoveRight" },
1616 { VK_RIGHT, ShiftKey, "MoveRightAndModifySelection" },
1617 { VK_RIGHT, CtrlKey, "MoveWordRight" },
1618 { VK_RIGHT, CtrlKey | ShiftKey, "MoveWordRightAndModifySelection" },
1619 { VK_UP, 0, "MoveUp" },
1620 { VK_UP, ShiftKey, "MoveUpAndModifySelection" },
1621 { VK_PRIOR, ShiftKey, "MovePageUpAndModifySelection" },
1622 { VK_DOWN, 0, "MoveDown" },
1623 { VK_DOWN, ShiftKey, "MoveDownAndModifySelection" },
1624 { VK_NEXT, ShiftKey, "MovePageDownAndModifySelection" },
1625 { VK_PRIOR, 0, "MovePageUp" },
1626 { VK_NEXT, 0, "MovePageDown" },
1627 { VK_HOME, 0, "MoveToBeginningOfLine" },
1628 { VK_HOME, ShiftKey, "MoveToBeginningOfLineAndModifySelection" },
1629 { VK_HOME, CtrlKey, "MoveToBeginningOfDocument" },
1630 { VK_HOME, CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
1632 { VK_END, 0, "MoveToEndOfLine" },
1633 { VK_END, ShiftKey, "MoveToEndOfLineAndModifySelection" },
1634 { VK_END, CtrlKey, "MoveToEndOfDocument" },
1635 { VK_END, CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection" },
1637 { VK_BACK, 0, "DeleteBackward" },
1638 { VK_BACK, ShiftKey, "DeleteBackward" },
1639 { VK_DELETE, 0, "DeleteForward" },
1640 { VK_BACK, CtrlKey, "DeleteWordBackward" },
1641 { VK_DELETE, CtrlKey, "DeleteWordForward" },
1643 { 'B', CtrlKey, "ToggleBold" },
1644 { 'I', CtrlKey, "ToggleItalic" },
1646 { VK_ESCAPE, 0, "Cancel" },
1647 { VK_OEM_PERIOD, CtrlKey, "Cancel" },
1648 { VK_TAB, 0, "InsertTab" },
1649 { VK_TAB, ShiftKey, "InsertBacktab" },
1650 { VK_RETURN, 0, "InsertNewline" },
1651 { VK_RETURN, CtrlKey, "InsertNewline" },
1652 { VK_RETURN, AltKey, "InsertNewline" },
1653 { VK_RETURN, ShiftKey, "InsertNewline" },
1654 { VK_RETURN, AltKey | ShiftKey, "InsertNewline" },
1656 // It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled
1657 // in the application or in WebKit. We chose WebKit.
1658 { 'C', CtrlKey, "Copy" },
1659 { 'V', CtrlKey, "Paste" },
1660 { 'X', CtrlKey, "Cut" },
1661 { 'A', CtrlKey, "SelectAll" },
1662 { VK_INSERT, CtrlKey, "Copy" },
1663 { VK_DELETE, ShiftKey, "Cut" },
1664 { VK_INSERT, ShiftKey, "Paste" },
1665 { 'Z', CtrlKey, "Undo" },
1666 { 'Z', CtrlKey | ShiftKey, "Redo" },
1669 static const KeyPressEntry keyPressEntries[] = {
1670 { '\t', 0, "InsertTab" },
1671 { '\t', ShiftKey, "InsertBacktab" },
1672 { '\r', 0, "InsertNewline" },
1673 { '\r', CtrlKey, "InsertNewline" },
1674 { '\r', AltKey, "InsertNewline" },
1675 { '\r', ShiftKey, "InsertNewline" },
1676 { '\r', AltKey | ShiftKey, "InsertNewline" },
1679 const char* WebView::interpretKeyEvent(const KeyboardEvent* evt)
1681 ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
1683 static HashMap<int, const char*>* keyDownCommandsMap = 0;
1684 static HashMap<int, const char*>* keyPressCommandsMap = 0;
1686 if (!keyDownCommandsMap) {
1687 keyDownCommandsMap = new HashMap<int, const char*>;
1688 keyPressCommandsMap = new HashMap<int, const char*>;
1690 for (unsigned i = 0; i < _countof(keyDownEntries); i++)
1691 keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
1693 for (unsigned i = 0; i < _countof(keyPressEntries); i++)
1694 keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
1697 unsigned modifiers = 0;
1698 if (evt->shiftKey())
1699 modifiers |= ShiftKey;
1701 modifiers |= AltKey;
1703 modifiers |= CtrlKey;
1705 if (evt->type() == eventNames().keydownEvent) {
1706 int mapKey = modifiers << 16 | evt->keyCode();
1707 return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
1710 int mapKey = modifiers << 16 | evt->charCode();
1711 return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
1714 bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
1716 Node* node = evt->target()->toNode();
1718 Frame* frame = node->document()->frame();
1721 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1722 if (!keyEvent || keyEvent->isSystemKey()) // do not treat this as text input if it's a system key event
1725 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1727 if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1728 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1729 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1730 // (e.g. Tab that inserts a Tab character, or Enter).
1731 return !command.isTextInsertion() && command.execute(evt);
1734 if (command.execute(evt))
1737 // Don't insert null or control characters as they can result in unexpected behaviour
1738 if (evt->charCode() < ' ')
1741 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1744 bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1746 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1747 if (virtualKeyCode == VK_CAPITAL)
1748 frame->eventHandler()->capsLockStateMayHaveChanged();
1750 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::RawKeyDown, systemKeyDown);
1751 bool handled = frame->eventHandler()->keyEvent(keyEvent);
1753 // These events cannot be canceled, and we have no default handling for them.
1754 // FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
1755 if (systemKeyDown && virtualKeyCode != VK_RETURN)
1759 // FIXME: remove WM_UNICHAR, too
1761 // WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
1763 ::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
1767 // We need to handle back/forward using either Backspace(+Shift) or Ctrl+Left/Right Arrow keys.
1768 if ((virtualKeyCode == VK_BACK && keyEvent.shiftKey()) || (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey()))
1769 m_page->goForward();
1770 else if (virtualKeyCode == VK_BACK || (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey()))
1773 // Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
1774 ScrollDirection direction;
1775 ScrollGranularity granularity;
1776 switch (virtualKeyCode) {
1778 granularity = ScrollByLine;
1779 direction = ScrollLeft;
1782 granularity = ScrollByLine;
1783 direction = ScrollRight;
1786 granularity = ScrollByLine;
1787 direction = ScrollUp;
1790 granularity = ScrollByLine;
1791 direction = ScrollDown;
1794 granularity = ScrollByDocument;
1795 direction = ScrollUp;
1798 granularity = ScrollByDocument;
1799 direction = ScrollDown;
1802 granularity = ScrollByPage;
1803 direction = ScrollUp;
1806 granularity = ScrollByPage;
1807 direction = ScrollDown;
1813 return frame->eventHandler()->scrollRecursively(direction, granularity);
1816 bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
1818 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1820 PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformKeyboardEvent::Char, systemKeyDown);
1821 // IE does not dispatch keypress event for WM_SYSCHAR.
1823 return frame->eventHandler()->handleAccessKey(keyEvent);
1824 return frame->eventHandler()->keyEvent(keyEvent);
1827 static bool registerWebViewWindowClass()
1829 static bool haveRegisteredWindowClass = false;
1830 if (haveRegisteredWindowClass)
1833 haveRegisteredWindowClass = true;
1837 wcex.cbSize = sizeof(WNDCLASSEX);
1839 wcex.style = CS_DBLCLKS;
1840 wcex.lpfnWndProc = WebViewWndProc;
1841 wcex.cbClsExtra = 0;
1842 wcex.cbWndExtra = 4; // 4 bytes for the IWebView pointer
1843 wcex.hInstance = gInstance;
1845 wcex.hCursor = ::LoadCursor(0, IDC_ARROW);
1846 wcex.hbrBackground = 0;
1847 wcex.lpszMenuName = 0;
1848 wcex.lpszClassName = kWebViewWindowClassName;
1851 return !!RegisterClassEx(&wcex);
1855 extern HCURSOR lastSetCursor;
1858 static HWND findTopLevelParent(HWND window)
1863 HWND current = window;
1864 for (HWND parent = GetParent(current); current; current = parent, parent = GetParent(parent))
1865 if (!parent || !(GetWindowLongPtr(current, GWL_STYLE) & (WS_POPUP | WS_CHILD)))
1867 ASSERT_NOT_REACHED();
1871 static LRESULT CALLBACK WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
1873 LRESULT lResult = 0;
1874 LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
1875 WebView* webView = reinterpret_cast<WebView*>(longPtr);
1876 WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
1877 if (!mainFrameImpl || webView->isBeingDestroyed())
1878 return DefWindowProc(hWnd, message, wParam, lParam);
1880 // hold a ref, since the WebView could go away in an event handler.
1881 COMPtr<WebView> protector(webView);
1884 // Windows Media Player has a modal message loop that will deliver messages
1885 // to us at inappropriate times and we will crash if we handle them when
1886 // they are delivered. We repost paint messages so that we eventually get
1887 // a chance to paint once the modal loop has exited, but other messages
1888 // aren't safe to repost, so we just drop them.
1889 if (PluginView::isCallingPlugin()) {
1890 if (message == WM_PAINT)
1891 PostMessage(hWnd, message, wParam, lParam);
1895 bool handled = true;
1899 webView->paint(0, 0);
1902 case WM_PRINTCLIENT:
1903 webView->paint((HDC)wParam, lParam);
1906 webView->setIsBeingDestroyed();
1908 webView->revokeDragDrop();
1910 case WM_GESTURENOTIFY:
1911 handled = webView->gestureNotify(wParam, lParam);
1914 handled = webView->gesture(wParam, lParam);
1917 case WM_LBUTTONDOWN:
1918 case WM_MBUTTONDOWN:
1919 case WM_RBUTTONDOWN:
1920 case WM_LBUTTONDBLCLK:
1921 case WM_MBUTTONDBLCLK:
1922 case WM_RBUTTONDBLCLK:
1927 if (Frame* coreFrame = core(mainFrameImpl))
1928 if (coreFrame->view()->didFirstLayout())
1929 handled = webView->handleMouseEvent(message, wParam, lParam);
1932 case WM_VISTA_MOUSEHWHEEL:
1933 if (Frame* coreFrame = core(mainFrameImpl))
1934 if (coreFrame->view()->didFirstLayout())
1935 handled = webView->mouseWheel(wParam, lParam, message == WM_VISTA_MOUSEHWHEEL);
1938 handled = webView->keyDown(wParam, lParam, true);
1941 handled = webView->keyDown(wParam, lParam);
1944 handled = webView->keyUp(wParam, lParam, true);
1947 handled = webView->keyUp(wParam, lParam);
1950 handled = webView->keyPress(wParam, lParam, true);
1953 handled = webView->keyPress(wParam, lParam);
1955 // FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
1957 if (webView->isBeingDestroyed())
1958 // If someone has sent us this message while we're being destroyed, we should bail out so we don't crash.
1962 webView->deleteBackingStore();
1963 #if USE(ACCELERATED_COMPOSITING)
1964 if (webView->isAcceleratedCompositing())
1965 webView->resizeLayerRenderer();
1967 if (Frame* coreFrame = core(mainFrameImpl))
1968 coreFrame->view()->resize(LOWORD(lParam), HIWORD(lParam));
1972 lResult = DefWindowProc(hWnd, message, wParam, lParam);
1974 // The window is being hidden (e.g., because we switched tabs).
1975 // Null out our backing store.
1976 webView->deleteBackingStore();
1978 #if USE(ACCELERATED_COMPOSITING)
1979 else if (webView->isAcceleratedCompositing())
1980 webView->layerRendererBecameVisible();
1984 COMPtr<IWebUIDelegate> uiDelegate;
1985 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
1986 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
1987 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
1988 uiDelegatePrivate->webViewReceivedFocus(webView);
1990 FocusController* focusController = webView->page()->focusController();
1991 if (Frame* frame = focusController->focusedFrame()) {
1992 // Send focus events unless the previously focused window is a
1993 // child of ours (for example a plugin).
1994 if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
1995 focusController->setFocused(true);
1997 focusController->setFocused(true);
1998 focusController->setFocusedFrame(webView->page()->mainFrame());
2002 case WM_KILLFOCUS: {
2003 COMPtr<IWebUIDelegate> uiDelegate;
2004 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2005 HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
2006 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
2007 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
2008 uiDelegatePrivate->webViewLostFocus(webView, (OLE_HANDLE)(ULONG64)newFocusWnd);
2010 FocusController* focusController = webView->page()->focusController();
2011 Frame* frame = focusController->focusedOrMainFrame();
2012 webView->resetIME(frame);
2013 // Send blur events unless we're losing focus to a child of ours.
2014 if (!IsChild(hWnd, newFocusWnd))
2015 focusController->setFocused(false);
2017 // If we are pan-scrolling when we lose focus, stop the pan scrolling.
2018 frame->eventHandler()->stopAutoscrollTimer();
2022 case WM_WINDOWPOSCHANGED:
2023 if (reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW)
2024 webView->updateActiveStateSoon();
2037 webView->delete_(0);
2041 handled = webView->execCommand(wParam, lParam);
2042 else // If the high word of wParam is 0, the message is from a menu
2043 webView->performContextMenuAction(wParam, lParam, false);
2045 case WM_MENUCOMMAND:
2046 webView->performContextMenuAction(wParam, lParam, true);
2048 case WM_CONTEXTMENU:
2049 handled = webView->handleContextMenuEvent(wParam, lParam);
2051 case WM_INITMENUPOPUP:
2052 handled = webView->onInitMenuPopup(wParam, lParam);
2054 case WM_MEASUREITEM:
2055 handled = webView->onMeasureItem(wParam, lParam);
2058 handled = webView->onDrawItem(wParam, lParam);
2060 case WM_UNINITMENUPOPUP:
2061 handled = webView->onUninitMenuPopup(wParam, lParam);
2063 case WM_XP_THEMECHANGED:
2064 if (Frame* coreFrame = core(mainFrameImpl)) {
2065 webView->deleteBackingStore();
2066 coreFrame->page()->theme()->themeChanged();
2067 ScrollbarTheme::nativeTheme()->themeChanged();
2069 ::GetClientRect(hWnd, &windowRect);
2070 ::InvalidateRect(hWnd, &windowRect, false);
2071 #if USE(ACCELERATED_COMPOSITING)
2072 if (webView->isAcceleratedCompositing())
2073 webView->setRootLayerNeedsDisplay();
2077 case WM_MOUSEACTIVATE:
2078 webView->setMouseActivated(true);
2080 case WM_GETDLGCODE: {
2081 COMPtr<IWebUIDelegate> uiDelegate;
2082 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
2083 LONG_PTR dlgCode = 0;
2086 LPMSG lpMsg = (LPMSG)lParam;
2087 if (lpMsg->message == WM_KEYDOWN)
2088 keyCode = (UINT) lpMsg->wParam;
2090 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
2091 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate &&
2092 SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
2098 handled = webView->onGetObject(wParam, lParam, lResult);
2100 case WM_IME_STARTCOMPOSITION:
2101 handled = webView->onIMEStartComposition();
2103 case WM_IME_REQUEST:
2104 webView->onIMERequest(wParam, lParam, &lResult);
2106 case WM_IME_COMPOSITION:
2107 handled = webView->onIMEComposition(lParam);
2109 case WM_IME_ENDCOMPOSITION:
2110 handled = webView->onIMEEndComposition();
2113 handled = webView->onIMEChar(wParam, lParam);
2116 handled = webView->onIMENotify(wParam, lParam, &lResult);
2119 handled = webView->onIMESelect(wParam, lParam);
2121 case WM_IME_SETCONTEXT:
2122 handled = webView->onIMESetContext(wParam, lParam);
2126 case UpdateActiveStateTimer:
2127 KillTimer(hWnd, UpdateActiveStateTimer);
2128 webView->updateActiveState();
2130 case DeleteBackingStoreTimer:
2131 webView->deleteBackingStore();
2136 if (handled = webView->page()->chrome()->setCursor(lastSetCursor))
2146 lResult = DefWindowProc(hWnd, message, wParam, lParam);
2148 // Let the client know whether we consider this message handled.
2149 return (message == WM_KEYDOWN || message == WM_SYSKEYDOWN || message == WM_KEYUP || message == WM_SYSKEYUP) ? !handled : lResult;
2152 bool WebView::developerExtrasEnabled() const
2154 if (m_preferences->developerExtrasDisabledByOverride())
2159 return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
2165 static String osVersion()
2168 OSVERSIONINFO versionInfo = {0};
2169 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
2170 GetVersionEx(&versionInfo);
2172 if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
2173 if (versionInfo.dwMajorVersion == 4) {
2174 if (versionInfo.dwMinorVersion == 0)
2175 osVersion = "Windows 95";
2176 else if (versionInfo.dwMinorVersion == 10)
2177 osVersion = "Windows 98";
2178 else if (versionInfo.dwMinorVersion == 90)
2179 osVersion = "Windows 98; Win 9x 4.90";
2181 } else if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
2182 osVersion = String::format("Windows NT %d.%d", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion);
2184 if (!osVersion.length())
2185 osVersion = String::format("Windows %d.%d", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion);
2190 static String webKitVersion()
2192 String versionStr = "420+";
2195 struct LANGANDCODEPAGE {
2200 TCHAR path[MAX_PATH];
2201 GetModuleFileName(gInstance, path, ARRAYSIZE(path));
2203 DWORD versionSize = GetFileVersionInfoSize(path, &handle);
2206 data = malloc(versionSize);
2209 if (!GetFileVersionInfo(path, 0, versionSize, data))
2212 if (!VerQueryValue(data, TEXT("\\VarFileInfo\\Translation"), (LPVOID*)&lpTranslate, &cbTranslate))
2215 _stprintf_s(key, ARRAYSIZE(key), TEXT("\\StringFileInfo\\%04x%04x\\ProductVersion"), lpTranslate[0].wLanguage, lpTranslate[0].wCodePage);
2216 LPCTSTR productVersion;
2217 UINT productVersionLength;
2218 if (!VerQueryValue(data, (LPTSTR)(LPCTSTR)key, (void**)&productVersion, &productVersionLength))
2220 versionStr = String(productVersion, productVersionLength);
2228 const String& WebView::userAgentForKURL(const KURL&)
2230 if (m_userAgentOverridden)
2231 return m_userAgentCustom;
2233 if (!m_userAgentStandard.length())
2234 m_userAgentStandard = WebView::standardUserAgentWithApplicationName(m_applicationName);
2235 return m_userAgentStandard;
2238 // IUnknown -------------------------------------------------------------------
2240 HRESULT STDMETHODCALLTYPE WebView::QueryInterface(REFIID riid, void** ppvObject)
2243 if (IsEqualGUID(riid, CLSID_WebView))
2245 else if (IsEqualGUID(riid, IID_IUnknown))
2246 *ppvObject = static_cast<IWebView*>(this);
2247 else if (IsEqualGUID(riid, IID_IWebView))
2248 *ppvObject = static_cast<IWebView*>(this);
2249 else if (IsEqualGUID(riid, IID_IWebViewPrivate))
2250 *ppvObject = static_cast<IWebViewPrivate*>(this);
2251 else if (IsEqualGUID(riid, IID_IWebIBActions))
2252 *ppvObject = static_cast<IWebIBActions*>(this);
2253 else if (IsEqualGUID(riid, IID_IWebViewCSS))
2254 *ppvObject = static_cast<IWebViewCSS*>(this);
2255 else if (IsEqualGUID(riid, IID_IWebViewEditing))
2256 *ppvObject = static_cast<IWebViewEditing*>(this);
2257 else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
2258 *ppvObject = static_cast<IWebViewUndoableEditing*>(this);
2259 else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
2260 *ppvObject = static_cast<IWebViewEditingActions*>(this);
2261 else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
2262 *ppvObject = static_cast<IWebNotificationObserver*>(this);
2263 else if (IsEqualGUID(riid, IID_IDropTarget))
2264 *ppvObject = static_cast<IDropTarget*>(this);
2266 return E_NOINTERFACE;
2272 ULONG STDMETHODCALLTYPE WebView::AddRef(void)
2274 return ++m_refCount;
2277 ULONG STDMETHODCALLTYPE WebView::Release(void)
2279 ULONG newRef = --m_refCount;
2286 // IWebView --------------------------------------------------------------------
2288 HRESULT STDMETHODCALLTYPE WebView::canShowMIMEType(
2289 /* [in] */ BSTR mimeType,
2290 /* [retval][out] */ BOOL* canShow)
2292 String mimeTypeStr(mimeType, SysStringLen(mimeType));
2297 *canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeTypeStr) ||
2298 MIMETypeRegistry::isSupportedNonImageMIMEType(mimeTypeStr) ||
2299 PluginInfoStore::supportsMIMEType(mimeTypeStr) ||
2300 shouldUseEmbeddedView(mimeTypeStr);
2305 HRESULT STDMETHODCALLTYPE WebView::canShowMIMETypeAsHTML(
2306 /* [in] */ BSTR /*mimeType*/,
2307 /* [retval][out] */ BOOL* canShow)
2314 HRESULT STDMETHODCALLTYPE WebView::MIMETypesShownAsHTML(
2315 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
2317 ASSERT_NOT_REACHED();
2321 HRESULT STDMETHODCALLTYPE WebView::setMIMETypesShownAsHTML(
2322 /* [size_is][in] */ BSTR* /*mimeTypes*/,
2323 /* [in] */ int /*cMimeTypes*/)
2325 ASSERT_NOT_REACHED();
2329 HRESULT STDMETHODCALLTYPE WebView::URLFromPasteboard(
2330 /* [in] */ IDataObject* /*pasteboard*/,
2331 /* [retval][out] */ BSTR* /*url*/)
2333 ASSERT_NOT_REACHED();
2337 HRESULT STDMETHODCALLTYPE WebView::URLTitleFromPasteboard(
2338 /* [in] */ IDataObject* /*pasteboard*/,
2339 /* [retval][out] */ BSTR* /*urlTitle*/)
2341 ASSERT_NOT_REACHED();
2345 static void WebKitSetApplicationCachePathIfNecessary()
2347 static bool initialized = false;
2351 String path = localUserSpecificStorageDirectory();
2353 cacheStorage().setCacheDirectory(path);
2358 HRESULT STDMETHODCALLTYPE WebView::initWithFrame(
2359 /* [in] */ RECT frame,
2360 /* [in] */ BSTR frameName,
2361 /* [in] */ BSTR groupName)
2368 registerWebViewWindowClass();
2370 m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
2371 frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow ? m_hostWindow : HWND_MESSAGE, 0, gInstance, 0);
2372 ASSERT(::IsWindow(m_viewWindow));
2374 hr = registerDragDrop();
2378 WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
2379 sharedPreferences->willAddToWebView();
2380 m_preferences = sharedPreferences;
2382 InitializeLoggingChannelsIfNecessary();
2383 #if ENABLE(DATABASE)
2384 WebKitSetWebDatabasesPathIfNecessary();
2386 WebKitSetApplicationCachePathIfNecessary();
2388 #if USE(SAFARI_THEME)
2389 BOOL shouldPaintNativeControls;
2390 if (SUCCEEDED(m_preferences->shouldPaintNativeControls(&shouldPaintNativeControls)))
2391 Settings::setShouldPaintNativeControls(shouldPaintNativeControls);
2394 BOOL useHighResolutionTimer;
2395 if (SUCCEEDED(m_preferences->shouldUseHighResolutionTimers(&useHighResolutionTimer)))
2396 Settings::setShouldUseHighResolutionTimers(useHighResolutionTimer);
2398 m_page = new Page(new WebChromeClient(this), new WebContextMenuClient(this), new WebEditorClient(this), new WebDragClient(this), new WebInspectorClient(this), new WebPluginHalterClient(this));
2400 BSTR localStoragePath;
2401 if (SUCCEEDED(m_preferences->localStorageDatabasePath(&localStoragePath))) {
2402 m_page->settings()->setLocalStorageDatabasePath(String(localStoragePath, SysStringLen(localStoragePath)));
2403 SysFreeString(localStoragePath);
2408 if (SUCCEEDED(m_uiDelegate->ftpDirectoryTemplatePath(this, &path))) {
2409 m_page->settings()->setFTPDirectoryTemplatePath(String(path, SysStringLen(path)));
2410 SysFreeString(path);
2414 WebFrame* webFrame = WebFrame::createInstance();
2415 RefPtr<Frame> coreFrame = webFrame->init(this, m_page, 0);
2416 m_mainFrame = webFrame;
2417 webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
2419 coreFrame->tree()->setName(String(frameName, SysStringLen(frameName)));
2421 setGroupName(groupName);
2423 addToAllWebViewsSet();
2425 #pragma warning(suppress: 4244)
2426 SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
2427 ShowWindow(m_viewWindow, SW_SHOW);
2429 initializeToolTipWindow();
2430 windowAncestryDidChange();
2432 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
2433 notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2434 m_preferences->postPreferencesChangesNotification();
2436 setSmartInsertDeleteEnabled(TRUE);
2440 static bool initCommonControls()
2442 static bool haveInitialized = false;
2443 if (haveInitialized)
2446 INITCOMMONCONTROLSEX init;
2447 init.dwSize = sizeof(init);
2448 init.dwICC = ICC_TREEVIEW_CLASSES;
2449 haveInitialized = !!::InitCommonControlsEx(&init);
2450 return haveInitialized;
2453 void WebView::initializeToolTipWindow()
2455 if (!initCommonControls())
2458 m_toolTipHwnd = CreateWindowEx(0, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
2459 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
2460 m_viewWindow, 0, 0, 0);
2464 TOOLINFO info = {0};
2465 info.cbSize = sizeof(info);
2466 info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
2467 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2469 ::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
2470 ::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, maxToolTipWidth);
2472 ::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
2475 void WebView::setToolTip(const String& toolTip)
2480 if (toolTip == m_toolTip)
2483 m_toolTip = toolTip;
2485 if (!m_toolTip.isEmpty()) {
2486 TOOLINFO info = {0};
2487 info.cbSize = sizeof(info);
2488 info.uFlags = TTF_IDISHWND;
2489 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2490 info.lpszText = const_cast<UChar*>(m_toolTip.charactersWithNullTermination());
2491 ::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
2494 ::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
2497 HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
2499 COMPtr<IPropertyBag> propertyBag;
2500 HRESULT hr = notification->userInfo(&propertyBag);
2506 COMPtr<CFDictionaryPropertyBag> dictionaryPropertyBag;
2507 hr = propertyBag->QueryInterface(&dictionaryPropertyBag);
2511 CFDictionaryRef dictionary = dictionaryPropertyBag->dictionary();
2515 CFTypeRef value = CFDictionaryGetValue(dictionary, WebIconDatabase::iconDatabaseNotificationUserInfoURLKey());
2518 if (CFGetTypeID(value) != CFStringGetTypeID())
2521 String mainFrameURL;
2523 mainFrameURL = m_mainFrame->url().string();
2525 if (!mainFrameURL.isEmpty() && mainFrameURL == String((CFStringRef)value))
2526 dispatchDidReceiveIconFromWebFrame(m_mainFrame);
2531 void WebView::registerForIconNotification(bool listen)
2533 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2535 nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2537 nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2540 void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
2542 registerForIconNotification(false);
2544 if (m_frameLoadDelegate)
2545 // FIXME: <rdar://problem/5491010> - Pass in the right HBITMAP.
2546 m_frameLoadDelegate->didReceiveIcon(this, 0, frame);
2549 HRESULT STDMETHODCALLTYPE WebView::setUIDelegate(
2550 /* [in] */ IWebUIDelegate* d)
2554 if (m_uiDelegatePrivate)
2555 m_uiDelegatePrivate = 0;
2558 if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
2559 m_uiDelegatePrivate = 0;
2565 HRESULT STDMETHODCALLTYPE WebView::uiDelegate(
2566 /* [out][retval] */ IWebUIDelegate** d)
2571 return m_uiDelegate.copyRefTo(d);
2574 HRESULT STDMETHODCALLTYPE WebView::setResourceLoadDelegate(
2575 /* [in] */ IWebResourceLoadDelegate* d)
2577 m_resourceLoadDelegate = d;
2581 HRESULT STDMETHODCALLTYPE WebView::resourceLoadDelegate(
2582 /* [out][retval] */ IWebResourceLoadDelegate** d)
2584 if (!m_resourceLoadDelegate)
2587 return m_resourceLoadDelegate.copyRefTo(d);
2590 HRESULT STDMETHODCALLTYPE WebView::setDownloadDelegate(
2591 /* [in] */ IWebDownloadDelegate* d)
2593 m_downloadDelegate = d;
2597 HRESULT STDMETHODCALLTYPE WebView::downloadDelegate(
2598 /* [out][retval] */ IWebDownloadDelegate** d)
2600 if (!m_downloadDelegate)
2603 return m_downloadDelegate.copyRefTo(d);
2606 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegate(
2607 /* [in] */ IWebFrameLoadDelegate* d)
2609 m_frameLoadDelegate = d;
2613 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegate(
2614 /* [out][retval] */ IWebFrameLoadDelegate** d)
2616 if (!m_frameLoadDelegate)
2619 return m_frameLoadDelegate.copyRefTo(d);
2622 HRESULT STDMETHODCALLTYPE WebView::setPolicyDelegate(
2623 /* [in] */ IWebPolicyDelegate* d)
2625 m_policyDelegate = d;
2629 HRESULT STDMETHODCALLTYPE WebView::policyDelegate(
2630 /* [out][retval] */ IWebPolicyDelegate** d)
2632 if (!m_policyDelegate)
2634 return m_policyDelegate.copyRefTo(d);
2637 HRESULT STDMETHODCALLTYPE WebView::mainFrame(
2638 /* [out][retval] */ IWebFrame** frame)
2641 ASSERT_NOT_REACHED();
2645 *frame = m_mainFrame;
2649 m_mainFrame->AddRef();
2653 HRESULT STDMETHODCALLTYPE WebView::focusedFrame(
2654 /* [out][retval] */ IWebFrame** frame)
2657 ASSERT_NOT_REACHED();
2662 Frame* f = m_page->focusController()->focusedFrame();
2666 WebFrame* webFrame = kit(f);
2670 return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
2672 HRESULT STDMETHODCALLTYPE WebView::backForwardList(
2673 /* [out][retval] */ IWebBackForwardList** list)
2675 if (!m_useBackForwardList)
2678 *list = WebBackForwardList::createInstance(m_page->backForwardList());
2683 HRESULT STDMETHODCALLTYPE WebView::setMaintainsBackForwardList(
2684 /* [in] */ BOOL flag)
2686 m_useBackForwardList = !!flag;
2690 HRESULT STDMETHODCALLTYPE WebView::goBack(
2691 /* [retval][out] */ BOOL* succeeded)
2693 *succeeded = m_page->goBack();
2697 HRESULT STDMETHODCALLTYPE WebView::goForward(
2698 /* [retval][out] */ BOOL* succeeded)
2700 *succeeded = m_page->goForward();
2704 HRESULT STDMETHODCALLTYPE WebView::goToBackForwardItem(
2705 /* [in] */ IWebHistoryItem* item,
2706 /* [retval][out] */ BOOL* succeeded)
2710 COMPtr<WebHistoryItem> webHistoryItem;
2711 HRESULT hr = item->QueryInterface(&webHistoryItem);
2715 m_page->goToItem(webHistoryItem->historyItem(), FrameLoadTypeIndexedBackForward);
2721 HRESULT STDMETHODCALLTYPE WebView::setTextSizeMultiplier(
2722 /* [in] */ float multiplier)
2726 setZoomMultiplier(multiplier, true);
2730 HRESULT STDMETHODCALLTYPE WebView::setPageSizeMultiplier(
2731 /* [in] */ float multiplier)
2735 setZoomMultiplier(multiplier, false);
2739 void WebView::setZoomMultiplier(float multiplier, bool isTextOnly)
2741 m_zoomMultiplier = multiplier;
2742 m_page->settings()->setZoomsTextOnly(isTextOnly);
2743 if (Frame* coreFrame = core(m_mainFrame))
2744 coreFrame->setZoomFactor(multiplier, isTextOnly);
2747 HRESULT STDMETHODCALLTYPE WebView::textSizeMultiplier(
2748 /* [retval][out] */ float* multiplier)
2750 *multiplier = zoomMultiplier(true);
2754 HRESULT STDMETHODCALLTYPE WebView::pageSizeMultiplier(
2755 /* [retval][out] */ float* multiplier)
2757 *multiplier = zoomMultiplier(false);
2761 float WebView::zoomMultiplier(bool isTextOnly)
2763 if (isTextOnly != m_page->settings()->zoomsTextOnly())
2765 return m_zoomMultiplier;
2768 HRESULT STDMETHODCALLTYPE WebView::setApplicationNameForUserAgent(
2769 /* [in] */ BSTR applicationName)
2771 m_applicationName = String(applicationName, SysStringLen(applicationName));
2772 m_userAgentStandard = String();
2776 HRESULT STDMETHODCALLTYPE WebView::applicationNameForUserAgent(
2777 /* [retval][out] */ BSTR* applicationName)
2779 *applicationName = SysAllocStringLen(m_applicationName.characters(), m_applicationName.length());
2780 if (!*applicationName && m_applicationName.length())
2781 return E_OUTOFMEMORY;
2785 HRESULT STDMETHODCALLTYPE WebView::setCustomUserAgent(
2786 /* [in] */ BSTR userAgentString)
2788 m_userAgentOverridden = userAgentString;
2789 m_userAgentCustom = String(userAgentString, SysStringLen(userAgentString));
2793 HRESULT STDMETHODCALLTYPE WebView::customUserAgent(
2794 /* [retval][out] */ BSTR* userAgentString)
2796 *userAgentString = 0;
2797 if (!m_userAgentOverridden)
2799 *userAgentString = SysAllocStringLen(m_userAgentCustom.characters(), m_userAgentCustom.length());
2800 if (!*userAgentString && m_userAgentCustom.length())
2801 return E_OUTOFMEMORY;
2805 HRESULT STDMETHODCALLTYPE WebView::userAgentForURL(
2806 /* [in] */ BSTR url,
2807 /* [retval][out] */ BSTR* userAgent)
2809 String userAgentString = userAgentForKURL(MarshallingHelpers::BSTRToKURL(url));
2810 *userAgent = SysAllocStringLen(userAgentString.characters(), userAgentString.length());
2811 if (!*userAgent && userAgentString.length())
2812 return E_OUTOFMEMORY;
2816 HRESULT STDMETHODCALLTYPE WebView::supportsTextEncoding(
2817 /* [retval][out] */ BOOL* supports)
2823 HRESULT STDMETHODCALLTYPE WebView::setCustomTextEncodingName(
2824 /* [in] */ BSTR encodingName)
2831 hr = customTextEncodingName(&oldEncoding);
2835 if (oldEncoding != encodingName && (!oldEncoding || !encodingName || _tcscmp(oldEncoding, encodingName))) {
2836 if (Frame* coreFrame = core(m_mainFrame))
2837 coreFrame->loader()->reloadWithOverrideEncoding(String(encodingName, SysStringLen(encodingName)));
2843 HRESULT STDMETHODCALLTYPE WebView::customTextEncodingName(
2844 /* [retval][out] */ BSTR* encodingName)
2847 COMPtr<IWebDataSource> dataSource;
2848 COMPtr<WebDataSource> dataSourceImpl;
2854 if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
2855 hr = m_mainFrame->dataSource(&dataSource);
2856 if (FAILED(hr) || !dataSource)
2860 hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
2864 BString str = dataSourceImpl->documentLoader()->overrideEncoding();
2869 *encodingName = SysAllocStringLen(m_overrideEncoding.characters(), m_overrideEncoding.length());
2871 if (!*encodingName && m_overrideEncoding.length())
2872 return E_OUTOFMEMORY;
2877 HRESULT STDMETHODCALLTYPE WebView::setMediaStyle(
2878 /* [in] */ BSTR /*media*/)
2880 ASSERT_NOT_REACHED();
2884 HRESULT STDMETHODCALLTYPE WebView::mediaStyle(
2885 /* [retval][out] */ BSTR* /*media*/)
2887 ASSERT_NOT_REACHED();
2891 HRESULT STDMETHODCALLTYPE WebView::stringByEvaluatingJavaScriptFromString(
2892 /* [in] */ BSTR script, // assumes input does not have "JavaScript" at the begining.
2893 /* [retval][out] */ BSTR* result)
2896 ASSERT_NOT_REACHED();
2902 Frame* coreFrame = core(m_mainFrame);
2906 JSC::JSValue scriptExecutionResult = coreFrame->script()->executeScript(WebCore::String(script), true).jsValue();
2907 if (!scriptExecutionResult)
2909 else if (scriptExecutionResult.isString()) {
2910 JSLock lock(JSC::SilenceAssertionsOnly);
2911 *result = BString(String(scriptExecutionResult.getString()));
2917 HRESULT STDMETHODCALLTYPE WebView::windowScriptObject(
2918 /* [retval][out] */ IWebScriptObject** /*webScriptObject*/)
2920 ASSERT_NOT_REACHED();
2924 HRESULT STDMETHODCALLTYPE WebView::setPreferences(
2925 /* [in] */ IWebPreferences* prefs)
2928 prefs = WebPreferences::sharedStandardPreferences();
2930 if (m_preferences == prefs)
2933 COMPtr<WebPreferences> webPrefs(Query, prefs);
2935 return E_NOINTERFACE;
2936 webPrefs->willAddToWebView();
2938 COMPtr<WebPreferences> oldPrefs = m_preferences;
2940 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2941 nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2943 BSTR identifier = 0;
2944 oldPrefs->identifier(&identifier);
2945 oldPrefs->didRemoveFromWebView();
2946 oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
2948 m_preferences = webPrefs;
2951 WebPreferences::removeReferenceForIdentifier(identifier);
2952 SysFreeString(identifier);
2955 nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2957 m_preferences->postPreferencesChangesNotification();
2962 HRESULT STDMETHODCALLTYPE WebView::preferences(
2963 /* [retval][out] */ IWebPreferences** prefs)
2967 *prefs = m_preferences.get();
2969 m_preferences->AddRef();
2973 HRESULT STDMETHODCALLTYPE WebView::setPreferencesIdentifier(
2974 /* [in] */ BSTR /*anIdentifier*/)
2976 ASSERT_NOT_REACHED();
2980 HRESULT STDMETHODCALLTYPE WebView::preferencesIdentifier(
2981 /* [retval][out] */ BSTR* /*anIdentifier*/)
2983 ASSERT_NOT_REACHED();
2987 void WebView::windowReceivedMessage(HWND, UINT message, WPARAM wParam, LPARAM)
2991 updateActiveStateSoon();
2993 deleteBackingStoreSoon();
2998 void WebView::updateActiveStateSoon() const
3000 // This function is called while processing the WM_NCACTIVATE message.
3001 // While processing WM_NCACTIVATE when we are being deactivated, GetActiveWindow() will
3002 // still return our window. If we were to call updateActiveState() in that case, we would
3003 // wrongly think that we are still the active window. To work around this, we update our
3004 // active state after a 0-delay timer fires, at which point GetActiveWindow() will return
3005 // the newly-activated window.
3007 SetTimer(m_viewWindow, UpdateActiveStateTimer, 0, 0);
3010 void WebView::deleteBackingStoreSoon()
3012 if (pendingDeleteBackingStoreSet.size() > 2) {
3013 Vector<WebView*> views;
3014 HashSet<WebView*>::iterator end = pendingDeleteBackingStoreSet.end();
3015 for (HashSet<WebView*>::iterator it = pendingDeleteBackingStoreSet.begin(); it != end; ++it)
3017 for (int i = 0; i < views.size(); ++i)
3018 views[i]->deleteBackingStore();
3019 ASSERT(pendingDeleteBackingStoreSet.isEmpty());
3022 pendingDeleteBackingStoreSet.add(this);
3023 m_deleteBackingStoreTimerActive = true;
3024 SetTimer(m_viewWindow, DeleteBackingStoreTimer, delayBeforeDeletingBackingStoreMsec, 0);
3027 void WebView::cancelDeleteBackingStoreSoon()
3029 if (!m_deleteBackingStoreTimerActive)
3031 pendingDeleteBackingStoreSet.remove(this);
3032 m_deleteBackingStoreTimerActive = false;
3033 KillTimer(m_viewWindow, DeleteBackingStoreTimer);
3036 HRESULT STDMETHODCALLTYPE WebView::setHostWindow(
3037 /* [in] */ OLE_HANDLE oleWindow)
3039 HWND window = (HWND)(ULONG64)oleWindow;
3042 SetParent(m_viewWindow, window);
3043 else if (!isBeingDestroyed()) {
3044 // Turn the WebView into a message-only window so it will no longer be a child of the
3045 // old host window and will be hidden from screen. We only do this when
3046 // isBeingDestroyed() is false because doing this while handling WM_DESTROY can leave
3047 // m_viewWindow in a weird state (see <http://webkit.org/b/29337>).
3048 SetParent(m_viewWindow, HWND_MESSAGE);
3052 m_hostWindow = window;
3055 windowAncestryDidChange();
3060 HRESULT STDMETHODCALLTYPE WebView::hostWindow(
3061 /* [retval][out] */ OLE_HANDLE* window)
3063 *window = (OLE_HANDLE)(ULONG64)m_hostWindow;
3068 static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
3071 ? curr->tree()->traverseNextWithWrap(wrapFlag)
3072 : curr->tree()->traversePreviousWithWrap(wrapFlag);
3075 HRESULT STDMETHODCALLTYPE WebView::searchFor(
3076 /* [in] */ BSTR str,
3077 /* [in] */ BOOL forward,
3078 /* [in] */ BOOL caseFlag,
3079 /* [in] */ BOOL wrapFlag,
3080 /* [retval][out] */ BOOL* found)
3083 return E_INVALIDARG;
3085 if (!m_page || !m_page->mainFrame())
3086 return E_UNEXPECTED;
3088 if (!str || !SysStringLen(str))
3089 return E_INVALIDARG;
3091 *found = m_page->findString(String(str, SysStringLen(str)), caseFlag ? TextCaseSensitive : TextCaseInsensitive, forward ? FindDirectionForward : FindDirectionBackward, wrapFlag);
3095 bool WebView::active()
3097 HWND activeWindow = GetActiveWindow();
3098 return (activeWindow && m_topLevelParent == findTopLevelParent(activeWindow));
3101 void WebView::updateActiveState()
3103 m_page->focusController()->setActive(active());
3106 HRESULT STDMETHODCALLTYPE WebView::updateFocusedAndActiveState()
3108 updateActiveState();
3110 bool active = m_page->focusController()->isActive();
3111 Frame* mainFrame = m_page->mainFrame();
3112 Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
3113 mainFrame->selection()->setFocused(active && mainFrame == focusedFrame);
3118 HRESULT STDMETHODCALLTYPE WebView::executeCoreCommandByName(BSTR bName, BSTR bValue)
3120 String name(bName, SysStringLen(bName));
3121 String value(bValue, SysStringLen(bValue));
3123 m_page->focusController()->focusedOrMainFrame()->editor()->command(name).execute(value);
3128 HRESULT STDMETHODCALLTYPE WebView::clearMainFrameName()
3130 m_page->mainFrame()->tree()->clearName();
3135 HRESULT STDMETHODCALLTYPE WebView::markAllMatchesForText(
3136 BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, UINT* matches)
3139 return E_INVALIDARG;
3141 if (!m_page || !m_page->mainFrame())
3142 return E_UNEXPECTED;
3144 if (!str || !SysStringLen(str))
3145 return E_INVALIDARG;
3147 *matches = m_page->markAllMatchesForText(String(str, SysStringLen(str)), caseSensitive ? TextCaseSensitive : TextCaseInsensitive, highlight, limit);
3151 HRESULT STDMETHODCALLTYPE WebView::unmarkAllTextMatches()
3153 if (!m_page || !m_page->mainFrame())
3154 return E_UNEXPECTED;
3156 m_page->unmarkAllTextMatches();
3160 HRESULT STDMETHODCALLTYPE WebView::rectsForTextMatches(
3161 IEnumTextMatches** pmatches)
3163 Vector<IntRect> allRects;
3164 WebCore::Frame* frame = m_page->mainFrame();
3166 if (Document* document = frame->document()) {
3167 IntRect visibleRect = frame->view()->visibleContentRect();
3168 Vector<IntRect> frameRects = document->renderedRectsForMarkers(DocumentMarker::TextMatch);
3169 IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
3170 frameOffset = frame->view()->convertToContainingWindow(frameOffset);
3172 Vector<IntRect>::iterator end = frameRects.end();
3173 for (Vector<IntRect>::iterator it = frameRects.begin(); it < end; it++) {
3174 it->intersect(visibleRect);
3175 it->move(frameOffset.x(), frameOffset.y());
3176 allRects.append(*it);
3179 frame = incrementFrame(frame, true, false);
3182 return createMatchEnumerator(&allRects, pmatches);
3185 HRESULT STDMETHODCALLTYPE WebView::generateSelectionImage(BOOL forceWhiteText, OLE_HANDLE* hBitmap)
3189 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
3192 HBITMAP bitmap = imageFromSelection(frame, forceWhiteText ? TRUE : FALSE);
3193 *hBitmap = (OLE_HANDLE)(ULONG64)bitmap;
3199 HRESULT STDMETHODCALLTYPE WebView::selectionRect(RECT* rc)
3201 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
3204 IntRect ir = enclosingIntRect(frame->selectionBounds());
3205 ir = frame->view()->convertToContainingWindow(ir);
3206 ir.move(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
3209 rc->bottom = rc->top + ir.height();
3210 rc->right = rc->left + ir.width();
3216 HRESULT STDMETHODCALLTYPE WebView::registerViewClass(
3217 /* [in] */ IWebDocumentView* /*view*/,
3218 /* [in] */ IWebDocumentRepresentation* /*representation*/,
3219 /* [in] */ BSTR /*forMIMEType*/)
3221 ASSERT_NOT_REACHED();
3225 HRESULT STDMETHODCALLTYPE WebView::setGroupName(
3226 /* [in] */ BSTR groupName)
3230 m_page->setGroupName(String(groupName, SysStringLen(groupName)));
3234 HRESULT STDMETHODCALLTYPE WebView::groupName(
3235 /* [retval][out] */ BSTR* groupName)
3240 String groupNameString = m_page->groupName();
3241 *groupName = SysAllocStringLen(groupNameString.characters(), groupNameString.length());
3242 if (!*groupName && groupNameString.length())
3243 return E_OUTOFMEMORY;
3247 HRESULT STDMETHODCALLTYPE WebView::estimatedProgress(
3248 /* [retval][out] */ double* estimatedProgress)
3250 *estimatedProgress = m_page->progress()->estimatedProgress();
3254 HRESULT STDMETHODCALLTYPE WebView::isLoading(
3255 /* [retval][out] */ BOOL* isLoading)
3257 COMPtr<IWebDataSource> dataSource;
3258 COMPtr<IWebDataSource> provisionalDataSource;
3265 if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
3266 dataSource->isLoading(isLoading);
3271 if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
3272 provisionalDataSource->isLoading(isLoading);
3276 HRESULT STDMETHODCALLTYPE WebView::elementAtPoint(
3277 /* [in] */ LPPOINT point,
3278 /* [retval][out] */ IPropertyBag** elementDictionary)
3280 if (!elementDictionary) {
3281 ASSERT_NOT_REACHED();
3285 *elementDictionary = 0;
3287 Frame* frame = core(m_mainFrame);
3291 IntPoint webCorePoint = IntPoint(point->x, point->y);
3292 HitTestResult result = HitTestResult(webCorePoint);
3293 if (frame->contentRenderer())
3294 result = frame->eventHandler()->hitTestResultAtPoint(webCorePoint, false);
3295 *elementDictionary = WebElementPropertyBag::createInstance(result);
3299 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForSelection(
3300 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3302 ASSERT_NOT_REACHED();
3306 HRESULT STDMETHODCALLTYPE WebView::writeSelectionWithPasteboardTypes(
3307 /* [size_is][in] */ BSTR* /*types*/,
3308 /* [in] */ int /*cTypes*/,
3309 /* [in] */ IDataObject* /*pasteboard*/)
3311 ASSERT_NOT_REACHED();
3315 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForElement(
3316 /* [in] */ IPropertyBag* /*elementDictionary*/,
3317 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3319 ASSERT_NOT_REACHED();
3323 HRESULT STDMETHODCALLTYPE WebView::writeElement(
3324 /* [in] */ IPropertyBag* /*elementDictionary*/,
3325 /* [size_is][in] */ BSTR* /*withPasteboardTypes*/,
3326 /* [in] */ int /*cWithPasteboardTypes*/,
3327 /* [in] */ IDataObject* /*pasteboard*/)
3329 ASSERT_NOT_REACHED();
3333 HRESULT STDMETHODCALLTYPE WebView::selectedText(
3334 /* [out, retval] */ BSTR* text)
3337 ASSERT_NOT_REACHED();
3343 Frame* focusedFrame = (m_page && m_page->focusController()) ? m_page->focusController()->focusedOrMainFrame() : 0;
3347 String frameSelectedText = focusedFrame->selectedText();
3348 *text = SysAllocStringLen(frameSelectedText.characters(), frameSelectedText.length());
3349 if (!*text && frameSelectedText.length())
3350 return E_OUTOFMEMORY;
3354 HRESULT STDMETHODCALLTYPE WebView::centerSelectionInVisibleArea(
3355 /* [in] */ IUnknown* /* sender */)
3357 Frame* coreFrame = core(m_mainFrame);
3361 coreFrame->revealSelection(ScrollAlignment::alignCenterAlways);
3366 HRESULT STDMETHODCALLTYPE WebView::moveDragCaretToPoint(
3367 /* [in] */ LPPOINT /*point*/)
3369 ASSERT_NOT_REACHED();
3373 HRESULT STDMETHODCALLTYPE WebView::removeDragCaret( void)
3375 ASSERT_NOT_REACHED();
3379 HRESULT STDMETHODCALLTYPE WebView::setDrawsBackground(
3380 /* [in] */ BOOL /*drawsBackground*/)
3382 ASSERT_NOT_REACHED();
3386 HRESULT STDMETHODCALLTYPE WebView::drawsBackground(
3387 /* [retval][out] */ BOOL* /*drawsBackground*/)
3389 ASSERT_NOT_REACHED();
3393 HRESULT STDMETHODCALLTYPE WebView::setMainFrameURL(
3394 /* [in] */ BSTR /*urlString*/)
3396 ASSERT_NOT_REACHED();
3400 HRESULT STDMETHODCALLTYPE WebView::mainFrameURL(
3401 /* [retval][out] */ BSTR* urlString)
3409 COMPtr<IWebDataSource> dataSource;
3411 if (FAILED(m_mainFrame->provisionalDataSource(&dataSource))) {
3412 if (FAILED(m_mainFrame->dataSource(&dataSource)))
3421 COMPtr<IWebMutableURLRequest> request;
3422 if (FAILED(dataSource->request(&request)) || !request)
3425 if (FAILED(request->URL(urlString)))
3431 HRESULT STDMETHODCALLTYPE WebView::mainFrameDocument(
3432 /* [retval][out] */ IDOMDocument** document)
3438 return m_mainFrame->DOMDocument(document);
3441 HRESULT STDMETHODCALLTYPE WebView::mainFrameTitle(
3442 /* [retval][out] */ BSTR* /*title*/)
3444 ASSERT_NOT_REACHED();
3448 HRESULT STDMETHODCALLTYPE WebView::mainFrameIcon(
3449 /* [retval][out] */ OLE_HANDLE* /*hBitmap*/)
3451 ASSERT_NOT_REACHED();
3455 HRESULT STDMETHODCALLTYPE WebView::registerURLSchemeAsLocal(
3456 /* [in] */ BSTR scheme)
3461 SecurityOrigin::registerURLSchemeAsLocal(String(scheme, ::SysStringLen(scheme)));
3466 // IWebIBActions ---------------------------------------------------------------
3468 HRESULT STDMETHODCALLTYPE WebView::takeStringURLFrom(
3469 /* [in] */ IUnknown* /*sender*/)
3471 ASSERT_NOT_REACHED();
3475 HRESULT STDMETHODCALLTYPE WebView::stopLoading(
3476 /* [in] */ IUnknown* /*sender*/)
3481 return m_mainFrame->stopLoading();
3484 HRESULT STDMETHODCALLTYPE WebView::reload(
3485 /* [in] */ IUnknown* /*sender*/)
3490 return m_mainFrame->reload();
3493 HRESULT STDMETHODCALLTYPE WebView::canGoBack(
3494 /* [in] */ IUnknown* /*sender*/,
3495 /* [retval][out] */ BOOL* result)
3497 *result = !!m_page->backForwardList()->backItem();
3501 HRESULT STDMETHODCALLTYPE WebView::goBack(
3502 /* [in] */ IUnknown* /*sender*/)
3504 ASSERT_NOT_REACHED();
3508 HRESULT STDMETHODCALLTYPE WebView::canGoForward(
3509 /* [in] */ IUnknown* /*sender*/,
3510 /* [retval][out] */ BOOL* result)
3512 *result = !!m_page->backForwardList()->forwardItem();
3516 HRESULT STDMETHODCALLTYPE WebView::goForward(
3517 /* [in] */ IUnknown* /*sender*/)
3519 ASSERT_NOT_REACHED();
3523 // FIXME: This code should move into WebCore so it can be shared by all the WebKits.
3524 #define MinimumZoomMultiplier 0.5f
3525 #define MaximumZoomMultiplier 3.0f
3526 #define ZoomMultiplierRatio 1.2f
3528 HRESULT STDMETHODCALLTYPE WebView::canMakeTextLarger(
3529 /* [in] */ IUnknown* /*sender*/,
3530 /* [retval][out] */ BOOL* result)
3532 bool canGrowMore = canZoomIn(m_page->settings()->zoomsTextOnly());
3533 *result = canGrowMore ? TRUE : FALSE;
3537 HRESULT STDMETHODCALLTYPE WebView::canZoomPageIn(
3538 /* [in] */ IUnknown* /*sender*/,
3539 /* [retval][out] */ BOOL* result)
3541 bool canGrowMore = canZoomIn(false);
3542 *result = canGrowMore ? TRUE : FALSE;
3546 bool WebView::canZoomIn(bool isTextOnly)
3548 return zoomMultiplier(isTextOnly) * ZoomMultiplierRatio < MaximumZoomMultiplier;
3551 HRESULT STDMETHODCALLTYPE WebView::makeTextLarger(
3552 /* [in] */ IUnknown* /*sender*/)
3554 return zoomIn(m_page->settings()->zoomsTextOnly());
3557 HRESULT STDMETHODCALLTYPE WebView::zoomPageIn(
3558 /* [in] */ IUnknown* /*sender*/)
3560 return zoomIn(false);
3563 HRESULT WebView::zoomIn(bool isTextOnly)
3565 if (!canZoomIn(isTextOnly))
3567 setZoomMultiplier(zoomMultiplier(isTextOnly) * ZoomMultiplierRatio, isTextOnly);
3571 HRESULT STDMETHODCALLTYPE WebView::canMakeTextSmaller(
3572 /* [in] */ IUnknown* /*sender*/,
3573 /* [retval][out] */ BOOL* result)
3575 bool canShrinkMore = canZoomOut(m_page->settings()->zoomsTextOnly());
3576 *result = canShrinkMore ? TRUE : FALSE;
3580 HRESULT STDMETHODCALLTYPE WebView::canZoomPageOut(
3581 /* [in] */ IUnknown* /*sender*/,
3582 /* [retval][out] */ BOOL* result)
3584 bool canShrinkMore = canZoomOut(false);
3585 *result = canShrinkMore ? TRUE : FALSE;
3589 bool WebView::canZoomOut(bool isTextOnly)
3591 return zoomMultiplier(isTextOnly) / ZoomMultiplierRatio > MinimumZoomMultiplier;
3594 HRESULT STDMETHODCALLTYPE WebView::makeTextSmaller(
3595 /* [in] */ IUnknown* /*sender*/)
3597 return zoomOut(m_page->settings()->zoomsTextOnly());
3600 HRESULT STDMETHODCALLTYPE WebView::zoomPageOut(
3601 /* [in] */ IUnknown* /*sender*/)
3603 return zoomOut(false);
3606 HRESULT WebView::zoomOut(bool isTextOnly)
3608 if (!canZoomOut(isTextOnly))
3610 setZoomMultiplier(zoomMultiplier(isTextOnly) / ZoomMultiplierRatio, isTextOnly);
3614 HRESULT STDMETHODCALLTYPE WebView::canMakeTextStandardSize(
3615 /* [in] */ IUnknown* /*sender*/,
3616 /* [retval][out] */ BOOL* result)
3618 // 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.
3619 bool notAlreadyStandard = canResetZoom(true);
3620 *result = notAlreadyStandard ? TRUE : FALSE;
3624 HRESULT STDMETHODCALLTYPE WebView::canResetPageZoom(
3625 /* [in] */ IUnknown* /*sender*/,
3626 /* [retval][out] */ BOOL* result)
3628 bool notAlreadyStandard = canResetZoom(false);
3629 *result = notAlreadyStandard ? TRUE : FALSE;
3633 bool WebView::canResetZoom(bool isTextOnly)
3635 return zoomMultiplier(isTextOnly) != 1.0f;
3638 HRESULT STDMETHODCALLTYPE WebView::makeTextStandardSize(
3639 /* [in] */ IUnknown* /*sender*/)
3641 return resetZoom(true);
3644 HRESULT STDMETHODCALLTYPE WebView::resetPageZoom(
3645 /* [in] */ IUnknown* /*sender*/)
3647 return resetZoom(false);
3650 HRESULT WebView::resetZoom(bool isTextOnly)
3652 if (!canResetZoom(isTextOnly))
3654 setZoomMultiplier(1.0f, isTextOnly);
3658 HRESULT STDMETHODCALLTYPE WebView::toggleContinuousSpellChecking(
3659 /* [in] */ IUnknown* /*sender*/)
3663 if (FAILED(hr = isContinuousSpellCheckingEnabled(&enabled)))
3665 return setContinuousSpellCheckingEnabled(enabled ? FALSE : TRUE);
3668 HRESULT STDMETHODCALLTYPE WebView::toggleSmartInsertDelete(
3669 /* [in] */ IUnknown* /*sender*/)
3671 BOOL enabled = FALSE;
3672 HRESULT hr = smartInsertDeleteEnabled(&enabled);
3676 return setSmartInsertDeleteEnabled(enabled ? FALSE : TRUE);
3679 HRESULT STDMETHODCALLTYPE WebView::toggleGrammarChecking(
3680 /* [in] */ IUnknown* /*sender*/)
3683 HRESULT hr = isGrammarCheckingEnabled(&enabled);
3687 return setGrammarCheckingEnabled(enabled ? FALSE : TRUE);
3690 HRESULT STDMETHODCALLTYPE WebView::reloadFromOrigin(
3691 /* [in] */ IUnknown* /*sender*/)
3696 return m_mainFrame->reloadFromOrigin();
3699 // IWebViewCSS -----------------------------------------------------------------
3701 HRESULT STDMETHODCALLTYPE WebView::computedStyleForElement(
3702 /* [in] */ IDOMElement* /*element*/,
3703 /* [in] */ BSTR /*pseudoElement*/,
3704 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3706 ASSERT_NOT_REACHED();
3710 // IWebViewEditing -------------------------------------------------------------
3712 HRESULT STDMETHODCALLTYPE WebView::editableDOMRangeForPoint(
3713 /* [in] */ LPPOINT /*point*/,