2 * Copyright (C) 2006, 2007 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 "IWebNotification.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 "WebDragClient.h"
42 #include "WebIconDatabase.h"
43 #include "WebInspector.h"
44 #include "WebInspectorClient.h"
46 #include "WebKitStatisticsPrivate.h"
47 #include "WebKitSystemBits.h"
48 #include "WebMutableURLRequest.h"
49 #include "WebNotificationCenter.h"
50 #include "WebPreferences.h"
51 #include "WebScriptDebugServer.h"
52 #pragma warning( push, 0 )
53 #include <CoreGraphics/CGContext.h>
54 #include <WebCore/BString.h>
55 #include <WebCore/Cache.h>
56 #include <WebCore/ContextMenu.h>
57 #include <WebCore/ContextMenuController.h>
58 #include <WebCore/CString.h>
59 #include <WebCore/Cursor.h>
60 #include <WebCore/Document.h>
61 #include <WebCore/DragController.h>
62 #include <WebCore/DragData.h>
63 #include <WebCore/Editor.h>
64 #include <WebCore/EventHandler.h>
65 #include <WebCore/EventNames.h>
66 #include <WebCore/FileSystem.h>
67 #include <WebCore/FocusController.h>
68 #include <WebCore/FontData.h>
69 #include <WebCore/FrameLoader.h>
70 #include <WebCore/FrameTree.h>
71 #include <WebCore/FrameView.h>
72 #include <WebCore/FrameWin.h>
73 #include <WebCore/GDIObjectCounter.h>
74 #include <WebCore/GraphicsContext.h>
75 #include <WebCore/HistoryItem.h>
76 #include <WebCore/HitTestResult.h>
77 #include <WebCore/IntRect.h>
78 #include <WebCore/KeyboardEvent.h>
79 #include <WebCore/Language.h>
80 #include <WebCore/MIMETypeRegistry.h>
81 #include <WebCore/NotImplemented.h>
82 #include <WebCore/Page.h>
83 #include <WebCore/PageCache.h>
84 #include <WebCore/PlatformKeyboardEvent.h>
85 #include <WebCore/PlatformMouseEvent.h>
86 #include <WebCore/PlatformWheelEvent.h>
87 #include <WebCore/PluginDatabaseWin.h>
88 #include <WebCore/PlugInInfoStore.h>
89 #include <WebCore/PluginViewWin.h>
90 #include <WebCore/ProgressTracker.h>
91 #include <WebCore/ResourceHandle.h>
92 #include <WebCore/ResourceHandleClient.h>
93 #include <WebCore/SelectionController.h>
94 #include <WebCore/Settings.h>
95 #include <WebCore/TypingCommand.h>
97 #include <JavaScriptCore/collector.h>
98 #include <JavaScriptCore/value.h>
99 #include <CFNetwork/CFURLCachePriv.h>
100 #include <CFNetwork/CFURLProtocolPriv.h>
101 #include <CoreFoundation/CoreFoundation.h>
102 #include <WebKitSystemInterface/WebKitSystemInterface.h>
103 #include <wtf/HashSet.h>
106 #include <windowsx.h>
109 using namespace WebCore;
110 using namespace WebCore::EventNames;
115 class PreferencesChangedOrRemovedObserver : public IWebNotificationObserver {
117 static PreferencesChangedOrRemovedObserver* sharedInstance();
120 PreferencesChangedOrRemovedObserver() {}
121 ~PreferencesChangedOrRemovedObserver() {}
123 virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) { return E_FAIL; }
124 virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; }
125 virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; }
128 // IWebNotificationObserver
129 virtual HRESULT STDMETHODCALLTYPE onNotify(
130 /* [in] */ IWebNotification* notification);
133 HRESULT notifyPreferencesChanged(WebCacheModel);
134 HRESULT notifyPreferencesRemoved(WebCacheModel);
137 PreferencesChangedOrRemovedObserver* PreferencesChangedOrRemovedObserver::sharedInstance()
139 static PreferencesChangedOrRemovedObserver* shared = new PreferencesChangedOrRemovedObserver;
143 HRESULT PreferencesChangedOrRemovedObserver::onNotify(IWebNotification* notification)
147 COMPtr<IUnknown> unkPrefs;
148 hr = notification->getObject(&unkPrefs);
152 COMPtr<IWebPreferences> preferences(Query, unkPrefs);
154 return E_NOINTERFACE;
156 WebCacheModel cacheModel;
157 hr = preferences->cacheModel(&cacheModel);
162 hr = notification->name(&nameBSTR);
166 name.adoptBSTR(nameBSTR);
168 if (wcscmp(name, WebPreferences::webPreferencesChangedNotification()) == 0)
169 return notifyPreferencesChanged(cacheModel);
171 if (wcscmp(name, WebPreferences::webPreferencesRemovedNotification()) == 0)
172 return notifyPreferencesRemoved(cacheModel);
174 ASSERT_NOT_REACHED();
178 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesChanged(WebCacheModel cacheModel)
182 if (WebView::didSetCacheModel() || cacheModel > WebView::cacheModel())
183 WebView::setCacheModel(cacheModel);
184 else if (cacheModel < WebView::cacheModel()) {
185 WebCacheModel sharedPreferencesCacheModel;
186 hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
189 WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
195 HRESULT PreferencesChangedOrRemovedObserver::notifyPreferencesRemoved(WebCacheModel cacheModel)
199 if (cacheModel == WebView::cacheModel()) {
200 WebCacheModel sharedPreferencesCacheModel;
201 hr = WebPreferences::sharedStandardPreferences()->cacheModel(&sharedPreferencesCacheModel);
204 WebView::setCacheModel(max(sharedPreferencesCacheModel, WebView::maxCacheModelInAnyInstance()));
211 const LPCWSTR kWebViewWindowClassName = L"WebViewWindowClass";
213 const int WM_XP_THEMECHANGED = 0x031A;
214 const int WM_VISTA_MOUSEHWHEEL = 0x020E;
216 static const int maxToolTipWidth = 250;
218 static ATOM registerWebView();
219 static LRESULT CALLBACK WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
221 static void initializeStaticObservers();
223 static HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences*);
225 HRESULT createMatchEnumerator(Vector<IntRect>* rects, IEnumTextMatches** matches);
227 static bool continuousSpellCheckingEnabled;
228 static bool grammarCheckingEnabled;
230 static bool s_didSetCacheModel;
231 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
233 // WebView ----------------------------------------------------------------
235 bool WebView::s_allowSiteSpecificHacks = false;
243 , m_hasCustomDropTarget(false)
244 , m_useBackForwardList(true)
245 , m_userAgentOverridden(false)
246 , m_textSizeMultiplier(1)
247 , m_mouseActivated(false)
249 , m_currentCharacterCode(0)
250 , m_isBeingDestroyed(false)
252 , m_hasSpellCheckerDocumentTag(false)
253 , m_smartInsertDeleteEnabled(false)
255 , m_inIMEComposition(0)
257 , m_closeWindowTimer(this, &WebView::closeWindowTimerFired)
259 KJS::Collector::registerAsMainThread();
261 m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
263 CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper,(void**)&m_dropTargetHelper);
265 initializeStaticObservers();
267 WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
269 if (SUCCEEDED(sharedPreferences->continuousSpellCheckingEnabled(&enabled)))
270 continuousSpellCheckingEnabled = !!enabled;
271 if (SUCCEEDED(sharedPreferences->grammarCheckingEnabled(&enabled)))
272 grammarCheckingEnabled = !!enabled;
280 deleteBackingStore();
282 // <rdar://4958382> m_viewWindow will be destroyed when m_hostWindow is destroyed, but if
283 // setHostWindow was never called we will leak our HWND. If we still have a valid HWND at
284 // this point, we should just destroy it ourselves.
285 if (::IsWindow(m_viewWindow))
286 ::DestroyWindow(m_viewWindow);
289 ASSERT(!m_preferences);
295 WebView* WebView::createInstance()
297 WebView* instance = new WebView();
302 void initializeStaticObservers()
304 static bool initialized;
309 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
310 notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesChangedNotification(), 0);
311 notifyCenter->addObserver(PreferencesChangedOrRemovedObserver::sharedInstance(), WebPreferences::webPreferencesRemovedNotification(), 0);
314 static HashSet<WebView*>& allWebViewsSet()
316 static HashSet<WebView*> allWebViewsSet;
317 return allWebViewsSet;
320 void WebView::addToAllWebViewsSet()
322 allWebViewsSet().add(this);
325 void WebView::removeFromAllWebViewsSet()
327 allWebViewsSet().remove(this);
330 void WebView::setCacheModel(WebCacheModel cacheModel)
332 if (s_didSetCacheModel && cacheModel == s_cacheModel)
335 RetainPtr<CFStringRef> cfurlCacheDirectory(AdoptCF, wkCopyFoundationCacheDirectory());
336 if (!cfurlCacheDirectory)
337 cfurlCacheDirectory.adoptCF(WebCore::localUserSpecificStorageDirectory().createCFString());
340 CFURLCacheRef cfurlSharedCache = CFURLCacheSharedURLCache();
342 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
343 // count doesn't align exactly to a megabyte boundary.
344 unsigned long long memSize = WebMemorySize() / 1024 / 1000;
345 unsigned long long diskFreeSize = WebVolumeFreeSize(cfurlCacheDirectory.get()) / 1024 / 1000;
347 unsigned cacheTotalCapacity = 0;
348 unsigned cacheMinDeadCapacity = 0;
349 unsigned cacheMaxDeadCapacity = 0;
351 unsigned pageCacheCapacity = 0;
353 CFIndex cfurlCacheMemoryCapacity = 0;
354 CFIndex cfurlCacheDiskCapacity = 0;
356 switch (cacheModel) {
357 case WebCacheModelDocumentViewer: {
358 // Page cache capacity (in pages)
359 pageCacheCapacity = 0;
361 // Object cache capacities (in bytes)
363 cacheTotalCapacity = 256 * 1024 * 1024;
364 else if (memSize >= 3072)
365 cacheTotalCapacity = 192 * 1024 * 1024;
366 else if (memSize >= 2048)
367 cacheTotalCapacity = 128 * 1024 * 1024;
368 else if (memSize >= 1536)
369 cacheTotalCapacity = 86 * 1024 * 1024;
370 else if (memSize >= 1024)
371 cacheTotalCapacity = 64 * 1024 * 1024;
372 else if (memSize >= 512)
373 cacheTotalCapacity = 32 * 1024 * 1024;
374 else if (memSize >= 256)
375 cacheTotalCapacity = 16 * 1024 * 1024;
377 cacheMinDeadCapacity = 0;
378 cacheMaxDeadCapacity = 0;
380 // Foundation memory cache capacity (in bytes)
381 cfurlCacheMemoryCapacity = 0;
383 // Foundation disk cache capacity (in bytes)
384 cfurlCacheDiskCapacity = CFURLCacheDiskCapacity(cfurlSharedCache);
388 case WebCacheModelDocumentBrowser: {
389 // Page cache capacity (in pages)
391 pageCacheCapacity = 3;
392 else if (memSize >= 512)
393 pageCacheCapacity = 2;
394 else if (memSize >= 256)
395 pageCacheCapacity = 1;
397 pageCacheCapacity = 0;
399 // Object cache capacities (in bytes)
401 cacheTotalCapacity = 256 * 1024 * 1024;
402 else if (memSize >= 3072)
403 cacheTotalCapacity = 192 * 1024 * 1024;
404 else if (memSize >= 2048)
405 cacheTotalCapacity = 128 * 1024 * 1024;
406 else if (memSize >= 1536)
407 cacheTotalCapacity = 86 * 1024 * 1024;
408 else if (memSize >= 1024)
409 cacheTotalCapacity = 64 * 1024 * 1024;
410 else if (memSize >= 512)
411 cacheTotalCapacity = 32 * 1024 * 1024;
412 else if (memSize >= 256)
413 cacheTotalCapacity = 16 * 1024 * 1024;
415 cacheMinDeadCapacity = cacheTotalCapacity / 8;
416 cacheMaxDeadCapacity = cacheTotalCapacity / 4;
418 // Foundation memory cache capacity (in bytes)
420 cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
421 else if (memSize >= 1024)
422 cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
423 else if (memSize >= 512)
424 cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
426 cfurlCacheMemoryCapacity = 512 * 1024;
428 // Foundation disk cache capacity (in bytes)
429 if (diskFreeSize >= 16384)
430 cfurlCacheDiskCapacity = 50 * 1024 * 1024;
431 else if (diskFreeSize >= 8192)
432 cfurlCacheDiskCapacity = 40 * 1024 * 1024;
433 else if (diskFreeSize >= 4096)
434 cfurlCacheDiskCapacity = 30 * 1024 * 1024;
436 cfurlCacheDiskCapacity = 20 * 1024 * 1024;
440 case WebCacheModelPrimaryWebBrowser: {
441 // Page cache capacity (in pages)
442 // (Research indicates that value / page drops substantially after 3 pages.)
444 pageCacheCapacity = 7;
446 pageCacheCapacity = 6;
447 else if (memSize >= 2048)
448 pageCacheCapacity = 5;
449 else if (memSize >= 1024)
450 pageCacheCapacity = 4;
451 else if (memSize >= 512)
452 pageCacheCapacity = 3;
453 else if (memSize >= 256)
454 pageCacheCapacity = 2;
456 pageCacheCapacity = 1;
458 // Object cache capacities (in bytes)
459 // (Testing indicates that value / MB depends heavily on content and
460 // browsing pattern. Even growth above 128MB can have substantial
461 // value / MB for some content / browsing patterns.)
463 cacheTotalCapacity = 512 * 1024 * 1024;
464 else if (memSize >= 3072)
465 cacheTotalCapacity = 384 * 1024 * 1024;
466 else if (memSize >= 2048)
467 cacheTotalCapacity = 256 * 1024 * 1024;
468 else if (memSize >= 1536)
469 cacheTotalCapacity = 172 * 1024 * 1024;
470 else if (memSize >= 1024)
471 cacheTotalCapacity = 128 * 1024 * 1024;
472 else if (memSize >= 512)
473 cacheTotalCapacity = 64 * 1024 * 1024;
474 else if (memSize >= 256)
475 cacheTotalCapacity = 32 * 1024 * 1024;
477 cacheMinDeadCapacity = cacheTotalCapacity / 4;
478 cacheMaxDeadCapacity = cacheTotalCapacity / 2;
480 // This code is here to avoid a PLT regression. We can remove it if we
481 // can prove that the overall system gain would justify the regression.
482 cacheMaxDeadCapacity = max(24u, cacheMaxDeadCapacity);
484 // Foundation memory cache capacity (in bytes)
485 // (These values are small because WebCore does most caching itself.)
487 cfurlCacheMemoryCapacity = 4 * 1024 * 1024;
488 else if (memSize >= 512)
489 cfurlCacheMemoryCapacity = 2 * 1024 * 1024;
490 else if (memSize >= 256)
491 cfurlCacheMemoryCapacity = 1 * 1024 * 1024;
493 cfurlCacheMemoryCapacity = 512 * 1024;
495 // Foundation disk cache capacity (in bytes)
496 if (diskFreeSize >= 16384)
497 cfurlCacheDiskCapacity = 175 * 1024 * 1024;
498 else if (diskFreeSize >= 8192)
499 cfurlCacheDiskCapacity = 150 * 1024 * 1024;
500 else if (diskFreeSize >= 4096)
501 cfurlCacheDiskCapacity = 125 * 1024 * 1024;
502 else if (diskFreeSize >= 2048)
503 cfurlCacheDiskCapacity = 100 * 1024 * 1024;
504 else if (diskFreeSize >= 1024)
505 cfurlCacheDiskCapacity = 75 * 1024 * 1024;
507 cfurlCacheDiskCapacity = 50 * 1024 * 1024;
512 ASSERT_NOT_REACHED();
515 // Don't shrink a big disk cache, since that would cause churn.
516 cfurlCacheDiskCapacity = max(cfurlCacheDiskCapacity, CFURLCacheDiskCapacity(cfurlSharedCache));
518 cache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
519 pageCache()->setCapacity(pageCacheCapacity);
521 CFURLCacheSetMemoryCapacity(cfurlSharedCache, cfurlCacheMemoryCapacity);
522 CFURLCacheSetDiskCapacity(cfurlSharedCache, cfurlCacheDiskCapacity);
524 s_didSetCacheModel = true;
525 s_cacheModel = cacheModel;
529 WebCacheModel WebView::cacheModel()
534 bool WebView::didSetCacheModel()
536 return s_didSetCacheModel;
539 WebCacheModel WebView::maxCacheModelInAnyInstance()
541 WebCacheModel cacheModel = WebCacheModelDocumentViewer;
543 HashSet<WebView*>::iterator end = allWebViewsSet().end();
544 for (HashSet<WebView*>::iterator it = allWebViewsSet().begin(); it != end; ++it) {
545 COMPtr<IWebPreferences> pref;
546 if (FAILED((*it)->preferences(&pref)))
548 WebCacheModel prefCacheModel = WebCacheModelDocumentViewer;
549 if (FAILED(pref->cacheModel(&prefCacheModel)))
552 cacheModel = max(cacheModel, prefCacheModel);
558 void WebView::close()
565 removeFromAllWebViewsSet();
567 Frame* frame = m_page->mainFrame();
569 frame->loader()->detachFromParent();
571 if (m_mouseOutTracker) {
572 m_mouseOutTracker->dwFlags = TME_CANCEL;
573 ::TrackMouseEvent(m_mouseOutTracker.get());
574 m_mouseOutTracker.set(0);
577 m_page->setGroupName(String());
580 setDownloadDelegate(0);
581 setEditingDelegate(0);
582 setFrameLoadDelegate(0);
583 setFrameLoadDelegatePrivate(0);
584 setPolicyDelegate(0);
585 setResourceLoadDelegate(0);
590 m_webInspector->webViewClosed();
595 registerForIconNotification(false);
596 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
597 notifyCenter->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
600 if (SUCCEEDED(m_preferences->identifier(&identifier)))
601 WebPreferences::removeReferenceForIdentifier(identifier);
603 SysFreeString(identifier);
605 COMPtr<WebPreferences> preferences = m_preferences;
607 preferences->didRemoveFromWebView();
609 deleteBackingStore();
612 void WebView::deleteBackingStore()
614 m_backingStoreBitmap.clear();
615 m_backingStoreDirtyRegion.clear();
617 m_backingStoreSize.cx = m_backingStoreSize.cy = 0;
620 bool WebView::ensureBackingStore()
623 ::GetClientRect(m_viewWindow, &windowRect);
624 LONG width = windowRect.right - windowRect.left;
625 LONG height = windowRect.bottom - windowRect.top;
626 if (width > 0 && height > 0 && (width != m_backingStoreSize.cx || height != m_backingStoreSize.cy)) {
627 deleteBackingStore();
629 m_backingStoreSize.cx = width;
630 m_backingStoreSize.cy = height;
631 BITMAPINFO bitmapInfo;
632 bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
633 bitmapInfo.bmiHeader.biWidth = width;
634 bitmapInfo.bmiHeader.biHeight = -height;
635 bitmapInfo.bmiHeader.biPlanes = 1;
636 bitmapInfo.bmiHeader.biBitCount = 32;
637 bitmapInfo.bmiHeader.biCompression = BI_RGB;
638 bitmapInfo.bmiHeader.biSizeImage = 0;
639 bitmapInfo.bmiHeader.biXPelsPerMeter = 0;
640 bitmapInfo.bmiHeader.biYPelsPerMeter = 0;
641 bitmapInfo.bmiHeader.biClrUsed = 0;
642 bitmapInfo.bmiHeader.biClrImportant = 0;
645 m_backingStoreBitmap.set(::CreateDIBSection(NULL, &bitmapInfo, DIB_RGB_COLORS, &pixels, NULL, 0));
652 void WebView::addToDirtyRegion(const IntRect& dirtyRect)
654 HRGN newRegion = ::CreateRectRgn(dirtyRect.x(), dirtyRect.y(),
655 dirtyRect.right(), dirtyRect.bottom());
656 addToDirtyRegion(newRegion);
659 void WebView::addToDirtyRegion(HRGN newRegion)
661 LOCAL_GDI_COUNTER(0, __FUNCTION__);
663 if (m_backingStoreDirtyRegion) {
664 HRGN combinedRegion = ::CreateRectRgn(0,0,0,0);
665 ::CombineRgn(combinedRegion, m_backingStoreDirtyRegion.get(), newRegion, RGN_OR);
666 ::DeleteObject(newRegion);
667 m_backingStoreDirtyRegion.set(combinedRegion);
669 m_backingStoreDirtyRegion.set(newRegion);
672 void WebView::scrollBackingStore(FrameView* frameView, int dx, int dy, const IntRect& scrollViewRect, const IntRect& clipRect)
674 LOCAL_GDI_COUNTER(0, __FUNCTION__);
676 // If there's no backing store we don't need to update it
677 if (!m_backingStoreBitmap) {
678 if (m_uiDelegatePrivate)
679 m_uiDelegatePrivate->webViewScrolled(this);
684 // Make a region to hold the invalidated scroll area.
685 HRGN updateRegion = ::CreateRectRgn(0, 0, 0, 0);
687 // Collect our device context info and select the bitmap to scroll.
688 HDC windowDC = ::GetDC(m_viewWindow);
689 HDC bitmapDC = ::CreateCompatibleDC(windowDC);
690 ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
692 // Scroll the bitmap.
693 RECT scrollRectWin(scrollViewRect);
694 RECT clipRectWin(clipRect);
695 ::ScrollDC(bitmapDC, dx, dy, &scrollRectWin, &clipRectWin, updateRegion, 0);
697 ::GetRgnBox(updateRegion, ®ionBox);
702 // Add the dirty region to the backing store's dirty region.
703 addToDirtyRegion(updateRegion);
705 if (m_uiDelegatePrivate)
706 m_uiDelegatePrivate->webViewScrolled(this);
708 // Update the backing store.
709 updateBackingStore(frameView, bitmapDC, false);
712 ::DeleteDC(bitmapDC);
713 ::ReleaseDC(m_viewWindow, windowDC);
717 // This emulates the Mac smarts for painting rects intelligently. This is very
718 // important for us, since we double buffer based off dirty rects.
719 static void getUpdateRects(HRGN region, const IntRect& dirtyRect, Vector<IntRect>& rects)
721 ASSERT_ARG(region, region);
723 const int cRectThreshold = 10;
724 const float cWastedSpaceThreshold = 0.75f;
728 DWORD regionDataSize = GetRegionData(region, sizeof(RGNDATA), NULL);
729 if (!regionDataSize) {
730 rects.append(dirtyRect);
734 Vector<unsigned char> buffer(regionDataSize);
735 RGNDATA* regionData = reinterpret_cast<RGNDATA*>(buffer.data());
736 GetRegionData(region, regionDataSize, regionData);
737 if (regionData->rdh.nCount > cRectThreshold) {
738 rects.append(dirtyRect);
742 double singlePixels = 0.0;
745 for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
746 singlePixels += (rect->right - rect->left) * (rect->bottom - rect->top);
748 double unionPixels = dirtyRect.width() * dirtyRect.height();
749 double wastedSpace = 1.0 - (singlePixels / unionPixels);
750 if (wastedSpace <= cWastedSpaceThreshold) {
751 rects.append(dirtyRect);
755 for (i = 0, rect = reinterpret_cast<RECT*>(regionData->Buffer); i < regionData->rdh.nCount; i++, rect++)
759 void WebView::updateBackingStore(FrameView* frameView, HDC dc, bool backingStoreCompletelyDirty)
761 LOCAL_GDI_COUNTER(0, __FUNCTION__);
766 windowDC = ::GetDC(m_viewWindow);
767 bitmapDC = ::CreateCompatibleDC(windowDC);
768 ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
771 if (m_backingStoreBitmap && (m_backingStoreDirtyRegion || backingStoreCompletelyDirty)) {
772 // Do a layout first so that everything we render to the backing store is always current.
773 if (Frame* coreFrame = core(m_mainFrame))
774 if (FrameView* view = coreFrame->view())
775 view->layoutIfNeededRecursive();
777 Vector<IntRect> paintRects;
778 if (!backingStoreCompletelyDirty) {
780 ::GetRgnBox(m_backingStoreDirtyRegion.get(), ®ionBox);
781 getUpdateRects(m_backingStoreDirtyRegion.get(), regionBox, paintRects);
784 ::GetClientRect(m_viewWindow, &clientRect);
785 paintRects.append(clientRect);
788 for (unsigned i = 0; i < paintRects.size(); ++i)
789 paintIntoBackingStore(frameView, bitmapDC, paintRects[i]);
791 if (m_uiDelegatePrivate) {
792 COMPtr<IWebUIDelegatePrivate2> uiDelegatePrivate2(Query, m_uiDelegatePrivate);
793 if (uiDelegatePrivate2)
794 uiDelegatePrivate2->webViewPainted(this);
797 m_backingStoreDirtyRegion.clear();
801 ::DeleteDC(bitmapDC);
802 ::ReleaseDC(m_viewWindow, windowDC);
808 void WebView::paint(HDC dc, LPARAM options)
810 LOCAL_GDI_COUNTER(0, __FUNCTION__);
812 Frame* coreFrame = core(m_mainFrame);
815 FrameView* frameView = coreFrame->view();
822 int regionType = NULLREGION;
825 region.set(CreateRectRgn(0,0,0,0));
826 regionType = GetUpdateRgn(m_viewWindow, region.get(), false);
827 hdc = BeginPaint(m_viewWindow, &ps);
828 rcPaint = ps.rcPaint;
831 ::GetClientRect(m_viewWindow, &rcPaint);
832 if (options & PRF_ERASEBKGND)
833 ::FillRect(hdc, &rcPaint, (HBRUSH)GetStockObject(WHITE_BRUSH));
836 HDC bitmapDC = ::CreateCompatibleDC(hdc);
837 bool backingStoreCompletelyDirty = ensureBackingStore();
838 ::SelectObject(bitmapDC, m_backingStoreBitmap.get());
840 // Update our backing store if needed.
841 updateBackingStore(frameView, bitmapDC, backingStoreCompletelyDirty);
843 // Now we blit the updated backing store
844 IntRect windowDirtyRect = rcPaint;
846 // Apply the same heuristic for this update region too.
847 Vector<IntRect> blitRects;
848 if (region && regionType == COMPLEXREGION)
849 getUpdateRects(region.get(), windowDirtyRect, blitRects);
851 blitRects.append(windowDirtyRect);
853 for (unsigned i = 0; i < blitRects.size(); ++i)
854 paintIntoWindow(bitmapDC, hdc, blitRects[i]);
856 ::DeleteDC(bitmapDC);
858 // Paint the gripper.
859 COMPtr<IWebUIDelegate> ui;
860 if (SUCCEEDED(uiDelegate(&ui))) {
861 COMPtr<IWebUIDelegatePrivate> uiPrivate;
862 if (SUCCEEDED(ui->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&uiPrivate))) {
864 if (SUCCEEDED(uiPrivate->webViewResizerRect(this, &r))) {
865 LOCAL_GDI_COUNTER(2, __FUNCTION__" webViewDrawResizer delegate call");
866 uiPrivate->webViewDrawResizer(this, hdc, (frameView->resizerOverlapsContent() ? true : false), &r);
872 EndPaint(m_viewWindow, &ps);
877 void WebView::paintIntoBackingStore(FrameView* frameView, HDC bitmapDC, const IntRect& dirtyRect)
879 LOCAL_GDI_COUNTER(0, __FUNCTION__);
881 RECT rect = dirtyRect;
883 #if FLASH_BACKING_STORE_REDRAW
884 HDC dc = ::GetDC(m_viewWindow);
885 OwnPtr<HBRUSH> yellowBrush = CreateSolidBrush(RGB(255, 255, 0));
886 FillRect(dc, &rect, yellowBrush.get());
889 paintIntoWindow(bitmapDC, dc, dirtyRect);
890 ::ReleaseDC(m_viewWindow, dc);
893 FillRect(bitmapDC, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
894 if (frameView && frameView->frame() && frameView->frame()->renderer()) {
895 GraphicsContext gc(bitmapDC);
898 frameView->paint(&gc, dirtyRect);
903 void WebView::paintIntoWindow(HDC bitmapDC, HDC windowDC, const IntRect& dirtyRect)
905 LOCAL_GDI_COUNTER(0, __FUNCTION__);
906 #if FLASH_WINDOW_REDRAW
907 OwnPtr<HBRUSH> greenBrush = CreateSolidBrush(RGB(0, 255, 0));
908 RECT rect = dirtyRect;
909 FillRect(windowDC, &rect, greenBrush.get());
914 // Blit the dirty rect from the backing store into the same position
915 // in the destination DC.
916 BitBlt(windowDC, dirtyRect.x(), dirtyRect.y(), dirtyRect.width(), dirtyRect.height(), bitmapDC,
917 dirtyRect.x(), dirtyRect.y(), SRCCOPY);
920 void WebView::frameRect(RECT* rect)
922 ::GetWindowRect(m_viewWindow, rect);
925 void WebView::closeWindowSoon()
927 m_closeWindowTimer.startOneShot(0);
931 void WebView::closeWindowTimerFired(WebCore::Timer<WebView>*)
937 void WebView::closeWindow()
939 if (m_hasSpellCheckerDocumentTag) {
940 if (m_editingDelegate)
941 m_editingDelegate->closeSpellDocument(this);
942 m_hasSpellCheckerDocumentTag = false;
945 COMPtr<IWebUIDelegate> ui;
946 if (SUCCEEDED(uiDelegate(&ui)))
947 ui->webViewClose(this);
950 bool WebView::canHandleRequest(const WebCore::ResourceRequest& request)
952 // On the mac there's an about url protocol implementation but CFNetwork doesn't have that.
953 if (equalIgnoringCase(String(request.url().protocol()), "about"))
956 if (CFURLProtocolCanHandleRequest(request.cfURLRequest()))
959 // FIXME: Mac WebKit calls _representationExistsForURLScheme here
963 Page* WebView::page()
968 bool WebView::handleContextMenuEvent(WPARAM wParam, LPARAM lParam)
970 static const int contextMenuMargin = 1;
972 // Translate the screen coordinates into window coordinates
973 POINT coords = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
974 if (coords.x == -1 || coords.y == -1) {
975 FrameView* view = m_page->mainFrame()->view();
979 int rightAligned = ::GetSystemMetrics(SM_MENUDROPALIGNMENT);
982 // The context menu event was generated from the keyboard, so show the context menu by the current selection.
983 Position start = m_page->mainFrame()->selectionController()->selection().start();
984 Position end = m_page->mainFrame()->selectionController()->selection().end();
986 if (!start.node() || !end.node())
987 location = IntPoint(rightAligned ? view->contentsWidth() - contextMenuMargin : contextMenuMargin, contextMenuMargin);
989 RenderObject* renderer = start.node()->renderer();
993 // Calculate the rect of the first line of the selection (cribbed from -[WebCoreFrameBridge firstRectForDOMRange:]).
994 int extraWidthToEndOfLine = 0;
995 IntRect startCaretRect = renderer->caretRect(start.offset(), DOWNSTREAM, &extraWidthToEndOfLine);
996 IntRect endCaretRect = renderer->caretRect(end.offset(), UPSTREAM);
999 if (startCaretRect.y() == endCaretRect.y())
1000 firstRect = IntRect(min(startCaretRect.x(), endCaretRect.x()), startCaretRect.y(), abs(endCaretRect.x() - startCaretRect.x()), max(startCaretRect.height(), endCaretRect.height()));
1002 firstRect = IntRect(startCaretRect.x(), startCaretRect.y(), startCaretRect.width() + extraWidthToEndOfLine, startCaretRect.height());
1004 location = IntPoint(rightAligned ? firstRect.right() : firstRect.x(), firstRect.bottom());
1007 location = view->contentsToWindow(location);
1008 // FIXME: The IntSize(0, -1) is a hack to get the hit-testing to result in the selected element.
1009 // Ideally we'd have the position of a context menu event be separate from its target node.
1010 coords = location + IntSize(0, -1);
1012 if (!::ScreenToClient(m_viewWindow, &coords))
1016 lParam = MAKELPARAM(coords.x, coords.y);
1018 // The contextMenuController() holds onto the last context menu that was popped up on the
1019 // page until a new one is created. We need to clear this menu before propagating the event
1020 // through the DOM so that we can detect if we create a new menu for this event, since we
1021 // won't create a new menu if the DOM swallows the event and the defaultEventHandler does
1023 m_page->contextMenuController()->clearContextMenu();
1025 HitTestResult result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(IntPoint(coords.x, coords.y), false);
1026 Frame* targetFrame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document()->frame() : m_page->focusController()->focusedOrMainFrame();
1028 targetFrame->view()->setCursor(pointerCursor());
1029 PlatformMouseEvent mouseEvent(m_viewWindow, WM_RBUTTONUP, wParam, lParam);
1030 bool handledEvent = targetFrame->eventHandler()->sendContextMenuEvent(mouseEvent);
1035 ContextMenu* coreMenu = m_page->contextMenuController()->contextMenu();
1039 Node* node = coreMenu->hitTestResult().innerNonSharedNode();
1043 Frame* frame = node->document()->frame();
1047 FrameView* view = frame->view();
1051 POINT point(view->contentsToWindow(coreMenu->hitTestResult().point()));
1053 // Translate the point to screen coordinates
1054 if (!::ClientToScreen(view->containingWindow(), &point))
1057 BOOL hasCustomMenus = false;
1059 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1062 m_uiDelegate->trackCustomPopupMenu((IWebView*)this, (OLE_HANDLE)(ULONG64)coreMenu->platformDescription(), &point);
1064 // Surprisingly, TPM_RIGHTBUTTON means that items are selectable with either the right OR left mouse button
1065 UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL
1066 | TPM_LEFTALIGN | TPM_HORPOSANIMATION;
1067 ::TrackPopupMenuEx(coreMenu->platformDescription(), flags, point.x, point.y, view->containingWindow(), 0);
1073 bool WebView::onMeasureItem(WPARAM /*wParam*/, LPARAM lParam)
1078 BOOL hasCustomMenus = false;
1079 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1080 if (!hasCustomMenus)
1083 m_uiDelegate->measureCustomMenuItem((IWebView*)this, (void*)lParam);
1087 bool WebView::onDrawItem(WPARAM /*wParam*/, LPARAM lParam)
1092 BOOL hasCustomMenus = false;
1093 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1094 if (!hasCustomMenus)
1097 m_uiDelegate->drawCustomMenuItem((IWebView*)this, (void*)lParam);
1101 bool WebView::onInitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1106 HMENU menu = (HMENU)wParam;
1110 BOOL hasCustomMenus = false;
1111 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1112 if (!hasCustomMenus)
1115 m_uiDelegate->addCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1119 bool WebView::onUninitMenuPopup(WPARAM wParam, LPARAM /*lParam*/)
1124 HMENU menu = (HMENU)wParam;
1128 BOOL hasCustomMenus = false;
1129 m_uiDelegate->hasCustomMenuImplementation(&hasCustomMenus);
1130 if (!hasCustomMenus)
1133 m_uiDelegate->cleanUpCustomMenuDrawingData((IWebView*)this, (OLE_HANDLE)(ULONG64)menu);
1137 void WebView::performContextMenuAction(WPARAM wParam, LPARAM lParam, bool byPosition)
1139 ContextMenu* menu = m_page->contextMenuController()->contextMenu();
1142 ContextMenuItem* item = byPosition ? menu->itemAtIndex((unsigned)wParam, (HMENU)lParam) : menu->itemWithAction((ContextMenuAction)wParam);
1145 m_page->contextMenuController()->contextMenuItemSelected(item);
1149 bool WebView::handleMouseEvent(UINT message, WPARAM wParam, LPARAM lParam)
1151 static LONG globalClickCount;
1152 static IntPoint globalPrevPoint;
1153 static MouseButton globalPrevButton;
1154 static LONG globalPrevMouseDownTime;
1156 // Create our event.
1157 // On WM_MOUSELEAVE we need to create a mouseout event, so we force the position
1158 // of the event to be at (MINSHORT, MINSHORT).
1159 LPARAM position = (message == WM_MOUSELEAVE) ? ((MINSHORT << 16) | MINSHORT) : lParam;
1160 PlatformMouseEvent mouseEvent(m_viewWindow, message, wParam, position, m_mouseActivated);
1162 bool insideThreshold = abs(globalPrevPoint.x() - mouseEvent.pos().x()) < ::GetSystemMetrics(SM_CXDOUBLECLK) &&
1163 abs(globalPrevPoint.y() - mouseEvent.pos().y()) < ::GetSystemMetrics(SM_CYDOUBLECLK);
1164 LONG messageTime = ::GetMessageTime();
1166 bool handled = false;
1167 if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || message == WM_RBUTTONDOWN) {
1168 // FIXME: I'm not sure if this is the "right" way to do this
1169 // but without this call, we never become focused since we don't allow
1170 // the default handling of mouse events.
1171 SetFocus(m_viewWindow);
1173 // Always start capturing events when the mouse goes down in our HWND.
1174 ::SetCapture(m_viewWindow);
1176 if (((messageTime - globalPrevMouseDownTime) < (LONG)::GetDoubleClickTime()) &&
1178 mouseEvent.button() == globalPrevButton)
1181 // Reset the click count.
1182 globalClickCount = 1;
1183 globalPrevMouseDownTime = messageTime;
1184 globalPrevButton = mouseEvent.button();
1185 globalPrevPoint = mouseEvent.pos();
1187 mouseEvent.setClickCount(globalClickCount);
1188 handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1189 } else if (message == WM_LBUTTONDBLCLK || message == WM_MBUTTONDBLCLK || message == WM_RBUTTONDBLCLK) {
1191 mouseEvent.setClickCount(globalClickCount);
1192 handled = m_page->mainFrame()->eventHandler()->handleMousePressEvent(mouseEvent);
1193 } else if (message == WM_LBUTTONUP || message == WM_MBUTTONUP || message == WM_RBUTTONUP) {
1194 // Record the global position and the button of the up.
1195 globalPrevButton = mouseEvent.button();
1196 globalPrevPoint = mouseEvent.pos();
1197 mouseEvent.setClickCount(globalClickCount);
1198 m_page->mainFrame()->eventHandler()->handleMouseReleaseEvent(mouseEvent);
1200 } else if (message == WM_MOUSELEAVE && m_mouseOutTracker) {
1201 // Once WM_MOUSELEAVE is fired windows clears this tracker
1202 // so there is no need to disable it ourselves.
1203 m_mouseOutTracker.set(0);
1204 m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1206 } else if (message == WM_MOUSEMOVE) {
1207 if (!insideThreshold)
1208 globalClickCount = 0;
1209 mouseEvent.setClickCount(globalClickCount);
1210 handled = m_page->mainFrame()->eventHandler()->mouseMoved(mouseEvent);
1211 if (!m_mouseOutTracker) {
1212 m_mouseOutTracker.set(new TRACKMOUSEEVENT);
1213 m_mouseOutTracker->cbSize = sizeof(TRACKMOUSEEVENT);
1214 m_mouseOutTracker->dwFlags = TME_LEAVE;
1215 m_mouseOutTracker->hwndTrack = m_viewWindow;
1216 ::TrackMouseEvent(m_mouseOutTracker.get());
1219 setMouseActivated(false);
1223 bool WebView::mouseWheel(WPARAM wParam, LPARAM lParam, bool isHorizontal)
1225 // Ctrl+Mouse wheel doesn't ever go into WebCore. It is used to
1226 // zoom instead (Mac zooms the whole Desktop, but Windows browsers trigger their
1227 // own local zoom modes for Ctrl+wheel).
1228 if (wParam & MK_CONTROL) {
1229 short delta = short(HIWORD(wParam));
1237 PlatformWheelEvent wheelEvent(m_viewWindow, wParam, lParam, isHorizontal);
1238 Frame* coreFrame = core(m_mainFrame);
1242 return coreFrame->eventHandler()->handleWheelEvent(wheelEvent);
1245 bool WebView::execCommand(WPARAM wParam, LPARAM /*lParam*/)
1247 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1248 switch (LOWORD(wParam)) {
1250 return frame->editor()->command("SelectAll").execute();
1252 return frame->editor()->command("Undo").execute();
1254 return frame->editor()->command("Redo").execute();
1259 bool WebView::keyUp(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1261 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::KeyUp, systemKeyDown);
1263 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1264 m_currentCharacterCode = 0;
1266 return frame->eventHandler()->keyEvent(keyEvent);
1269 static const unsigned CtrlKey = 1 << 0;
1270 static const unsigned AltKey = 1 << 1;
1271 static const unsigned ShiftKey = 1 << 2;
1274 struct KeyDownEntry {
1275 unsigned virtualKey;
1280 struct KeyPressEntry {
1286 static const KeyDownEntry keyDownEntries[] = {
1287 { VK_LEFT, 0, "MoveLeft" },
1288 { VK_LEFT, ShiftKey, "MoveLeftAndModifySelection" },
1289 { VK_LEFT, CtrlKey, "MoveWordLeft" },
1290 { VK_LEFT, CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection" },
1291 { VK_RIGHT, 0, "MoveRight" },
1292 { VK_RIGHT, ShiftKey, "MoveRightAndModifySelection" },
1293 { VK_RIGHT, CtrlKey, "MoveWordRight" },
1294 { VK_RIGHT, CtrlKey | ShiftKey, "MoveWordRightAndModifySelection" },
1295 { VK_UP, 0, "MoveUp" },
1296 { VK_UP, ShiftKey, "MoveUpAndModifySelection" },
1297 { VK_PRIOR, ShiftKey, "MoveUpAndModifySelection" },
1298 { VK_DOWN, 0, "MoveDown" },
1299 { VK_DOWN, ShiftKey, "MoveDownAndModifySelection" },
1300 { VK_NEXT, ShiftKey, "MoveDownAndModifySelection" },
1301 { VK_PRIOR, 0, "MovePageUp" },
1302 { VK_NEXT, 0, "MovePageDown" },
1303 { VK_HOME, 0, "MoveToBeginningOfLine" },
1304 { VK_HOME, ShiftKey, "MoveToBeginningOfLineAndModifySelection" },
1305 { VK_HOME, CtrlKey, "MoveToBeginningOfDocument" },
1306 { VK_HOME, CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
1308 { VK_END, 0, "MoveToEndOfLine" },
1309 { VK_END, ShiftKey, "MoveToEndOfLineAndModifySelection" },
1310 { VK_END, CtrlKey, "MoveToEndOfDocument" },
1311 { VK_END, CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection" },
1313 { VK_BACK, 0, "BackwardDelete" },
1314 { VK_BACK, ShiftKey, "BackwardDelete" },
1315 { VK_DELETE, 0, "ForwardDelete" },
1316 { VK_DELETE, ShiftKey, "ForwardDelete" },
1317 { VK_BACK, CtrlKey, "DeleteWordBackward" },
1318 { VK_DELETE, CtrlKey, "DeleteWordForward" },
1320 { 'B', CtrlKey, "ToggleBold" },
1321 { 'I', CtrlKey, "ToggleItalic" },
1323 { VK_ESCAPE, 0, "Cancel" },
1324 { VK_OEM_PERIOD, CtrlKey, "Cancel" },
1325 { VK_TAB, 0, "InsertTab" },
1326 { VK_TAB, ShiftKey, "InsertBacktab" },
1327 { VK_RETURN, 0, "InsertNewline" },
1328 { VK_RETURN, CtrlKey, "InsertNewline" },
1329 { VK_RETURN, AltKey, "InsertNewline" },
1330 { VK_RETURN, AltKey | ShiftKey, "InsertNewline" },
1332 { 'C', CtrlKey, "Copy" },
1333 { 'V', CtrlKey, "Paste" },
1334 { 'X', CtrlKey, "Cut" },
1335 { 'A', CtrlKey, "SelectAll" },
1336 { 'Z', CtrlKey, "Undo" },
1337 { 'Z', CtrlKey | ShiftKey, "Redo" },
1340 static const KeyPressEntry keyPressEntries[] = {
1341 { '\t', 0, "InsertTab" },
1342 { '\t', ShiftKey, "InsertBacktab" },
1343 { '\r', 0, "InsertNewline" },
1344 { '\r', CtrlKey, "InsertNewline" },
1345 { '\r', AltKey, "InsertNewline" },
1346 { '\r', AltKey | ShiftKey, "InsertNewline" },
1349 const char* WebView::interpretKeyEvent(const KeyboardEvent* evt)
1351 ASSERT(evt->type() == keydownEvent || evt->type() == keypressEvent);
1353 static HashMap<int, const char*>* keyDownCommandsMap = 0;
1354 static HashMap<int, const char*>* keyPressCommandsMap = 0;
1356 if (!keyDownCommandsMap) {
1357 keyDownCommandsMap = new HashMap<int, const char*>;
1358 keyPressCommandsMap = new HashMap<int, const char*>;
1360 for (unsigned i = 0; i < _countof(keyDownEntries); i++)
1361 keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
1363 for (unsigned i = 0; i < _countof(keyPressEntries); i++)
1364 keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
1367 unsigned modifiers = 0;
1368 if (evt->shiftKey())
1369 modifiers |= ShiftKey;
1371 modifiers |= AltKey;
1373 modifiers |= CtrlKey;
1375 return evt->type() == keydownEvent ?
1376 keyDownCommandsMap->get(modifiers << 16 | evt->keyCode()) :
1377 keyPressCommandsMap->get(modifiers << 16 | evt->charCode());
1380 bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
1382 Node* node = evt->target()->toNode();
1384 Frame* frame = node->document()->frame();
1387 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1388 if (!keyEvent || keyEvent->isSystemKey()) // do not treat this as text input if it's a system key event
1391 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1393 if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1394 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1395 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1396 // (e.g. Tab that inserts a Tab character, or Enter).
1397 return !command.isTextInsertion() && command.execute(evt);
1400 if (command.execute(evt))
1403 // Don't insert null or control characters as they can result in unexpected behaviour
1404 if (evt->charCode() < ' ')
1407 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1410 bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1412 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1413 if (virtualKeyCode == VK_CAPITAL)
1414 frame->eventHandler()->capsLockStateMayHaveChanged();
1416 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::RawKeyDown, systemKeyDown);
1417 bool handled = frame->eventHandler()->keyEvent(keyEvent);
1419 // These events cannot be canceled.
1420 // FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
1425 // FIXME: remove WM_UNICHAR, too
1427 // WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
1429 ::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
1433 // We need to handle back/forward using either Backspace(+Shift) or Ctrl+Left/Right Arrow keys.
1434 if ((virtualKeyCode == VK_BACK && keyEvent.shiftKey()) || (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey()))
1435 m_page->goForward();
1436 else if (virtualKeyCode == VK_BACK || (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey()))
1439 // Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
1440 ScrollDirection direction;
1441 ScrollGranularity granularity;
1442 switch (virtualKeyCode) {
1444 granularity = ScrollByLine;
1445 direction = ScrollLeft;
1448 granularity = ScrollByLine;
1449 direction = ScrollRight;
1452 granularity = ScrollByLine;
1453 direction = ScrollUp;
1456 granularity = ScrollByLine;
1457 direction = ScrollDown;
1460 granularity = ScrollByDocument;
1461 direction = ScrollUp;
1464 granularity = ScrollByDocument;
1465 direction = ScrollDown;
1468 granularity = ScrollByPage;
1469 direction = ScrollUp;
1472 granularity = ScrollByPage;
1473 direction = ScrollDown;
1479 if (!frame->eventHandler()->scrollOverflow(direction, granularity))
1480 frame->view()->scroll(direction, granularity);
1484 bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
1486 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1488 PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformKeyboardEvent::Char, systemKeyDown);
1489 if (frame->eventHandler()->keyEvent(keyEvent))
1492 // Need to scroll the page if space is hit.
1493 if (charCode == ' ') {
1494 ScrollDirection direction = keyEvent.shiftKey() ? ScrollUp : ScrollDown;
1495 if (!frame->eventHandler()->scrollOverflow(direction, ScrollByPage))
1496 frame->view()->scroll(direction, ScrollByPage);
1502 bool WebView::inResizer(LPARAM lParam)
1504 if (!m_uiDelegatePrivate)
1508 if (FAILED(m_uiDelegatePrivate->webViewResizerRect(this, &r)))
1512 pt.x = LOWORD(lParam);
1513 pt.y = HIWORD(lParam);
1514 return !!PtInRect(&r, pt);
1517 static bool registerWebViewWindowClass()
1519 static bool haveRegisteredWindowClass = false;
1520 if (haveRegisteredWindowClass)
1523 haveRegisteredWindowClass = true;
1527 wcex.cbSize = sizeof(WNDCLASSEX);
1529 wcex.style = CS_DBLCLKS;
1530 wcex.lpfnWndProc = WebViewWndProc;
1531 wcex.cbClsExtra = 0;
1532 wcex.cbWndExtra = 4; // 4 bytes for the IWebView pointer
1533 wcex.hInstance = gInstance;
1535 wcex.hCursor = ::LoadCursor(0, IDC_ARROW);
1536 wcex.hbrBackground = 0;
1537 wcex.lpszMenuName = 0;
1538 wcex.lpszClassName = kWebViewWindowClassName;
1541 return !!RegisterClassEx(&wcex);
1545 extern HCURSOR lastSetCursor;
1548 static LRESULT CALLBACK WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
1550 LRESULT lResult = 0;
1551 LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
1552 WebView* webView = reinterpret_cast<WebView*>(longPtr);
1553 WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
1554 if (!mainFrameImpl || webView->isBeingDestroyed())
1555 return DefWindowProc(hWnd, message, wParam, lParam);
1559 // Windows Media Player has a modal message loop that will deliver messages
1560 // to us at inappropriate times and we will crash if we handle them when
1561 // they are delivered. We repost paint messages so that we eventually get
1562 // a chance to paint once the modal loop has exited, but other messages
1563 // aren't safe to repost, so we just drop them.
1564 if (PluginViewWin::isCallingPlugin()) {
1565 if (message == WM_PAINT)
1566 PostMessage(hWnd, message, wParam, lParam);
1570 bool handled = true;
1574 COMPtr<IWebDataSource> dataSource;
1575 mainFrameImpl->dataSource(&dataSource);
1576 Frame* coreFrame = core(mainFrameImpl);
1577 if (!webView->isPainting() && (!dataSource || coreFrame && (coreFrame->view()->didFirstLayout() || !coreFrame->loader()->committedFirstRealDocumentLoad())))
1578 webView->paint(0, 0);
1580 ValidateRect(hWnd, 0);
1583 case WM_PRINTCLIENT:
1584 webView->paint((HDC)wParam, lParam);
1588 webView->setIsBeingDestroyed();
1589 webView->revokeDragDrop();
1592 if (webView->inResizer(lParam))
1593 SetCursor(LoadCursor(0, IDC_SIZENWSE));
1595 case WM_LBUTTONDOWN:
1596 case WM_MBUTTONDOWN:
1597 case WM_RBUTTONDOWN:
1598 case WM_LBUTTONDBLCLK:
1599 case WM_MBUTTONDBLCLK:
1600 case WM_RBUTTONDBLCLK:
1605 if (Frame* coreFrame = core(mainFrameImpl))
1606 if (coreFrame->view()->didFirstLayout())
1607 handled = webView->handleMouseEvent(message, wParam, lParam);
1610 case WM_VISTA_MOUSEHWHEEL:
1611 if (Frame* coreFrame = core(mainFrameImpl))
1612 if (coreFrame->view()->didFirstLayout())
1613 handled = webView->mouseWheel(wParam, lParam, (wParam & MK_SHIFT) || message == WM_VISTA_MOUSEHWHEEL);
1616 handled = webView->keyDown(wParam, lParam, true);
1619 handled = webView->keyDown(wParam, lParam);
1622 handled = webView->keyUp(wParam, lParam, true);
1625 handled = webView->keyUp(wParam, lParam);
1628 handled = webView->keyPress(wParam, lParam, true);
1631 handled = webView->keyPress(wParam, lParam);
1633 // FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
1635 if (webView->isBeingDestroyed())
1636 // If someone has sent us this message while we're being destroyed, we should bail out so we don't crash.
1640 webView->deleteBackingStore();
1641 if (Frame* coreFrame = core(mainFrameImpl))
1642 coreFrame->view()->resize(LOWORD(lParam), HIWORD(lParam));
1646 lResult = DefWindowProc(hWnd, message, wParam, lParam);
1648 // The window is being hidden (e.g., because we switched tabs.
1649 // Null out our backing store.
1650 webView->deleteBackingStore();
1653 COMPtr<IWebUIDelegate> uiDelegate;
1654 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
1655 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
1656 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
1657 uiDelegatePrivate->webViewReceivedFocus(webView);
1658 // FIXME: Merge this logic with updateActiveState, and switch this over to use updateActiveState
1660 // It's ok to just always do setWindowHasFocus, since we won't fire the focus event on the DOM
1661 // window unless the value changes. It's also ok to do setIsActive inside focus,
1662 // because Windows has no concept of having to update control tints (e.g., graphite vs. aqua)
1663 // and therefore only needs to update the selection (which is limited to the focused frame).
1664 FocusController* focusController = webView->page()->focusController();
1665 if (Frame* frame = focusController->focusedFrame()) {
1666 frame->setIsActive(true);
1668 // If the previously focused window is a child of ours (for example a plugin), don't send any
1670 if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
1671 frame->setWindowHasFocus(true);
1673 focusController->setFocusedFrame(webView->page()->mainFrame());
1676 case WM_KILLFOCUS: {
1677 COMPtr<IWebUIDelegate> uiDelegate;
1678 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
1679 HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
1680 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
1681 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
1682 uiDelegatePrivate->webViewLostFocus(webView, (OLE_HANDLE)(ULONG64)newFocusWnd);
1683 // FIXME: Merge this logic with updateActiveState, and switch this over to use updateActiveState
1685 // However here we have to be careful. If we are losing focus because of a deactivate,
1686 // then we need to remember our focused target for restoration later.
1687 // If we are losing focus to another part of our window, then we are no longer focused for real
1688 // and we need to clear out the focused target.
1689 FocusController* focusController = webView->page()->focusController();
1690 webView->resetIME(focusController->focusedOrMainFrame());
1691 if (GetAncestor(hWnd, GA_ROOT) != newFocusWnd) {
1692 if (Frame* frame = focusController->focusedOrMainFrame()) {
1693 frame->setIsActive(false);
1695 // If we're losing focus to a child of ours, don't send blur events.
1696 if (!IsChild(hWnd, newFocusWnd))
1697 frame->setWindowHasFocus(false);
1700 focusController->setFocusedFrame(0);
1713 webView->delete_(0);
1717 handled = webView->execCommand(wParam, lParam);
1718 else // If the high word of wParam is 0, the message is from a menu
1719 webView->performContextMenuAction(wParam, lParam, false);
1721 case WM_MENUCOMMAND:
1722 webView->performContextMenuAction(wParam, lParam, true);
1724 case WM_CONTEXTMENU:
1725 handled = webView->handleContextMenuEvent(wParam, lParam);
1727 case WM_INITMENUPOPUP:
1728 handled = webView->onInitMenuPopup(wParam, lParam);
1730 case WM_MEASUREITEM:
1731 handled = webView->onMeasureItem(wParam, lParam);
1734 handled = webView->onDrawItem(wParam, lParam);
1736 case WM_UNINITMENUPOPUP:
1737 handled = webView->onUninitMenuPopup(wParam, lParam);
1739 case WM_XP_THEMECHANGED:
1740 if (Frame* coreFrame = core(mainFrameImpl)) {
1741 webView->deleteBackingStore();
1742 coreFrame->view()->themeChanged();
1745 case WM_MOUSEACTIVATE:
1746 webView->setMouseActivated(true);
1748 case WM_GETDLGCODE: {
1749 COMPtr<IWebUIDelegate> uiDelegate;
1750 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
1751 LONG_PTR dlgCode = 0;
1754 LPMSG lpMsg = (LPMSG)lParam;
1755 if (lpMsg->message == WM_KEYDOWN)
1756 keyCode = (UINT) lpMsg->wParam;
1758 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
1759 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate &&
1760 SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
1766 case WM_IME_STARTCOMPOSITION:
1767 handled = webView->onIMEStartComposition();
1769 case WM_IME_REQUEST:
1770 webView->onIMERequest(wParam, lParam, &lResult);
1772 case WM_IME_COMPOSITION:
1773 handled = webView->onIMEComposition(lParam);
1775 case WM_IME_ENDCOMPOSITION:
1776 handled = webView->onIMEEndComposition();
1779 handled = webView->onIMEChar(wParam, lParam);
1782 handled = webView->onIMENotify(wParam, lParam, &lResult);
1785 handled = webView->onIMESelect(wParam, lParam);
1787 case WM_IME_SETCONTEXT:
1788 handled = webView->onIMESetContext(wParam, lParam);
1791 if (lastSetCursor) {
1792 SetCursor(lastSetCursor);
1802 lResult = DefWindowProc(hWnd, message, wParam, lParam);
1807 bool WebView::developerExtrasEnabled() const
1809 if (m_preferences->developerExtrasDisabledByOverride())
1814 return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
1820 static String osVersion()
1823 OSVERSIONINFO versionInfo = {0};
1824 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1825 GetVersionEx(&versionInfo);
1827 if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1828 if (versionInfo.dwMajorVersion == 4) {
1829 if (versionInfo.dwMinorVersion == 0)
1830 osVersion = "Windows 95";
1831 else if (versionInfo.dwMinorVersion == 10)
1832 osVersion = "Windows 98";
1833 else if (versionInfo.dwMinorVersion == 90)
1834 osVersion = "Windows 98; Win 9x 4.90";
1836 } else if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
1837 osVersion = String::format("Windows NT %d.%d", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion);
1839 if (!osVersion.length())
1840 osVersion = String::format("Windows %d.%d", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion);
1845 static String webKitVersion()
1847 String versionStr = "420+";
1850 struct LANGANDCODEPAGE {
1855 TCHAR path[MAX_PATH];
1856 GetModuleFileName(gInstance, path, ARRAYSIZE(path));
1858 DWORD versionSize = GetFileVersionInfoSize(path, &handle);
1861 data = malloc(versionSize);
1864 if (!GetFileVersionInfo(path, 0, versionSize, data))
1867 if (!VerQueryValue(data, TEXT("\\VarFileInfo\\Translation"), (LPVOID*)&lpTranslate, &cbTranslate))
1870 _stprintf_s(key, ARRAYSIZE(key), TEXT("\\StringFileInfo\\%04x%04x\\ProductVersion"), lpTranslate[0].wLanguage, lpTranslate[0].wCodePage);
1871 LPCTSTR productVersion;
1872 UINT productVersionLength;
1873 if (!VerQueryValue(data, (LPTSTR)(LPCTSTR)key, (void**)&productVersion, &productVersionLength))
1875 versionStr = String(productVersion, productVersionLength);
1883 const String& WebView::userAgentForKURL(const KURL&)
1885 if (m_userAgentOverridden)
1886 return m_userAgentCustom;
1888 if (!m_userAgentStandard.length())
1889 m_userAgentStandard = 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(), (m_applicationName.length() ? " " : ""), m_applicationName.latin1().data());
1890 return m_userAgentStandard;
1893 // IUnknown -------------------------------------------------------------------
1895 HRESULT STDMETHODCALLTYPE WebView::QueryInterface(REFIID riid, void** ppvObject)
1898 if (IsEqualGUID(riid, CLSID_WebView))
1900 else if (IsEqualGUID(riid, IID_IUnknown))
1901 *ppvObject = static_cast<IWebView*>(this);
1902 else if (IsEqualGUID(riid, IID_IWebView))
1903 *ppvObject = static_cast<IWebView*>(this);
1904 else if (IsEqualGUID(riid, IID_IWebViewPrivate))
1905 *ppvObject = static_cast<IWebViewPrivate*>(this);
1906 else if (IsEqualGUID(riid, IID_IWebIBActions))
1907 *ppvObject = static_cast<IWebIBActions*>(this);
1908 else if (IsEqualGUID(riid, IID_IWebViewCSS))
1909 *ppvObject = static_cast<IWebViewCSS*>(this);
1910 else if (IsEqualGUID(riid, IID_IWebViewEditing))
1911 *ppvObject = static_cast<IWebViewEditing*>(this);
1912 else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
1913 *ppvObject = static_cast<IWebViewUndoableEditing*>(this);
1914 else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
1915 *ppvObject = static_cast<IWebViewEditingActions*>(this);
1916 else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
1917 *ppvObject = static_cast<IWebNotificationObserver*>(this);
1918 else if (IsEqualGUID(riid, IID_IDropTarget))
1919 *ppvObject = static_cast<IDropTarget*>(this);
1921 return E_NOINTERFACE;
1927 ULONG STDMETHODCALLTYPE WebView::AddRef(void)
1929 return ++m_refCount;
1932 ULONG STDMETHODCALLTYPE WebView::Release(void)
1934 ULONG newRef = --m_refCount;
1941 // IWebView --------------------------------------------------------------------
1943 HRESULT STDMETHODCALLTYPE WebView::canShowMIMEType(
1944 /* [in] */ BSTR mimeType,
1945 /* [retval][out] */ BOOL* canShow)
1947 String mimeTypeStr(mimeType, SysStringLen(mimeType));
1952 *canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeTypeStr) ||
1953 MIMETypeRegistry::isSupportedNonImageMIMEType(mimeTypeStr) ||
1954 PlugInInfoStore::supportsMIMEType(mimeTypeStr);
1959 HRESULT STDMETHODCALLTYPE WebView::canShowMIMETypeAsHTML(
1960 /* [in] */ BSTR /*mimeType*/,
1961 /* [retval][out] */ BOOL* canShow)
1968 HRESULT STDMETHODCALLTYPE WebView::MIMETypesShownAsHTML(
1969 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
1971 ASSERT_NOT_REACHED();
1975 HRESULT STDMETHODCALLTYPE WebView::setMIMETypesShownAsHTML(
1976 /* [size_is][in] */ BSTR* /*mimeTypes*/,
1977 /* [in] */ int /*cMimeTypes*/)
1979 ASSERT_NOT_REACHED();
1983 HRESULT STDMETHODCALLTYPE WebView::URLFromPasteboard(
1984 /* [in] */ IDataObject* /*pasteboard*/,
1985 /* [retval][out] */ BSTR* /*url*/)
1987 ASSERT_NOT_REACHED();
1991 HRESULT STDMETHODCALLTYPE WebView::URLTitleFromPasteboard(
1992 /* [in] */ IDataObject* /*pasteboard*/,
1993 /* [retval][out] */ BSTR* /*urlTitle*/)
1995 ASSERT_NOT_REACHED();
1999 HRESULT STDMETHODCALLTYPE WebView::initWithFrame(
2000 /* [in] */ RECT frame,
2001 /* [in] */ BSTR frameName,
2002 /* [in] */ BSTR groupName)
2009 registerWebViewWindowClass();
2011 if (!::IsWindow(m_hostWindow)) {
2012 ASSERT_NOT_REACHED();
2016 m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPCHILDREN,
2017 frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow, 0, gInstance, 0);
2018 ASSERT(::IsWindow(m_viewWindow));
2020 hr = registerDragDrop();
2024 WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
2025 sharedPreferences->willAddToWebView();
2026 m_preferences = sharedPreferences;
2028 m_groupName = String(groupName, SysStringLen(groupName));
2030 WebKitSetWebDatabasesPathIfNecessary();
2032 m_page = new Page(new WebChromeClient(this), new WebContextMenuClient(this), new WebEditorClient(this), new WebDragClient(this), new WebInspectorClient(this));
2033 // FIXME: 4931464 - When we do cache pages on Windows this needs to be removed so the "should I cache this page?" check
2034 // in FrameLoader::provisionalLoadStarted() doesn't always fail
2035 m_page->settings()->setUsesPageCache(false);
2038 COMPtr<IWebUIDelegate2> uiDelegate2;
2039 if (SUCCEEDED(m_uiDelegate->QueryInterface(IID_IWebUIDelegate2, (void**)&uiDelegate2))) {
2041 if (SUCCEEDED(uiDelegate2->ftpDirectoryTemplatePath(this, &path))) {
2042 m_page->settings()->setFTPDirectoryTemplatePath(String(path, SysStringLen(path)));
2043 SysFreeString(path);
2048 WebFrame* webFrame = WebFrame::createInstance();
2049 webFrame->initWithWebFrameView(0 /*FIXME*/, this, m_page, 0);
2050 m_mainFrame = webFrame;
2051 webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
2052 m_page->mainFrame()->view()->attachToWindow();
2053 m_page->mainFrame()->view()->resize(frame.right - frame.left, frame.bottom - frame.top);
2055 m_page->mainFrame()->tree()->setName(String(frameName, SysStringLen(frameName)));
2056 m_page->mainFrame()->init();
2057 m_page->setGroupName(m_groupName);
2059 addToAllWebViewsSet();
2061 #pragma warning(suppress: 4244)
2062 SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
2063 ShowWindow(m_viewWindow, SW_SHOW);
2065 initializeToolTipWindow();
2067 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
2068 notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2069 m_preferences->postPreferencesChangesNotification();
2071 setSmartInsertDeleteEnabled(TRUE);
2075 static bool initCommonControls()
2077 static bool haveInitialized = false;
2078 if (haveInitialized)
2081 INITCOMMONCONTROLSEX init;
2082 init.dwSize = sizeof(init);
2083 init.dwICC = ICC_TREEVIEW_CLASSES;
2084 haveInitialized = !!::InitCommonControlsEx(&init);
2085 return haveInitialized;
2088 void WebView::initializeToolTipWindow()
2090 if (!initCommonControls())
2093 m_toolTipHwnd = CreateWindowEx(0, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
2094 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
2095 m_viewWindow, 0, 0, 0);
2099 TOOLINFO info = {0};
2100 info.cbSize = sizeof(info);
2101 info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
2102 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2104 ::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
2105 ::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, maxToolTipWidth);
2107 ::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
2110 void WebView::setToolTip(const String& toolTip)
2115 if (toolTip == m_toolTip)
2118 m_toolTip = toolTip;
2120 if (!m_toolTip.isEmpty()) {
2121 TOOLINFO info = {0};
2122 info.cbSize = sizeof(info);
2123 info.uFlags = TTF_IDISHWND;
2124 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2125 info.lpszText = const_cast<UChar*>(m_toolTip.charactersWithNullTermination());
2126 ::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
2129 ::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
2132 HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
2134 COMPtr<IPropertyBag> propertyBag;
2135 HRESULT hr = notification->userInfo(&propertyBag);
2141 COMPtr<CFDictionaryPropertyBag> dictionaryPropertyBag;
2142 hr = propertyBag->QueryInterface(&dictionaryPropertyBag);
2146 CFDictionaryRef dictionary = dictionaryPropertyBag->dictionary();
2150 CFTypeRef value = CFDictionaryGetValue(dictionary, WebIconDatabase::iconDatabaseNotificationUserInfoURLKey());
2153 if (CFGetTypeID(value) != CFStringGetTypeID())
2156 String mainFrameURL;
2158 mainFrameURL = m_mainFrame->url().string();
2160 if (!mainFrameURL.isEmpty() && mainFrameURL == String((CFStringRef)value))
2161 dispatchDidReceiveIconFromWebFrame(m_mainFrame);
2166 void WebView::registerForIconNotification(bool listen)
2168 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2170 nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2172 nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2175 void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
2177 registerForIconNotification(false);
2179 if (m_frameLoadDelegate)
2180 // FIXME: <rdar://problem/5491010> - Pass in the right HBITMAP.
2181 m_frameLoadDelegate->didReceiveIcon(this, 0, frame);
2184 HRESULT STDMETHODCALLTYPE WebView::setUIDelegate(
2185 /* [in] */ IWebUIDelegate* d)
2189 if (m_uiDelegatePrivate)
2190 m_uiDelegatePrivate = 0;
2193 if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
2194 m_uiDelegatePrivate = 0;
2200 HRESULT STDMETHODCALLTYPE WebView::uiDelegate(
2201 /* [out][retval] */ IWebUIDelegate** d)
2206 return m_uiDelegate.copyRefTo(d);
2209 HRESULT STDMETHODCALLTYPE WebView::setResourceLoadDelegate(
2210 /* [in] */ IWebResourceLoadDelegate* d)
2212 m_resourceLoadDelegate = d;
2216 HRESULT STDMETHODCALLTYPE WebView::resourceLoadDelegate(
2217 /* [out][retval] */ IWebResourceLoadDelegate** d)
2219 if (!m_resourceLoadDelegate)
2222 return m_resourceLoadDelegate.copyRefTo(d);
2225 HRESULT STDMETHODCALLTYPE WebView::setDownloadDelegate(
2226 /* [in] */ IWebDownloadDelegate* d)
2228 m_downloadDelegate = d;
2232 HRESULT STDMETHODCALLTYPE WebView::downloadDelegate(
2233 /* [out][retval] */ IWebDownloadDelegate** d)
2235 if (!m_downloadDelegate)
2238 return m_downloadDelegate.copyRefTo(d);
2241 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegate(
2242 /* [in] */ IWebFrameLoadDelegate* d)
2244 m_frameLoadDelegate = d;
2248 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegate(
2249 /* [out][retval] */ IWebFrameLoadDelegate** d)
2251 if (!m_frameLoadDelegate)
2254 return m_frameLoadDelegate.copyRefTo(d);
2257 HRESULT STDMETHODCALLTYPE WebView::setPolicyDelegate(
2258 /* [in] */ IWebPolicyDelegate* d)
2260 m_policyDelegate = d;
2264 HRESULT STDMETHODCALLTYPE WebView::policyDelegate(
2265 /* [out][retval] */ IWebPolicyDelegate** d)
2267 if (!m_policyDelegate)
2269 return m_policyDelegate.copyRefTo(d);
2272 HRESULT STDMETHODCALLTYPE WebView::mainFrame(
2273 /* [out][retval] */ IWebFrame** frame)
2276 ASSERT_NOT_REACHED();
2280 *frame = m_mainFrame;
2284 m_mainFrame->AddRef();
2288 HRESULT STDMETHODCALLTYPE WebView::focusedFrame(
2289 /* [out][retval] */ IWebFrame** frame)
2292 ASSERT_NOT_REACHED();
2297 Frame* f = m_page->focusController()->focusedFrame();
2301 WebFrame* webFrame = kit(f);
2305 return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
2307 HRESULT STDMETHODCALLTYPE WebView::backForwardList(
2308 /* [out][retval] */ IWebBackForwardList** list)
2310 if (!m_useBackForwardList)
2313 *list = WebBackForwardList::createInstance(m_page->backForwardList());
2318 HRESULT STDMETHODCALLTYPE WebView::setMaintainsBackForwardList(
2319 /* [in] */ BOOL flag)
2321 m_useBackForwardList = !!flag;
2325 HRESULT STDMETHODCALLTYPE WebView::goBack(
2326 /* [retval][out] */ BOOL* succeeded)
2328 *succeeded = m_page->goBack();
2332 HRESULT STDMETHODCALLTYPE WebView::goForward(
2333 /* [retval][out] */ BOOL* succeeded)
2335 *succeeded = m_page->goForward();
2339 HRESULT STDMETHODCALLTYPE WebView::goToBackForwardItem(
2340 /* [in] */ IWebHistoryItem* item,
2341 /* [retval][out] */ BOOL* succeeded)
2345 COMPtr<WebHistoryItem> webHistoryItem;
2346 HRESULT hr = item->QueryInterface(&webHistoryItem);
2350 m_page->goToItem(webHistoryItem->historyItem(), FrameLoadTypeIndexedBackForward);
2356 HRESULT STDMETHODCALLTYPE WebView::setTextSizeMultiplier(
2357 /* [in] */ float multiplier)
2359 if (m_textSizeMultiplier != multiplier)
2360 m_textSizeMultiplier = multiplier;
2365 m_mainFrame->setTextSizeMultiplier(multiplier);
2369 HRESULT STDMETHODCALLTYPE WebView::textSizeMultiplier(
2370 /* [retval][out] */ float* multiplier)
2372 *multiplier = m_textSizeMultiplier;
2376 HRESULT STDMETHODCALLTYPE WebView::setApplicationNameForUserAgent(
2377 /* [in] */ BSTR applicationName)
2379 m_applicationName = String(applicationName, SysStringLen(applicationName));
2380 m_userAgentStandard = String();
2384 HRESULT STDMETHODCALLTYPE WebView::applicationNameForUserAgent(
2385 /* [retval][out] */ BSTR* applicationName)
2387 *applicationName = SysAllocStringLen(m_applicationName.characters(), m_applicationName.length());
2388 if (!*applicationName && m_applicationName.length())
2389 return E_OUTOFMEMORY;
2393 HRESULT STDMETHODCALLTYPE WebView::setCustomUserAgent(
2394 /* [in] */ BSTR userAgentString)
2396 m_userAgentOverridden = userAgentString;
2397 m_userAgentCustom = String(userAgentString, SysStringLen(userAgentString));
2401 HRESULT STDMETHODCALLTYPE WebView::customUserAgent(
2402 /* [retval][out] */ BSTR* userAgentString)
2404 *userAgentString = 0;
2405 if (!m_userAgentOverridden)
2407 *userAgentString = SysAllocStringLen(m_userAgentCustom.characters(), m_userAgentCustom.length());
2408 if (!*userAgentString && m_userAgentCustom.length())
2409 return E_OUTOFMEMORY;
2413 HRESULT STDMETHODCALLTYPE WebView::userAgentForURL(
2414 /* [in] */ BSTR url,
2415 /* [retval][out] */ BSTR* userAgent)
2417 DeprecatedString urlStr((DeprecatedChar*)url, SysStringLen(url));
2418 String userAgentString = this->userAgentForKURL(KURL(urlStr));
2419 *userAgent = SysAllocStringLen(userAgentString.characters(), userAgentString.length());
2420 if (!*userAgent && userAgentString.length())
2421 return E_OUTOFMEMORY;
2425 HRESULT STDMETHODCALLTYPE WebView::supportsTextEncoding(
2426 /* [retval][out] */ BOOL* supports)
2432 HRESULT STDMETHODCALLTYPE WebView::setCustomTextEncodingName(
2433 /* [in] */ BSTR encodingName)
2440 hr = customTextEncodingName(&oldEncoding);
2444 if (oldEncoding != encodingName && (!oldEncoding || !encodingName || _tcscmp(oldEncoding, encodingName))) {
2445 if (Frame* coreFrame = core(m_mainFrame))
2446 coreFrame->loader()->reloadAllowingStaleData(String(encodingName, SysStringLen(encodingName)));
2452 HRESULT STDMETHODCALLTYPE WebView::customTextEncodingName(
2453 /* [retval][out] */ BSTR* encodingName)
2456 COMPtr<IWebDataSource> dataSource;
2457 COMPtr<WebDataSource> dataSourceImpl;
2463 if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
2464 hr = m_mainFrame->dataSource(&dataSource);
2465 if (FAILED(hr) || !dataSource)
2469 hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
2473 BString str = dataSourceImpl->documentLoader()->overrideEncoding();
2478 *encodingName = SysAllocStringLen(m_overrideEncoding.characters(), m_overrideEncoding.length());
2480 if (!*encodingName && m_overrideEncoding.length())
2481 return E_OUTOFMEMORY;
2486 HRESULT STDMETHODCALLTYPE WebView::setMediaStyle(
2487 /* [in] */ BSTR /*media*/)
2489 ASSERT_NOT_REACHED();
2493 HRESULT STDMETHODCALLTYPE WebView::mediaStyle(
2494 /* [retval][out] */ BSTR* /*media*/)
2496 ASSERT_NOT_REACHED();
2500 HRESULT STDMETHODCALLTYPE WebView::stringByEvaluatingJavaScriptFromString(
2501 /* [in] */ BSTR script, // assumes input does not have "JavaScript" at the begining.
2502 /* [retval][out] */ BSTR* result)
2505 ASSERT_NOT_REACHED();
2511 Frame* coreFrame = core(m_mainFrame);
2515 KJS::JSValue* scriptExecutionResult = coreFrame->loader()->executeScript(WebCore::String(script), true);
2516 if(!scriptExecutionResult)
2518 else if (scriptExecutionResult->isString()) {
2520 *result = BString(String(scriptExecutionResult->getString()));
2526 HRESULT STDMETHODCALLTYPE WebView::windowScriptObject(
2527 /* [retval][out] */ IWebScriptObject** /*webScriptObject*/)
2529 ASSERT_NOT_REACHED();
2533 HRESULT STDMETHODCALLTYPE WebView::setPreferences(
2534 /* [in] */ IWebPreferences* prefs)
2537 prefs = WebPreferences::sharedStandardPreferences();
2539 if (m_preferences == prefs)
2542 COMPtr<WebPreferences> webPrefs(Query, prefs);
2544 return E_NOINTERFACE;
2545 webPrefs->willAddToWebView();
2547 COMPtr<WebPreferences> oldPrefs = m_preferences;
2549 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2550 nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2552 BSTR identifierBSTR = 0;
2553 HRESULT hr = oldPrefs->identifier(&identifierBSTR);
2554 oldPrefs->didRemoveFromWebView();
2555 oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
2556 if (SUCCEEDED(hr)) {
2558 identifier.adoptBSTR(identifierBSTR);
2559 WebPreferences::removeReferenceForIdentifier(identifier);
2562 m_preferences = webPrefs;
2564 nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2566 m_preferences->postPreferencesChangesNotification();
2571 HRESULT STDMETHODCALLTYPE WebView::preferences(
2572 /* [retval][out] */ IWebPreferences** prefs)
2576 *prefs = m_preferences.get();
2578 m_preferences->AddRef();
2582 HRESULT STDMETHODCALLTYPE WebView::setPreferencesIdentifier(
2583 /* [in] */ BSTR /*anIdentifier*/)
2585 ASSERT_NOT_REACHED();
2589 HRESULT STDMETHODCALLTYPE WebView::preferencesIdentifier(
2590 /* [retval][out] */ BSTR* /*anIdentifier*/)
2592 ASSERT_NOT_REACHED();
2596 HRESULT STDMETHODCALLTYPE WebView::setHostWindow(
2597 /* [in] */ OLE_HANDLE oleWindow)
2599 HWND window = (HWND)(ULONG64)oleWindow;
2600 if (m_viewWindow && window)
2601 SetParent(m_viewWindow, window);
2603 m_hostWindow = window;
2608 HRESULT STDMETHODCALLTYPE WebView::hostWindow(
2609 /* [retval][out] */ OLE_HANDLE* window)
2611 *window = (OLE_HANDLE)(ULONG64)m_hostWindow;
2616 static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
2619 ? curr->tree()->traverseNextWithWrap(wrapFlag)
2620 : curr->tree()->traversePreviousWithWrap(wrapFlag);
2623 HRESULT STDMETHODCALLTYPE WebView::searchFor(
2624 /* [in] */ BSTR str,
2625 /* [in] */ BOOL forward,
2626 /* [in] */ BOOL caseFlag,
2627 /* [in] */ BOOL wrapFlag,
2628 /* [retval][out] */ BOOL* found)
2631 return E_INVALIDARG;
2633 if (!m_page || !m_page->mainFrame())
2634 return E_UNEXPECTED;
2636 if (!str || !SysStringLen(str))
2637 return E_INVALIDARG;
2639 String search(str, SysStringLen(str));
2642 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
2643 WebCore::Frame* startFrame = frame;
2645 *found = frame->findString(search, !!forward, !!caseFlag, false, true);
2647 if (frame != startFrame)
2648 startFrame->selectionController()->clear();
2649 m_page->focusController()->setFocusedFrame(frame);
2652 frame = incrementFrame(frame, !!forward, !!wrapFlag);
2653 } while (frame && frame != startFrame);
2655 // Search contents of startFrame, on the other side of the selection that we did earlier.
2656 // We cheat a bit and just research with wrap on
2657 if (wrapFlag && !startFrame->selectionController()->isNone()) {
2658 *found = startFrame->findString(search, !!forward, !!caseFlag, true, true);
2659 m_page->focusController()->setFocusedFrame(frame);
2665 HRESULT STDMETHODCALLTYPE WebView::updateActiveState()
2667 Frame* frame = m_page->mainFrame();
2669 HWND window = ::GetAncestor(m_viewWindow, GA_ROOT);
2670 HWND activeWindow = ::GetActiveWindow();
2671 bool windowIsKey = window == activeWindow;
2672 activeWindow = ::GetAncestor(activeWindow, GA_ROOTOWNER);
2674 bool windowOrSheetIsKey = windowIsKey || (window == activeWindow);
2676 frame->setIsActive(windowIsKey);
2678 Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
2679 frame->setWindowHasFocus(frame == focusedFrame && windowOrSheetIsKey);
2684 HRESULT STDMETHODCALLTYPE WebView::markAllMatchesForText(
2685 BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, UINT* matches)
2688 return E_INVALIDARG;
2690 if (!m_page || !m_page->mainFrame())
2691 return E_UNEXPECTED;
2693 if (!str || !SysStringLen(str))
2694 return E_INVALIDARG;
2696 String search(str, SysStringLen(str));
2699 WebCore::Frame* frame = m_page->mainFrame();
2701 frame->setMarkedTextMatchesAreHighlighted(!!highlight);
2702 *matches += frame->markAllMatchesForText(search, !!caseSensitive, (limit == 0)? 0 : (limit - *matches));
2703 frame = incrementFrame(frame, true, false);
2710 HRESULT STDMETHODCALLTYPE WebView::unmarkAllTextMatches()
2712 if (!m_page || !m_page->mainFrame())
2713 return E_UNEXPECTED;
2715 WebCore::Frame* frame = m_page->mainFrame();
2717 if (Document* document = frame->document())
2718 document->removeMarkers(DocumentMarker::TextMatch);
2719 frame = incrementFrame(frame, true, false);
2726 HRESULT STDMETHODCALLTYPE WebView::rectsForTextMatches(
2727 IEnumTextMatches** pmatches)
2729 Vector<IntRect> allRects;
2730 WebCore::Frame* frame = m_page->mainFrame();
2732 if (Document* document = frame->document()) {
2733 IntRect visibleRect = enclosingIntRect(frame->view()->visibleContentRect());
2734 Vector<IntRect> frameRects = document->renderedRectsForMarkers(DocumentMarker::TextMatch);
2735 IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
2736 frameOffset = frame->view()->convertToContainingWindow(frameOffset);
2738 Vector<IntRect>::iterator end = frameRects.end();
2739 for (Vector<IntRect>::iterator it = frameRects.begin(); it < end; it++) {
2740 it->intersect(visibleRect);
2741 it->move(frameOffset.x(), frameOffset.y());
2742 allRects.append(*it);
2745 frame = incrementFrame(frame, true, false);
2748 return createMatchEnumerator(&allRects, pmatches);
2751 HRESULT STDMETHODCALLTYPE WebView::generateSelectionImage(BOOL forceWhiteText, OLE_HANDLE* hBitmap)
2755 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
2758 HBITMAP bitmap = imageFromSelection(frame, forceWhiteText ? TRUE : FALSE);
2759 *hBitmap = (OLE_HANDLE)(ULONG64)bitmap;
2765 HRESULT STDMETHODCALLTYPE WebView::selectionRect(RECT* rc)
2767 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
2770 IntRect ir = enclosingIntRect(frame->selectionRect());
2771 ir = frame->view()->convertToContainingWindow(ir);
2772 ir.move(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
2775 rc->bottom = rc->top + ir.height();
2776 rc->right = rc->left + ir.width();
2782 HRESULT STDMETHODCALLTYPE WebView::registerViewClass(
2783 /* [in] */ IWebDocumentView* /*view*/,
2784 /* [in] */ IWebDocumentRepresentation* /*representation*/,
2785 /* [in] */ BSTR /*forMIMEType*/)
2787 ASSERT_NOT_REACHED();
2791 HRESULT STDMETHODCALLTYPE WebView::setGroupName(
2792 /* [in] */ BSTR groupName)
2794 m_groupName = String(groupName, SysStringLen(groupName));
2798 HRESULT STDMETHODCALLTYPE WebView::groupName(
2799 /* [retval][out] */ BSTR* groupName)
2801 *groupName = SysAllocStringLen(m_groupName.characters(), m_groupName.length());
2802 if (!*groupName && m_groupName.length())
2803 return E_OUTOFMEMORY;
2807 HRESULT STDMETHODCALLTYPE WebView::estimatedProgress(
2808 /* [retval][out] */ double* estimatedProgress)
2810 *estimatedProgress = m_page->progress()->estimatedProgress();
2814 HRESULT STDMETHODCALLTYPE WebView::isLoading(
2815 /* [retval][out] */ BOOL* isLoading)
2817 COMPtr<IWebDataSource> dataSource;
2818 COMPtr<IWebDataSource> provisionalDataSource;
2825 if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
2826 dataSource->isLoading(isLoading);
2831 if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
2832 provisionalDataSource->isLoading(isLoading);
2836 HRESULT STDMETHODCALLTYPE WebView::elementAtPoint(
2837 /* [in] */ LPPOINT point,
2838 /* [retval][out] */ IPropertyBag** elementDictionary)
2840 if (!elementDictionary) {
2841 ASSERT_NOT_REACHED();
2845 *elementDictionary = 0;
2847 Frame* frame = core(m_mainFrame);
2851 IntPoint webCorePoint = IntPoint(point->x, point->y);
2852 HitTestResult result = HitTestResult(webCorePoint);
2853 if (frame->renderer())
2854 result = frame->eventHandler()->hitTestResultAtPoint(webCorePoint, false);
2855 *elementDictionary = WebElementPropertyBag::createInstance(result);
2859 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForSelection(
2860 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
2862 ASSERT_NOT_REACHED();
2866 HRESULT STDMETHODCALLTYPE WebView::writeSelectionWithPasteboardTypes(
2867 /* [size_is][in] */ BSTR* /*types*/,
2868 /* [in] */ int /*cTypes*/,
2869 /* [in] */ IDataObject* /*pasteboard*/)
2871 ASSERT_NOT_REACHED();
2875 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForElement(
2876 /* [in] */ IPropertyBag* /*elementDictionary*/,
2877 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
2879 ASSERT_NOT_REACHED();
2883 HRESULT STDMETHODCALLTYPE WebView::writeElement(
2884 /* [in] */ IPropertyBag* /*elementDictionary*/,
2885 /* [size_is][in] */ BSTR* /*withPasteboardTypes*/,
2886 /* [in] */ int /*cWithPasteboardTypes*/,
2887 /* [in] */ IDataObject* /*pasteboard*/)
2889 ASSERT_NOT_REACHED();
2893 HRESULT STDMETHODCALLTYPE WebView::selectedText(
2894 /* [out, retval] */ BSTR* text)
2897 ASSERT_NOT_REACHED();
2903 Frame* focusedFrame = (m_page && m_page->focusController()) ? m_page->focusController()->focusedOrMainFrame() : 0;
2907 String frameSelectedText = focusedFrame->selectedText();
2908 *text = SysAllocStringLen(frameSelectedText.characters(), frameSelectedText.length());
2909 if (!*text && frameSelectedText.length())
2910 return E_OUTOFMEMORY;
2914 HRESULT STDMETHODCALLTYPE WebView::centerSelectionInVisibleArea(
2915 /* [in] */ IUnknown* /* sender */)
2917 Frame* coreFrame = core(m_mainFrame);
2921 coreFrame->revealSelection(RenderLayer::gAlignCenterAlways);
2926 HRESULT STDMETHODCALLTYPE WebView::moveDragCaretToPoint(
2927 /* [in] */ LPPOINT /*point*/)
2929 ASSERT_NOT_REACHED();
2933 HRESULT STDMETHODCALLTYPE WebView::removeDragCaret( void)
2935 ASSERT_NOT_REACHED();
2939 HRESULT STDMETHODCALLTYPE WebView::setDrawsBackground(
2940 /* [in] */ BOOL /*drawsBackground*/)
2942 ASSERT_NOT_REACHED();
2946 HRESULT STDMETHODCALLTYPE WebView::drawsBackground(
2947 /* [retval][out] */ BOOL* /*drawsBackground*/)
2949 ASSERT_NOT_REACHED();
2953 HRESULT STDMETHODCALLTYPE WebView::setMainFrameURL(
2954 /* [in] */ BSTR /*urlString*/)
2956 ASSERT_NOT_REACHED();
2960 HRESULT STDMETHODCALLTYPE WebView::mainFrameURL(
2961 /* [retval][out] */ BSTR* /*urlString*/)
2963 ASSERT_NOT_REACHED();
2967 HRESULT STDMETHODCALLTYPE WebView::mainFrameDocument(
2968 /* [retval][out] */ IDOMDocument** document)
2974 return m_mainFrame->DOMDocument(document);
2977 HRESULT STDMETHODCALLTYPE WebView::mainFrameTitle(
2978 /* [retval][out] */ BSTR* /*title*/)
2980 ASSERT_NOT_REACHED();
2984 HRESULT STDMETHODCALLTYPE WebView::mainFrameIcon(
2985 /* [retval][out] */ OLE_HANDLE* /*hBitmap*/)
2987 ASSERT_NOT_REACHED();
2991 HRESULT STDMETHODCALLTYPE WebView::registerURLSchemeAsLocal(
2992 /* [in] */ BSTR scheme)
2997 FrameLoader::registerURLSchemeAsLocal(String(scheme, ::SysStringLen(scheme)));
3002 // IWebIBActions ---------------------------------------------------------------
3004 HRESULT STDMETHODCALLTYPE WebView::takeStringURLFrom(
3005 /* [in] */ IUnknown* /*sender*/)
3007 ASSERT_NOT_REACHED();
3011 HRESULT STDMETHODCALLTYPE WebView::stopLoading(
3012 /* [in] */ IUnknown* /*sender*/)
3017 return m_mainFrame->stopLoading();
3020 HRESULT STDMETHODCALLTYPE WebView::reload(
3021 /* [in] */ IUnknown* /*sender*/)
3026 return m_mainFrame->reload();
3029 HRESULT STDMETHODCALLTYPE WebView::canGoBack(
3030 /* [in] */ IUnknown* /*sender*/,
3031 /* [retval][out] */ BOOL* result)
3033 *result = !!m_page->backForwardList()->backItem();
3037 HRESULT STDMETHODCALLTYPE WebView::goBack(
3038 /* [in] */ IUnknown* /*sender*/)
3040 ASSERT_NOT_REACHED();
3044 HRESULT STDMETHODCALLTYPE WebView::canGoForward(
3045 /* [in] */ IUnknown* /*sender*/,
3046 /* [retval][out] */ BOOL* result)
3048 *result = !!m_page->backForwardList()->forwardItem();
3052 HRESULT STDMETHODCALLTYPE WebView::goForward(
3053 /* [in] */ IUnknown* /*sender*/)
3055 ASSERT_NOT_REACHED();
3059 #define MinimumTextSizeMultiplier 0.5f
3060 #define MaximumTextSizeMultiplier 3.0f
3061 #define TextSizeMultiplierRatio 1.2f
3063 HRESULT STDMETHODCALLTYPE WebView::canMakeTextLarger(
3064 /* [in] */ IUnknown* /*sender*/,
3065 /* [retval][out] */ BOOL* result)
3067 bool canGrowMore = m_textSizeMultiplier*TextSizeMultiplierRatio < MaximumTextSizeMultiplier;
3068 *result = canGrowMore ? TRUE : FALSE;
3072 HRESULT STDMETHODCALLTYPE WebView::makeTextLarger(
3073 /* [in] */ IUnknown* /*sender*/)
3075 float newScale = m_textSizeMultiplier*TextSizeMultiplierRatio;
3076 bool canGrowMore = newScale < MaximumTextSizeMultiplier;
3079 return setTextSizeMultiplier(newScale);
3083 HRESULT STDMETHODCALLTYPE WebView::canMakeTextSmaller(
3084 /* [in] */ IUnknown* /*sender*/,
3085 /* [retval][out] */ BOOL* result)
3087 bool canShrinkMore = m_textSizeMultiplier/TextSizeMultiplierRatio > MinimumTextSizeMultiplier;
3088 *result = canShrinkMore ? TRUE : FALSE;
3092 HRESULT STDMETHODCALLTYPE WebView::makeTextSmaller(
3093 /* [in] */ IUnknown* /*sender*/)
3095 float newScale = m_textSizeMultiplier/TextSizeMultiplierRatio;
3096 bool canShrinkMore = newScale > MinimumTextSizeMultiplier;
3099 return setTextSizeMultiplier(newScale);
3102 HRESULT STDMETHODCALLTYPE WebView::canMakeTextStandardSize(
3103 /* [in] */ IUnknown* /*sender*/,
3104 /* [retval][out] */ BOOL* result)
3106 bool notAlreadyStandard = m_textSizeMultiplier != 1.0f;
3107 *result = notAlreadyStandard ? TRUE : FALSE;
3111 HRESULT STDMETHODCALLTYPE WebView::makeTextStandardSize(
3112 /* [in] */ IUnknown* /*sender*/)
3114 bool notAlreadyStandard = m_textSizeMultiplier != 1.0f;
3115 if (notAlreadyStandard)
3116 return setTextSizeMultiplier(1.0f);
3120 HRESULT STDMETHODCALLTYPE WebView::toggleContinuousSpellChecking(
3121 /* [in] */ IUnknown* /*sender*/)
3125 if (FAILED(hr = isContinuousSpellCheckingEnabled(&enabled)))
3127 return setContinuousSpellCheckingEnabled(enabled ? FALSE : TRUE);
3130 HRESULT STDMETHODCALLTYPE WebView::toggleSmartInsertDelete(
3131 /* [in] */ IUnknown* /*sender*/)
3133 BOOL enabled = FALSE;
3134 HRESULT hr = smartInsertDeleteEnabled(&enabled);
3138 return setSmartInsertDeleteEnabled(enabled ? FALSE : TRUE);
3141 HRESULT STDMETHODCALLTYPE WebView::toggleGrammarChecking(
3142 /* [in] */ IUnknown* /*sender*/)
3145 HRESULT hr = isGrammarCheckingEnabled(&enabled);
3149 return setGrammarCheckingEnabled(enabled ? FALSE : TRUE);
3152 // IWebViewCSS -----------------------------------------------------------------
3154 HRESULT STDMETHODCALLTYPE WebView::computedStyleForElement(
3155 /* [in] */ IDOMElement* /*element*/,
3156 /* [in] */ BSTR /*pseudoElement*/,
3157 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3159 ASSERT_NOT_REACHED();
3163 // IWebViewEditing -------------------------------------------------------------
3165 HRESULT STDMETHODCALLTYPE WebView::editableDOMRangeForPoint(
3166 /* [in] */ LPPOINT /*point*/,
3167 /* [retval][out] */ IDOMRange** /*range*/)
3169 ASSERT_NOT_REACHED();
3173 HRESULT STDMETHODCALLTYPE WebView::setSelectedDOMRange(
3174 /* [in] */ IDOMRange* /*range*/,
3175 /* [in] */ WebSelectionAffinity /*affinity*/)
3177 ASSERT_NOT_REACHED();
3181 HRESULT STDMETHODCALLTYPE WebView::selectedDOMRange(
3182 /* [retval][out] */ IDOMRange** /*range*/)
3184 ASSERT_NOT_REACHED();
3188 HRESULT STDMETHODCALLTYPE WebView::selectionAffinity(
3189 /* [retval][out][retval][out] */ WebSelectionAffinity* /*affinity*/)
3191 ASSERT_NOT_REACHED();
3195 HRESULT STDMETHODCALLTYPE WebView::setEditable(
3196 /* [in] */ BOOL /*flag*/)
3198 ASSERT_NOT_REACHED();
3202 HRESULT STDMETHODCALLTYPE WebView::isEditable(
3203 /* [retval][out] */ BOOL* /*isEditable*/)
3205 ASSERT_NOT_REACHED();
3209 HRESULT STDMETHODCALLTYPE WebView::setTypingStyle(
3210 /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
3212 ASSERT_NOT_REACHED();
3216 HRESULT STDMETHODCALLTYPE WebView::typingStyle(
3217 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3219 ASSERT_NOT_REACHED();
3223 HRESULT STDMETHODCALLTYPE WebView::setSmartInsertDeleteEnabled(
3224 /* [in] */ BOOL flag)
3226 m_smartInsertDeleteEnabled = !!flag;
3230 HRESULT STDMETHODCALLTYPE WebView::smartInsertDeleteEnabled(
3231 /* [retval][out] */ BOOL* enabled)
3233 *enabled = m_smartInsertDeleteEnabled ? TRUE : FALSE;
3237 HRESULT STDMETHODCALLTYPE WebView::setContinuousSpellCheckingEnabled(
3238 /* [in] */ BOOL flag)
3240 if (continuousSpellCheckingEnabled != !!flag) {
3241 continuousSpellCheckingEnabled = !!flag;
3242 COMPtr<IWebPreferences> prefs;
3243 if (SUCCEEDED(preferences(&prefs)))
3244 prefs->setContinuousSpellCheckingEnabled(flag);
3247 BOOL spellCheckingEnabled;
3248 if (SUCCEEDED(isContinuousSpellCheckingEnabled(&spellCheckingEnabled)) && spellCheckingEnabled)
3249 preflightSpellChecker();
3251 m_mainFrame->unmarkAllMisspellings();
3256 HRESULT STDMETHODCALLTYPE WebView::isContinuousSpellCheckingEnabled(
3257 /* [retval][out] */ BOOL* enabled)
3259 *enabled = (continuousSpellCheckingEnabled && continuousCheckingAllowed()) ? TRUE : FALSE;
3263 HRESULT STDMETHODCALLTYPE WebView::spellCheckerDocumentTag(
3264 /* [retval][out] */ int* tag)
3266 // we just use this as a flag to indicate that we've spell checked the document
3267 // and need to close the spell checker out when the view closes.
3269 m_hasSpellCheckerDocumentTag = true;
3273 static COMPtr<IWebEditingDelegate> spellingDelegateForTimer;
3275 static void preflightSpellCheckerNow()
3277 spellingDelegateForTimer->preflightChosenSpellServer();
3278 spellingDelegateForTimer = 0;
3281 static void CALLBACK preflightSpellCheckerTimerCallback(HWND, UINT, UINT_PTR id, DWORD)
3284 preflightSpellCheckerNow();
3287 void WebView::preflightSpellChecker()
3289 // As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
3290 if (!m_editingDelegate)
3294 spellingDelegateForTimer = m_editingDelegate;
3295 if (SUCCEEDED(m_editingDelegate->sharedSpellCheckerExists(&exists)) && exists)
3296 preflightSpellCheckerNow();
3298 ::SetTimer(0, 0, 2000, preflightSpellCheckerTimerCallback);
3301 bool WebView::continuousCheckingAllowed()
3303 static bool allowContinuousSpellChecking = true;
3304 static bool readAllowContinuousSpellCheckingDefault = false;
3305 if (!readAllowContinuousSpellCheckingDefault) {
3306 COMPtr<IWebPreferences> prefs;
3307 if (SUCCEEDED(preferences(&prefs))) {
3309 prefs->allowContinuousSpellChecking(&allowed);
3310 allowContinuousSpellChecking = !!allowed;
3312 readAllowContinuousSpellCheckingDefault = true;
3314 return allowContinuousSpellChecking;
3317 HRESULT STDMETHODCALLTYPE WebView::undoManager(
3318 /* [retval][out] */ IWebUndoManager** /*manager*/)
3320 ASSERT_NOT_REACHED();
3324 HRESULT STDMETHODCALLTYPE WebView::setEditingDelegate(
3325 /* [in] */ IWebEditingDelegate* d)
3327 m_editingDelegate = d;
3331 HRESULT STDMETHODCALLTYPE WebView::editingDelegate(
3332 /* [retval][out] */ IWebEditingDelegate** d)
3335 ASSERT_NOT_REACHED();
3339 *d = m_editingDelegate.get();
3347 HRESULT STDMETHODCALLTYPE WebView::styleDeclarationWithText(
3348 /* [in] */ BSTR /*text*/,
3349 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3351 ASSERT_NOT_REACHED();
3355 HRESULT STDMETHODCALLTYPE WebView::hasSelectedRange(
3356 /* [retval][out] */ BOOL* hasSelectedRange)
3358 *hasSelectedRange = m_page->mainFrame()->selectionController()->isRange();
3362 HRESULT STDMETHODCALLTYPE WebView::cutEnabled(
3363 /* [retval][out] */ BOOL* enabled)
3365 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3366 *enabled = editor->canCut() || editor->canDHTMLCut();
3370 HRESULT STDMETHODCALLTYPE WebView::copyEnabled(
3371 /* [retval][out] */ BOOL* enabled)
3373 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3374 *enabled = editor->canCopy() || editor->canDHTMLCopy();
3378 HRESULT STDMETHODCALLTYPE WebView::pasteEnabled(
3379 /* [retval][out] */ BOOL* enabled)
3381 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3382 *enabled = editor->canPaste() || editor->canDHTMLPaste();
3386 HRESULT STDMETHODCALLTYPE WebView::deleteEnabled(
3387 /* [retval][out] */ BOOL* enabled)
3389 *enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canDelete();
3393 HRESULT STDMETHODCALLTYPE WebView::editingEnabled(
3394 /* [retval][out] */ BOOL* enabled)
3396 *enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canEdit();
3400 HRESULT STDMETHODCALLTYPE WebView::isGrammarCheckingEnabled(
3401 /* [retval][out] */ BOOL* enabled)
3403 *enabled = grammarCheckingEnabled ? TRUE : FALSE;
3407 HRESULT STDMETHODCALLTYPE WebView::setGrammarCheckingEnabled(
3410 if (!m_editingDelegate) {
3411 LOG_ERROR("No NSSpellChecker");
3415 if (grammarCheckingEnabled == !!enabled)
3418 grammarCheckingEnabled = !!enabled;
3419 COMPtr<IWebPreferences> prefs;
3420 if (SUCCEEDED(preferences(&prefs)))
3421 prefs->setGrammarCheckingEnabled(enabled);
3423 m_editingDelegate->updateGrammar();
3425 // We call _preflightSpellChecker when turning continuous spell checking on, but we don't need to do that here
3426 // because grammar checking only occurs on code paths that already preflight spell checking appropriately.
3428 BOOL grammarEnabled;
3429 if (SUCCEEDED(isGrammarCheckingEnabled(&grammarEnabled)) && !grammarEnabled)
3430 m_mainFrame->unmarkAllBadGrammar();
3435 // IWebViewUndoableEditing -----------------------------------------------------
3437 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithNode(
3438 /* [in] */ IDOMNode* /*node*/)
3440 ASSERT_NOT_REACHED();
3444 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithText(
3445 /* [in] */ BSTR text)
3447 String textString(text, ::SysStringLen(text));
3448 Position start = m_page->mainFrame()->selectionController()->selection().start();
3449 m_page->focusController()->focusedOrMainFrame()->editor()->insertText(textString, 0);
3450 m_page->mainFrame()->selectionController()->setBase(start);
3454 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithMarkupString(
3455 /* [in] */ BSTR /*markupString*/)
3457 ASSERT_NOT_REACHED();
3461 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithArchive(
3462 /* [in] */ IWebArchive* /*archive*/)
3464 ASSERT_NOT_REACHED();
3468 HRESULT STDMETHODCALLTYPE WebView::deleteSelection( void)
3470 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3471 editor->deleteSelectionWithSmartDelete(editor->canSmartCopyOrDelete());
3475 HRESULT STDMETHODCALLTYPE WebView::clearSelection( void)
3477 m_page->focusController()->focusedOrMainFrame()->selectionController()->clear();
3481 HRESULT STDMETHODCALLTYPE WebView::applyStyle(
3482 /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
3484 ASSERT_NOT_REACHED();
3488 // IWebViewEditingActions ------------------------------------------------------
3490 HRESULT STDMETHODCALLTYPE WebView::copy(
3491 /* [in] */ IUnknown* /*sender*/)
3493 m_page->focusController()->focusedOrMainFrame()->editor()->command("Copy").execute();
3497 HRESULT STDMETHODCALLTYPE WebView::cut(
3498 /* [in] */ IUnknown* /*sender*/)
3500 m_page->focusController()->focusedOrMainFrame()->editor()->command("Cut").execute();
3504 HRESULT STDMETHODCALLTYPE WebView::paste(
3505 /* [in] */ IUnknown* /*sender*/)
3507 m_page->focusController()->focusedOrMainFrame()->editor()->command("Paste").execute();
3511 HRESULT STDMETHODCALLTYPE WebView::copyURL(
3512 /* [in] */ BSTR url)
3514 String temp(url, SysStringLen(url));
3515 m_page->focusController()->focusedOrMainFrame()->editor()->copyURL(KURL(temp.deprecatedString()), "");
3520 HRESULT STDMETHODCALLTYPE WebView::copyFont(
3521 /* [in] */ IUnknown* /*sender*/)
3523 ASSERT_NOT_REACHED();
3527 HRESULT STDMETHODCALLTYPE WebView::pasteFont(
3528 /* [in] */ IUnknown* /*sender*/)
3530 ASSERT_NOT_REACHED();
3534 HRESULT STDMETHODCALLTYPE WebView::delete_(
3535 /* [in] */ IUnknown* /*sender*/)
3537 m_page->focusController()->focusedOrMainFrame()->editor()->command("Delete").execute();
3541 HRESULT STDMETHODCALLTYPE WebView::pasteAsPlainText(
3542 /* [in] */ IUnknown* /*sender*/)
3544 ASSERT_NOT_REACHED();
3548 HRESULT STDMETHODCALLTYPE WebView::pasteAsRichText(
3549 /* [in] */ IUnknown* /*sender*/)
3551 ASSERT_NOT_REACHED();
3555 HRESULT STDMETHODCALLTYPE WebView::changeFont(
3556 /* [in] */ IUnknown* /*sender*/)
3558 ASSERT_NOT_REACHED();
3562 HRESULT STDMETHODCALLTYPE WebView::changeAttributes(
3563 /* [in] */ IUnknown* /*sender*/)
3565 ASSERT_NOT_REACHED();
3569 HRESULT STDMETHODCALLTYPE WebView::changeDocumentBackgroundColor(
3570 /* [in] */ IUnknown* /*sender*/)
3572 ASSERT_NOT_REACHED();
3576 HRESULT STDMETHODCALLTYPE WebView::changeColor(
3577 /* [in] */ IUnknown* /*sender*/)
3579 ASSERT_NOT_REACHED();
3583 HRESULT STDMETHODCALLTYPE WebView::alignCenter(
3584 /* [in] */ IUnknown* /*sender*/)
3586 ASSERT_NOT_REACHED();
3590 HRESULT STDMETHODCALLTYPE WebView::alignJustified(
3591 /* [in] */ IUnknown* /*sender*/)
3593 ASSERT_NOT_REACHED();
3597 HRESULT STDMETHODCALLTYPE WebView::alignLeft(
3598 /* [in] */ IUnknown* /*sender*/)
3600 ASSERT_NOT_REACHED();
3604 HRESULT STDMETHODCALLTYPE WebView::alignRight(
3605 /* [in] */ IUnknown* /*sender*/)
3607 ASSERT_NOT_REACHED();
3611 HRESULT STDMETHODCALLTYPE WebView::checkSpelling(
3612 /* [in] */ IUnknown* /*sender*/)
3614 if (!m_editingDelegate) {
3615 LOG_ERROR("No NSSpellChecker");
3619 core(m_mainFrame)->editor()->advanceToNextMisspelling();
3623 HRESULT STDMETHODCALLTYPE WebView::showGuessPanel(
3624 /* [in] */ IUnknown* /*sender*/)
3626 if (!m_editingDelegate) {
3627 LOG_ERROR("No NSSpellChecker");
3631 // Post-Tiger, this menu item is a show/hide toggle, to match AppKit. Leave Tiger behavior alone
3632 // to match rest of OS X.
3634 if (SUCCEEDED(m_editingDelegate->spellingUIIsShowing(&showing)) && showing) {
3635 m_editingDelegate->showSpellingUI(FALSE);
3638 core(m_mainFrame)->editor()->advanceToNextMisspelling(true);
3639 m_editingDelegate->showSpellingUI(TRUE);
3643 HRESULT STDMETHODCALLTYPE WebView::performFindPanelAction(
3644 /* [in] */ IUnknown* /*sender*/)
3646 ASSERT_NOT_REACHED();
3650 HRESULT STDMETHODCALLTYPE WebView::startSpeaking(
3651 /* [in] */ IUnknown* /*sender*/)
3653 ASSERT_NOT_REACHED();
3657 HRESULT STDMETHODCALLTYPE WebView::stopSpeaking(
3658 /* [in] */ IUnknown* /*sender*/)
3660 ASSERT_NOT_REACHED();
3664 // IWebNotificationObserver -----------------------------------------------------------------
3666 HRESULT STDMETHODCALLTYPE WebView::onNotify(
3667 /* [in] */ IWebNotification* notification)
3670 HRESULT hr = notification->name(&nameBSTR);
3675 name.adoptBSTR(nameBSTR);
3677 if (!wcscmp(name, WebIconDatabase::iconDatabaseDidAddIconNotification()))
3678 return notifyDidAddIcon(notification);
3680 if (!wcscmp(name, WebPreferences::webPreferencesChangedNotification()))
3681 return notifyPreferencesChanged(notification);
3686 HRESULT WebView::notifyPreferencesChanged(IWebNotification* notification)
3690 COMPtr<IUnknown> unkPrefs;
3691 hr = notification->getObject(&unkPrefs);
3695 COMPtr<IWebPreferences> preferences(Query, unkPrefs);
3697 return E_NOINTERFACE;
3699 ASSERT(preferences == m_preferences);
3705 Settings* settings = m_page->settings();
3707 hr = preferences->cursiveFontFamily(&str);
3710 settings->setCursiveFontFamily(AtomicString(str, SysStringLen(str)));
3713 hr = preferences->defaultFixedFontSize(&size);
3716 settings->setDefaultFixedFontSize(size);
3718 hr = preferences->defaultFontSize(&size);
3721 settings->setDefaultFontSize(size);
3723 hr = preferences->defaultTextEncodingName(&str);
3726 settings->setDefaultTextEncodingName(String(str, SysStringLen(str)));
3729 hr = preferences->fantasyFontFamily(&str);
3732 settings->setFantasyFontFamily(AtomicString(str, SysStringLen(str)));
3735 hr = preferences->fixedFontFamily(&str);
3738 settings->setFixedFontFamily(AtomicString(str, SysStringLen(str)));
3741 hr = preferences->isJavaEnabled(&enabled);
3744 settings->setJavaEnabled(!!enabled);
3746 hr = preferences->isJavaScriptEnabled(&enabled);
3749 settings->setJavaScriptEnabled(!!enabled);
3751 hr = preferences->javaScriptCanOpenWindowsAutomatically(&enabled);
3754 settings->setJavaScriptCanOpenWindowsAutomatically(!!enabled);
3756 hr = preferences->minimumFontSize(&size);
3759 settings->setMinimumFontSize(size);
3761 hr = preferences->minimumLogicalFontSize(&size);
3764 settings->setMinimumLogicalFontSize(size);
3766 hr = preferences->arePlugInsEnabled(&enabled);
3769 settings->setPluginsEnabled(!!enabled);
3771 hr = preferences->privateBrowsingEnabled(&enabled);
3774 settings->setPrivateBrowsingEnabled(!!enabled);
3776 hr = preferences->sansSerifFontFamily(&str);
3779 settings->setSansSerifFontFamily(AtomicString(str, SysStringLen(str)));
3782 hr = preferences->serifFontFamily(&str);
3785 settings->setSerifFontFamily(AtomicString(str, SysStringLen(str)));
3788 hr = preferences->standardFontFamily(&str);
3791 settings->setStandardFontFamily(AtomicString(str, SysStringLen(str)));
3794 hr = preferences->loadsImagesAutomatically(&enabled);
3797 settings->setLoadsImagesAutomatically(!!enabled);
3799 hr = preferences->userStyleSheetEnabled(&enabled);
3803 hr = preferences->userStyleSheetLocation(&str);
3807 RetainPtr<CFStringRef> urlString(AdoptCF, String(str, SysStringLen(str)).createCFString());
3808 RetainPtr<CFURLRef> url(AdoptCF, CFURLCreateWithString(kCFAllocatorDefault, urlString.get(), 0));
3810 // Check if the passed in string is a path and convert it to a URL.
3811 // FIXME: This is a workaround for nightly builds until we can get Safari to pass
3812 // in an URL here. See <rdar://problem/5478378>
3814 DWORD len = SysStringLen(str) + 1;
3816 int result = WideCharToMultiByte(CP_UTF8, 0, str, len, 0, 0, 0, 0);
3817 Vector<UInt8> utf8Path(result);
3818 if (!WideCharToMultiByte(CP_UTF8, 0, str, len, (LPSTR)utf8Path.data(), result, 0, 0))
3821 url.adoptCF(CFURLCreateFromFileSystemRepresentation(0, utf8Path.data(), result - 1, false));
3824 settings->setUserStyleSheetLocation(url.get());
3827 settings->setUserStyleSheetLocation(KURL(DeprecatedString("")));
3830 hr = preferences->shouldPrintBackgrounds(&enabled);
3833 settings->setShouldPrintBackgrounds(!!enabled);
3835 hr = preferences->textAreasAreResizable(&enabled);
3838 settings->setTextAreasAreResizable(!!enabled);
3840 WebKitEditableLinkBehavior behavior;
3841 hr = preferences->editableLinkBehavior(&behavior);
3844 settings->setEditableLinkBehavior((EditableLinkBehavior)behavior);
3846 hr = preferences->usesPageCache(&enabled);
3849 settings->setUsesPageCache(!!enabled);
3851 hr = preferences->isDOMPasteAllowed(&enabled);
3854 settings->setDOMPasteAllowed(!!enabled);
3856 settings->setShowsURLsInToolTips(false);
3857 settings->setForceFTPDirectoryListings(true);
3858 settings->setDeveloperExtrasEnabled(developerExtrasEnabled());
3860 COMPtr<IWebPreferencesPrivate> prefsPrivate(Query, preferences);
3862 unsigned long long defaultQuota = 0;
3863 hr = prefsPrivate->defaultDatabaseQuota(&defaultQuota);
3866 settings->setDefaultDatabaseOriginQuota(defaultQuota);
3868 hr = prefsPrivate->authorAndUserStylesEnabled(&enabled);
3871 settings->setAuthorAndUserStylesEnabled(enabled);
3874 m_mainFrame->invalidate(); // FIXME
3876 hr = updateSharedSettingsFromPreferencesIfNeeded(preferences.get());
3883 HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences* preferences)
3885 if (preferences != WebPreferences::sharedStandardPreferences())
3888 WebKitCookieStorageAcceptPolicy acceptPolicy;
3889 HRESULT hr = preferences->cookieStorageAcceptPolicy(&acceptPolicy);
3893 // Set cookie storage accept policy
3894 if (CFHTTPCookieStorageRef defaultCookieStorage = wkGetDefaultHTTPCookieStorage())
3895 CFHTTPCookieStorageSetCookieAcceptPolicy(defaultCookieStorage, acceptPolicy);
3900 // IWebViewPrivate ------------------------------------------------------------
3902 HRESULT STDMETHODCALLTYPE WebView::setCustomDropTarget(
3903 /* [in] */ IDropTarget* dt)
3905 ASSERT(::IsWindow(m_viewWindow));
3908 m_hasCustomDropTarget = true;
3910 return ::RegisterDragDrop(m_viewWindow,dt);
3913 HRESULT STDMETHODCALLTYPE WebView::removeCustomDropTarget()
3915 if (!m_hasCustomDropTarget)
3917 m_hasCustomDropTarget = false;
3919 return registerDragDrop();
3922 HRESULT STDMETHODCALLTYPE WebView::setInViewSourceMode(
3923 /* [in] */ BOOL flag)
3928 return m_mainFrame->setInViewSourceMode(flag);
3931 HRESULT STDMETHODCALLTYPE WebView::inViewSourceMode(
3932 /* [retval][out] */ BOOL* flag)
3937 return m_mainFrame->inViewSourceMode(flag);
3940 HRESULT STDMETHODCALLTYPE WebView::viewWindow(
3941 /* [retval][out] */ OLE_HANDLE *window)
3943 *window = (OLE_HANDLE)(ULONG64)m_viewWindow;
3947 HRESULT STDMETHODCALLTYPE WebView::setFormDelegate(
3948 /* [in] */ IWebFormDelegate *formDelegate)
3950 m_formDelegate = formDelegate;
3954 HRESULT STDMETHODCALLTYPE WebView::formDelegate(
3955 /* [retval][out] */ IWebFormDelegate **formDelegate)
3957 if (!m_formDelegate)
3960 return m_formDelegate.copyRefTo(formDelegate);
3963 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegatePrivate(
3964 /* [in] */ IWebFrameLoadDelegatePrivate* d)
3966 m_frameLoadDelegatePrivate = d;
3970 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegatePrivate(
3971 /* [out][retval] */ IWebFrameLoadDelegatePrivate** d)
3973 if (!m_frameLoadDelegatePrivate)
3976 return m_frameLoadDelegatePrivate.copyRefTo(d);
3979 HRESULT STDMETHODCALLTYPE WebView::scrollOffset(
3980 /* [retval][out] */ LPPOINT offset)
3984 IntSize offsetIntSize = m_page->mainFrame()->view()->scrollOffset();
3985 offset->x = offsetIntSize.width();
3986 offset->y = offsetIntSize.height();
3990 HRESULT STDMETHODCALLTYPE WebView::scrollBy(
3991 /* [in] */ LPPOINT offset)
3995 m_page->mainFrame()->view()->scrollBy(offset->x, offset->y);
3999 HRESULT STDMETHODCALLTYPE WebView::visibleContentRect(
4000 /* [retval][out] */ LPRECT rect)
4004 FloatRect visibleContent = m_page->mainFrame()->view()->visibleContentRect();
4005 rect->left = (LONG) visibleContent.x();
4006 rect->top = (LONG) visibleContent.y();
4007 rect->right = (LONG) visibleContent.right();
4008 rect->bottom = (LONG) visibleContent.bottom();
4012 static DWORD dragOperationToDragCursor(DragOperation op) {
4013 DWORD res = DROPEFFECT_NONE;
4014 if (op & DragOperationCopy)
4015 res = DROPEFFECT_COPY;
4016 else if (op & DragOperationLink)
4017 res = DROPEFFECT_LINK;
4018 else if (op & DragOperationMove)
4019 res = DROPEFFECT_MOVE;
4020 else if (op & DragOperationGeneric)
4021 res = DROPEFFECT_MOVE; //This appears to be the Firefox behaviour
4025 static DragOperation keyStateToDragOperation(DWORD) {
4026 //FIXME: This is currently very simple, it may need to actually
4027 //work out an appropriate DragOperation in future -- however this
4028 //behaviour appears to match FireFox
4029 return (DragOperation)(DragOperationCopy | DragOperationLink);
4032 HRESULT STDMETHODCALLTYPE WebView::DragEnter(
4033 IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
4037 if (m_dropTargetHelper)
4038 m_dropTargetHelper->DragEnter(m_viewWindow, pDataObject, (POINT*)&pt, *pdwEffect);
4040 POINTL localpt = pt;
4041 ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
4042 DragData data(pDataObject, IntPoint(localpt.x, localpt.y),
4043 IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
4044 *pdwEffect = dragOperationToDragCursor(m_page->dragController()->dragEntered(&data));
4046 m_dragData = pDataObject;
4051 HRESULT STDMETHODCALLTYPE WebView::DragOver(
4052 DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
4054 if (m_dropTargetHelper)
4055 m_dropTargetHelper->DragOver((POINT*)&pt, *pdwEffect);
4058 POINTL localpt = pt;
4059 ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
4060 DragData data(m_dragData.get(), IntPoint(localpt.x, localpt.y),
4061 IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
4062 *pdwEffect = dragOperationToDragCursor(m_page->dragController()->dragUpdated(&data));
4064 *pdwEffect = DROPEFFECT_NONE;
4069 HRESULT STDMETHODCALLTYPE WebView::DragLeave()
4071 if (m_dropTargetHelper)
4072 m_dropTargetHelper->DragLeave();
4075 DragData data(m_dragData.get(), IntPoint(), IntPoint(),
4077 m_page->dragController()->dragExited(&data);
4083 HRESULT STDMETHODCALLTYPE WebView::Drop(
4084 IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
4086 if (m_dropTargetHelper)
4087 m_dropTargetHelper->Drop(pDataObject, (POINT*)&pt, *pdwEffect);
4090 *pdwEffect = DROPEFFECT_NONE;
4091 POINTL localpt = pt;
4092 ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
4093 DragData data(pDataObject, IntPoint(localpt.x, localpt.y),
4094 IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
4095 m_page->dragController()->performDrag(&data);
4099 HRESULT STDMETHODCALLTYPE WebView::canHandleRequest(
4100 IWebURLRequest *request,
4103 COMPtr<WebMutableURLRequest> requestImpl;
4105 HRESULT hr = request->QueryInterface(&requestImpl);
4109 *result = !!canHandleRequest(requestImpl->resourceRequest());
4113 HRESULT STDMETHODCALLTYPE WebView::clearFocusNode()
4115 if (m_page && m_page->focusController())
4116 m_page->focusController()->setFocusedNode(0, 0);
4120 HRESULT STDMETHODCALLTYPE WebView::setInitialFocus(
4121 /* [in] */ BOOL forward)
4123 if (m_page && m_page->focusController()) {
4124 Frame* frame = m_page->focusController()->focusedOrMainFrame();
4125 frame->document()->setFocusedNode(0);
4126 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
4131 HRESULT STDMETHODCALLTYPE WebView::setTabKeyCyclesThroughElements(
4132 /* [in] */ BOOL cycles)
4135 m_page->setTabKeyCyclesThroughElements(!!cycles);
4140 HRESULT STDMETHODCALLTYPE WebView::tabKeyCyclesThroughElements(
4141 /* [retval][out] */ BOOL* result)
4144 ASSERT_NOT_REACHED();
4148 *result = m_page && m_page->tabKeyCyclesThroughElements() ? TRUE : FALSE;
4152 HRESULT STDMETHODCALLTYPE WebView::setAllowSiteSpecificHacks(
4153 /* [in] */ BOOL allow)
4155 s_allowSiteSpecificHacks = !!allow;
4159 HRESULT STDMETHODCALLTYPE WebView::addAdditionalPluginPath(
4160 /* [in] */ BSTR path)
4162 PluginDatabaseWin::installedPlugins()->addExtraPluginPath(String(path, SysStringLen(path)));
4166 HRESULT STDMETHODCALLTYPE WebView::loadBackForwardListFromOtherView(
4167 /* [in] */ IWebView* otherView)
4172 // It turns out the right combination of behavior is done with the back/forward load
4173 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
4174 // in the back forward list, and go to the current one.
4175 BackForwardList* backForwardList = m_page->backForwardList();
4176 ASSERT(!backForwardList->currentItem()); // destination list should be empty
4178 COMPtr<WebView> otherWebView;
4179 if (FAILED(otherView->QueryInterface(&otherWebView)))
4181 BackForwardList* otherBackForwardList = otherWebView->m_page->backForwardList();
4182 if (!otherBackForwardList->currentItem())
4183 return S_OK; // empty back forward list, bail
4185 HistoryItem* newItemToGoTo = 0;
4187 int lastItemIndex = otherBackForwardList->forwardListCount();
4188 for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
4190 // If this item is showing , save away its current scroll and form state,
4191 // since that might have changed since loading and it is normally not saved
4192 // until we leave that page.
4193 otherWebView->m_page->mainFrame()->loader()->saveDocumentAndScrollState();
4195 RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
4197 newItemToGoTo = newItem.get();
4198 backForwardList->addItem(newItem.release());
4201 ASSERT(newItemToGoTo);
4202 m_page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
4206 HRESULT STDMETHODCALLTYPE WebView::clearUndoRedoOperations()
4208 if (Frame* frame = m_page->focusController()->focusedOrMainFrame())
4209 frame->editor()->clearUndoRedoOperations();
4213 HRESULT STDMETHODCALLTYPE WebView::shouldClose(
4214 /* [retval][out] */ BOOL* result)
4217 ASSERT_NOT_REACHED();
4222 if (Frame* frame = m_page->focusController()->focusedOrMainFrame())
4223 *result = frame->shouldClose() ? TRUE : FALSE;
4227 HRESULT WebView::registerDragDrop()
4229 ASSERT(::IsWindow(m_viewWindow));
4230 return ::RegisterDragDrop(m_viewWindow, this);
4233 HRESULT WebView::revokeDragDrop()
4235 ASSERT(::IsWindow(m_viewWindow));
4236 return ::RevokeDragDrop(m_viewWindow);
4239 HRESULT WebView::setProhibitsMainFrameScrolling(BOOL b)
4244 m_page->mainFrame()->setProhibitsScrolling(b);
4248 HRESULT WebView::setShouldApplyMacFontAscentHack(BOOL b)
4250 FontData::setShouldApplyMacAscentHack(b);
4255 typedef HIMC (CALLBACK *getContextPtr)(HWND);
4256 typedef BOOL (CALLBACK *releaseContextPtr)(HWND, HIMC);
4257 typedef LONG (CALLBACK *getCompositionStringPtr)(HIMC, DWORD, LPVOID, DWORD);
4258 typedef BOOL (CALLBACK *setCandidateWindowPtr)(HIMC, LPCANDIDATEFORM);
4259 typedef BOOL (CALLBACK *setOpenStatusPtr)(HIMC, BOOL);
4260 typedef BOOL (CALLBACK *notifyIMEPtr)(HIMC, DWORD, DWORD, DWORD);
4261 typedef BOOL (CALLBACK *associateContextExPtr)(HWND, HIMC, DWORD);
4264 getContextPtr getContext;
4265 releaseContextPtr releaseContext;
4266 getCompositionStringPtr getCompositionString;
4267 setCandidateWindowPtr setCandidateWindow;
4268 setOpenStatusPtr setOpenStatus;
4269 notifyIMEPtr notifyIME;
4270 associateContextExPtr associateContextEx;
4272 static const IMMDict& dict();
4278 const IMMDict& IMMDict::dict()
4280 static IMMDict instance;
4286 m_instance = ::LoadLibrary(TEXT("IMM32.DLL"));
4287 getContext = reinterpret_cast<getContextPtr>(::GetProcAddress(m_instance, "ImmGetContext"));
4289 releaseContext = reinterpret_cast<releaseContextPtr>(::GetProcAddress(m_instance, "ImmReleaseContext"));
4290 ASSERT(releaseContext);
4291 getCompositionString = reinterpret_cast<getCompositionStringPtr>(::GetProcAddress(m_instance, "ImmGetCompositionStringW"));
4292 ASSERT(getCompositionString);
4293 setCandidateWindow = reinterpret_cast<setCandidateWindowPtr>(::GetProcAddress(m_instance, "ImmSetCandidateWindow"));
4294 ASSERT(setCandidateWindow);
4295 setOpenStatus = reinterpret_cast<setOpenStatusPtr>(::GetProcAddress(m_instance, "ImmSetOpenStatus"));
4296 ASSERT(setOpenStatus);
4297 notifyIME = reinterpret_cast<notifyIMEPtr>(::GetProcAddress(m_instance, "ImmNotifyIME"));
4299 associateContextEx = reinterpret_cast<associateContextExPtr>(::GetProcAddress(m_instance, "ImmAssociateContextEx"));
4300 ASSERT(associateContextEx);
4303 HIMC WebView::getIMMContext()
4305 HIMC context = IMMDict::dict().getContext(m_viewWindow);
4309 void WebView::releaseIMMContext(HIMC hIMC)
4313 IMMDict::dict().releaseContext(m_viewWindow, hIMC);
4316 void WebView::prepareCandidateWindow(Frame* targetFrame, HIMC hInputContext)
4319 if (RefPtr<Range> range = targetFrame->selectionController()->selection().toRange()) {
4320 ExceptionCode ec = 0;
4321 RefPtr<Range> tempRange = range->cloneRange(ec);
4322 caret = targetFrame->firstRectForRange(tempRange.get());
4324 caret = targetFrame->view()->contentsToWindow(caret);
4327 form.dwStyle = CFS_EXCLUDE;
4328 form.ptCurrentPos.x = caret.x();
4329 form.ptCurrentPos.y = caret.y() + caret.height();
4330 form.rcArea.top = caret.y();
4331 form.rcArea.bottom = caret.bottom();
4332 form.rcArea.left = caret.x();
4333 form.rcArea.right = caret.right();
4334 IMMDict::dict().setCandidateWindow(hInputContext, &form);
4337 void WebView::resetIME(Frame* targetFrame)
4340 targetFrame->editor()->confirmCompositionWithoutDisturbingSelection();
4342 if (HIMC hInputContext = getIMMContext()) {
4343 IMMDict::dict().notifyIME(hInputContext, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
4344 releaseIMMContext(hInputContext);
4348 void WebView::updateSelectionForIME()
4350 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
4351 if (!targetFrame || !targetFrame->editor()->hasComposition())
4354 if (targetFrame->editor()->ignoreCompositionSelectionChange())
4359 if (!targetFrame->editor()->getCompositionSelection(start, end))
4360 resetIME(targetFrame);
4363 void WebView::setInputMethodState(bool enabled)
4365 IMMDict::dict().associateContextEx(m_viewWindow, 0, enabled ? IACE_DEFAULT : 0);
4368 void WebView::selectionChanged()
4370 updateSelectionForIME();
4373 bool WebView::onIMEStartComposition()
4375 m_inIMEComposition++;
4376 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
4380 HIMC hInputContext = getIMMContext();
4381 prepareCandidateWindow(targetFrame, hInputContext);
4382 releaseIMMContext(hInputContext);
4386 static bool getCompositionString(HIMC hInputContext, DWORD type, String& result)
4388 int compositionLength = IMMDict::dict().getCompositionString(hInputContext, type, 0, 0);
4389 if (compositionLength <= 0)
4391 Vector<UChar> compositionBuffer(compositionLength / 2);
4392 compositionLength = IMMDict::dict().getCompositionString(hInputContext, type, (LPVOID)compositionBuffer.data(), compositionLength);
4393 result = String(compositionBuffer.data(), compositionLength / 2);
4394 ASSERT(!compositionLength || compositionBuffer[0]);
4395 ASSERT(!compositionLength || compositionBuffer[compositionLength / 2 - 1]);
4399 static void compositionToUnderlines(const Vector<DWORD>& clauses, const Vector<BYTE>& attributes, Vector<CompositionUnderline>& underlines)
4401 if (clauses.isEmpty()) {
4406 const size_t numBoundaries = clauses.size() - 1;
4407 underlines.resize(numBoundaries);
4408 for (unsigned i = 0; i < numBoundaries; i++) {
4409 underlines[i].startOffset = clauses[i];
4410 underlines[i].endOffset = clauses[i + 1];
4411 BYTE attribute = attributes[clauses[i]];
4412 underlines[i].thick = attribute == ATTR_TARGET_CONVERTED || attribute == ATTR_TARGET_NOTCONVERTED;
4413 underlines[i].color = Color(0,0,0);
4417 bool WebView::onIMEComposition(LPARAM lparam)
4419 HIMC hInputContext = getIMMContext();
4423 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
4424 if (!targetFrame || !targetFrame->editor()->canEdit())
4427 prepareCandidateWindow(targetFrame, hInputContext);
4429 if (lparam & GCS_RESULTSTR || !lparam) {
4430 String compositionString;
4431 if (!getCompositionString(hInputContext, GCS_RESULTSTR, compositionString) && lparam)
4434 targetFrame->editor()->confirmComposition(compositionString);
4436 String compositionString;
4437 if (!getCompositionString(hInputContext, GCS_COMPSTR, compositionString))
4440 // Composition string attributes
4441 int numAttributes = IMMDict::dict().getCompositionString(hInputContext, GCS_COMPATTR, 0, 0);
4442 Vector<BYTE> attributes(numAttributes);
4443 IMMDict::dict().getCompositionString(hInputContext, GCS_COMPATTR, attributes.data(), numAttributes);
4446 int numClauses = IMMDict::dict().getCompositionString(hInputContext, GCS_COMPCLAUSE, 0, 0);
4447 Vector<DWORD> clauses(numClauses / sizeof(DWORD));
4448 IMMDict::dict().getCompositionString(hInputContext, GCS_COMPCLAUSE, clauses.data(), numClauses);
4450 Vector<CompositionUnderline> underlines;
4451 compositionToUnderlines(clauses, attributes, underlines);
4453 int cursorPosition = LOWORD(IMMDict::dict().getCompositionString(hInputContext, GCS_CURSORPOS, 0, 0));
4455 targetFrame->editor()->setComposition(compositionString, underlines, cursorPosition, 0);
4461 bool WebView::onIMEEndComposition()
4463 if (m_inIMEComposition)
4464 m_inIMEComposition--;