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 "WebDatabaseManager.h"
34 #include "WebDocumentLoader.h"
35 #include "WebEditorClient.h"
36 #include "WebElementPropertyBag.h"
38 #include "WebBackForwardList.h"
39 #include "WebChromeClient.h"
40 #include "WebContextMenuClient.h"
41 #include "WebCoreTextRenderer.h"
42 #include "WebDragClient.h"
43 #include "WebIconDatabase.h"
44 #include "WebInspector.h"
45 #include "WebInspectorClient.h"
47 #include "WebKitStatisticsPrivate.h"
48 #include "WebKitSystemBits.h"
49 #include "WebMutableURLRequest.h"
50 #include "WebNotificationCenter.h"
51 #include "WebPreferences.h"
52 #pragma warning( push, 0 )
53 #include <WebCore/ApplicationCacheStorage.h>
54 #include <WebCore/AXObjectCache.h>
55 #include <WebCore/BString.h>
56 #include <WebCore/Cache.h>
57 #include <WebCore/ContextMenu.h>
58 #include <WebCore/ContextMenuController.h>
59 #include <WebCore/CookieStorageWin.h>
60 #include <WebCore/CString.h>
61 #include <WebCore/Cursor.h>
62 #include <WebCore/Document.h>
63 #include <WebCore/DragController.h>
64 #include <WebCore/DragData.h>
65 #include <WebCore/Editor.h>
66 #include <WebCore/EventHandler.h>
67 #include <WebCore/EventNames.h>
68 #include <WebCore/FileSystem.h>
69 #include <WebCore/FocusController.h>
70 #include <WebCore/FloatQuad.h>
71 #include <WebCore/FrameLoader.h>
72 #include <WebCore/FrameTree.h>
73 #include <WebCore/FrameView.h>
74 #include <WebCore/FrameWin.h>
75 #include <WebCore/GDIObjectCounter.h>
76 #include <WebCore/GraphicsContext.h>
77 #include <WebCore/HistoryItem.h>
78 #include <WebCore/HitTestResult.h>
79 #include <WebCore/IntRect.h>
80 #include <WebCore/KeyboardEvent.h>
81 #include <WebCore/Language.h>
82 #include <WebCore/Logging.h>
83 #include <WebCore/MIMETypeRegistry.h>
84 #include <WebCore/Page.h>
85 #include <WebCore/PageCache.h>
86 #include <WebCore/PlatformKeyboardEvent.h>
87 #include <WebCore/PlatformMouseEvent.h>
88 #include <WebCore/PlatformWheelEvent.h>
89 #include <WebCore/PluginDatabase.h>
90 #include <WebCore/PluginInfoStore.h>
91 #include <WebCore/PluginView.h>
92 #include <WebCore/ProgressTracker.h>
93 #include <WebCore/RenderTheme.h>
94 #include <WebCore/ResourceHandle.h>
95 #include <WebCore/ResourceHandleClient.h>
96 #include <WebCore/ScriptValue.h>
97 #include <WebCore/ScrollbarTheme.h>
98 #include <WebCore/SelectionController.h>
99 #include <WebCore/Settings.h>
100 #include <WebCore/SimpleFontData.h>
101 #include <WebCore/TypingCommand.h>
102 #include <WebCore/WindowMessageBroadcaster.h>
104 #include <JavaScriptCore/InitializeThreading.h>
105 #include <JavaScriptCore/JSLock.h>
106 #include <JavaScriptCore/JSValue.h>
109 #include <CoreGraphics/CGContext.h>
113 #include <CoreFoundation/CoreFoundation.h>
117 #include <CFNetwork/CFURLCachePriv.h>
118 #include <CFNetwork/CFURLProtocolPriv.h>
119 #include <WebKitSystemInterface/WebKitSystemInterface.h>
122 #include <wtf/HashSet.h>
127 #include <windowsx.h>
129 using namespace WebCore;
134 static HMODULE accessibilityLib;
135 static HashSet<WebView*> pendingDeleteBackingStoreSet;
137 static String osVersion();
138 static String webKitVersion();
140 WebView* kit(Page* page)
142 return page ? static_cast<WebChromeClient*>(page->chrome()->client())->webView() : 0;
145 class PreferencesChangedOrRemovedObserver : public IWebNotificationObserver {
147 static PreferencesChangedOrRemovedObserver* sharedInstance();
150 PreferencesChangedOrRemovedObserver() {}
151 ~PreferencesChangedOrRemovedObserver() {}
153 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) { return E_FAIL; }
154 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; }
155 virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; }
158 // IWebNotificationObserver
159 virtual HRESULT STDMETHODCALLTYPE onNotify(
160 /* [in] */ IWebNotification* notification);
163 HRESULT notifyPreferencesChanged(WebCacheModel);
164 HRESULT notifyPreferencesRemoved(WebCacheModel);
167 PreferencesChangedOrRemovedObserver* PreferencesChangedOrRemovedObserver::sharedInstance()
169 static PreferencesChangedOrRemovedObserver* shared = new PreferencesChangedOrRemovedObserver;
173 HRESULT PreferencesChangedOrRemovedObserver::onNotify(IWebNotification* notification)
177 COMPtr<IUnknown> unkPrefs;
178 hr = notification->getObject(&unkPrefs);
182 COMPtr<IWebPreferences> preferences(Query, unkPrefs);
184 return E_NOINTERFACE;
186 WebCacheModel cacheModel;
187 hr = preferences->cacheModel(&cacheModel);
192 hr = notification->name(&nameBSTR);
196 name.adoptBSTR(nameBSTR);
198 if (wcscmp(name, WebPreferences::webPreferencesChangedNotification()) == 0)
199 return notifyPreferencesChanged(cacheModel);
201 if (wcscmp(name, WebPreferences::webPreferencesRemovedNotification()) == 0)
202 return notifyPreferencesRemoved(cacheModel);
204 ASSERT_NOT_REACHED();
208 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesChanged(WebCacheModel cacheModel)
212 if (!WebView::didSetCacheModel() || cacheModel > WebView::cacheModel())
213 WebView::setCacheModel(cacheModel);
214 else if (cacheModel < WebView::cacheModel()) {
215 WebCacheModel sharedPreferencesCacheModel;
216 hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
219 WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
225 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesRemoved(WebCacheModel cacheModel)
229 if (cacheModel == WebView::cacheModel()) {
230 WebCacheModel sharedPreferencesCacheModel;
231 hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
234 WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
241 const LPCWSTR kWebViewWindowClassName = L"WebViewWindowClass";
243 const int WM_XP_THEMECHANGED = 0x031A;
244 const int WM_VISTA_MOUSEHWHEEL = 0x020E;
246 static const int maxToolTipWidth = 250;
248 static const int delayBeforeDeletingBackingStoreMsec = 5000;
250 static ATOM registerWebView();
251 static LRESULT CALLBACK WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
253 static void initializeStaticObservers();
255 static HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences*);
257 HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches);
259 static bool continuousSpellCheckingEnabled;
260 static bool grammarCheckingEnabled;
262 static bool s_didSetCacheModel;
263 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
266 UpdateActiveStateTimer = 1,
267 DeleteBackingStoreTimer = 2,
270 // WebView ----------------------------------------------------------------
272 bool WebView::s_allowSiteSpecificHacks = false;
280 , m_hasCustomDropTarget(false)
281 , m_useBackForwardList(true)
282 , m_userAgentOverridden(false)
283 , m_zoomMultiplier(1.0f)
284 , m_mouseActivated(false)
286 , m_currentCharacterCode(0)
287 , m_isBeingDestroyed(false)
289 , m_hasSpellCheckerDocumentTag(false)
290 , m_smartInsertDeleteEnabled(false)
292 , m_inIMEComposition(0)
294 , m_closeWindowTimer(this, &WebView::closeWindowTimerFired)
295 , m_topLevelParent(0)
296 , m_deleteBackingStoreTimerActive(false)
297 , m_transparent(false)
298 , m_selectTrailingWhitespaceEnabled(false)
300 JSC::initializeThreading();
302 m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
304 CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper,(void**)&m_dropTargetHelper);
306 initializeStaticObservers();
308 WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
310 if (SUCCEEDED(sharedPreferences->continuousSpellCheckingEnabled(&enabled)))
311 continuousSpellCheckingEnabled = !!enabled;
312 if (SUCCEEDED(sharedPreferences->grammarCheckingEnabled(&enabled)))
313 grammarCheckingEnabled = !!enabled;
317 gClassNameCount.add("WebView");
322 deleteBackingStore();
324 // <rdar://4958382> m_viewWindow will be destroyed when m_hostWindow is destroyed, but if
325 // setHostWindow was never called we will leak our HWND. If we still have a valid HWND at
326 // this point, we should just destroy it ourselves.
327 if (!isBeingDestroyed() && ::IsWindow(m_viewWindow))
328 ::DestroyWindow(m_viewWindow);
330 // the tooltip window needs to be explicitly destroyed since it isn't a WS_CHILD
331 if (::IsWindow(m_toolTipHwnd))
332 ::DestroyWindow(m_toolTipHwnd);
335 ASSERT(!m_preferences);
339 gClassNameCount.remove("WebView");
342 WebView* WebView::createInstance()
344 WebView* instance = new WebView();
349 void initializeStaticObservers()
351 static bool initialized;
356 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
357 notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesChangedNotification(), 0);
358 notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesRemovedNotification(), 0);
361 static HashSet<WebView*>& allWebViewsSet()
363 static HashSet<WebView*> allWebViewsSet;
364 return allWebViewsSet;
367 void WebView::addToAllWebViewsSet()
369 allWebViewsSet().add(this);
372 void WebView::removeFromAllWebViewsSet()
374 allWebViewsSet().remove(this);
377 void WebView::setCacheModel(WebCacheModel cacheModel)
380 if (s_didSetCacheModel && cacheModel == s_cacheModel)
383 RetainPtr<CFURLCacheRef> cfurlCache(AdoptCF, CFURLCacheCopySharedURLCache());
384 RetainPtr<CFStringRef> cfurlCacheDirectory(AdoptCF, wkCopyFoundationCacheDirectory());
385 if (!cfurlCacheDirectory)
386 cfurlCacheDirectory.adoptCF(WebCore::localUserSpecificStorageDirectory().createCFString());
388 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
389 // count doesn't align exactly to a megabyte boundary.
390 unsigned long long memSize = WebMemorySize() / 1024 / 1000;
391 unsigned long long diskFreeSize = WebVolumeFreeSize(cfurlCacheDirectory.get()) / 1024 / 1000;
393 unsigned cacheTotalCapacity = 0;
394 unsigned cacheMinDeadCapacity = 0;
395 unsigned cacheMaxDeadCapacity = 0;
396 double deadDecodedDataDeletionInterval = 0;
398 unsigned pageCacheCapacity = 0;
400 CFIndex cfurlCacheMemoryCapacity = 0;
401 CFIndex cfurlCacheDiskCapacity = 0;
403 switch (cacheModel) {
404 case WebCacheModelDocumentViewer: {
405 // Page cache capacity (in pages)
406 pageCacheCapacity = 0;
408 // Object cache capacities (in bytes)
410 cacheTotalCapacity = 96 * 1024 * 1024;
411 else if (memSize >= 1536)
412 cacheTotalCapacity = 64 * 1024 * 1024;
413 else if (memSize >= 1024)
414 cacheTotalCapacity = 32 * 1024 * 1024;
415 else if (memSize >= 512)
416 cacheTotalCapacity = 16 * 1024 * 1024;
418 cacheMinDeadCapacity = 0;
419 cacheMaxDeadCapacity = 0;
421 // Foundation memory cache capacity (in bytes)
422 cfurlCacheMemoryCapacity = 0;
424 // Foundation disk cache capacity (in bytes)
425 cfurlCacheDiskCapacity = CFURLCacheDiskCapacity(cfurlCache.get());
429 case WebCacheModelDocumentBrowser: {
430 // Page cache capacity (in pages)
432 pageCacheCapacity = 3;
433 else if (memSize >= 512)
434 pageCacheCapacity = 2;
435 else if (memSize >= 256)
436 pageCacheCapacity = 1;
438 pageCacheCapacity = 0;
440 // Object cache capacities (in bytes)
442 cacheTotalCapacity = 96 * 1024 * 1024;
443 else if (memSize >= 1536)
444 cacheTotalCapacity = 64 * 1024 * 1024;
445 else if (memSize >= 1024)
446 cacheTotalCapacity = 32 * 1024 * 1024;
447 else if (memSize >= 512)
448 cacheTotalCapacity = 16 * 1024 * 1024;
450 cacheMinDeadCapacity = cacheTotalCapacity / 8;
451 cacheMaxDeadCapacity = cacheTotalCapacity / 4;
453 // Foundation memory cache capacity (in bytes)
455 cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
456 else if (memSize >= 1024)
457 cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
458 else if (memSize >= 512)
459 cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
461 cfurlCacheMemoryCapacity = 512 * 1024;
463 // Foundation disk cache capacity (in bytes)
464 if (diskFreeSize >= 16384)
465 cfurlCacheDiskCapacity = 50 * 1024 * 1024;
466 else if (diskFreeSize >= 8192)
467 cfurlCacheDiskCapacity = 40 * 1024 * 1024;
468 else if (diskFreeSize >= 4096)
469 cfurlCacheDiskCapacity = 30 * 1024 * 1024;
471 cfurlCacheDiskCapacity = 20 * 1024 * 1024;
475 case WebCacheModelPrimaryWebBrowser: {
476 // Page cache capacity (in pages)
477 // (Research indicates that value / page drops substantially after 3 pages.)
479 pageCacheCapacity = 5;
480 else if (memSize >= 1024)
481 pageCacheCapacity = 4;
482 else if (memSize >= 512)
483 pageCacheCapacity = 3;
484 else if (memSize >= 256)
485 pageCacheCapacity = 2;
487 pageCacheCapacity = 1;
489 // Object cache capacities (in bytes)
490 // (Testing indicates that value / MB depends heavily on content and
491 // browsing pattern. Even growth above 128MB can have substantial
492 // value / MB for some content / browsing patterns.)
494 cacheTotalCapacity = 128 * 1024 * 1024;
495 else if (memSize >= 1536)
496 cacheTotalCapacity = 96 * 1024 * 1024;
497 else if (memSize >= 1024)
498 cacheTotalCapacity = 64 * 1024 * 1024;
499 else if (memSize >= 512)
500 cacheTotalCapacity = 32 * 1024 * 1024;
502 cacheMinDeadCapacity = cacheTotalCapacity / 4;
503 cacheMaxDeadCapacity = cacheTotalCapacity / 2;
505 // This code is here to avoid a PLT regression. We can remove it if we
506 // can prove that the overall system gain would justify the regression.
507 cacheMaxDeadCapacity = max(24u, cacheMaxDeadCapacity);
509 deadDecodedDataDeletionInterval = 60;
511 // Foundation memory cache capacity (in bytes)
512 // (These values are small because WebCore does most caching itself.)
514 cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
515 else if (memSize >= 512)
516 cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
517 else if (memSize >= 256)
518 cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
520 cfurlCacheMemoryCapacity = 512 * 1024;
522 // Foundation disk cache capacity (in bytes)
523 if (diskFreeSize >= 16384)
524 cfurlCacheDiskCapacity = 175 * 1024 * 1024;
525 else if (diskFreeSize >= 8192)
526 cfurlCacheDiskCapacity = 150 * 1024 * 1024;
527 else if (diskFreeSize >= 4096)
528 cfurlCacheDiskCapacity = 125 * 1024 * 1024;
529 else if (diskFreeSize >= 2048)
530 cfurlCacheDiskCapacity = 100 * 1024 * 1024;
531 else if (diskFreeSize >= 1024)
532 cfurlCacheDiskCapacity = 75 * 1024 * 1024;
534 cfurlCacheDiskCapacity = 50 * 1024 * 1024;
539 ASSERT_NOT_REACHED();
542 // Don't shrink a big disk cache, since that would cause churn.
543 cfurlCacheDiskCapacity = max(cfurlCacheDiskCapacity, CFURLCacheDiskCapacity(cfurlCache.get()));
545 cache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
546 cache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
547 pageCache()->setCapacity(pageCacheCapacity);
549 CFURLCacheSetMemoryCapacity(cfurlCache.get(), cfurlCacheMemoryCapacity);
550 CFURLCacheSetDiskCapacity(cfurlCache.get(), cfurlCacheDiskCapacity);
552 s_didSetCacheModel = true;
553 s_cacheModel = cacheModel;
558 WebCacheModel WebView::cacheModel()
563 bool WebView::didSetCacheModel()
565 return s_didSetCacheModel;
568 WebCacheModel WebView::maxCacheModelInAnyInstance()
570 WebCacheModel cacheModel = WebCacheModelDocumentViewer;
572 HashSet<WebView*>::iterator end = allWebViewsSet().end();
573 for (HashSet<WebView*>::iterator it = allWebViewsSet().begin(); it != end; ++it) {
574 COMPtr<IWebPreferences> pref;
575 if (FAILED((*it)->preferences(&pref)))
577 WebCacheModel prefCacheModel = WebCacheModelDocumentViewer;
578 if (FAILED(pref->cacheModel(&prefCacheModel)))
581 cacheModel = max(cacheModel, prefCacheModel);
587 HRESULT STDMETHODCALLTYPE WebView::close()
594 if (m_uiDelegatePrivate) {
595 COMPtr<IWebUIDelegatePrivate5> uiDelegatePrivate5(Query, m_uiDelegatePrivate);
596 if (uiDelegatePrivate5)
597 uiDelegatePrivate5->webViewClosing(this);
600 removeFromAllWebViewsSet();
602 Frame* frame = m_page->mainFrame();
604 frame->loader()->detachFromParent();
606 if (m_mouseOutTracker) {
607 m_mouseOutTracker->dwFlags = TME_CANCEL;
608 ::TrackMouseEvent(m_mouseOutTracker.get());
609 m_mouseOutTracker.set(0);
614 setDownloadDelegate(0);
615 setEditingDelegate(0);
616 setFrameLoadDelegate(0);
617 setFrameLoadDelegatePrivate(0);
618 setPolicyDelegate(0);
619 setResourceLoadDelegate(0);
624 m_webInspector->webViewClosed();
629 registerForIconNotification(false);
630 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
631 notifyCenter->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
634 m_preferences->identifier(&identifier);
636 COMPtr<WebPreferences> preferences = m_preferences;
638 preferences->didRemoveFromWebView();
639 // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
642 WebPreferences::removeReferenceForIdentifier(identifier);
643 SysFreeString(identifier);
646 deleteBackingStore();
650 void WebView::repaint(const WebCore::IntRect& windowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
652 if (!repaintContentOnly) {
653 RECT rect = windowRect;
654 ::InvalidateRect(m_viewWindow, &rect, false);
657 addToDirtyRegion(windowRect);
659 if (repaintContentOnly)
660 updateBackingStore(core(topLevelFrame())->view());
662 ::UpdateWindow(m_viewWindow);
666 void WebView::deleteBackingStore()
668 pendingDeleteBackingStoreSet.remove(this);
670 if (m_deleteBackingStoreTimerActive) {
671 KillTimer(m_viewWindow, DeleteBackingStoreTimer);
672 m_deleteBackingStoreTimerActive = false;
674 m_backingStoreBitmap.clear();
675 m_backingStoreDirtyRegion.clear();
677 m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
680 bool WebView::ensureBackingStore()
683 ::GetClientRect(m_viewWindow, &windowRect);
684 LONG width = windowRect.right - windowRect.left;
685 LONG height = windowRect.bottom - windowRect.top;
686 if (width > 0 && height > 0 && (width != m_backingStoreSize.cx || height != m_backingStoreSize.cy)) {
687 deleteBackingStore();
689 m_backingStoreSize.cx = width;
690 m_backingStoreSize.cy = height;
691 BITMAPINFO bitmapInfo;
692 bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
693 bitmapInfo.bmiHeader.biWidth = width;
694 bitmapInfo.bmiHeader.biHeight = -height;
695 bitmapInfo.bmiHeader.biPlanes = 1;
696 bitmapInfo.bmiHeader.biBitCount = 32;
697 bitmapInfo.bmiHeader.biCompression = BI_RGB;
698 bitmapInfo.bmiHeader.biSizeImage = 0;
699 bitmapInfo.bmiHeader.biXPelsPerMeter = 0;
700 bitmapInfo.bmiHeader.biYPelsPerMeter = 0;
701 bitmapInfo.bmiHeader.biClrUsed = 0;
702 bitmapInfo.bmiHeader.biClrImportant = 0;
705 m_backingStoreBitmap.set(::CreateDIBSection(NULL, &bitmapInfo, DIB_RGB_COLORS, &pixels, NULL, 0));
712 void WebView::addToDirtyRegion(const IntRect& dirtyRect)
714 HRGN newRegion = ::CreateRectRgn(dirtyRect.x(), dirtyRect.y(),
715 dirtyRect.right(), dirtyRect.bottom());
716 addToDirtyRegion(newRegion);
719 void WebView::addToDirtyRegion(HRGN newRegion)
721 LOCAL_GDI_COUNTER(0, __FUNCTION__);
723 if (m_backingStoreDirtyRegion) {
724 HRGN combinedRegion = ::CreateRectRgn(0,0,0,0);
725 ::CombineRgn(combinedRegion, m_backingStoreDirtyRegion.get(), newRegion, RGN_OR);
726 ::DeleteObject(newRegion);
727 m_backingStoreDirtyRegion.set(combinedRegion);
729 m_backingStoreDirtyRegion.set(newRegion);
731 COMPtr<IWebUIDelegatePrivate5> delegate(Query, m_uiDelegatePrivate);
733 delegate->webViewDidInvalidate(this);
736 void WebView::scrollBackingStore(FrameView* frameView, int dx, int dy, const IntRect& scrollViewRect, const IntRect& clipRect)
738 LOCAL_GDI_COUNTER(0, __FUNCTION__);
740 // If there's no backing store we don't need to update it
741 if (!m_backingStoreBitmap) {
742 if (m_uiDelegatePrivate)
743 m_uiDelegatePrivate->webViewScrolled(this);
748 // Make a region to hold the invalidated scroll area.
749 HRGN updateRegion = ::CreateRectRgn(0, 0, 0, 0);
751 // Collect our device context info and select the bitmap to scroll.
752 HDC windowDC = ::GetDC(m_viewWindow);
753 HDC bitmapDC = ::CreateCompatibleDC(windowDC);
754 ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
756 // Scroll the bitmap.
757 RECT scrollRectWin(scrollViewRect);
758 RECT clipRectWin(clipRect);
759 ::ScrollDC(bitmapDC, dx, dy, &scrollRectWin, &clipRectWin, updateRegion, 0);
761 ::GetRgnBox(updateRegion, ®ionBox);
766 // Add the dirty region to the backing store's dirty region.
767 addToDirtyRegion(updateRegion);
769 if (m_uiDelegatePrivate)
770 m_uiDelegatePrivate->webViewScrolled(this);
772 // Update the backing store.
773 updateBackingStore(frameView, bitmapDC, false);
776 ::DeleteDC(bitmapDC);
777 ::ReleaseDC(m_viewWindow, windowDC);
781 // This emulates the Mac smarts for painting rects intelligently. This is very
782 // important for us, since we double buffer based off dirty rects.
783 static void getUpdateRects(HRGN region, const IntRect& dirtyRect, Vector<IntRect>& rects)
785 ASSERT_ARG(region, region);
787 const int cRectThreshold = 10;
788 const float cWastedSpaceThreshold = 0.75f;
792 DWORD regionDataSize = GetRegionData(region, sizeof(RGNDATA), NULL);
793 if (!regionDataSize) {
794 rects.append(dirtyRect);
798 Vector<unsigned char> buffer(regionDataSize);
799 RGNDATA* regionData = reinterpret_cast<RGNDATA*>(buffer.data());
800 GetRegionData(region, regionDataSize, regionData);
801 if (regionData->rdh.nCount > cRectThreshold) {
802 rects.append(dirtyRect);
806 double singlePixels = 0.0;
809 for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
810 singlePixels += (rect->right - rect->left) * (rect->bottom - rect->top);
812 double unionPixels = dirtyRect.width() * dirtyRect.height();
813 double wastedSpace = 1.0 - (singlePixels / unionPixels);
814 if (wastedSpace <= cWastedSpaceThreshold) {
815 rects.append(dirtyRect);
819 for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
823 void WebView::updateBackingStore(FrameView* frameView, HDC dc, bool backingStoreCompletelyDirty, WindowsToPaint windowsToPaint)
825 LOCAL_GDI_COUNTER(0, __FUNCTION__);
830 windowDC = ::GetDC(m_viewWindow);
831 bitmapDC = ::CreateCompatibleDC(windowDC);
832 ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
835 if (m_backingStoreBitmap && (m_backingStoreDirtyRegion || backingStoreCompletelyDirty)) {
836 // Do a layout first so that everything we render to the backing store is always current.
837 if (Frame* coreFrame = core(m_mainFrame))
838 if (FrameView* view = coreFrame->view())
839 view->layoutIfNeededRecursive();
841 Vector<IntRect> paintRects;
842 if (!backingStoreCompletelyDirty) {
844 ::GetRgnBox(m_backingStoreDirtyRegion.get(), ®ionBox);
845 getUpdateRects(m_backingStoreDirtyRegion.get(), regionBox, paintRects);
848 ::GetClientRect(m_viewWindow, &clientRect);
849 paintRects.append(clientRect);
852 for (unsigned i = 0; i < paintRects.size(); ++i)
853 paintIntoBackingStore(frameView, bitmapDC, paintRects[i], windowsToPaint);
855 if (m_uiDelegatePrivate) {
856 COMPtr<IWebUIDelegatePrivate2> uiDelegatePrivate2(Query, m_uiDelegatePrivate);
857 if (uiDelegatePrivate2)
858 uiDelegatePrivate2->webViewPainted(this);
861 m_backingStoreDirtyRegion.clear();
865 ::DeleteDC(bitmapDC);
866 ::ReleaseDC(m_viewWindow, windowDC);
872 void WebView::paint(HDC dc, LPARAM options)
874 LOCAL_GDI_COUNTER(0, __FUNCTION__);
876 Frame* coreFrame = core(m_mainFrame);
879 FrameView* frameView = coreFrame->view();
886 int regionType = NULLREGION;
888 WindowsToPaint windowsToPaint;
890 region.set(CreateRectRgn(0,0,0,0));
891 regionType = GetUpdateRgn(m_viewWindow, region.get(), false);
892 hdc = BeginPaint(m_viewWindow, &ps);
893 rcPaint = ps.rcPaint;
894 // We're painting to the screen, and our child windows can handle
895 // painting themselves to the screen.
896 windowsToPaint = PaintWebViewOnly;
899 ::GetClientRect(m_viewWindow, &rcPaint);
900 if (options & PRF_ERASEBKGND)
901 ::FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
902 // Since we aren't painting to the screen, we want to paint all our
903 // children into the HDC.
904 windowsToPaint = PaintWebViewAndChildren;
907 HDC bitmapDC = ::CreateCompatibleDC(hdc);
908 bool backingStoreCompletelyDirty = ensureBackingStore();
909 ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
911 // Update our backing store if needed.
912 updateBackingStore(frameView, bitmapDC, backingStoreCompletelyDirty, windowsToPaint);
914 // Now we blit the updated backing store
915 IntRect windowDirtyRect = rcPaint;
917 // Apply the same heuristic for this update region too.
918 Vector<IntRect> blitRects;
919 if (region && regionType == COMPLEXREGION)
920 getUpdateRects(region.get(), windowDirtyRect, blitRects);
922 blitRects.append(windowDirtyRect);
924 for (unsigned i = 0; i < blitRects.size(); ++i)
925 paintIntoWindow(bitmapDC, hdc, blitRects[i]);
927 ::DeleteDC(bitmapDC);
929 // Paint the gripper.
930 COMPtr<IWebUIDelegate> ui;
931 if (SUCCEEDED(uiDelegate(&ui))) {
932 COMPtr<IWebUIDelegatePrivate> uiPrivate;
933 if (SUCCEEDED(ui->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&uiPrivate))) {
935 if (SUCCEEDED(uiPrivate->webViewResizerRect(this, &r))) {
936 LOCAL_GDI_COUNTER(2, __FUNCTION__" webViewDrawResizer delegate call");
937 uiPrivate->webViewDrawResizer(this, hdc, (frameView->containsScrollbarsAvoidingResizer() ? true : false), &r);
943 EndPaint(m_viewWindow, &ps);
948 cancelDeleteBackingStoreSoon();
950 deleteBackingStoreSoon();
953 void WebView::paintIntoBackingStore(FrameView* frameView, HDC bitmapDC, const IntRect& dirtyRect, WindowsToPaint windowsToPaint)
955 LOCAL_GDI_COUNTER(0, __FUNCTION__);
957 RECT rect = dirtyRect;
959 #if FLASH_BACKING_STORE_REDRAW
960 HDC dc = ::GetDC(m_viewWindow);
961 OwnPtr<HBRUSH> yellowBrush = CreateSolidBrush(RGB(255, 255, 0));
962 FillRect(dc, &rect, yellowBrush.get());
965 paintIntoWindow(bitmapDC, dc, dirtyRect);
966 ::ReleaseDC(m_viewWindow, dc);
969 GraphicsContext gc(bitmapDC, m_transparent);
970 gc.setShouldIncludeChildWindows(windowsToPaint == PaintWebViewAndChildren);
973 gc.clearRect(dirtyRect);
975 FillRect(bitmapDC, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
976 if (frameView && frameView->frame() && frameView->frame()->contentRenderer()) {
978 frameView->paint(&gc, dirtyRect);
983 void WebView::paintIntoWindow(HDC bitmapDC, HDC windowDC, const IntRect& dirtyRect)
985 LOCAL_GDI_COUNTER(0, __FUNCTION__);
986 #if FLASH_WINDOW_REDRAW
987 OwnPtr<HBRUSH> greenBrush = CreateSolidBrush(RGB(0, 255, 0));
988 RECT rect = dirtyRect;
989 FillRect(windowDC, &rect, greenBrush.get());
994 // Blit the dirty rect from the backing store into the same position
995 // in the destination DC.
996 BitBlt(windowDC, dirtyRect.x(), dirtyRect.y(), dirtyRect.width(), dirtyRect.height(), bitmapDC,
997 dirtyRect.x(), dirtyRect.y(), SRCCOPY);
1000 void WebView::frameRect(RECT* rect)
1002 ::GetWindowRect(m_viewWindow, rect);
1005 void WebView::closeWindowSoon()
1007 m_closeWindowTimer.startOneShot(0);
1011 void WebView::closeWindowTimerFired(WebCore::Timer<WebView>*)
1017 void WebView::closeWindow()
1019 if (m_hasSpellCheckerDocumentTag) {
1020 if (m_editingDelegate)
1021 m_editingDelegate->closeSpellDocument(this);
1022 m_hasSpellCheckerDocumentTag = false;
1025 COMPtr<IWebUIDelegate> ui;
1026 if (SUCCEEDED(uiDelegate(&ui)))
1027 ui->webViewClose(this);
1030 bool WebView::canHandleRequest(const WebCore::ResourceRequest& request)
1032 // On the mac there's an about url protocol implementation but CFNetwork doesn't have that.
1033 if (equalIgnoringCase(String(request.url().protocol()), "about"))
1037 if (CFURLProtocolCanHandleRequest(request.cfURLRequest()))
1040 // FIXME: Mac WebKit calls _representationExistsForURLScheme here
1047 String WebView::standardUserAgentWithApplicationName(const String& applicationName)
1049 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());
1052 Page* WebView::page()
1057 bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam)
1059 static const int contextMenuMargin = 1;
1061 // Translate the screen coordinates into window coordinates
1062 POINT coords = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
1063 if (coords.x == -1 || coords.y == -1) {
1064 FrameView* view = m_page->mainFrame()->view();
1068 int rightAligned = ::GetSystemMetrics(SM_MENUDROPALIGNMENT);
1071 // The context menu event was generated from the keyboard, so show the context menu by the current selection.
1072 Position start = m_page->mainFrame()->selection()->selection().start();
1073 Position end = m_page->mainFrame()->selection()->selection().end();
1075 if (!start.node() || !end.node())
1076 location = IntPoint(rightAligned ? view->contentsWidth() - contextMenuMargin : contextMenuMargin, contextMenuMargin);
1078 RenderObject* renderer = start.node()->renderer();
1082 // Calculate the rect of the first line of the selection (cribbed from -[WebCoreFrameBridge firstRectForDOMRange:],
1083 // now Frame::firstRectForRange(), which perhaps this should call).
1084 int extraWidthToEndOfLine = 0;
1086 InlineBox* startInlineBox;
1087 int startCaretOffset;
1088 start.getInlineBoxAndOffset(DOWNSTREAM, startInlineBox, startCaretOffset);
1089 IntRect startCaretRect = renderer->localCaretRect(startInlineBox, startCaretOffset, &extraWidthToEndOfLine);
1090 if (startCaretRect != IntRect())
1091 startCaretRect = renderer->localToAbsoluteQuad(FloatRect(startCaretRect)).enclosingBoundingBox();
1093 InlineBox* endInlineBox;
1095 end.getInlineBoxAndOffset(UPSTREAM, endInlineBox, endCaretOffset);
1096 IntRect endCaretRect = renderer->localCaretRect(endInlineBox, endCaretOffset);
1097 if (endCaretRect != IntRect())
1098 endCaretRect = renderer->localToAbsoluteQuad(FloatRect(endCaretRect)).enclosingBoundingBox();
1101 if (startCaretRect.y() == endCaretRect.y())
1102 firstRect = IntRect(min(startCaretRect.x(), endCaretRect.x()), startCaretRect.y(), abs(endCaretRect.x() - startCaretRect.x()), max(startCaretRect.height(), endCaretRect.height()));
1104 firstRect = IntRect(startCaretRect.x(), startCaretRect.y(), startCaretRect.width() + extraWidthToEndOfLine, startCaretRect.height());
1106 location = IntPoint(rightAligned ? firstRect.right() : firstRect.x(), firstRect.bottom());
1109 location = view->contentsToWindow(location);
1110 // FIXME: The IntSize(0, -1) is a hack to get the hit-testing to result in the selected element.
1111 // Ideally we'd have the position of a context menu event be separate from its target node.
1112 coords = location + IntSize(0, -1);
1114 if (!::ScreenToClient(m_viewWindow, &coords))
1118 lParam = MAKELPARAM(coords.x, coords.y);
1120 // The contextMenuController() holds onto the last context menu that was popped up on the
1121 // page until a new one is created. We need to clear this menu before propagating the event
1122 // through the DOM so that we can detect if we create a new menu for this event, since we
1123 // won't create a new menu if the DOM swallows the event and the defaultEventHandler does
1125 m_page->contextMenuController()->clearContextMenu();
1127 IntPoint documentPoint(m_page->mainFrame()->view()->windowToContents(coords));
1128 HitTestResult result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(documentPoint, false);
1129 Frame* targetFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : m_page->focusController()->focusedOrMainFrame();
1131 targetFrame->view()->setCursor(pointerCursor());
1132 PlatformMouseEvent mouseEvent(m_viewWindow, WM_RBUTTONUP, wParam, lParam);
1133 bool handledEvent = targetFrame->eventHandler()->sendContextMenuEvent(mouseEvent);
1138 ContextMenu* coreMenu = m_page->contextMenuController()->contextMenu();
1142 Node* node = coreMenu->hitTestResult().innerNonSharedNode();
1146 Frame* frame = node->document()->frame();
1150 FrameView* view = frame->view();
1154 POINT point(view->contentsToWindow(coreMenu->hitTestResult().point()));
1156 // Translate the point to screen coordinates
1157 if (!::ClientToScreen(m_viewWindow, &point))
1160 BOOL hasCustomMenus = false;
1162 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1165 m_uiDelegate->trackCustomPopupMenu((IWebView*)this, (OLE_HANDLE)(ULONG64)coreMenu->platformDescription(), &point);
1167 // Surprisingly, TPM_RIGHTBUTTON means that items are selectable with either the right OR left mouse button
1168 UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL
1169 | TPM_LEFTALIGN | TPM_HORPOSANIMATION;
1170 ::TrackPopupMenuEx(coreMenu->platformDescription(), flags, point.x, point.y, m_viewWindow, 0);
1176 bool WebView::onMeasureItem(WPARAM /*wParam*/, LPARAM lParam)
1181 BOOL hasCustomMenus = false;
1182 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1183 if (!hasCustomMenus)
1186 m_uiDelegate->measureCustomMenuItem((IWebView*)this, (void*)lParam);
1190 bool WebView::onDrawItem(WPARAM /*wParam*/, LPARAM lParam)
1195 BOOL hasCustomMenus = false;
1196 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1197 if (!hasCustomMenus)
1200 m_uiDelegate->drawCustomMenuItem((IWebView*)this, (void*)lParam);
1204 bool WebView::onInitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1209 HMENU menu = (HMENU)wParam;
1213 BOOL hasCustomMenus = false;
1214 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1215 if (!hasCustomMenus)
1218 m_uiDelegate->addCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1222 bool WebView::onUninitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1227 HMENU menu = (HMENU)wParam;
1231 BOOL hasCustomMenus = false;
1232 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1233 if (!hasCustomMenus)
1236 m_uiDelegate->cleanUpCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1240 void WebView::performContextMenuAction(WPARAM wParam, LPARAM lParam, bool byPosition)
1242 ContextMenu* menu = m_page->contextMenuController()->contextMenu();
1245 ContextMenuItem* item = byPosition ? menu->itemAtIndex((unsigned)wParam, (HMENU)lParam) : menu->itemWithAction((ContextMenuAction)wParam);
1248 m_page->contextMenuController()->contextMenuItemSelected(item);
1252 bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
1254 static LONG globalClickCount;
1255 static IntPoint globalPrevPoint;
1256 static MouseButton globalPrevButton;
1257 static LONG globalPrevMouseDownTime;
1259 // Create our event.
1260 // On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
1261 // of the event to be at (MINSHORT, MINSHORT).
1262 LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
1263 PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
1265 bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.pos().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
1266 abs(globalPrevPoint.y() - mouseEvent.pos().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
1267 LONG messageTime = ::GetMessageTime();
1269 if (inResizer(position)) {
1271 COMPtr<IWebUIDelegatePrivate4> uiPrivate(Query, m_uiDelegate);
1274 uiPrivate->webViewSendResizeMessage(message, wParam, position);
1279 bool handled = false;
1281 if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
1282 // FIXME: I'm not sure if this is the "right" way to do this
1283 // but without this call, we never become focused since we don't allow
1284 // the default handling of mouse events.
1285 SetFocus(m_viewWindow);
1287 // Always start capturing events when the mouse goes down in our HWND.
1288 ::SetCapture(m_viewWindow);
1290 if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) &&
1292 mouseEvent.button() == globalPrevButton)
1295 // Reset the click count.
1296 globalClickCount = 1;
1297 globalPrevMouseDownTime = messageTime;
1298 globalPrevButton = mouseEvent.button();
1299 globalPrevPoint = mouseEvent.pos();
1301 mouseEvent.setClickCount(globalClickCount);
1302 handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1303 } else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
1305 mouseEvent.setClickCount(globalClickCount);
1306 handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1307 } else if (message == WM_LBUTTONUP || message == WM_MBUTTONUP || message == WM_RBUTTONUP) {
1308 // Record the global position and the button of the up.
1309 globalPrevButton = mouseEvent.button();
1310 globalPrevPoint = mouseEvent.pos();
1311 mouseEvent.setClickCount(globalClickCount);
1312 m_page->mainFrame()->eventHandler()->handleMouseReleaseEvent(mouseEvent);
1314 } else if (message == WM_MOUSELEAVE && m_mouseOutTracker) {
1315 // Once WM_MOUSELEAVE is fired windows clears this tracker
1316 // so there is no need to disable it ourselves.
1317 m_mouseOutTracker.set(0);
1318 m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1320 } else if (message == WM_MOUSEMOVE) {
1321 if (!insideThreshold)
1322 globalClickCount = 0;
1323 mouseEvent.setClickCount(globalClickCount);
1324 handled = m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1325 if (!m_mouseOutTracker) {
1326 m_mouseOutTracker.set(new TRACKMOUSEEVENT);
1327 m_mouseOutTracker->cbSize = sizeof(TRACKMOUSEEVENT);
1328 m_mouseOutTracker->dwFlags = TME_LEAVE;
1329 m_mouseOutTracker->hwndTrack = m_viewWindow;
1330 ::TrackMouseEvent(m_mouseOutTracker.get());
1333 setMouseActivated(false);
1337 bool WebView::mouseWheel(WPARAM wParam, LPARAM lParam, bool isMouseHWheel)
1339 // Ctrl+Mouse wheel doesn't ever go into WebCore. It is used to
1340 // zoom instead (Mac zooms the whole Desktop, but Windows browsers trigger their
1341 // own local zoom modes for Ctrl+wheel).
1342 if (wParam & MK_CONTROL) {
1343 short delta = short(HIWORD(wParam));
1351 PlatformWheelEvent wheelEvent(m_viewWindow, wParam, lParam, isMouseHWheel);
1352 Frame* coreFrame = core(m_mainFrame);
1356 return coreFrame->eventHandler()->handleWheelEvent(wheelEvent);
1359 bool WebView::execCommand(WPARAM wParam, LPARAM /*lParam*/)
1361 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1362 switch (LOWORD(wParam)) {
1364 return frame->editor()->command("SelectAll").execute();
1366 return frame->editor()->command("Undo").execute();
1368 return frame->editor()->command("Redo").execute();
1373 bool WebView::keyUp(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1375 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::KeyUp, systemKeyDown);
1377 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1378 m_currentCharacterCode = 0;
1380 return frame->eventHandler()->keyEvent(keyEvent);
1383 static const unsigned CtrlKey = 1 << 0;
1384 static const unsigned AltKey = 1 << 1;
1385 static const unsigned ShiftKey = 1 << 2;
1388 struct KeyDownEntry {
1389 unsigned virtualKey;
1394 struct KeyPressEntry {
1400 static const KeyDownEntry keyDownEntries[] = {
1401 { VK_LEFT, 0, "MoveLeft" },
1402 { VK_LEFT, ShiftKey, "MoveLeftAndModifySelection" },
1403 { VK_LEFT, CtrlKey, "MoveWordLeft" },
1404 { VK_LEFT, CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection" },
1405 { VK_RIGHT, 0, "MoveRight" },
1406 { VK_RIGHT, ShiftKey, "MoveRightAndModifySelection" },
1407 { VK_RIGHT, CtrlKey, "MoveWordRight" },
1408 { VK_RIGHT, CtrlKey | ShiftKey, "MoveWordRightAndModifySelection" },
1409 { VK_UP, 0, "MoveUp" },
1410 { VK_UP, ShiftKey, "MoveUpAndModifySelection" },
1411 { VK_PRIOR, ShiftKey, "MovePageUpAndModifySelection" },
1412 { VK_DOWN, 0, "MoveDown" },
1413 { VK_DOWN, ShiftKey, "MoveDownAndModifySelection" },
1414 { VK_NEXT, ShiftKey, "MovePageDownAndModifySelection" },
1415 { VK_PRIOR, 0, "MovePageUp" },
1416 { VK_NEXT, 0, "MovePageDown" },
1417 { VK_HOME, 0, "MoveToBeginningOfLine" },
1418 { VK_HOME, ShiftKey, "MoveToBeginningOfLineAndModifySelection" },
1419 { VK_HOME, CtrlKey, "MoveToBeginningOfDocument" },
1420 { VK_HOME, CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
1422 { VK_END, 0, "MoveToEndOfLine" },
1423 { VK_END, ShiftKey, "MoveToEndOfLineAndModifySelection" },
1424 { VK_END, CtrlKey, "MoveToEndOfDocument" },
1425 { VK_END, CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection" },
1427 { VK_BACK, 0, "DeleteBackward" },
1428 { VK_BACK, ShiftKey, "DeleteBackward" },
1429 { VK_DELETE, 0, "DeleteForward" },
1430 { VK_BACK, CtrlKey, "DeleteWordBackward" },
1431 { VK_DELETE, CtrlKey, "DeleteWordForward" },
1433 { 'B', CtrlKey, "ToggleBold" },
1434 { 'I', CtrlKey, "ToggleItalic" },
1436 { VK_ESCAPE, 0, "Cancel" },
1437 { VK_OEM_PERIOD, CtrlKey, "Cancel" },
1438 { VK_TAB, 0, "InsertTab" },
1439 { VK_TAB, ShiftKey, "InsertBacktab" },
1440 { VK_RETURN, 0, "InsertNewline" },
1441 { VK_RETURN, CtrlKey, "InsertNewline" },
1442 { VK_RETURN, AltKey, "InsertNewline" },
1443 { VK_RETURN, AltKey | ShiftKey, "InsertNewline" },
1445 // It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled
1446 // in the application or in WebKit. We chose WebKit.
1447 { 'C', CtrlKey, "Copy" },
1448 { 'V', CtrlKey, "Paste" },
1449 { 'X', CtrlKey, "Cut" },
1450 { 'A', CtrlKey, "SelectAll" },
1451 { VK_INSERT, CtrlKey, "Copy" },
1452 { VK_DELETE, ShiftKey, "Cut" },
1453 { VK_INSERT, ShiftKey, "Paste" },
1454 { 'Z', CtrlKey, "Undo" },
1455 { 'Z', CtrlKey | ShiftKey, "Redo" },
1458 static const KeyPressEntry keyPressEntries[] = {
1459 { '\t', 0, "InsertTab" },
1460 { '\t', ShiftKey, "InsertBacktab" },
1461 { '\r', 0, "InsertNewline" },
1462 { '\r', CtrlKey, "InsertNewline" },
1463 { '\r', AltKey, "InsertNewline" },
1464 { '\r', AltKey | ShiftKey, "InsertNewline" },
1467 const char* WebView::interpretKeyEvent(const KeyboardEvent* evt)
1469 ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
1471 static HashMap<int, const char*>* keyDownCommandsMap = 0;
1472 static HashMap<int, const char*>* keyPressCommandsMap = 0;
1474 if (!keyDownCommandsMap) {
1475 keyDownCommandsMap = new HashMap<int, const char*>;
1476 keyPressCommandsMap = new HashMap<int, const char*>;
1478 for (unsigned i = 0; i < _countof(keyDownEntries); i++)
1479 keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
1481 for (unsigned i = 0; i < _countof(keyPressEntries); i++)
1482 keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
1485 unsigned modifiers = 0;
1486 if (evt->shiftKey())
1487 modifiers |= ShiftKey;
1489 modifiers |= AltKey;
1491 modifiers |= CtrlKey;
1493 if (evt->type() == eventNames().keydownEvent) {
1494 int mapKey = modifiers << 16 | evt->keyCode();
1495 return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
1498 int mapKey = modifiers << 16 | evt->charCode();
1499 return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
1502 bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
1504 Node* node = evt->target()->toNode();
1506 Frame* frame = node->document()->frame();
1509 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1510 if (!keyEvent || keyEvent->isSystemKey()) // do not treat this as text input if it's a system key event
1513 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1515 if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1516 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1517 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1518 // (e.g. Tab that inserts a Tab character, or Enter).
1519 return !command.isTextInsertion() && command.execute(evt);
1522 if (command.execute(evt))
1525 // Don't insert null or control characters as they can result in unexpected behaviour
1526 if (evt->charCode() < ' ')
1529 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1532 bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1534 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1535 if (virtualKeyCode == VK_CAPITAL)
1536 frame->eventHandler()->capsLockStateMayHaveChanged();
1538 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::RawKeyDown, systemKeyDown);
1539 bool handled = frame->eventHandler()->keyEvent(keyEvent);
1541 // These events cannot be canceled, and we have no default handling for them.
1542 // FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
1543 if (systemKeyDown && virtualKeyCode != VK_RETURN)
1547 // FIXME: remove WM_UNICHAR, too
1549 // WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
1551 ::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
1555 // We need to handle back/forward using either Backspace(+Shift) or Ctrl+Left/Right Arrow keys.
1556 if ((virtualKeyCode == VK_BACK && keyEvent.shiftKey()) || (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey()))
1557 m_page->goForward();
1558 else if (virtualKeyCode == VK_BACK || (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey()))
1561 // Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
1562 ScrollDirection direction;
1563 ScrollGranularity granularity;
1564 switch (virtualKeyCode) {
1566 granularity = ScrollByLine;
1567 direction = ScrollLeft;
1570 granularity = ScrollByLine;
1571 direction = ScrollRight;
1574 granularity = ScrollByLine;
1575 direction = ScrollUp;
1578 granularity = ScrollByLine;
1579 direction = ScrollDown;
1582 granularity = ScrollByDocument;
1583 direction = ScrollUp;
1586 granularity = ScrollByDocument;
1587 direction = ScrollDown;
1590 granularity = ScrollByPage;
1591 direction = ScrollUp;
1594 granularity = ScrollByPage;
1595 direction = ScrollDown;
1601 if (!frame->eventHandler()->scrollOverflow(direction, granularity)) {
1602 handled = frame->view()->scroll(direction, granularity);
1603 Frame* parent = frame->tree()->parent();
1604 while(!handled && parent) {
1605 handled = parent->view()->scroll(direction, granularity);
1606 parent = parent->tree()->parent();
1612 bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
1614 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1616 PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformKeyboardEvent::Char, systemKeyDown);
1617 // IE does not dispatch keypress event for WM_SYSCHAR.
1619 return frame->eventHandler()->handleAccessKey(keyEvent);
1620 return frame->eventHandler()->keyEvent(keyEvent);
1623 bool WebView::inResizer(LPARAM lParam)
1625 if (!m_uiDelegatePrivate)
1629 if (FAILED(m_uiDelegatePrivate->webViewResizerRect(this, &r)))
1633 pt.x = LOWORD(lParam);
1634 pt.y = HIWORD(lParam);
1635 return !!PtInRect(&r, pt);
1638 static bool registerWebViewWindowClass()
1640 static bool haveRegisteredWindowClass = false;
1641 if (haveRegisteredWindowClass)
1644 haveRegisteredWindowClass = true;
1648 wcex.cbSize = sizeof(WNDCLASSEX);
1650 wcex.style = CS_DBLCLKS;
1651 wcex.lpfnWndProc = WebViewWndProc;
1652 wcex.cbClsExtra = 0;
1653 wcex.cbWndExtra = 4; // 4 bytes for the IWebView pointer
1654 wcex.hInstance = gInstance;
1656 wcex.hCursor = ::LoadCursor(0, IDC_ARROW);
1657 wcex.hbrBackground = 0;
1658 wcex.lpszMenuName = 0;
1659 wcex.lpszClassName = kWebViewWindowClassName;
1662 return !!RegisterClassEx(&wcex);
1666 extern HCURSOR lastSetCursor;
1669 static HWND findTopLevelParent(HWND window)
1674 HWND current = window;
1675 for (HWND parent = GetParent(current); current; current = parent, parent = GetParent(parent))
1676 if (!parent || !(GetWindowLongPtr(current, GWL_STYLE) & (WS_POPUP | WS_CHILD)))
1678 ASSERT_NOT_REACHED();
1682 static LRESULT CALLBACK WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
1684 LRESULT lResult = 0;
1685 LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
1686 WebView* webView = reinterpret_cast<WebView*>(longPtr);
1687 WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
1688 if (!mainFrameImpl || webView->isBeingDestroyed())
1689 return DefWindowProc(hWnd, message, wParam, lParam);
1691 // hold a ref, since the WebView could go away in an event handler.
1692 COMPtr<WebView> protector(webView);
1695 // Windows Media Player has a modal message loop that will deliver messages
1696 // to us at inappropriate times and we will crash if we handle them when
1697 // they are delivered. We repost paint messages so that we eventually get
1698 // a chance to paint once the modal loop has exited, but other messages
1699 // aren't safe to repost, so we just drop them.
1700 if (PluginView::isCallingPlugin()) {
1701 if (message == WM_PAINT)
1702 PostMessage(hWnd, message, wParam, lParam);
1706 bool handled = true;
1710 webView->paint(0, 0);
1713 case WM_PRINTCLIENT:
1714 webView->paint((HDC)wParam, lParam);
1718 webView->setIsBeingDestroyed();
1719 webView->revokeDragDrop();
1722 case WM_LBUTTONDOWN:
1723 case WM_MBUTTONDOWN:
1724 case WM_RBUTTONDOWN:
1725 case WM_LBUTTONDBLCLK:
1726 case WM_MBUTTONDBLCLK:
1727 case WM_RBUTTONDBLCLK:
1732 if (Frame* coreFrame = core(mainFrameImpl))
1733 if (coreFrame->view()->didFirstLayout())
1734 handled = webView->handleMouseEvent(message, wParam, lParam);
1737 case WM_VISTA_MOUSEHWHEEL:
1738 if (Frame* coreFrame = core(mainFrameImpl))
1739 if (coreFrame->view()->didFirstLayout())
1740 handled = webView->mouseWheel(wParam, lParam, message == WM_VISTA_MOUSEHWHEEL);
1743 handled = webView->keyDown(wParam, lParam, true);
1746 handled = webView->keyDown(wParam, lParam);
1749 handled = webView->keyUp(wParam, lParam, true);
1752 handled = webView->keyUp(wParam, lParam);
1755 handled = webView->keyPress(wParam, lParam, true);
1758 handled = webView->keyPress(wParam, lParam);
1760 // FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
1762 if (webView->isBeingDestroyed())
1763 // If someone has sent us this message while we're being destroyed, we should bail out so we don't crash.
1767 webView->deleteBackingStore();
1768 if (Frame* coreFrame = core(mainFrameImpl))
1769 coreFrame->view()->resize(LOWORD(lParam), HIWORD(lParam));
1773 lResult = DefWindowProc(hWnd, message, wParam, lParam);
1775 // The window is being hidden (e.g., because we switched tabs.
1776 // Null out our backing store.
1777 webView->deleteBackingStore();
1780 COMPtr<IWebUIDelegate> uiDelegate;
1781 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
1782 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
1783 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
1784 uiDelegatePrivate->webViewReceivedFocus(webView);
1786 FocusController* focusController = webView->page()->focusController();
1787 if (Frame* frame = focusController->focusedFrame()) {
1788 // Send focus events unless the previously focused window is a
1789 // child of ours (for example a plugin).
1790 if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
1791 frame->selection()->setFocused(true);
1793 focusController->setFocusedFrame(webView->page()->mainFrame());
1796 case WM_KILLFOCUS: {
1797 COMPtr<IWebUIDelegate> uiDelegate;
1798 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
1799 HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
1800 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
1801 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
1802 uiDelegatePrivate->webViewLostFocus(webView, (OLE_HANDLE)(ULONG64)newFocusWnd);
1804 FocusController* focusController = webView->page()->focusController();
1805 Frame* frame = focusController->focusedOrMainFrame();
1806 webView->resetIME(frame);
1807 // Send blur events unless we're losing focus to a child of ours.
1808 if (!IsChild(hWnd, newFocusWnd))
1809 frame->selection()->setFocused(false);
1812 case WM_WINDOWPOSCHANGED:
1813 if (reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW)
1814 webView->updateActiveStateSoon();
1827 webView->delete_(0);
1831 handled = webView->execCommand(wParam, lParam);
1832 else // If the high word of wParam is 0, the message is from a menu
1833 webView->performContextMenuAction(wParam, lParam, false);
1835 case WM_MENUCOMMAND:
1836 webView->performContextMenuAction(wParam, lParam, true);
1838 case WM_CONTEXTMENU:
1839 handled = webView->handleContextMenuEvent(wParam, lParam);
1841 case WM_INITMENUPOPUP:
1842 handled = webView->onInitMenuPopup(wParam, lParam);
1844 case WM_MEASUREITEM:
1845 handled = webView->onMeasureItem(wParam, lParam);
1848 handled = webView->onDrawItem(wParam, lParam);
1850 case WM_UNINITMENUPOPUP:
1851 handled = webView->onUninitMenuPopup(wParam, lParam);
1853 case WM_XP_THEMECHANGED:
1854 if (Frame* coreFrame = core(mainFrameImpl)) {
1855 webView->deleteBackingStore();
1856 theme()->themeChanged();
1857 ScrollbarTheme::nativeTheme()->themeChanged();
1859 ::GetClientRect(hWnd, &windowRect);
1860 ::InvalidateRect(hWnd, &windowRect, false);
1863 case WM_MOUSEACTIVATE:
1864 webView->setMouseActivated(true);
1866 case WM_GETDLGCODE: {
1867 COMPtr<IWebUIDelegate> uiDelegate;
1868 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
1869 LONG_PTR dlgCode = 0;
1872 LPMSG lpMsg = (LPMSG)lParam;
1873 if (lpMsg->message == WM_KEYDOWN)
1874 keyCode = (UINT) lpMsg->wParam;
1876 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
1877 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate &&
1878 SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
1884 handled = webView->onGetObject(wParam, lParam, lResult);
1886 case WM_IME_STARTCOMPOSITION:
1887 handled = webView->onIMEStartComposition();
1889 case WM_IME_REQUEST:
1890 webView->onIMERequest(wParam, lParam, &lResult);
1892 case WM_IME_COMPOSITION:
1893 handled = webView->onIMEComposition(lParam);
1895 case WM_IME_ENDCOMPOSITION:
1896 handled = webView->onIMEEndComposition();
1899 handled = webView->onIMEChar(wParam, lParam);
1902 handled = webView->onIMENotify(wParam, lParam, &lResult);
1905 handled = webView->onIMESelect(wParam, lParam);
1907 case WM_IME_SETCONTEXT:
1908 handled = webView->onIMESetContext(wParam, lParam);
1912 case UpdateActiveStateTimer:
1913 KillTimer(hWnd, UpdateActiveStateTimer);
1914 webView->updateActiveState();
1916 case DeleteBackingStoreTimer:
1917 webView->deleteBackingStore();
1922 if (handled = webView->page()->chrome()->setCursor(lastSetCursor))
1932 lResult = DefWindowProc(hWnd, message, wParam, lParam);
1934 // Let the client know whether we consider this message handled.
1935 return (message == WM_KEYDOWN || message == WM_SYSKEYDOWN || message == WM_KEYUP || message == WM_SYSKEYUP) ? !handled : lResult;
1938 bool WebView::developerExtrasEnabled() const
1940 if (m_preferences->developerExtrasDisabledByOverride())
1945 return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
1951 static String osVersion()
1954 OSVERSIONINFO versionInfo = {0};
1955 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1956 GetVersionEx(&versionInfo);
1958 if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1959 if (versionInfo.dwMajorVersion == 4) {
1960 if (versionInfo.dwMinorVersion == 0)
1961 osVersion = "Windows 95";
1962 else if (versionInfo.dwMinorVersion == 10)
1963 osVersion = "Windows 98";
1964 else if (versionInfo.dwMinorVersion == 90)
1965 osVersion = "Windows 98; Win 9x 4.90";
1967 } else if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
1968 osVersion = String::format("Windows NT %d.%d", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion);
1970 if (!osVersion.length())
1971 osVersion = String::format("Windows %d.%d", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion);
1976 static String webKitVersion()
1978 String versionStr = "420+";
1981 struct LANGANDCODEPAGE {
1986 TCHAR path[MAX_PATH];
1987 GetModuleFileName(gInstance, path, ARRAYSIZE(path));
1989 DWORD versionSize = GetFileVersionInfoSize(path, &handle);
1992 data = malloc(versionSize);
1995 if (!GetFileVersionInfo(path, 0, versionSize, data))
1998 if (!VerQueryValue(data, TEXT("\\VarFileInfo\\Translation"), (LPVOID*)&lpTranslate, &cbTranslate))
2001 _stprintf_s(key, ARRAYSIZE(key), TEXT("\\StringFileInfo\\%04x%04x\\ProductVersion"), lpTranslate[0].wLanguage, lpTranslate[0].wCodePage);
2002 LPCTSTR productVersion;
2003 UINT productVersionLength;
2004 if (!VerQueryValue(data, (LPTSTR)(LPCTSTR)key, (void**)&productVersion, &productVersionLength))
2006 versionStr = String(productVersion, productVersionLength);
2014 const String& WebView::userAgentForKURL(const KURL& url)
2016 if (m_userAgentOverridden)
2017 return m_userAgentCustom;
2019 if (allowSiteSpecificHacks()) {
2020 if (url.host() == "ads.pointroll.com") {
2021 // <rdar://problem/6899044> Can't see Apple ad on nytimes.com unless I spoof the user agent
2022 DEFINE_STATIC_LOCAL(const String, uaForAdsPointroll, ("Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.28.3 (KHTML, like Gecko) Version/3.2.3 Safari/525.29"));
2023 return uaForAdsPointroll;
2027 if (!m_userAgentStandard.length())
2028 m_userAgentStandard = WebView::standardUserAgentWithApplicationName(m_applicationName);
2029 return m_userAgentStandard;
2032 // IUnknown -------------------------------------------------------------------
2034 HRESULT STDMETHODCALLTYPE WebView::QueryInterface(REFIID riid, void** ppvObject)
2037 if (IsEqualGUID(riid, CLSID_WebView))
2039 else if (IsEqualGUID(riid, IID_IUnknown))
2040 *ppvObject = static_cast<IWebView*>(this);
2041 else if (IsEqualGUID(riid, IID_IWebView))
2042 *ppvObject = static_cast<IWebView*>(this);
2043 else if (IsEqualGUID(riid, IID_IWebViewPrivate))
2044 *ppvObject = static_cast<IWebViewPrivate*>(this);
2045 else if (IsEqualGUID(riid, IID_IWebIBActions))
2046 *ppvObject = static_cast<IWebIBActions*>(this);
2047 else if (IsEqualGUID(riid, IID_IWebViewCSS))
2048 *ppvObject = static_cast<IWebViewCSS*>(this);
2049 else if (IsEqualGUID(riid, IID_IWebViewEditing))
2050 *ppvObject = static_cast<IWebViewEditing*>(this);
2051 else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
2052 *ppvObject = static_cast<IWebViewUndoableEditing*>(this);
2053 else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
2054 *ppvObject = static_cast<IWebViewEditingActions*>(this);
2055 else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
2056 *ppvObject = static_cast<IWebNotificationObserver*>(this);
2057 else if (IsEqualGUID(riid, IID_IDropTarget))
2058 *ppvObject = static_cast<IDropTarget*>(this);
2060 return E_NOINTERFACE;
2066 ULONG STDMETHODCALLTYPE WebView::AddRef(void)
2068 return ++m_refCount;
2071 ULONG STDMETHODCALLTYPE WebView::Release(void)
2073 ULONG newRef = --m_refCount;
2080 // IWebView --------------------------------------------------------------------
2082 HRESULT STDMETHODCALLTYPE WebView::canShowMIMEType(
2083 /* [in] */ BSTR mimeType,
2084 /* [retval][out] */ BOOL* canShow)
2086 String mimeTypeStr(mimeType, SysStringLen(mimeType));
2091 *canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeTypeStr) ||
2092 MIMETypeRegistry::isSupportedNonImageMIMEType(mimeTypeStr) ||
2093 PluginInfoStore::supportsMIMEType(mimeTypeStr) ||
2094 shouldUseEmbeddedView(mimeTypeStr);
2099 HRESULT STDMETHODCALLTYPE WebView::canShowMIMETypeAsHTML(
2100 /* [in] */ BSTR /*mimeType*/,
2101 /* [retval][out] */ BOOL* canShow)
2108 HRESULT STDMETHODCALLTYPE WebView::MIMETypesShownAsHTML(
2109 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
2111 ASSERT_NOT_REACHED();
2115 HRESULT STDMETHODCALLTYPE WebView::setMIMETypesShownAsHTML(
2116 /* [size_is][in] */ BSTR* /*mimeTypes*/,
2117 /* [in] */ int /*cMimeTypes*/)
2119 ASSERT_NOT_REACHED();
2123 HRESULT STDMETHODCALLTYPE WebView::URLFromPasteboard(
2124 /* [in] */ IDataObject* /*pasteboard*/,
2125 /* [retval][out] */ BSTR* /*url*/)
2127 ASSERT_NOT_REACHED();
2131 HRESULT STDMETHODCALLTYPE WebView::URLTitleFromPasteboard(
2132 /* [in] */ IDataObject* /*pasteboard*/,
2133 /* [retval][out] */ BSTR* /*urlTitle*/)
2135 ASSERT_NOT_REACHED();
2139 static void WebKitSetApplicationCachePathIfNecessary()
2141 static bool initialized = false;
2145 String path = localUserSpecificStorageDirectory();
2147 cacheStorage().setCacheDirectory(path);
2152 HRESULT STDMETHODCALLTYPE WebView::initWithFrame(
2153 /* [in] */ RECT frame,
2154 /* [in] */ BSTR frameName,
2155 /* [in] */ BSTR groupName)
2162 registerWebViewWindowClass();
2164 if (!::IsWindow(m_hostWindow)) {
2165 ASSERT_NOT_REACHED();
2169 m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPCHILDREN,
2170 frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow, 0, gInstance, 0);
2171 ASSERT(::IsWindow(m_viewWindow));
2173 hr = registerDragDrop();
2177 WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
2178 sharedPreferences->willAddToWebView();
2179 m_preferences = sharedPreferences;
2181 InitializeLoggingChannelsIfNecessary();
2182 #if ENABLE(DATABASE)
2183 WebKitSetWebDatabasesPathIfNecessary();
2185 WebKitSetApplicationCachePathIfNecessary();
2187 m_page = new Page(new WebChromeClient(this), new WebContextMenuClient(this), new WebEditorClient(this), new WebDragClient(this), new WebInspectorClient(this));
2189 BSTR localStoragePath;
2190 if (SUCCEEDED(m_preferences->localStorageDatabasePath(&localStoragePath))) {
2191 m_page->settings()->setLocalStorageDatabasePath(String(localStoragePath, SysStringLen(localStoragePath)));
2192 SysFreeString(localStoragePath);
2196 COMPtr<IWebUIDelegate2> uiDelegate2;
2197 if (SUCCEEDED(m_uiDelegate->QueryInterface(IID_IWebUIDelegate2, (void**)&uiDelegate2))) {
2199 if (SUCCEEDED(uiDelegate2->ftpDirectoryTemplatePath(this, &path))) {
2200 m_page->settings()->setFTPDirectoryTemplatePath(String(path, SysStringLen(path)));
2201 SysFreeString(path);
2206 WebFrame* webFrame = WebFrame::createInstance();
2207 RefPtr<Frame> coreFrame = webFrame->init(this, m_page, 0);
2208 m_mainFrame = webFrame;
2209 webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
2211 coreFrame->tree()->setName(String(frameName, SysStringLen(frameName)));
2213 setGroupName(groupName);
2215 addToAllWebViewsSet();
2217 #pragma warning(suppress: 4244)
2218 SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
2219 ShowWindow(m_viewWindow, SW_SHOW);
2221 initializeToolTipWindow();
2222 windowAncestryDidChange();
2224 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
2225 notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2226 m_preferences->postPreferencesChangesNotification();
2228 setSmartInsertDeleteEnabled(TRUE);
2232 static bool initCommonControls()
2234 static bool haveInitialized = false;
2235 if (haveInitialized)
2238 INITCOMMONCONTROLSEX init;
2239 init.dwSize = sizeof(init);
2240 init.dwICC = ICC_TREEVIEW_CLASSES;
2241 haveInitialized = !!::InitCommonControlsEx(&init);
2242 return haveInitialized;
2245 void WebView::initializeToolTipWindow()
2247 if (!initCommonControls())
2250 m_toolTipHwnd = CreateWindowEx(0, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
2251 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
2252 m_viewWindow, 0, 0, 0);
2256 TOOLINFO info = {0};
2257 info.cbSize = sizeof(info);
2258 info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
2259 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2261 ::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
2262 ::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, maxToolTipWidth);
2264 ::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
2267 void WebView::setToolTip(const String& toolTip)
2272 if (toolTip == m_toolTip)
2275 m_toolTip = toolTip;
2277 if (!m_toolTip.isEmpty()) {
2278 TOOLINFO info = {0};
2279 info.cbSize = sizeof(info);
2280 info.uFlags = TTF_IDISHWND;
2281 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2282 info.lpszText = const_cast<UChar*>(m_toolTip.charactersWithNullTermination());
2283 ::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
2286 ::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
2289 HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
2291 COMPtr<IPropertyBag> propertyBag;
2292 HRESULT hr = notification->userInfo(&propertyBag);
2298 COMPtr<CFDictionaryPropertyBag> dictionaryPropertyBag;
2299 hr = propertyBag->QueryInterface(&dictionaryPropertyBag);
2303 CFDictionaryRef dictionary = dictionaryPropertyBag->dictionary();
2307 CFTypeRef value = CFDictionaryGetValue(dictionary, WebIconDatabase::iconDatabaseNotificationUserInfoURLKey());
2310 if (CFGetTypeID(value) != CFStringGetTypeID())
2313 String mainFrameURL;
2315 mainFrameURL = m_mainFrame->url().string();
2317 if (!mainFrameURL.isEmpty() && mainFrameURL == String((CFStringRef)value))
2318 dispatchDidReceiveIconFromWebFrame(m_mainFrame);
2323 void WebView::registerForIconNotification(bool listen)
2325 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2327 nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2329 nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2332 void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
2334 registerForIconNotification(false);
2336 if (m_frameLoadDelegate)
2337 // FIXME: <rdar://problem/5491010> - Pass in the right HBITMAP.
2338 m_frameLoadDelegate->didReceiveIcon(this, 0, frame);
2341 HRESULT STDMETHODCALLTYPE WebView::setUIDelegate(
2342 /* [in] */ IWebUIDelegate* d)
2346 if (m_uiDelegatePrivate)
2347 m_uiDelegatePrivate = 0;
2350 if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
2351 m_uiDelegatePrivate = 0;
2357 HRESULT STDMETHODCALLTYPE WebView::uiDelegate(
2358 /* [out][retval] */ IWebUIDelegate** d)
2363 return m_uiDelegate.copyRefTo(d);
2366 HRESULT STDMETHODCALLTYPE WebView::setResourceLoadDelegate(
2367 /* [in] */ IWebResourceLoadDelegate* d)
2369 m_resourceLoadDelegate = d;
2373 HRESULT STDMETHODCALLTYPE WebView::resourceLoadDelegate(
2374 /* [out][retval] */ IWebResourceLoadDelegate** d)
2376 if (!m_resourceLoadDelegate)
2379 return m_resourceLoadDelegate.copyRefTo(d);
2382 HRESULT STDMETHODCALLTYPE WebView::setDownloadDelegate(
2383 /* [in] */ IWebDownloadDelegate* d)
2385 m_downloadDelegate = d;
2389 HRESULT STDMETHODCALLTYPE WebView::downloadDelegate(
2390 /* [out][retval] */ IWebDownloadDelegate** d)
2392 if (!m_downloadDelegate)
2395 return m_downloadDelegate.copyRefTo(d);
2398 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegate(
2399 /* [in] */ IWebFrameLoadDelegate* d)
2401 m_frameLoadDelegate = d;
2405 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegate(
2406 /* [out][retval] */ IWebFrameLoadDelegate** d)
2408 if (!m_frameLoadDelegate)
2411 return m_frameLoadDelegate.copyRefTo(d);
2414 HRESULT STDMETHODCALLTYPE WebView::setPolicyDelegate(
2415 /* [in] */ IWebPolicyDelegate* d)
2417 m_policyDelegate = d;
2421 HRESULT STDMETHODCALLTYPE WebView::policyDelegate(
2422 /* [out][retval] */ IWebPolicyDelegate** d)
2424 if (!m_policyDelegate)
2426 return m_policyDelegate.copyRefTo(d);
2429 HRESULT STDMETHODCALLTYPE WebView::mainFrame(
2430 /* [out][retval] */ IWebFrame** frame)
2433 ASSERT_NOT_REACHED();
2437 *frame = m_mainFrame;
2441 m_mainFrame->AddRef();
2445 HRESULT STDMETHODCALLTYPE WebView::focusedFrame(
2446 /* [out][retval] */ IWebFrame** frame)
2449 ASSERT_NOT_REACHED();
2454 Frame* f = m_page->focusController()->focusedFrame();
2458 WebFrame* webFrame = kit(f);
2462 return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
2464 HRESULT STDMETHODCALLTYPE WebView::backForwardList(
2465 /* [out][retval] */ IWebBackForwardList** list)
2467 if (!m_useBackForwardList)
2470 *list = WebBackForwardList::createInstance(m_page->backForwardList());
2475 HRESULT STDMETHODCALLTYPE WebView::setMaintainsBackForwardList(
2476 /* [in] */ BOOL flag)
2478 m_useBackForwardList = !!flag;
2482 HRESULT STDMETHODCALLTYPE WebView::goBack(
2483 /* [retval][out] */ BOOL* succeeded)
2485 *succeeded = m_page->goBack();
2489 HRESULT STDMETHODCALLTYPE WebView::goForward(
2490 /* [retval][out] */ BOOL* succeeded)
2492 *succeeded = m_page->goForward();
2496 HRESULT STDMETHODCALLTYPE WebView::goToBackForwardItem(
2497 /* [in] */ IWebHistoryItem* item,
2498 /* [retval][out] */ BOOL* succeeded)
2502 COMPtr<WebHistoryItem> webHistoryItem;
2503 HRESULT hr = item->QueryInterface(&webHistoryItem);
2507 m_page->goToItem(webHistoryItem->historyItem(), FrameLoadTypeIndexedBackForward);
2513 HRESULT STDMETHODCALLTYPE WebView::setTextSizeMultiplier(
2514 /* [in] */ float multiplier)
2518 setZoomMultiplier(multiplier, true);
2522 HRESULT STDMETHODCALLTYPE WebView::setPageSizeMultiplier(
2523 /* [in] */ float multiplier)
2527 setZoomMultiplier(multiplier, false);
2531 void WebView::setZoomMultiplier(float multiplier, bool isTextOnly)
2533 m_zoomMultiplier = multiplier;
2534 m_page->settings()->setZoomsTextOnly(isTextOnly);
2535 if (Frame* coreFrame = core(m_mainFrame))
2536 coreFrame->setZoomFactor(multiplier, isTextOnly);
2539 HRESULT STDMETHODCALLTYPE WebView::textSizeMultiplier(
2540 /* [retval][out] */ float* multiplier)
2542 *multiplier = zoomMultiplier(true);
2546 HRESULT STDMETHODCALLTYPE WebView::pageSizeMultiplier(
2547 /* [retval][out] */ float* multiplier)
2549 *multiplier = zoomMultiplier(false);
2553 float WebView::zoomMultiplier(bool isTextOnly)
2555 if (isTextOnly != m_page->settings()->zoomsTextOnly())
2557 return m_zoomMultiplier;
2560 HRESULT STDMETHODCALLTYPE WebView::setApplicationNameForUserAgent(
2561 /* [in] */ BSTR applicationName)
2563 m_applicationName = String(applicationName, SysStringLen(applicationName));
2564 m_userAgentStandard = String();
2568 HRESULT STDMETHODCALLTYPE WebView::applicationNameForUserAgent(
2569 /* [retval][out] */ BSTR* applicationName)
2571 *applicationName = SysAllocStringLen(m_applicationName.characters(), m_applicationName.length());
2572 if (!*applicationName && m_applicationName.length())
2573 return E_OUTOFMEMORY;
2577 HRESULT STDMETHODCALLTYPE WebView::setCustomUserAgent(
2578 /* [in] */ BSTR userAgentString)
2580 m_userAgentOverridden = userAgentString;
2581 m_userAgentCustom = String(userAgentString, SysStringLen(userAgentString));
2585 HRESULT STDMETHODCALLTYPE WebView::customUserAgent(
2586 /* [retval][out] */ BSTR* userAgentString)
2588 *userAgentString = 0;
2589 if (!m_userAgentOverridden)
2591 *userAgentString = SysAllocStringLen(m_userAgentCustom.characters(), m_userAgentCustom.length());
2592 if (!*userAgentString && m_userAgentCustom.length())
2593 return E_OUTOFMEMORY;
2597 HRESULT STDMETHODCALLTYPE WebView::userAgentForURL(
2598 /* [in] */ BSTR url,
2599 /* [retval][out] */ BSTR* userAgent)
2601 String userAgentString = userAgentForKURL(MarshallingHelpers::BSTRToKURL(url));
2602 *userAgent = SysAllocStringLen(userAgentString.characters(), userAgentString.length());
2603 if (!*userAgent && userAgentString.length())
2604 return E_OUTOFMEMORY;
2608 HRESULT STDMETHODCALLTYPE WebView::supportsTextEncoding(
2609 /* [retval][out] */ BOOL* supports)
2615 HRESULT STDMETHODCALLTYPE WebView::setCustomTextEncodingName(
2616 /* [in] */ BSTR encodingName)
2623 hr = customTextEncodingName(&oldEncoding);
2627 if (oldEncoding != encodingName && (!oldEncoding || !encodingName || _tcscmp(oldEncoding, encodingName))) {
2628 if (Frame* coreFrame = core(m_mainFrame))
2629 coreFrame->loader()->reloadWithOverrideEncoding(String(encodingName, SysStringLen(encodingName)));
2635 HRESULT STDMETHODCALLTYPE WebView::customTextEncodingName(
2636 /* [retval][out] */ BSTR* encodingName)
2639 COMPtr<IWebDataSource> dataSource;
2640 COMPtr<WebDataSource> dataSourceImpl;
2646 if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
2647 hr = m_mainFrame->dataSource(&dataSource);
2648 if (FAILED(hr) || !dataSource)
2652 hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
2656 BString str = dataSourceImpl->documentLoader()->overrideEncoding();
2661 *encodingName = SysAllocStringLen(m_overrideEncoding.characters(), m_overrideEncoding.length());
2663 if (!*encodingName && m_overrideEncoding.length())
2664 return E_OUTOFMEMORY;
2669 HRESULT STDMETHODCALLTYPE WebView::setMediaStyle(
2670 /* [in] */ BSTR /*media*/)
2672 ASSERT_NOT_REACHED();
2676 HRESULT STDMETHODCALLTYPE WebView::mediaStyle(
2677 /* [retval][out] */ BSTR* /*media*/)
2679 ASSERT_NOT_REACHED();
2683 HRESULT STDMETHODCALLTYPE WebView::stringByEvaluatingJavaScriptFromString(
2684 /* [in] */ BSTR script, // assumes input does not have "JavaScript" at the begining.
2685 /* [retval][out] */ BSTR* result)
2688 ASSERT_NOT_REACHED();
2694 Frame* coreFrame = core(m_mainFrame);
2698 JSC::JSValue scriptExecutionResult = coreFrame->loader()->executeScript(WebCore::String(script), true).jsValue();
2699 if (!scriptExecutionResult)
2701 else if (scriptExecutionResult.isString()) {
2703 *result = BString(String(scriptExecutionResult.getString()));
2709 HRESULT STDMETHODCALLTYPE WebView::windowScriptObject(
2710 /* [retval][out] */ IWebScriptObject** /*webScriptObject*/)
2712 ASSERT_NOT_REACHED();
2716 HRESULT STDMETHODCALLTYPE WebView::setPreferences(
2717 /* [in] */ IWebPreferences* prefs)
2720 prefs = WebPreferences::sharedStandardPreferences();
2722 if (m_preferences == prefs)
2725 COMPtr<WebPreferences> webPrefs(Query, prefs);
2727 return E_NOINTERFACE;
2728 webPrefs->willAddToWebView();
2730 COMPtr<WebPreferences> oldPrefs = m_preferences;
2732 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2733 nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2735 BSTR identifier = 0;
2736 oldPrefs->identifier(&identifier);
2737 oldPrefs->didRemoveFromWebView();
2738 oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
2740 m_preferences = webPrefs;
2743 WebPreferences::removeReferenceForIdentifier(identifier);
2744 SysFreeString(identifier);
2747 nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2749 m_preferences->postPreferencesChangesNotification();
2754 HRESULT STDMETHODCALLTYPE WebView::preferences(
2755 /* [retval][out] */ IWebPreferences** prefs)
2759 *prefs = m_preferences.get();
2761 m_preferences->AddRef();
2765 HRESULT STDMETHODCALLTYPE WebView::setPreferencesIdentifier(
2766 /* [in] */ BSTR /*anIdentifier*/)
2768 ASSERT_NOT_REACHED();
2772 HRESULT STDMETHODCALLTYPE WebView::preferencesIdentifier(
2773 /* [retval][out] */ BSTR* /*anIdentifier*/)
2775 ASSERT_NOT_REACHED();
2779 void WebView::windowReceivedMessage(HWND, UINT message, WPARAM wParam, LPARAM)
2783 updateActiveStateSoon();
2785 deleteBackingStoreSoon();
2790 void WebView::updateActiveStateSoon() const
2792 // This function is called while processing the WM_NCACTIVATE message.
2793 // While processing WM_NCACTIVATE when we are being deactivated, GetActiveWindow() will
2794 // still return our window. If we were to call updateActiveState() in that case, we would
2795 // wrongly think that we are still the active window. To work around this, we update our
2796 // active state after a 0-delay timer fires, at which point GetActiveWindow() will return
2797 // the newly-activated window.
2799 SetTimer(m_viewWindow, UpdateActiveStateTimer, 0, 0);
2802 void WebView::deleteBackingStoreSoon()
2804 if (pendingDeleteBackingStoreSet.size() > 2) {
2805 Vector<WebView*> views;
2806 HashSet<WebView*>::iterator end = pendingDeleteBackingStoreSet.end();
2807 for (HashSet<WebView*>::iterator it = pendingDeleteBackingStoreSet.begin(); it != end; ++it)
2809 for (int i = 0; i < views.size(); ++i)
2810 views[i]->deleteBackingStore();
2811 ASSERT(pendingDeleteBackingStoreSet.isEmpty());
2814 pendingDeleteBackingStoreSet.add(this);
2815 m_deleteBackingStoreTimerActive = true;
2816 SetTimer(m_viewWindow, DeleteBackingStoreTimer, delayBeforeDeletingBackingStoreMsec, 0);
2819 void WebView::cancelDeleteBackingStoreSoon()
2821 if (!m_deleteBackingStoreTimerActive)
2823 pendingDeleteBackingStoreSet.remove(this);
2824 m_deleteBackingStoreTimerActive = false;
2825 KillTimer(m_viewWindow, DeleteBackingStoreTimer);
2828 HRESULT STDMETHODCALLTYPE WebView::setHostWindow(
2829 /* [in] */ OLE_HANDLE oleWindow)
2831 HWND window = (HWND)(ULONG64)oleWindow;
2832 if (m_viewWindow && window)
2833 SetParent(m_viewWindow, window);
2835 m_hostWindow = window;
2838 windowAncestryDidChange();
2843 HRESULT STDMETHODCALLTYPE WebView::hostWindow(
2844 /* [retval][out] */ OLE_HANDLE* window)
2846 *window = (OLE_HANDLE)(ULONG64)m_hostWindow;
2851 static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
2854 ? curr->tree()->traverseNextWithWrap(wrapFlag)
2855 : curr->tree()->traversePreviousWithWrap(wrapFlag);
2858 HRESULT STDMETHODCALLTYPE WebView::searchFor(
2859 /* [in] */ BSTR str,
2860 /* [in] */ BOOL forward,
2861 /* [in] */ BOOL caseFlag,
2862 /* [in] */ BOOL wrapFlag,
2863 /* [retval][out] */ BOOL* found)
2866 return E_INVALIDARG;
2868 if (!m_page || !m_page->mainFrame())
2869 return E_UNEXPECTED;
2871 if (!str || !SysStringLen(str))
2872 return E_INVALIDARG;
2874 *found = m_page->findString(String(str, SysStringLen(str)), caseFlag ? TextCaseSensitive : TextCaseInsensitive, forward ? FindDirectionForward : FindDirectionBackward, wrapFlag);
2878 bool WebView::active()
2880 HWND activeWindow = GetActiveWindow();
2881 return (activeWindow && m_topLevelParent == findTopLevelParent(activeWindow));
2884 void WebView::updateActiveState()
2886 m_page->focusController()->setActive(active());
2889 HRESULT STDMETHODCALLTYPE WebView::updateFocusedAndActiveState()
2891 updateActiveState();
2893 bool active = m_page->focusController()->isActive();
2894 Frame* mainFrame = m_page->mainFrame();
2895 Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
2896 mainFrame->selection()->setFocused(active && mainFrame == focusedFrame);
2901 HRESULT STDMETHODCALLTYPE WebView::executeCoreCommandByName(BSTR bName, BSTR bValue)
2903 String name(bName, SysStringLen(bName));
2904 String value(bValue, SysStringLen(bValue));
2906 m_page->focusController()->focusedOrMainFrame()->editor()->command(name).execute(value);
2911 HRESULT STDMETHODCALLTYPE WebView::clearMainFrameName()
2913 m_page->mainFrame()->tree()->clearName();
2918 HRESULT STDMETHODCALLTYPE WebView::markAllMatchesForText(
2919 BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, UINT* matches)
2922 return E_INVALIDARG;
2924 if (!m_page || !m_page->mainFrame())
2925 return E_UNEXPECTED;
2927 if (!str || !SysStringLen(str))
2928 return E_INVALIDARG;
2930 *matches = m_page->markAllMatchesForText(String(str, SysStringLen(str)), caseSensitive ? TextCaseSensitive : TextCaseInsensitive, highlight, limit);
2934 HRESULT STDMETHODCALLTYPE WebView::unmarkAllTextMatches()
2936 if (!m_page || !m_page->mainFrame())
2937 return E_UNEXPECTED;
2939 m_page->unmarkAllTextMatches();
2943 HRESULT STDMETHODCALLTYPE WebView::rectsForTextMatches(
2944 IEnumTextMatches** pmatches)
2946 Vector<IntRect> allRects;
2947 WebCore::Frame* frame = m_page->mainFrame();
2949 if (Document* document = frame->document()) {
2950 IntRect visibleRect = frame->view()->visibleContentRect();
2951 Vector<IntRect> frameRects = document->renderedRectsForMarkers(DocumentMarker::TextMatch);
2952 IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
2953 frameOffset = frame->view()->convertToContainingWindow(frameOffset);
2955 Vector<IntRect>::iterator end = frameRects.end();
2956 for (Vector<IntRect>::iterator it = frameRects.begin(); it < end; it++) {
2957 it->intersect(visibleRect);
2958 it->move(frameOffset.x(), frameOffset.y());
2959 allRects.append(*it);
2962 frame = incrementFrame(frame, true, false);
2965 return createMatchEnumerator(&allRects, pmatches);
2968 HRESULT STDMETHODCALLTYPE WebView::generateSelectionImage(BOOL forceWhiteText, OLE_HANDLE* hBitmap)
2972 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
2975 HBITMAP bitmap = imageFromSelection(frame, forceWhiteText ? TRUE : FALSE);
2976 *hBitmap = (OLE_HANDLE)(ULONG64)bitmap;
2982 HRESULT STDMETHODCALLTYPE WebView::selectionRect(RECT* rc)
2984 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
2987 IntRect ir = enclosingIntRect(frame->selectionBounds());
2988 ir = frame->view()->convertToContainingWindow(ir);
2989 ir.move(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
2992 rc->bottom = rc->top + ir.height();
2993 rc->right = rc->left + ir.width();
2999 HRESULT STDMETHODCALLTYPE WebView::registerViewClass(
3000 /* [in] */ IWebDocumentView* /*view*/,
3001 /* [in] */ IWebDocumentRepresentation* /*representation*/,
3002 /* [in] */ BSTR /*forMIMEType*/)
3004 ASSERT_NOT_REACHED();
3008 HRESULT STDMETHODCALLTYPE WebView::setGroupName(
3009 /* [in] */ BSTR groupName)
3013 m_page->setGroupName(String(groupName, SysStringLen(groupName)));
3017 HRESULT STDMETHODCALLTYPE WebView::groupName(
3018 /* [retval][out] */ BSTR* groupName)
3023 String groupNameString = m_page->groupName();
3024 *groupName = SysAllocStringLen(groupNameString.characters(), groupNameString.length());
3025 if (!*groupName && groupNameString.length())
3026 return E_OUTOFMEMORY;
3030 HRESULT STDMETHODCALLTYPE WebView::estimatedProgress(
3031 /* [retval][out] */ double* estimatedProgress)
3033 *estimatedProgress = m_page->progress()->estimatedProgress();
3037 HRESULT STDMETHODCALLTYPE WebView::isLoading(
3038 /* [retval][out] */ BOOL* isLoading)
3040 COMPtr<IWebDataSource> dataSource;
3041 COMPtr<IWebDataSource> provisionalDataSource;
3048 if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
3049 dataSource->isLoading(isLoading);
3054 if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
3055 provisionalDataSource->isLoading(isLoading);
3059 HRESULT STDMETHODCALLTYPE WebView::elementAtPoint(
3060 /* [in] */ LPPOINT point,
3061 /* [retval][out] */ IPropertyBag** elementDictionary)
3063 if (!elementDictionary) {
3064 ASSERT_NOT_REACHED();
3068 *elementDictionary = 0;
3070 Frame* frame = core(m_mainFrame);
3074 IntPoint webCorePoint = IntPoint(point->x, point->y);
3075 HitTestResult result = HitTestResult(webCorePoint);
3076 if (frame->contentRenderer())
3077 result = frame->eventHandler()->hitTestResultAtPoint(webCorePoint, false);
3078 *elementDictionary = WebElementPropertyBag::createInstance(result);
3082 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForSelection(
3083 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3085 ASSERT_NOT_REACHED();
3089 HRESULT STDMETHODCALLTYPE WebView::writeSelectionWithPasteboardTypes(
3090 /* [size_is][in] */ BSTR* /*types*/,
3091 /* [in] */ int /*cTypes*/,
3092 /* [in] */ IDataObject* /*pasteboard*/)
3094 ASSERT_NOT_REACHED();
3098 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForElement(
3099 /* [in] */ IPropertyBag* /*elementDictionary*/,
3100 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
3102 ASSERT_NOT_REACHED();
3106 HRESULT STDMETHODCALLTYPE WebView::writeElement(
3107 /* [in] */ IPropertyBag* /*elementDictionary*/,
3108 /* [size_is][in] */ BSTR* /*withPasteboardTypes*/,
3109 /* [in] */ int /*cWithPasteboardTypes*/,
3110 /* [in] */ IDataObject* /*pasteboard*/)
3112 ASSERT_NOT_REACHED();
3116 HRESULT STDMETHODCALLTYPE WebView::selectedText(
3117 /* [out, retval] */ BSTR* text)
3120 ASSERT_NOT_REACHED();
3126 Frame* focusedFrame = (m_page && m_page->focusController()) ? m_page->focusController()->focusedOrMainFrame() : 0;
3130 String frameSelectedText = focusedFrame->selectedText();
3131 *text = SysAllocStringLen(frameSelectedText.characters(), frameSelectedText.length());
3132 if (!*text && frameSelectedText.length())
3133 return E_OUTOFMEMORY;
3137 HRESULT STDMETHODCALLTYPE WebView::centerSelectionInVisibleArea(
3138 /* [in] */ IUnknown* /* sender */)
3140 Frame* coreFrame = core(m_mainFrame);
3144 coreFrame->revealSelection(ScrollAlignment::alignCenterAlways);
3149 HRESULT STDMETHODCALLTYPE WebView::moveDragCaretToPoint(
3150 /* [in] */ LPPOINT /*point*/)
3152 ASSERT_NOT_REACHED();
3156 HRESULT STDMETHODCALLTYPE WebView::removeDragCaret( void)
3158 ASSERT_NOT_REACHED();
3162 HRESULT STDMETHODCALLTYPE WebView::setDrawsBackground(
3163 /* [in] */ BOOL /*drawsBackground*/)
3165 ASSERT_NOT_REACHED();
3169 HRESULT STDMETHODCALLTYPE WebView::drawsBackground(
3170 /* [retval][out] */ BOOL* /*drawsBackground*/)
3172 ASSERT_NOT_REACHED();
3176 HRESULT STDMETHODCALLTYPE WebView::setMainFrameURL(
3177 /* [in] */ BSTR /*urlString*/)
3179 ASSERT_NOT_REACHED();
3183 HRESULT STDMETHODCALLTYPE WebView::mainFrameURL(
3184 /* [retval][out] */ BSTR* /*urlString*/)
3186 ASSERT_NOT_REACHED();
3190 HRESULT STDMETHODCALLTYPE WebView::mainFrameDocument(
3191 /* [retval][out] */ IDOMDocument** document)
3197 return m_mainFrame->DOMDocument(document);
3200 HRESULT STDMETHODCALLTYPE WebView::mainFrameTitle(
3201 /* [retval][out] */ BSTR* /*title*/)
3203 ASSERT_NOT_REACHED();
3207 HRESULT STDMETHODCALLTYPE WebView::mainFrameIcon(
3208 /* [retval][out] */ OLE_HANDLE* /*hBitmap*/)
3210 ASSERT_NOT_REACHED();
3214 HRESULT STDMETHODCALLTYPE WebView::registerURLSchemeAsLocal(
3215 /* [in] */ BSTR scheme)
3220 FrameLoader::registerURLSchemeAsLocal(String(scheme, ::SysStringLen(scheme)));
3225 // IWebIBActions ---------------------------------------------------------------
3227 HRESULT STDMETHODCALLTYPE WebView::takeStringURLFrom(
3228 /* [in] */ IUnknown* /*sender*/)
3230 ASSERT_NOT_REACHED();
3234 HRESULT STDMETHODCALLTYPE WebView::stopLoading(
3235 /* [in] */ IUnknown* /*sender*/)
3240 return m_mainFrame->stopLoading();
3243 HRESULT STDMETHODCALLTYPE WebView::reload(
3244 /* [in] */ IUnknown* /*sender*/)
3249 return m_mainFrame->reload();
3252 HRESULT STDMETHODCALLTYPE WebView::canGoBack(
3253 /* [in] */ IUnknown* /*sender*/,
3254 /* [retval][out] */ BOOL* result)
3256 *result = !!m_page->backForwardList()->backItem();
3260 HRESULT STDMETHODCALLTYPE WebView::goBack(
3261 /* [in] */ IUnknown* /*sender*/)
3263 ASSERT_NOT_REACHED();
3267 HRESULT STDMETHODCALLTYPE WebView::canGoForward(
3268 /* [in] */ IUnknown* /*sender*/,
3269 /* [retval][out] */ BOOL* result)
3271 *result = !!m_page->backForwardList()->forwardItem();
3275 HRESULT STDMETHODCALLTYPE WebView::goForward(
3276 /* [in] */ IUnknown* /*sender*/)
3278 ASSERT_NOT_REACHED();
3282 // FIXME: This code should move into WebCore so it can be shared by all the WebKits.
3283 #define MinimumZoomMultiplier 0.5f
3284 #define MaximumZoomMultiplier 3.0f
3285 #define ZoomMultiplierRatio 1.2f
3287 HRESULT STDMETHODCALLTYPE WebView::canMakeTextLarger(
3288 /* [in] */ IUnknown* /*sender*/,
3289 /* [retval][out] */ BOOL* result)
3291 bool canGrowMore = canZoomIn(m_page->settings()->zoomsTextOnly());
3292 *result = canGrowMore ? TRUE : FALSE;
3296 HRESULT STDMETHODCALLTYPE WebView::canZoomPageIn(
3297 /* [in] */ IUnknown* /*sender*/,
3298 /* [retval][out] */ BOOL* result)
3300 bool canGrowMore = canZoomIn(false);
3301 *result = canGrowMore ? TRUE : FALSE;
3305 bool WebView::canZoomIn(bool isTextOnly)
3307 return zoomMultiplier(isTextOnly) * ZoomMultiplierRatio < MaximumZoomMultiplier;
3310 HRESULT STDMETHODCALLTYPE WebView::makeTextLarger(
3311 /* [in] */ IUnknown* /*sender*/)
3313 return zoomIn(m_page->settings()->zoomsTextOnly());
3316 HRESULT STDMETHODCALLTYPE WebView::zoomPageIn(
3317 /* [in] */ IUnknown* /*sender*/)
3319 return zoomIn(false);
3322 HRESULT WebView::zoomIn(bool isTextOnly)
3324 if (!canZoomIn(isTextOnly))
3326 setZoomMultiplier(zoomMultiplier(isTextOnly) * ZoomMultiplierRatio, isTextOnly);
3330 HRESULT STDMETHODCALLTYPE WebView::canMakeTextSmaller(
3331 /* [in] */ IUnknown* /*sender*/,
3332 /* [retval][out] */ BOOL* result)
3334 bool canShrinkMore = canZoomOut(m_page->settings()->zoomsTextOnly());
3335 *result = canShrinkMore ? TRUE : FALSE;
3339 HRESULT STDMETHODCALLTYPE WebView::canZoomPageOut(
3340 /* [in] */ IUnknown* /*sender*/,
3341 /* [retval][out] */ BOOL* result)
3343 bool canShrinkMore = canZoomOut(false);
3344 *result = canShrinkMore ? TRUE : FALSE;
3348 bool WebView::canZoomOut(bool isTextOnly)
3350 return zoomMultiplier(isTextOnly) / ZoomMultiplierRatio > MinimumZoomMultiplier;
3353 HRESULT STDMETHODCALLTYPE WebView::makeTextSmaller(
3354 /* [in] */ IUnknown* /*sender*/)
3356 return zoomOut(m_page->settings()->zoomsTextOnly());
3359 HRESULT STDMETHODCALLTYPE WebView::zoomPageOut(
3360 /* [in] */ IUnknown* /*sender*/)
3362 return zoomOut(false);
3365 HRESULT WebView::zoomOut(bool isTextOnly)
3367 if (!canZoomOut(isTextOnly))
3369 setZoomMultiplier(zoomMultiplier(isTextOnly) / ZoomMultiplierRatio, isTextOnly);
3373 HRESULT STDMETHODCALLTYPE WebView::canMakeTextStandardSize(
3374 /* [in] */ IUnknown* /*sender*/,
3375 /* [retval][out] */ BOOL* result)
3377 // 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.
3378 bool notAlreadyStandard = canResetZoom(true);
3379 *result = notAlreadyStandard ? TRUE : FALSE;
3383 HRESULT STDMETHODCALLTYPE WebView::canResetPageZoom(
3384 /* [in] */ IUnknown* /*sender*/,
3385 /* [retval][out] */ BOOL* result)
3387 bool notAlreadyStandard = canResetZoom(false);
3388 *result = notAlreadyStandard ? TRUE : FALSE;
3392 bool WebView::canResetZoom(bool isTextOnly)
3394 return zoomMultiplier(isTextOnly) != 1.0f;
3397 HRESULT STDMETHODCALLTYPE WebView::makeTextStandardSize(
3398 /* [in] */ IUnknown* /*sender*/)
3400 return resetZoom(true);
3403 HRESULT STDMETHODCALLTYPE WebView::resetPageZoom(
3404 /* [in] */ IUnknown* /*sender*/)
3406 return resetZoom(false);
3409 HRESULT WebView::resetZoom(bool isTextOnly)
3411 if (!canResetZoom(isTextOnly))
3413 setZoomMultiplier(1.0f, isTextOnly);
3417 HRESULT STDMETHODCALLTYPE WebView::toggleContinuousSpellChecking(
3418 /* [in] */ IUnknown* /*sender*/)
3422 if (FAILED(hr = isContinuousSpellCheckingEnabled(&enabled)))
3424 return setContinuousSpellCheckingEnabled(enabled ? FALSE : TRUE);
3427 HRESULT STDMETHODCALLTYPE WebView::toggleSmartInsertDelete(
3428 /* [in] */ IUnknown* /*sender*/)
3430 BOOL enabled = FALSE;
3431 HRESULT hr = smartInsertDeleteEnabled(&enabled);
3435 return setSmartInsertDeleteEnabled(enabled ? FALSE : TRUE);
3438 HRESULT STDMETHODCALLTYPE WebView::toggleGrammarChecking(
3439 /* [in] */ IUnknown* /*sender*/)
3442 HRESULT hr = isGrammarCheckingEnabled(&enabled);
3446 return setGrammarCheckingEnabled(enabled ? FALSE : TRUE);
3449 // IWebViewCSS -----------------------------------------------------------------
3451 HRESULT STDMETHODCALLTYPE WebView::computedStyleForElement(
3452 /* [in] */ IDOMElement* /*element*/,
3453 /* [in] */ BSTR /*pseudoElement*/,
3454 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3456 ASSERT_NOT_REACHED();
3460 // IWebViewEditing -------------------------------------------------------------
3462 HRESULT STDMETHODCALLTYPE WebView::editableDOMRangeForPoint(
3463 /* [in] */ LPPOINT /*point*/,
3464 /* [retval][out] */ IDOMRange** /*range*/)
3466 ASSERT_NOT_REACHED();
3470 HRESULT STDMETHODCALLTYPE WebView::setSelectedDOMRange(
3471 /* [in] */ IDOMRange* /*range*/,
3472 /* [in] */ WebSelectionAffinity /*affinity*/)
3474 ASSERT_NOT_REACHED();
3478 HRESULT STDMETHODCALLTYPE WebView::selectedDOMRange(
3479 /* [retval][out] */ IDOMRange** /*range*/)
3481 ASSERT_NOT_REACHED();
3485 HRESULT STDMETHODCALLTYPE WebView::selectionAffinity(
3486 /* [retval][out][retval][out] */ WebSelectionAffinity* /*affinity*/)
3488 ASSERT_NOT_REACHED();
3492 HRESULT STDMETHODCALLTYPE WebView::setEditable(
3493 /* [in] */ BOOL /*flag*/)
3495 ASSERT_NOT_REACHED();
3499 HRESULT STDMETHODCALLTYPE WebView::isEditable(
3500 /* [retval][out] */ BOOL* /*isEditable*/)
3502 ASSERT_NOT_REACHED();
3506 HRESULT STDMETHODCALLTYPE WebView::setTypingStyle(
3507 /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
3509 ASSERT_NOT_REACHED();
3513 HRESULT STDMETHODCALLTYPE WebView::typingStyle(
3514 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3516 ASSERT_NOT_REACHED();
3520 HRESULT STDMETHODCALLTYPE WebView::setSmartInsertDeleteEnabled(
3521 /* [in] */ BOOL flag)
3523 m_smartInsertDeleteEnabled = !!flag;
3524 if (m_smartInsertDeleteEnabled)
3525 setSelectTrailingWhitespaceEnabled(false);
3529 HRESULT STDMETHODCALLTYPE WebView::smartInsertDeleteEnabled(
3530 /* [retval][out] */ BOOL* enabled)
3532 *enabled = m_smartInsertDeleteEnabled ? TRUE : FALSE;
3536 HRESULT STDMETHODCALLTYPE WebView::setSelectTrailingWhitespaceEnabled(
3537 /* [in] */ BOOL flag)
3539 m_selectTrailingWhitespaceEnabled = !!flag;
3540 if (m_selectTrailingWhitespaceEnabled)
3541 setSmartInsertDeleteEnabled(false);
3545 HRESULT STDMETHODCALLTYPE WebView::isSelectTrailingWhitespaceEnabled(
3546 /* [retval][out] */ BOOL* enabled)
3548 *enabled = m_selectTrailingWhitespaceEnabled ? TRUE : FALSE;
3552 HRESULT STDMETHODCALLTYPE WebView::setContinuousSpellCheckingEnabled(
3553 /* [in] */ BOOL flag)
3555 if (continuousSpellCheckingEnabled != !!flag) {
3556 continuousSpellCheckingEnabled = !!flag;
3557 COMPtr<IWebPreferences> prefs;
3558 if (SUCCEEDED(preferences(&prefs)))
3559 prefs->setContinuousSpellCheckingEnabled(flag);
3562 BOOL spellCheckingEnabled;
3563 if (SUCCEEDED(isContinuousSpellCheckingEnabled(&spellCheckingEnabled)) && spellCheckingEnabled)
3564 preflightSpellChecker();
3566 m_mainFrame->unmarkAllMisspellings();
3571 HRESULT STDMETHODCALLTYPE WebView::isContinuousSpellCheckingEnabled(
3572 /* [retval][out] */ BOOL* enabled)
3574 *enabled = (continuousSpellCheckingEnabled && continuousCheckingAllowed()) ? TRUE : FALSE;
3578 HRESULT STDMETHODCALLTYPE WebView::spellCheckerDocumentTag(
3579 /* [retval][out] */ int* tag)
3581 // we just use this as a flag to indicate that we've spell checked the document
3582 // and need to close the spell checker out when the view closes.
3584 m_hasSpellCheckerDocumentTag = true;
3588 static COMPtr<IWebEditingDelegate> spellingDelegateForTimer;
3590 static void preflightSpellCheckerNow()
3592 spellingDelegateForTimer->preflightChosenSpellServer();
3593 spellingDelegateForTimer = 0;
3596 static void CALLBACK preflightSpellCheckerTimerCallback(HWND, UINT, UINT_PTR id, DWORD)
3599 preflightSpellCheckerNow();
3602 void WebView::preflightSpellChecker()
3604 // As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
3605 if (!m_editingDelegate)
3609 spellingDelegateForTimer = m_editingDelegate;
3610 if (SUCCEEDED(m_editingDelegate->sharedSpellCheckerExists(&exists)) && exists)
3611 preflightSpellCheckerNow();
3613 ::SetTimer(0, 0, 2000, preflightSpellCheckerTimerCallback);
3616 bool WebView::continuousCheckingAllowed()
3618 static bool allowContinuousSpellChecking = true;
3619 static bool readAllowContinuousSpellCheckingDefault = false;
3620 if (!readAllowContinuousSpellCheckingDefault) {
3621 COMPtr<IWebPreferences> prefs;
3622 if (SUCCEEDED(preferences(&prefs))) {
3624 prefs->allowContinuousSpellChecking(&allowed);
3625 allowContinuousSpellChecking = !!allowed;
3627 readAllowContinuousSpellCheckingDefault = true;
3629 return allowContinuousSpellChecking;
3632 HRESULT STDMETHODCALLTYPE WebView::undoManager(
3633 /* [retval][out] */ IWebUndoManager** /*manager*/)
3635 ASSERT_NOT_REACHED();
3639 HRESULT STDMETHODCALLTYPE WebView::setEditingDelegate(
3640 /* [in] */ IWebEditingDelegate* d)
3642 m_editingDelegate = d;
3646 HRESULT STDMETHODCALLTYPE WebView::editingDelegate(
3647 /* [retval][out] */ IWebEditingDelegate** d)
3650 ASSERT_NOT_REACHED();
3654 *d = m_editingDelegate.get();
3662 HRESULT STDMETHODCALLTYPE WebView::styleDeclarationWithText(
3663 /* [in] */ BSTR /*text*/,
3664 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3666 ASSERT_NOT_REACHED();
3670 HRESULT STDMETHODCALLTYPE WebView::hasSelectedRange(
3671 /* [retval][out] */ BOOL* hasSelectedRange)
3673 *hasSelectedRange = m_page->mainFrame()->selection()->isRange();
3677 HRESULT STDMETHODCALLTYPE WebView::cutEnabled(
3678 /* [retval][out] */ BOOL* enabled)
3680 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3681 *enabled = editor->canCut() || editor->canDHTMLCut();
3685 HRESULT STDMETHODCALLTYPE WebView::copyEnabled(
3686 /* [retval][out] */ BOOL* enabled)
3688 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3689 *enabled = editor->canCopy() || editor->canDHTMLCopy();
3693 HRESULT STDMETHODCALLTYPE WebView::pasteEnabled(
3694 /* [retval][out] */ BOOL* enabled)
3696 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3697 *enabled = editor->canPaste() || editor->canDHTMLPaste();
3701 HRESULT STDMETHODCALLTYPE WebView::deleteEnabled(
3702 /* [retval][out] */ BOOL* enabled)
3704 *enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canDelete();
3708 HRESULT STDMETHODCALLTYPE WebView::editingEnabled(
3709 /* [retval][out] */ BOOL* enabled)
3711 *enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canEdit();
3715 HRESULT STDMETHODCALLTYPE WebView::isGrammarCheckingEnabled(
3716 /* [retval][out] */ BOOL* enabled)
3718 *enabled = grammarCheckingEnabled ? TRUE : FALSE;
3722 HRESULT STDMETHODCALLTYPE WebView::setGrammarCheckingEnabled(
3725 if (!m_editingDelegate) {
3726 LOG_ERROR("No NSSpellChecker");
3730 if (grammarCheckingEnabled == !!enabled)
3733 grammarCheckingEnabled = !!enabled;
3734 COMPtr<IWebPreferences> prefs;
3735 if (SUCCEEDED(preferences(&prefs)))
3736 prefs->setGrammarCheckingEnabled(enabled);
3738 m_editingDelegate->updateGrammar();
3740 // We call _preflightSpellChecker when turning continuous spell checking on, but we don't need to do that here
3741 // because grammar checking only occurs on code paths that already preflight spell checking appropriately.
3743 BOOL grammarEnabled;
3744 if (SUCCEEDED(isGrammarCheckingEnabled(&grammarEnabled)) && !grammarEnabled)
3745 m_mainFrame->unmarkAllBadGrammar();
3750 // IWebViewUndoableEditing -----------------------------------------------------
3752 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithNode(
3753 /* [in] */ IDOMNode* /*node*/)
3755 ASSERT_NOT_REACHED();
3759 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithText(
3760 /* [in] */ BSTR text)
3762 String textString(text, ::SysStringLen(text));
3763 Position start = m_page->mainFrame()->selection()->selection().start();
3764 m_page->focusController()->focusedOrMainFrame()->editor()->insertText(textString, 0);
3765 m_page->mainFrame()->selection()->setBase(start);
3769 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithMarkupString(
3770 /* [in] */ BSTR /*markupString*/)
3772 ASSERT_NOT_REACHED();
3776 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithArchive(
3777 /* [in] */ IWebArchive* /*archive*/)
3779 ASSERT_NOT_REACHED();
3783 HRESULT STDMETHODCALLTYPE WebView::deleteSelection( void)
3785 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3786 editor->deleteSelectionWithSmartDelete(editor->canSmartCopyOrDelete());
3790 HRESULT STDMETHODCALLTYPE WebView::clearSelection( void)
3792 m_page->focusController()->focusedOrMainFrame()->selection()->clear();
3796 HRESULT STDMETHODCALLTYPE WebView::applyStyle(
3797 /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
3799 ASSERT_NOT_REACHED();
3803 // IWebViewEditingActions ------------------------------------------------------
3805 HRESULT STDMETHODCALLTYPE WebView::copy(
3806 /* [in] */ IUnknown* /*sender*/)
3808 m_page->focusController()->focusedOrMainFrame()->editor()->command("Copy").execute();
3812 HRESULT STDMETHODCALLTYPE WebView::cut(
3813 /* [in] */ IUnknown* /*sender*/)
3815 m_page->focusController()->focusedOrMainFrame()->editor()->command("Cut").execute();
3819 HRESULT STDMETHODCALLTYPE WebView::paste(
3820 /* [in] */ IUnknown* /*sender*/)
3822 m_page->focusController()->focusedOrMainFrame()->editor()->command("Paste").execute();
3826 HRESULT STDMETHODCALLTYPE WebView::copyURL(
3827 /* [in] */ BSTR url)