2 * Copyright (C) 2006, 2007, 2008 Apple, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "WebKitDLL.h"
30 #include "CFDictionaryPropertyBag.h"
31 #include "DOMCoreClasses.h"
32 #include "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/FrameLoader.h>
69 #include <WebCore/FrameTree.h>
70 #include <WebCore/FrameView.h>
71 #include <WebCore/FrameWin.h>
72 #include <WebCore/GDIObjectCounter.h>
73 #include <WebCore/GraphicsContext.h>
74 #include <WebCore/HistoryItem.h>
75 #include <WebCore/HitTestResult.h>
76 #include <WebCore/IntRect.h>
77 #include <WebCore/KeyboardEvent.h>
78 #include <WebCore/Language.h>
79 #include <WebCore/MIMETypeRegistry.h>
80 #include <WebCore/NotImplemented.h>
81 #include <WebCore/Page.h>
82 #include <WebCore/PageCache.h>
83 #include <WebCore/PlatformKeyboardEvent.h>
84 #include <WebCore/PlatformMouseEvent.h>
85 #include <WebCore/PlatformWheelEvent.h>
86 #include <WebCore/PluginDatabaseWin.h>
87 #include <WebCore/PlugInInfoStore.h>
88 #include <WebCore/PluginViewWin.h>
89 #include <WebCore/ProgressTracker.h>
90 #include <WebCore/ResourceHandle.h>
91 #include <WebCore/ResourceHandleClient.h>
92 #include <WebCore/SelectionController.h>
93 #include <WebCore/Settings.h>
94 #include <WebCore/SimpleFontData.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, "MovePageUpAndModifySelection" },
1298 { VK_DOWN, 0, "MoveDown" },
1299 { VK_DOWN, ShiftKey, "MoveDownAndModifySelection" },
1300 { VK_NEXT, ShiftKey, "MovePageDownAndModifySelection" },
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, "DeleteBackward" },
1314 { VK_BACK, ShiftKey, "DeleteBackward" },
1315 { VK_DELETE, 0, "DeleteForward" },
1316 { VK_DELETE, ShiftKey, "DeleteForward" },
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 if (evt->type() == keydownEvent) {
1376 int mapKey = modifiers << 16 | evt->keyCode();
1377 return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
1380 int mapKey = modifiers << 16 | evt->charCode();
1381 return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
1384 bool WebView::handleEditingKeyboardEvent(KeyboardEvent* evt)
1386 Node* node = evt->target()->toNode();
1388 Frame* frame = node->document()->frame();
1391 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1392 if (!keyEvent || keyEvent->isSystemKey()) // do not treat this as text input if it's a system key event
1395 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1397 if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1398 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1399 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1400 // (e.g. Tab that inserts a Tab character, or Enter).
1401 return !command.isTextInsertion() && command.execute(evt);
1404 if (command.execute(evt))
1407 // Don't insert null or control characters as they can result in unexpected behaviour
1408 if (evt->charCode() < ' ')
1411 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1414 bool WebView::keyDown(WPARAM virtualKeyCode, LPARAM keyData, bool systemKeyDown)
1416 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1417 if (virtualKeyCode == VK_CAPITAL)
1418 frame->eventHandler()->capsLockStateMayHaveChanged();
1420 PlatformKeyboardEvent keyEvent(m_viewWindow, virtualKeyCode, keyData, PlatformKeyboardEvent::RawKeyDown, systemKeyDown);
1421 bool handled = frame->eventHandler()->keyEvent(keyEvent);
1423 // These events cannot be canceled, and we have no default handling for them.
1424 // FIXME: match IE list more closely, see <http://msdn2.microsoft.com/en-us/library/ms536938.aspx>.
1429 // FIXME: remove WM_UNICHAR, too
1431 // WM_SYSCHAR events should not be removed, because access keys are implemented in WebCore in WM_SYSCHAR handler.
1433 ::PeekMessage(&msg, m_viewWindow, WM_CHAR, WM_CHAR, PM_REMOVE);
1437 // We need to handle back/forward using either Backspace(+Shift) or Ctrl+Left/Right Arrow keys.
1438 if ((virtualKeyCode == VK_BACK && keyEvent.shiftKey()) || (virtualKeyCode == VK_RIGHT && keyEvent.ctrlKey()))
1439 m_page->goForward();
1440 else if (virtualKeyCode == VK_BACK || (virtualKeyCode == VK_LEFT && keyEvent.ctrlKey()))
1443 // Need to scroll the page if the arrow keys, pgup/dn, or home/end are hit.
1444 ScrollDirection direction;
1445 ScrollGranularity granularity;
1446 switch (virtualKeyCode) {
1448 granularity = ScrollByLine;
1449 direction = ScrollLeft;
1452 granularity = ScrollByLine;
1453 direction = ScrollRight;
1456 granularity = ScrollByLine;
1457 direction = ScrollUp;
1460 granularity = ScrollByLine;
1461 direction = ScrollDown;
1464 granularity = ScrollByDocument;
1465 direction = ScrollUp;
1468 granularity = ScrollByDocument;
1469 direction = ScrollDown;
1472 granularity = ScrollByPage;
1473 direction = ScrollUp;
1476 granularity = ScrollByPage;
1477 direction = ScrollDown;
1483 if (!frame->eventHandler()->scrollOverflow(direction, granularity)) {
1484 handled = frame->view()->scroll(direction, granularity);
1485 Frame* parent = frame->tree()->parent();
1486 while(!handled && parent) {
1487 handled = parent->view()->scroll(direction, granularity);
1488 parent = parent->tree()->parent();
1494 bool WebView::keyPress(WPARAM charCode, LPARAM keyData, bool systemKeyDown)
1496 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1498 PlatformKeyboardEvent keyEvent(m_viewWindow, charCode, keyData, PlatformKeyboardEvent::Char, systemKeyDown);
1499 // IE does not dispatch keypress event for WM_SYSCHAR.
1501 return frame->eventHandler()->handleAccessKey(keyEvent);
1502 if (frame->eventHandler()->keyEvent(keyEvent))
1505 // Need to scroll the page if space is hit.
1506 if (charCode == ' ') {
1507 ScrollDirection direction = keyEvent.shiftKey() ? ScrollUp : ScrollDown;
1508 if (!frame->eventHandler()->scrollOverflow(direction, ScrollByPage))
1509 frame->view()->scroll(direction, ScrollByPage);
1515 bool WebView::inResizer(LPARAM lParam)
1517 if (!m_uiDelegatePrivate)
1521 if (FAILED(m_uiDelegatePrivate->webViewResizerRect(this, &r)))
1525 pt.x = LOWORD(lParam);
1526 pt.y = HIWORD(lParam);
1527 return !!PtInRect(&r, pt);
1530 static bool registerWebViewWindowClass()
1532 static bool haveRegisteredWindowClass = false;
1533 if (haveRegisteredWindowClass)
1536 haveRegisteredWindowClass = true;
1540 wcex.cbSize = sizeof(WNDCLASSEX);
1542 wcex.style = CS_DBLCLKS;
1543 wcex.lpfnWndProc = WebViewWndProc;
1544 wcex.cbClsExtra = 0;
1545 wcex.cbWndExtra = 4; // 4 bytes for the IWebView pointer
1546 wcex.hInstance = gInstance;
1548 wcex.hCursor = ::LoadCursor(0, IDC_ARROW);
1549 wcex.hbrBackground = 0;
1550 wcex.lpszMenuName = 0;
1551 wcex.lpszClassName = kWebViewWindowClassName;
1554 return !!RegisterClassEx(&wcex);
1558 extern HCURSOR lastSetCursor;
1561 static LRESULT CALLBACK WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
1563 LRESULT lResult = 0;
1564 LONG_PTR longPtr = GetWindowLongPtr(hWnd, 0);
1565 WebView* webView = reinterpret_cast<WebView*>(longPtr);
1566 WebFrame* mainFrameImpl = webView ? webView->topLevelFrame() : 0;
1567 if (!mainFrameImpl || webView->isBeingDestroyed())
1568 return DefWindowProc(hWnd, message, wParam, lParam);
1572 // Windows Media Player has a modal message loop that will deliver messages
1573 // to us at inappropriate times and we will crash if we handle them when
1574 // they are delivered. We repost paint messages so that we eventually get
1575 // a chance to paint once the modal loop has exited, but other messages
1576 // aren't safe to repost, so we just drop them.
1577 if (PluginViewWin::isCallingPlugin()) {
1578 if (message == WM_PAINT)
1579 PostMessage(hWnd, message, wParam, lParam);
1583 bool handled = true;
1587 webView->paint(0, 0);
1590 case WM_PRINTCLIENT:
1591 webView->paint((HDC)wParam, lParam);
1595 webView->setIsBeingDestroyed();
1596 webView->revokeDragDrop();
1599 if (webView->inResizer(lParam))
1600 SetCursor(LoadCursor(0, IDC_SIZENWSE));
1602 case WM_LBUTTONDOWN:
1603 case WM_MBUTTONDOWN:
1604 case WM_RBUTTONDOWN:
1605 case WM_LBUTTONDBLCLK:
1606 case WM_MBUTTONDBLCLK:
1607 case WM_RBUTTONDBLCLK:
1612 if (Frame* coreFrame = core(mainFrameImpl))
1613 if (coreFrame->view()->didFirstLayout())
1614 handled = webView->handleMouseEvent(message, wParam, lParam);
1617 case WM_VISTA_MOUSEHWHEEL:
1618 if (Frame* coreFrame = core(mainFrameImpl))
1619 if (coreFrame->view()->didFirstLayout())
1620 handled = webView->mouseWheel(wParam, lParam, (wParam & MK_SHIFT) || message == WM_VISTA_MOUSEHWHEEL);
1623 handled = webView->keyDown(wParam, lParam, true);
1626 handled = webView->keyDown(wParam, lParam);
1629 handled = webView->keyUp(wParam, lParam, true);
1632 handled = webView->keyUp(wParam, lParam);
1635 handled = webView->keyPress(wParam, lParam, true);
1638 handled = webView->keyPress(wParam, lParam);
1640 // FIXME: We need to check WM_UNICHAR to support supplementary characters (that don't fit in 16 bits).
1642 if (webView->isBeingDestroyed())
1643 // If someone has sent us this message while we're being destroyed, we should bail out so we don't crash.
1647 webView->deleteBackingStore();
1648 if (Frame* coreFrame = core(mainFrameImpl))
1649 coreFrame->view()->resize(LOWORD(lParam), HIWORD(lParam));
1653 lResult = DefWindowProc(hWnd, message, wParam, lParam);
1655 // The window is being hidden (e.g., because we switched tabs.
1656 // Null out our backing store.
1657 webView->deleteBackingStore();
1660 COMPtr<IWebUIDelegate> uiDelegate;
1661 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
1662 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
1663 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
1664 uiDelegatePrivate->webViewReceivedFocus(webView);
1665 // FIXME: Merge this logic with updateActiveState, and switch this over to use updateActiveState
1667 // It's ok to just always do setWindowHasFocus, since we won't fire the focus event on the DOM
1668 // window unless the value changes. It's also ok to do setIsActive inside focus,
1669 // because Windows has no concept of having to update control tints (e.g., graphite vs. aqua)
1670 // and therefore only needs to update the selection (which is limited to the focused frame).
1671 FocusController* focusController = webView->page()->focusController();
1672 if (Frame* frame = focusController->focusedFrame()) {
1673 frame->setIsActive(true);
1675 // If the previously focused window is a child of ours (for example a plugin), don't send any
1677 if (!IsChild(hWnd, reinterpret_cast<HWND>(wParam)))
1678 frame->setWindowHasFocus(true);
1680 focusController->setFocusedFrame(webView->page()->mainFrame());
1683 case WM_KILLFOCUS: {
1684 COMPtr<IWebUIDelegate> uiDelegate;
1685 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
1686 HWND newFocusWnd = reinterpret_cast<HWND>(wParam);
1687 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
1688 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate)
1689 uiDelegatePrivate->webViewLostFocus(webView, (OLE_HANDLE)(ULONG64)newFocusWnd);
1690 // FIXME: Merge this logic with updateActiveState, and switch this over to use updateActiveState
1692 // However here we have to be careful. If we are losing focus because of a deactivate,
1693 // then we need to remember our focused target for restoration later.
1694 // If we are losing focus to another part of our window, then we are no longer focused for real
1695 // and we need to clear out the focused target.
1696 FocusController* focusController = webView->page()->focusController();
1697 webView->resetIME(focusController->focusedOrMainFrame());
1698 if (GetAncestor(hWnd, GA_ROOT) != newFocusWnd) {
1699 if (Frame* frame = focusController->focusedOrMainFrame()) {
1700 frame->setIsActive(false);
1702 // If we're losing focus to a child of ours, don't send blur events.
1703 if (!IsChild(hWnd, newFocusWnd))
1704 frame->setWindowHasFocus(false);
1707 focusController->setFocusedFrame(0);
1720 webView->delete_(0);
1724 handled = webView->execCommand(wParam, lParam);
1725 else // If the high word of wParam is 0, the message is from a menu
1726 webView->performContextMenuAction(wParam, lParam, false);
1728 case WM_MENUCOMMAND:
1729 webView->performContextMenuAction(wParam, lParam, true);
1731 case WM_CONTEXTMENU:
1732 handled = webView->handleContextMenuEvent(wParam, lParam);
1734 case WM_INITMENUPOPUP:
1735 handled = webView->onInitMenuPopup(wParam, lParam);
1737 case WM_MEASUREITEM:
1738 handled = webView->onMeasureItem(wParam, lParam);
1741 handled = webView->onDrawItem(wParam, lParam);
1743 case WM_UNINITMENUPOPUP:
1744 handled = webView->onUninitMenuPopup(wParam, lParam);
1746 case WM_XP_THEMECHANGED:
1747 if (Frame* coreFrame = core(mainFrameImpl)) {
1748 webView->deleteBackingStore();
1749 coreFrame->view()->themeChanged();
1752 case WM_MOUSEACTIVATE:
1753 webView->setMouseActivated(true);
1755 case WM_GETDLGCODE: {
1756 COMPtr<IWebUIDelegate> uiDelegate;
1757 COMPtr<IWebUIDelegatePrivate> uiDelegatePrivate;
1758 LONG_PTR dlgCode = 0;
1761 LPMSG lpMsg = (LPMSG)lParam;
1762 if (lpMsg->message == WM_KEYDOWN)
1763 keyCode = (UINT) lpMsg->wParam;
1765 if (SUCCEEDED(webView->uiDelegate(&uiDelegate)) && uiDelegate &&
1766 SUCCEEDED(uiDelegate->QueryInterface(IID_IWebUIDelegatePrivate, (void**) &uiDelegatePrivate)) && uiDelegatePrivate &&
1767 SUCCEEDED(uiDelegatePrivate->webViewGetDlgCode(webView, keyCode, &dlgCode)))
1773 case WM_IME_STARTCOMPOSITION:
1774 handled = webView->onIMEStartComposition();
1776 case WM_IME_REQUEST:
1777 webView->onIMERequest(wParam, lParam, &lResult);
1779 case WM_IME_COMPOSITION:
1780 handled = webView->onIMEComposition(lParam);
1782 case WM_IME_ENDCOMPOSITION:
1783 handled = webView->onIMEEndComposition();
1786 handled = webView->onIMEChar(wParam, lParam);
1789 handled = webView->onIMENotify(wParam, lParam, &lResult);
1792 handled = webView->onIMESelect(wParam, lParam);
1794 case WM_IME_SETCONTEXT:
1795 handled = webView->onIMESetContext(wParam, lParam);
1798 if (lastSetCursor) {
1799 SetCursor(lastSetCursor);
1809 lResult = DefWindowProc(hWnd, message, wParam, lParam);
1811 // Let the client know whether we consider this message handled.
1812 return (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) ? !handled : lResult;
1815 bool WebView::developerExtrasEnabled() const
1817 if (m_preferences->developerExtrasDisabledByOverride())
1822 return SUCCEEDED(m_preferences->developerExtrasEnabled(&enabled)) && enabled;
1828 static String osVersion()
1831 OSVERSIONINFO versionInfo = {0};
1832 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1833 GetVersionEx(&versionInfo);
1835 if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
1836 if (versionInfo.dwMajorVersion == 4) {
1837 if (versionInfo.dwMinorVersion == 0)
1838 osVersion = "Windows 95";
1839 else if (versionInfo.dwMinorVersion == 10)
1840 osVersion = "Windows 98";
1841 else if (versionInfo.dwMinorVersion == 90)
1842 osVersion = "Windows 98; Win 9x 4.90";
1844 } else if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
1845 osVersion = String::format("Windows NT %d.%d", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion);
1847 if (!osVersion.length())
1848 osVersion = String::format("Windows %d.%d", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion);
1853 static String webKitVersion()
1855 String versionStr = "420+";
1858 struct LANGANDCODEPAGE {
1863 TCHAR path[MAX_PATH];
1864 GetModuleFileName(gInstance, path, ARRAYSIZE(path));
1866 DWORD versionSize = GetFileVersionInfoSize(path, &handle);
1869 data = malloc(versionSize);
1872 if (!GetFileVersionInfo(path, 0, versionSize, data))
1875 if (!VerQueryValue(data, TEXT("\\VarFileInfo\\Translation"), (LPVOID*)&lpTranslate, &cbTranslate))
1878 _stprintf_s(key, ARRAYSIZE(key), TEXT("\\StringFileInfo\\%04x%04x\\ProductVersion"), lpTranslate[0].wLanguage, lpTranslate[0].wCodePage);
1879 LPCTSTR productVersion;
1880 UINT productVersionLength;
1881 if (!VerQueryValue(data, (LPTSTR)(LPCTSTR)key, (void**)&productVersion, &productVersionLength))
1883 versionStr = String(productVersion, productVersionLength);
1891 const String& WebView::userAgentForKURL(const KURL&)
1893 if (m_userAgentOverridden)
1894 return m_userAgentCustom;
1896 if (!m_userAgentStandard.length())
1897 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());
1898 return m_userAgentStandard;
1901 // IUnknown -------------------------------------------------------------------
1903 HRESULT STDMETHODCALLTYPE WebView::QueryInterface(REFIID riid, void** ppvObject)
1906 if (IsEqualGUID(riid, CLSID_WebView))
1908 else if (IsEqualGUID(riid, IID_IUnknown))
1909 *ppvObject = static_cast<IWebView*>(this);
1910 else if (IsEqualGUID(riid, IID_IWebView))
1911 *ppvObject = static_cast<IWebView*>(this);
1912 else if (IsEqualGUID(riid, IID_IWebViewPrivate))
1913 *ppvObject = static_cast<IWebViewPrivate*>(this);
1914 else if (IsEqualGUID(riid, IID_IWebIBActions))
1915 *ppvObject = static_cast<IWebIBActions*>(this);
1916 else if (IsEqualGUID(riid, IID_IWebViewCSS))
1917 *ppvObject = static_cast<IWebViewCSS*>(this);
1918 else if (IsEqualGUID(riid, IID_IWebViewEditing))
1919 *ppvObject = static_cast<IWebViewEditing*>(this);
1920 else if (IsEqualGUID(riid, IID_IWebViewUndoableEditing))
1921 *ppvObject = static_cast<IWebViewUndoableEditing*>(this);
1922 else if (IsEqualGUID(riid, IID_IWebViewEditingActions))
1923 *ppvObject = static_cast<IWebViewEditingActions*>(this);
1924 else if (IsEqualGUID(riid, IID_IWebNotificationObserver))
1925 *ppvObject = static_cast<IWebNotificationObserver*>(this);
1926 else if (IsEqualGUID(riid, IID_IDropTarget))
1927 *ppvObject = static_cast<IDropTarget*>(this);
1929 return E_NOINTERFACE;
1935 ULONG STDMETHODCALLTYPE WebView::AddRef(void)
1937 return ++m_refCount;
1940 ULONG STDMETHODCALLTYPE WebView::Release(void)
1942 ULONG newRef = --m_refCount;
1949 // IWebView --------------------------------------------------------------------
1951 HRESULT STDMETHODCALLTYPE WebView::canShowMIMEType(
1952 /* [in] */ BSTR mimeType,
1953 /* [retval][out] */ BOOL* canShow)
1955 String mimeTypeStr(mimeType, SysStringLen(mimeType));
1960 *canShow = MIMETypeRegistry::isSupportedImageMIMEType(mimeTypeStr) ||
1961 MIMETypeRegistry::isSupportedNonImageMIMEType(mimeTypeStr) ||
1962 PlugInInfoStore::supportsMIMEType(mimeTypeStr);
1967 HRESULT STDMETHODCALLTYPE WebView::canShowMIMETypeAsHTML(
1968 /* [in] */ BSTR /*mimeType*/,
1969 /* [retval][out] */ BOOL* canShow)
1976 HRESULT STDMETHODCALLTYPE WebView::MIMETypesShownAsHTML(
1977 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
1979 ASSERT_NOT_REACHED();
1983 HRESULT STDMETHODCALLTYPE WebView::setMIMETypesShownAsHTML(
1984 /* [size_is][in] */ BSTR* /*mimeTypes*/,
1985 /* [in] */ int /*cMimeTypes*/)
1987 ASSERT_NOT_REACHED();
1991 HRESULT STDMETHODCALLTYPE WebView::URLFromPasteboard(
1992 /* [in] */ IDataObject* /*pasteboard*/,
1993 /* [retval][out] */ BSTR* /*url*/)
1995 ASSERT_NOT_REACHED();
1999 HRESULT STDMETHODCALLTYPE WebView::URLTitleFromPasteboard(
2000 /* [in] */ IDataObject* /*pasteboard*/,
2001 /* [retval][out] */ BSTR* /*urlTitle*/)
2003 ASSERT_NOT_REACHED();
2007 HRESULT STDMETHODCALLTYPE WebView::initWithFrame(
2008 /* [in] */ RECT frame,
2009 /* [in] */ BSTR frameName,
2010 /* [in] */ BSTR groupName)
2017 registerWebViewWindowClass();
2019 if (!::IsWindow(m_hostWindow)) {
2020 ASSERT_NOT_REACHED();
2024 m_viewWindow = CreateWindowEx(0, kWebViewWindowClassName, 0, WS_CHILD | WS_CLIPCHILDREN,
2025 frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, m_hostWindow, 0, gInstance, 0);
2026 ASSERT(::IsWindow(m_viewWindow));
2028 hr = registerDragDrop();
2032 WebPreferences* sharedPreferences = WebPreferences::sharedStandardPreferences();
2033 sharedPreferences->willAddToWebView();
2034 m_preferences = sharedPreferences;
2036 m_groupName = String(groupName, SysStringLen(groupName));
2038 WebKitSetWebDatabasesPathIfNecessary();
2040 m_page = new Page(new WebChromeClient(this), new WebContextMenuClient(this), new WebEditorClient(this), new WebDragClient(this), new WebInspectorClient(this));
2043 COMPtr<IWebUIDelegate2> uiDelegate2;
2044 if (SUCCEEDED(m_uiDelegate->QueryInterface(IID_IWebUIDelegate2, (void**)&uiDelegate2))) {
2046 if (SUCCEEDED(uiDelegate2->ftpDirectoryTemplatePath(this, &path))) {
2047 m_page->settings()->setFTPDirectoryTemplatePath(String(path, SysStringLen(path)));
2048 SysFreeString(path);
2053 WebFrame* webFrame = WebFrame::createInstance();
2054 webFrame->initWithWebFrameView(0 /*FIXME*/, this, m_page, 0);
2055 m_mainFrame = webFrame;
2056 webFrame->Release(); // The WebFrame is owned by the Frame, so release our reference to it.
2058 m_page->mainFrame()->tree()->setName(String(frameName, SysStringLen(frameName)));
2059 m_page->mainFrame()->init();
2060 m_page->setGroupName(m_groupName);
2062 addToAllWebViewsSet();
2064 #pragma warning(suppress: 4244)
2065 SetWindowLongPtr(m_viewWindow, 0, (LONG_PTR)this);
2066 ShowWindow(m_viewWindow, SW_SHOW);
2068 initializeToolTipWindow();
2070 IWebNotificationCenter* notifyCenter = WebNotificationCenter::defaultCenterInternal();
2071 notifyCenter->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2072 m_preferences->postPreferencesChangesNotification();
2074 setSmartInsertDeleteEnabled(TRUE);
2078 static bool initCommonControls()
2080 static bool haveInitialized = false;
2081 if (haveInitialized)
2084 INITCOMMONCONTROLSEX init;
2085 init.dwSize = sizeof(init);
2086 init.dwICC = ICC_TREEVIEW_CLASSES;
2087 haveInitialized = !!::InitCommonControlsEx(&init);
2088 return haveInitialized;
2091 void WebView::initializeToolTipWindow()
2093 if (!initCommonControls())
2096 m_toolTipHwnd = CreateWindowEx(0, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
2097 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
2098 m_viewWindow, 0, 0, 0);
2102 TOOLINFO info = {0};
2103 info.cbSize = sizeof(info);
2104 info.uFlags = TTF_IDISHWND | TTF_SUBCLASS ;
2105 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2107 ::SendMessage(m_toolTipHwnd, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info));
2108 ::SendMessage(m_toolTipHwnd, TTM_SETMAXTIPWIDTH, 0, maxToolTipWidth);
2110 ::SetWindowPos(m_toolTipHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
2113 void WebView::setToolTip(const String& toolTip)
2118 if (toolTip == m_toolTip)
2121 m_toolTip = toolTip;
2123 if (!m_toolTip.isEmpty()) {
2124 TOOLINFO info = {0};
2125 info.cbSize = sizeof(info);
2126 info.uFlags = TTF_IDISHWND;
2127 info.uId = reinterpret_cast<UINT_PTR>(m_viewWindow);
2128 info.lpszText = const_cast<UChar*>(m_toolTip.charactersWithNullTermination());
2129 ::SendMessage(m_toolTipHwnd, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info));
2132 ::SendMessage(m_toolTipHwnd, TTM_ACTIVATE, !m_toolTip.isEmpty(), 0);
2135 HRESULT WebView::notifyDidAddIcon(IWebNotification* notification)
2137 COMPtr<IPropertyBag> propertyBag;
2138 HRESULT hr = notification->userInfo(&propertyBag);
2144 COMPtr<CFDictionaryPropertyBag> dictionaryPropertyBag;
2145 hr = propertyBag->QueryInterface(&dictionaryPropertyBag);
2149 CFDictionaryRef dictionary = dictionaryPropertyBag->dictionary();
2153 CFTypeRef value = CFDictionaryGetValue(dictionary, WebIconDatabase::iconDatabaseNotificationUserInfoURLKey());
2156 if (CFGetTypeID(value) != CFStringGetTypeID())
2159 String mainFrameURL;
2161 mainFrameURL = m_mainFrame->url().string();
2163 if (!mainFrameURL.isEmpty() && mainFrameURL == String((CFStringRef)value))
2164 dispatchDidReceiveIconFromWebFrame(m_mainFrame);
2169 void WebView::registerForIconNotification(bool listen)
2171 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2173 nc->addObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2175 nc->removeObserver(this, WebIconDatabase::iconDatabaseDidAddIconNotification(), 0);
2178 void WebView::dispatchDidReceiveIconFromWebFrame(WebFrame* frame)
2180 registerForIconNotification(false);
2182 if (m_frameLoadDelegate)
2183 // FIXME: <rdar://problem/5491010> - Pass in the right HBITMAP.
2184 m_frameLoadDelegate->didReceiveIcon(this, 0, frame);
2187 HRESULT STDMETHODCALLTYPE WebView::setUIDelegate(
2188 /* [in] */ IWebUIDelegate* d)
2192 if (m_uiDelegatePrivate)
2193 m_uiDelegatePrivate = 0;
2196 if (FAILED(d->QueryInterface(IID_IWebUIDelegatePrivate, (void**)&m_uiDelegatePrivate)))
2197 m_uiDelegatePrivate = 0;
2203 HRESULT STDMETHODCALLTYPE WebView::uiDelegate(
2204 /* [out][retval] */ IWebUIDelegate** d)
2209 return m_uiDelegate.copyRefTo(d);
2212 HRESULT STDMETHODCALLTYPE WebView::setResourceLoadDelegate(
2213 /* [in] */ IWebResourceLoadDelegate* d)
2215 m_resourceLoadDelegate = d;
2219 HRESULT STDMETHODCALLTYPE WebView::resourceLoadDelegate(
2220 /* [out][retval] */ IWebResourceLoadDelegate** d)
2222 if (!m_resourceLoadDelegate)
2225 return m_resourceLoadDelegate.copyRefTo(d);
2228 HRESULT STDMETHODCALLTYPE WebView::setDownloadDelegate(
2229 /* [in] */ IWebDownloadDelegate* d)
2231 m_downloadDelegate = d;
2235 HRESULT STDMETHODCALLTYPE WebView::downloadDelegate(
2236 /* [out][retval] */ IWebDownloadDelegate** d)
2238 if (!m_downloadDelegate)
2241 return m_downloadDelegate.copyRefTo(d);
2244 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegate(
2245 /* [in] */ IWebFrameLoadDelegate* d)
2247 m_frameLoadDelegate = d;
2251 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegate(
2252 /* [out][retval] */ IWebFrameLoadDelegate** d)
2254 if (!m_frameLoadDelegate)
2257 return m_frameLoadDelegate.copyRefTo(d);
2260 HRESULT STDMETHODCALLTYPE WebView::setPolicyDelegate(
2261 /* [in] */ IWebPolicyDelegate* d)
2263 m_policyDelegate = d;
2267 HRESULT STDMETHODCALLTYPE WebView::policyDelegate(
2268 /* [out][retval] */ IWebPolicyDelegate** d)
2270 if (!m_policyDelegate)
2272 return m_policyDelegate.copyRefTo(d);
2275 HRESULT STDMETHODCALLTYPE WebView::mainFrame(
2276 /* [out][retval] */ IWebFrame** frame)
2279 ASSERT_NOT_REACHED();
2283 *frame = m_mainFrame;
2287 m_mainFrame->AddRef();
2291 HRESULT STDMETHODCALLTYPE WebView::focusedFrame(
2292 /* [out][retval] */ IWebFrame** frame)
2295 ASSERT_NOT_REACHED();
2300 Frame* f = m_page->focusController()->focusedFrame();
2304 WebFrame* webFrame = kit(f);
2308 return webFrame->QueryInterface(IID_IWebFrame, (void**) frame);
2310 HRESULT STDMETHODCALLTYPE WebView::backForwardList(
2311 /* [out][retval] */ IWebBackForwardList** list)
2313 if (!m_useBackForwardList)
2316 *list = WebBackForwardList::createInstance(m_page->backForwardList());
2321 HRESULT STDMETHODCALLTYPE WebView::setMaintainsBackForwardList(
2322 /* [in] */ BOOL flag)
2324 m_useBackForwardList = !!flag;
2328 HRESULT STDMETHODCALLTYPE WebView::goBack(
2329 /* [retval][out] */ BOOL* succeeded)
2331 *succeeded = m_page->goBack();
2335 HRESULT STDMETHODCALLTYPE WebView::goForward(
2336 /* [retval][out] */ BOOL* succeeded)
2338 *succeeded = m_page->goForward();
2342 HRESULT STDMETHODCALLTYPE WebView::goToBackForwardItem(
2343 /* [in] */ IWebHistoryItem* item,
2344 /* [retval][out] */ BOOL* succeeded)
2348 COMPtr<WebHistoryItem> webHistoryItem;
2349 HRESULT hr = item->QueryInterface(&webHistoryItem);
2353 m_page->goToItem(webHistoryItem->historyItem(), FrameLoadTypeIndexedBackForward);
2359 HRESULT STDMETHODCALLTYPE WebView::setTextSizeMultiplier(
2360 /* [in] */ float multiplier)
2362 if (m_textSizeMultiplier != multiplier)
2363 m_textSizeMultiplier = multiplier;
2368 m_mainFrame->setTextSizeMultiplier(multiplier);
2372 HRESULT STDMETHODCALLTYPE WebView::textSizeMultiplier(
2373 /* [retval][out] */ float* multiplier)
2375 *multiplier = m_textSizeMultiplier;
2379 HRESULT STDMETHODCALLTYPE WebView::setApplicationNameForUserAgent(
2380 /* [in] */ BSTR applicationName)
2382 m_applicationName = String(applicationName, SysStringLen(applicationName));
2383 m_userAgentStandard = String();
2387 HRESULT STDMETHODCALLTYPE WebView::applicationNameForUserAgent(
2388 /* [retval][out] */ BSTR* applicationName)
2390 *applicationName = SysAllocStringLen(m_applicationName.characters(), m_applicationName.length());
2391 if (!*applicationName && m_applicationName.length())
2392 return E_OUTOFMEMORY;
2396 HRESULT STDMETHODCALLTYPE WebView::setCustomUserAgent(
2397 /* [in] */ BSTR userAgentString)
2399 m_userAgentOverridden = userAgentString;
2400 m_userAgentCustom = String(userAgentString, SysStringLen(userAgentString));
2404 HRESULT STDMETHODCALLTYPE WebView::customUserAgent(
2405 /* [retval][out] */ BSTR* userAgentString)
2407 *userAgentString = 0;
2408 if (!m_userAgentOverridden)
2410 *userAgentString = SysAllocStringLen(m_userAgentCustom.characters(), m_userAgentCustom.length());
2411 if (!*userAgentString && m_userAgentCustom.length())
2412 return E_OUTOFMEMORY;
2416 HRESULT STDMETHODCALLTYPE WebView::userAgentForURL(
2417 /* [in] */ BSTR url,
2418 /* [retval][out] */ BSTR* userAgent)
2420 DeprecatedString urlStr((DeprecatedChar*)url, SysStringLen(url));
2421 String userAgentString = this->userAgentForKURL(KURL(urlStr));
2422 *userAgent = SysAllocStringLen(userAgentString.characters(), userAgentString.length());
2423 if (!*userAgent && userAgentString.length())
2424 return E_OUTOFMEMORY;
2428 HRESULT STDMETHODCALLTYPE WebView::supportsTextEncoding(
2429 /* [retval][out] */ BOOL* supports)
2435 HRESULT STDMETHODCALLTYPE WebView::setCustomTextEncodingName(
2436 /* [in] */ BSTR encodingName)
2443 hr = customTextEncodingName(&oldEncoding);
2447 if (oldEncoding != encodingName && (!oldEncoding || !encodingName || _tcscmp(oldEncoding, encodingName))) {
2448 if (Frame* coreFrame = core(m_mainFrame))
2449 coreFrame->loader()->reloadAllowingStaleData(String(encodingName, SysStringLen(encodingName)));
2455 HRESULT STDMETHODCALLTYPE WebView::customTextEncodingName(
2456 /* [retval][out] */ BSTR* encodingName)
2459 COMPtr<IWebDataSource> dataSource;
2460 COMPtr<WebDataSource> dataSourceImpl;
2466 if (FAILED(m_mainFrame->provisionalDataSource(&dataSource)) || !dataSource) {
2467 hr = m_mainFrame->dataSource(&dataSource);
2468 if (FAILED(hr) || !dataSource)
2472 hr = dataSource->QueryInterface(IID_WebDataSource, (void**)&dataSourceImpl);
2476 BString str = dataSourceImpl->documentLoader()->overrideEncoding();
2481 *encodingName = SysAllocStringLen(m_overrideEncoding.characters(), m_overrideEncoding.length());
2483 if (!*encodingName && m_overrideEncoding.length())
2484 return E_OUTOFMEMORY;
2489 HRESULT STDMETHODCALLTYPE WebView::setMediaStyle(
2490 /* [in] */ BSTR /*media*/)
2492 ASSERT_NOT_REACHED();
2496 HRESULT STDMETHODCALLTYPE WebView::mediaStyle(
2497 /* [retval][out] */ BSTR* /*media*/)
2499 ASSERT_NOT_REACHED();
2503 HRESULT STDMETHODCALLTYPE WebView::stringByEvaluatingJavaScriptFromString(
2504 /* [in] */ BSTR script, // assumes input does not have "JavaScript" at the begining.
2505 /* [retval][out] */ BSTR* result)
2508 ASSERT_NOT_REACHED();
2514 Frame* coreFrame = core(m_mainFrame);
2518 KJS::JSValue* scriptExecutionResult = coreFrame->loader()->executeScript(WebCore::String(script), true);
2519 if(!scriptExecutionResult)
2521 else if (scriptExecutionResult->isString()) {
2523 *result = BString(String(scriptExecutionResult->getString()));
2529 HRESULT STDMETHODCALLTYPE WebView::windowScriptObject(
2530 /* [retval][out] */ IWebScriptObject** /*webScriptObject*/)
2532 ASSERT_NOT_REACHED();
2536 HRESULT STDMETHODCALLTYPE WebView::setPreferences(
2537 /* [in] */ IWebPreferences* prefs)
2540 prefs = WebPreferences::sharedStandardPreferences();
2542 if (m_preferences == prefs)
2545 COMPtr<WebPreferences> webPrefs(Query, prefs);
2547 return E_NOINTERFACE;
2548 webPrefs->willAddToWebView();
2550 COMPtr<WebPreferences> oldPrefs = m_preferences;
2552 IWebNotificationCenter* nc = WebNotificationCenter::defaultCenterInternal();
2553 nc->removeObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2555 BSTR identifierBSTR = 0;
2556 HRESULT hr = oldPrefs->identifier(&identifierBSTR);
2557 oldPrefs->didRemoveFromWebView();
2558 oldPrefs = 0; // Make sure we release the reference, since WebPreferences::removeReferenceForIdentifier will check for last reference to WebPreferences
2559 if (SUCCEEDED(hr)) {
2561 identifier.adoptBSTR(identifierBSTR);
2562 WebPreferences::removeReferenceForIdentifier(identifier);
2565 m_preferences = webPrefs;
2567 nc->addObserver(this, WebPreferences::webPreferencesChangedNotification(), static_cast<IWebPreferences*>(m_preferences.get()));
2569 m_preferences->postPreferencesChangesNotification();
2574 HRESULT STDMETHODCALLTYPE WebView::preferences(
2575 /* [retval][out] */ IWebPreferences** prefs)
2579 *prefs = m_preferences.get();
2581 m_preferences->AddRef();
2585 HRESULT STDMETHODCALLTYPE WebView::setPreferencesIdentifier(
2586 /* [in] */ BSTR /*anIdentifier*/)
2588 ASSERT_NOT_REACHED();
2592 HRESULT STDMETHODCALLTYPE WebView::preferencesIdentifier(
2593 /* [retval][out] */ BSTR* /*anIdentifier*/)
2595 ASSERT_NOT_REACHED();
2599 HRESULT STDMETHODCALLTYPE WebView::setHostWindow(
2600 /* [in] */ OLE_HANDLE oleWindow)
2602 HWND window = (HWND)(ULONG64)oleWindow;
2603 if (m_viewWindow && window)
2604 SetParent(m_viewWindow, window);
2606 m_hostWindow = window;
2611 HRESULT STDMETHODCALLTYPE WebView::hostWindow(
2612 /* [retval][out] */ OLE_HANDLE* window)
2614 *window = (OLE_HANDLE)(ULONG64)m_hostWindow;
2619 static Frame *incrementFrame(Frame *curr, bool forward, bool wrapFlag)
2622 ? curr->tree()->traverseNextWithWrap(wrapFlag)
2623 : curr->tree()->traversePreviousWithWrap(wrapFlag);
2626 HRESULT STDMETHODCALLTYPE WebView::searchFor(
2627 /* [in] */ BSTR str,
2628 /* [in] */ BOOL forward,
2629 /* [in] */ BOOL caseFlag,
2630 /* [in] */ BOOL wrapFlag,
2631 /* [retval][out] */ BOOL* found)
2634 return E_INVALIDARG;
2636 if (!m_page || !m_page->mainFrame())
2637 return E_UNEXPECTED;
2639 if (!str || !SysStringLen(str))
2640 return E_INVALIDARG;
2642 String search(str, SysStringLen(str));
2645 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
2646 WebCore::Frame* startFrame = frame;
2648 *found = frame->findString(search, !!forward, !!caseFlag, false, true);
2650 if (frame != startFrame)
2651 startFrame->selectionController()->clear();
2652 m_page->focusController()->setFocusedFrame(frame);
2655 frame = incrementFrame(frame, !!forward, !!wrapFlag);
2656 } while (frame && frame != startFrame);
2658 // Search contents of startFrame, on the other side of the selection that we did earlier.
2659 // We cheat a bit and just research with wrap on
2660 if (wrapFlag && !startFrame->selectionController()->isNone()) {
2661 *found = startFrame->findString(search, !!forward, !!caseFlag, true, true);
2662 m_page->focusController()->setFocusedFrame(frame);
2668 HRESULT STDMETHODCALLTYPE WebView::updateActiveState()
2670 Frame* frame = m_page->mainFrame();
2672 HWND window = ::GetAncestor(m_viewWindow, GA_ROOT);
2673 HWND activeWindow = ::GetActiveWindow();
2674 bool windowIsKey = window == activeWindow;
2675 activeWindow = ::GetAncestor(activeWindow, GA_ROOTOWNER);
2677 bool windowOrSheetIsKey = windowIsKey || (window == activeWindow);
2679 frame->setIsActive(windowIsKey);
2681 Frame* focusedFrame = m_page->focusController()->focusedOrMainFrame();
2682 frame->setWindowHasFocus(frame == focusedFrame && windowOrSheetIsKey);
2687 HRESULT STDMETHODCALLTYPE WebView::executeCoreCommandByName(BSTR bName, BSTR bValue)
2689 String name(bName, SysStringLen(bName));
2690 String value(bValue, SysStringLen(bValue));
2692 m_page->focusController()->focusedOrMainFrame()->editor()->command(name).execute(value);
2697 HRESULT STDMETHODCALLTYPE WebView::markAllMatchesForText(
2698 BSTR str, BOOL caseSensitive, BOOL highlight, UINT limit, UINT* matches)
2701 return E_INVALIDARG;
2703 if (!m_page || !m_page->mainFrame())
2704 return E_UNEXPECTED;
2706 if (!str || !SysStringLen(str))
2707 return E_INVALIDARG;
2709 String search(str, SysStringLen(str));
2712 WebCore::Frame* frame = m_page->mainFrame();
2714 frame->setMarkedTextMatchesAreHighlighted(!!highlight);
2715 *matches += frame->markAllMatchesForText(search, !!caseSensitive, (limit == 0)? 0 : (limit - *matches));
2716 frame = incrementFrame(frame, true, false);
2723 HRESULT STDMETHODCALLTYPE WebView::unmarkAllTextMatches()
2725 if (!m_page || !m_page->mainFrame())
2726 return E_UNEXPECTED;
2728 WebCore::Frame* frame = m_page->mainFrame();
2730 if (Document* document = frame->document())
2731 document->removeMarkers(DocumentMarker::TextMatch);
2732 frame = incrementFrame(frame, true, false);
2739 HRESULT STDMETHODCALLTYPE WebView::rectsForTextMatches(
2740 IEnumTextMatches** pmatches)
2742 Vector<IntRect> allRects;
2743 WebCore::Frame* frame = m_page->mainFrame();
2745 if (Document* document = frame->document()) {
2746 IntRect visibleRect = enclosingIntRect(frame->view()->visibleContentRect());
2747 Vector<IntRect> frameRects = document->renderedRectsForMarkers(DocumentMarker::TextMatch);
2748 IntPoint frameOffset(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
2749 frameOffset = frame->view()->convertToContainingWindow(frameOffset);
2751 Vector<IntRect>::iterator end = frameRects.end();
2752 for (Vector<IntRect>::iterator it = frameRects.begin(); it < end; it++) {
2753 it->intersect(visibleRect);
2754 it->move(frameOffset.x(), frameOffset.y());
2755 allRects.append(*it);
2758 frame = incrementFrame(frame, true, false);
2761 return createMatchEnumerator(&allRects, pmatches);
2764 HRESULT STDMETHODCALLTYPE WebView::generateSelectionImage(BOOL forceWhiteText, OLE_HANDLE* hBitmap)
2768 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
2771 HBITMAP bitmap = imageFromSelection(frame, forceWhiteText ? TRUE : FALSE);
2772 *hBitmap = (OLE_HANDLE)(ULONG64)bitmap;
2778 HRESULT STDMETHODCALLTYPE WebView::selectionRect(RECT* rc)
2780 WebCore::Frame* frame = m_page->focusController()->focusedOrMainFrame();
2783 IntRect ir = enclosingIntRect(frame->selectionRect());
2784 ir = frame->view()->convertToContainingWindow(ir);
2785 ir.move(-frame->view()->scrollOffset().width(), -frame->view()->scrollOffset().height());
2788 rc->bottom = rc->top + ir.height();
2789 rc->right = rc->left + ir.width();
2795 HRESULT STDMETHODCALLTYPE WebView::registerViewClass(
2796 /* [in] */ IWebDocumentView* /*view*/,
2797 /* [in] */ IWebDocumentRepresentation* /*representation*/,
2798 /* [in] */ BSTR /*forMIMEType*/)
2800 ASSERT_NOT_REACHED();
2804 HRESULT STDMETHODCALLTYPE WebView::setGroupName(
2805 /* [in] */ BSTR groupName)
2807 m_groupName = String(groupName, SysStringLen(groupName));
2811 HRESULT STDMETHODCALLTYPE WebView::groupName(
2812 /* [retval][out] */ BSTR* groupName)
2814 *groupName = SysAllocStringLen(m_groupName.characters(), m_groupName.length());
2815 if (!*groupName && m_groupName.length())
2816 return E_OUTOFMEMORY;
2820 HRESULT STDMETHODCALLTYPE WebView::estimatedProgress(
2821 /* [retval][out] */ double* estimatedProgress)
2823 *estimatedProgress = m_page->progress()->estimatedProgress();
2827 HRESULT STDMETHODCALLTYPE WebView::isLoading(
2828 /* [retval][out] */ BOOL* isLoading)
2830 COMPtr<IWebDataSource> dataSource;
2831 COMPtr<IWebDataSource> provisionalDataSource;
2838 if (SUCCEEDED(m_mainFrame->dataSource(&dataSource)))
2839 dataSource->isLoading(isLoading);
2844 if (SUCCEEDED(m_mainFrame->provisionalDataSource(&provisionalDataSource)))
2845 provisionalDataSource->isLoading(isLoading);
2849 HRESULT STDMETHODCALLTYPE WebView::elementAtPoint(
2850 /* [in] */ LPPOINT point,
2851 /* [retval][out] */ IPropertyBag** elementDictionary)
2853 if (!elementDictionary) {
2854 ASSERT_NOT_REACHED();
2858 *elementDictionary = 0;
2860 Frame* frame = core(m_mainFrame);
2864 IntPoint webCorePoint = IntPoint(point->x, point->y);
2865 HitTestResult result = HitTestResult(webCorePoint);
2866 if (frame->renderer())
2867 result = frame->eventHandler()->hitTestResultAtPoint(webCorePoint, false);
2868 *elementDictionary = WebElementPropertyBag::createInstance(result);
2872 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForSelection(
2873 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
2875 ASSERT_NOT_REACHED();
2879 HRESULT STDMETHODCALLTYPE WebView::writeSelectionWithPasteboardTypes(
2880 /* [size_is][in] */ BSTR* /*types*/,
2881 /* [in] */ int /*cTypes*/,
2882 /* [in] */ IDataObject* /*pasteboard*/)
2884 ASSERT_NOT_REACHED();
2888 HRESULT STDMETHODCALLTYPE WebView::pasteboardTypesForElement(
2889 /* [in] */ IPropertyBag* /*elementDictionary*/,
2890 /* [retval][out] */ IEnumVARIANT** /*enumVariant*/)
2892 ASSERT_NOT_REACHED();
2896 HRESULT STDMETHODCALLTYPE WebView::writeElement(
2897 /* [in] */ IPropertyBag* /*elementDictionary*/,
2898 /* [size_is][in] */ BSTR* /*withPasteboardTypes*/,
2899 /* [in] */ int /*cWithPasteboardTypes*/,
2900 /* [in] */ IDataObject* /*pasteboard*/)
2902 ASSERT_NOT_REACHED();
2906 HRESULT STDMETHODCALLTYPE WebView::selectedText(
2907 /* [out, retval] */ BSTR* text)
2910 ASSERT_NOT_REACHED();
2916 Frame* focusedFrame = (m_page && m_page->focusController()) ? m_page->focusController()->focusedOrMainFrame() : 0;
2920 String frameSelectedText = focusedFrame->selectedText();
2921 *text = SysAllocStringLen(frameSelectedText.characters(), frameSelectedText.length());
2922 if (!*text && frameSelectedText.length())
2923 return E_OUTOFMEMORY;
2927 HRESULT STDMETHODCALLTYPE WebView::centerSelectionInVisibleArea(
2928 /* [in] */ IUnknown* /* sender */)
2930 Frame* coreFrame = core(m_mainFrame);
2934 coreFrame->revealSelection(RenderLayer::gAlignCenterAlways);
2939 HRESULT STDMETHODCALLTYPE WebView::moveDragCaretToPoint(
2940 /* [in] */ LPPOINT /*point*/)
2942 ASSERT_NOT_REACHED();
2946 HRESULT STDMETHODCALLTYPE WebView::removeDragCaret( void)
2948 ASSERT_NOT_REACHED();
2952 HRESULT STDMETHODCALLTYPE WebView::setDrawsBackground(
2953 /* [in] */ BOOL /*drawsBackground*/)
2955 ASSERT_NOT_REACHED();
2959 HRESULT STDMETHODCALLTYPE WebView::drawsBackground(
2960 /* [retval][out] */ BOOL* /*drawsBackground*/)
2962 ASSERT_NOT_REACHED();
2966 HRESULT STDMETHODCALLTYPE WebView::setMainFrameURL(
2967 /* [in] */ BSTR /*urlString*/)
2969 ASSERT_NOT_REACHED();
2973 HRESULT STDMETHODCALLTYPE WebView::mainFrameURL(
2974 /* [retval][out] */ BSTR* /*urlString*/)
2976 ASSERT_NOT_REACHED();
2980 HRESULT STDMETHODCALLTYPE WebView::mainFrameDocument(
2981 /* [retval][out] */ IDOMDocument** document)
2987 return m_mainFrame->DOMDocument(document);
2990 HRESULT STDMETHODCALLTYPE WebView::mainFrameTitle(
2991 /* [retval][out] */ BSTR* /*title*/)
2993 ASSERT_NOT_REACHED();
2997 HRESULT STDMETHODCALLTYPE WebView::mainFrameIcon(
2998 /* [retval][out] */ OLE_HANDLE* /*hBitmap*/)
3000 ASSERT_NOT_REACHED();
3004 HRESULT STDMETHODCALLTYPE WebView::registerURLSchemeAsLocal(
3005 /* [in] */ BSTR scheme)
3010 FrameLoader::registerURLSchemeAsLocal(String(scheme, ::SysStringLen(scheme)));
3015 // IWebIBActions ---------------------------------------------------------------
3017 HRESULT STDMETHODCALLTYPE WebView::takeStringURLFrom(
3018 /* [in] */ IUnknown* /*sender*/)
3020 ASSERT_NOT_REACHED();
3024 HRESULT STDMETHODCALLTYPE WebView::stopLoading(
3025 /* [in] */ IUnknown* /*sender*/)
3030 return m_mainFrame->stopLoading();
3033 HRESULT STDMETHODCALLTYPE WebView::reload(
3034 /* [in] */ IUnknown* /*sender*/)
3039 return m_mainFrame->reload();
3042 HRESULT STDMETHODCALLTYPE WebView::canGoBack(
3043 /* [in] */ IUnknown* /*sender*/,
3044 /* [retval][out] */ BOOL* result)
3046 *result = !!m_page->backForwardList()->backItem();
3050 HRESULT STDMETHODCALLTYPE WebView::goBack(
3051 /* [in] */ IUnknown* /*sender*/)
3053 ASSERT_NOT_REACHED();
3057 HRESULT STDMETHODCALLTYPE WebView::canGoForward(
3058 /* [in] */ IUnknown* /*sender*/,
3059 /* [retval][out] */ BOOL* result)
3061 *result = !!m_page->backForwardList()->forwardItem();
3065 HRESULT STDMETHODCALLTYPE WebView::goForward(
3066 /* [in] */ IUnknown* /*sender*/)
3068 ASSERT_NOT_REACHED();
3072 #define MinimumTextSizeMultiplier 0.5f
3073 #define MaximumTextSizeMultiplier 3.0f
3074 #define TextSizeMultiplierRatio 1.2f
3076 HRESULT STDMETHODCALLTYPE WebView::canMakeTextLarger(
3077 /* [in] */ IUnknown* /*sender*/,
3078 /* [retval][out] */ BOOL* result)
3080 bool canGrowMore = m_textSizeMultiplier*TextSizeMultiplierRatio < MaximumTextSizeMultiplier;
3081 *result = canGrowMore ? TRUE : FALSE;
3085 HRESULT STDMETHODCALLTYPE WebView::makeTextLarger(
3086 /* [in] */ IUnknown* /*sender*/)
3088 float newScale = m_textSizeMultiplier*TextSizeMultiplierRatio;
3089 bool canGrowMore = newScale < MaximumTextSizeMultiplier;
3092 return setTextSizeMultiplier(newScale);
3096 HRESULT STDMETHODCALLTYPE WebView::canMakeTextSmaller(
3097 /* [in] */ IUnknown* /*sender*/,
3098 /* [retval][out] */ BOOL* result)
3100 bool canShrinkMore = m_textSizeMultiplier/TextSizeMultiplierRatio > MinimumTextSizeMultiplier;
3101 *result = canShrinkMore ? TRUE : FALSE;
3105 HRESULT STDMETHODCALLTYPE WebView::makeTextSmaller(
3106 /* [in] */ IUnknown* /*sender*/)
3108 float newScale = m_textSizeMultiplier/TextSizeMultiplierRatio;
3109 bool canShrinkMore = newScale > MinimumTextSizeMultiplier;
3112 return setTextSizeMultiplier(newScale);
3115 HRESULT STDMETHODCALLTYPE WebView::canMakeTextStandardSize(
3116 /* [in] */ IUnknown* /*sender*/,
3117 /* [retval][out] */ BOOL* result)
3119 bool notAlreadyStandard = m_textSizeMultiplier != 1.0f;
3120 *result = notAlreadyStandard ? TRUE : FALSE;
3124 HRESULT STDMETHODCALLTYPE WebView::makeTextStandardSize(
3125 /* [in] */ IUnknown* /*sender*/)
3127 bool notAlreadyStandard = m_textSizeMultiplier != 1.0f;
3128 if (notAlreadyStandard)
3129 return setTextSizeMultiplier(1.0f);
3133 HRESULT STDMETHODCALLTYPE WebView::toggleContinuousSpellChecking(
3134 /* [in] */ IUnknown* /*sender*/)
3138 if (FAILED(hr = isContinuousSpellCheckingEnabled(&enabled)))
3140 return setContinuousSpellCheckingEnabled(enabled ? FALSE : TRUE);
3143 HRESULT STDMETHODCALLTYPE WebView::toggleSmartInsertDelete(
3144 /* [in] */ IUnknown* /*sender*/)
3146 BOOL enabled = FALSE;
3147 HRESULT hr = smartInsertDeleteEnabled(&enabled);
3151 return setSmartInsertDeleteEnabled(enabled ? FALSE : TRUE);
3154 HRESULT STDMETHODCALLTYPE WebView::toggleGrammarChecking(
3155 /* [in] */ IUnknown* /*sender*/)
3158 HRESULT hr = isGrammarCheckingEnabled(&enabled);
3162 return setGrammarCheckingEnabled(enabled ? FALSE : TRUE);
3165 // IWebViewCSS -----------------------------------------------------------------
3167 HRESULT STDMETHODCALLTYPE WebView::computedStyleForElement(
3168 /* [in] */ IDOMElement* /*element*/,
3169 /* [in] */ BSTR /*pseudoElement*/,
3170 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3172 ASSERT_NOT_REACHED();
3176 // IWebViewEditing -------------------------------------------------------------
3178 HRESULT STDMETHODCALLTYPE WebView::editableDOMRangeForPoint(
3179 /* [in] */ LPPOINT /*point*/,
3180 /* [retval][out] */ IDOMRange** /*range*/)
3182 ASSERT_NOT_REACHED();
3186 HRESULT STDMETHODCALLTYPE WebView::setSelectedDOMRange(
3187 /* [in] */ IDOMRange* /*range*/,
3188 /* [in] */ WebSelectionAffinity /*affinity*/)
3190 ASSERT_NOT_REACHED();
3194 HRESULT STDMETHODCALLTYPE WebView::selectedDOMRange(
3195 /* [retval][out] */ IDOMRange** /*range*/)
3197 ASSERT_NOT_REACHED();
3201 HRESULT STDMETHODCALLTYPE WebView::selectionAffinity(
3202 /* [retval][out][retval][out] */ WebSelectionAffinity* /*affinity*/)
3204 ASSERT_NOT_REACHED();
3208 HRESULT STDMETHODCALLTYPE WebView::setEditable(
3209 /* [in] */ BOOL /*flag*/)
3211 ASSERT_NOT_REACHED();
3215 HRESULT STDMETHODCALLTYPE WebView::isEditable(
3216 /* [retval][out] */ BOOL* /*isEditable*/)
3218 ASSERT_NOT_REACHED();
3222 HRESULT STDMETHODCALLTYPE WebView::setTypingStyle(
3223 /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
3225 ASSERT_NOT_REACHED();
3229 HRESULT STDMETHODCALLTYPE WebView::typingStyle(
3230 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3232 ASSERT_NOT_REACHED();
3236 HRESULT STDMETHODCALLTYPE WebView::setSmartInsertDeleteEnabled(
3237 /* [in] */ BOOL flag)
3239 m_smartInsertDeleteEnabled = !!flag;
3243 HRESULT STDMETHODCALLTYPE WebView::smartInsertDeleteEnabled(
3244 /* [retval][out] */ BOOL* enabled)
3246 *enabled = m_smartInsertDeleteEnabled ? TRUE : FALSE;
3250 HRESULT STDMETHODCALLTYPE WebView::setContinuousSpellCheckingEnabled(
3251 /* [in] */ BOOL flag)
3253 if (continuousSpellCheckingEnabled != !!flag) {
3254 continuousSpellCheckingEnabled = !!flag;
3255 COMPtr<IWebPreferences> prefs;
3256 if (SUCCEEDED(preferences(&prefs)))
3257 prefs->setContinuousSpellCheckingEnabled(flag);
3260 BOOL spellCheckingEnabled;
3261 if (SUCCEEDED(isContinuousSpellCheckingEnabled(&spellCheckingEnabled)) && spellCheckingEnabled)
3262 preflightSpellChecker();
3264 m_mainFrame->unmarkAllMisspellings();
3269 HRESULT STDMETHODCALLTYPE WebView::isContinuousSpellCheckingEnabled(
3270 /* [retval][out] */ BOOL* enabled)
3272 *enabled = (continuousSpellCheckingEnabled && continuousCheckingAllowed()) ? TRUE : FALSE;
3276 HRESULT STDMETHODCALLTYPE WebView::spellCheckerDocumentTag(
3277 /* [retval][out] */ int* tag)
3279 // we just use this as a flag to indicate that we've spell checked the document
3280 // and need to close the spell checker out when the view closes.
3282 m_hasSpellCheckerDocumentTag = true;
3286 static COMPtr<IWebEditingDelegate> spellingDelegateForTimer;
3288 static void preflightSpellCheckerNow()
3290 spellingDelegateForTimer->preflightChosenSpellServer();
3291 spellingDelegateForTimer = 0;
3294 static void CALLBACK preflightSpellCheckerTimerCallback(HWND, UINT, UINT_PTR id, DWORD)
3297 preflightSpellCheckerNow();
3300 void WebView::preflightSpellChecker()
3302 // As AppKit does, we wish to delay tickling the shared spellchecker into existence on application launch.
3303 if (!m_editingDelegate)
3307 spellingDelegateForTimer = m_editingDelegate;
3308 if (SUCCEEDED(m_editingDelegate->sharedSpellCheckerExists(&exists)) && exists)
3309 preflightSpellCheckerNow();
3311 ::SetTimer(0, 0, 2000, preflightSpellCheckerTimerCallback);
3314 bool WebView::continuousCheckingAllowed()
3316 static bool allowContinuousSpellChecking = true;
3317 static bool readAllowContinuousSpellCheckingDefault = false;
3318 if (!readAllowContinuousSpellCheckingDefault) {
3319 COMPtr<IWebPreferences> prefs;
3320 if (SUCCEEDED(preferences(&prefs))) {
3322 prefs->allowContinuousSpellChecking(&allowed);
3323 allowContinuousSpellChecking = !!allowed;
3325 readAllowContinuousSpellCheckingDefault = true;
3327 return allowContinuousSpellChecking;
3330 HRESULT STDMETHODCALLTYPE WebView::undoManager(
3331 /* [retval][out] */ IWebUndoManager** /*manager*/)
3333 ASSERT_NOT_REACHED();
3337 HRESULT STDMETHODCALLTYPE WebView::setEditingDelegate(
3338 /* [in] */ IWebEditingDelegate* d)
3340 m_editingDelegate = d;
3344 HRESULT STDMETHODCALLTYPE WebView::editingDelegate(
3345 /* [retval][out] */ IWebEditingDelegate** d)
3348 ASSERT_NOT_REACHED();
3352 *d = m_editingDelegate.get();
3360 HRESULT STDMETHODCALLTYPE WebView::styleDeclarationWithText(
3361 /* [in] */ BSTR /*text*/,
3362 /* [retval][out] */ IDOMCSSStyleDeclaration** /*style*/)
3364 ASSERT_NOT_REACHED();
3368 HRESULT STDMETHODCALLTYPE WebView::hasSelectedRange(
3369 /* [retval][out] */ BOOL* hasSelectedRange)
3371 *hasSelectedRange = m_page->mainFrame()->selectionController()->isRange();
3375 HRESULT STDMETHODCALLTYPE WebView::cutEnabled(
3376 /* [retval][out] */ BOOL* enabled)
3378 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3379 *enabled = editor->canCut() || editor->canDHTMLCut();
3383 HRESULT STDMETHODCALLTYPE WebView::copyEnabled(
3384 /* [retval][out] */ BOOL* enabled)
3386 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3387 *enabled = editor->canCopy() || editor->canDHTMLCopy();
3391 HRESULT STDMETHODCALLTYPE WebView::pasteEnabled(
3392 /* [retval][out] */ BOOL* enabled)
3394 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3395 *enabled = editor->canPaste() || editor->canDHTMLPaste();
3399 HRESULT STDMETHODCALLTYPE WebView::deleteEnabled(
3400 /* [retval][out] */ BOOL* enabled)
3402 *enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canDelete();
3406 HRESULT STDMETHODCALLTYPE WebView::editingEnabled(
3407 /* [retval][out] */ BOOL* enabled)
3409 *enabled = m_page->focusController()->focusedOrMainFrame()->editor()->canEdit();
3413 HRESULT STDMETHODCALLTYPE WebView::isGrammarCheckingEnabled(
3414 /* [retval][out] */ BOOL* enabled)
3416 *enabled = grammarCheckingEnabled ? TRUE : FALSE;
3420 HRESULT STDMETHODCALLTYPE WebView::setGrammarCheckingEnabled(
3423 if (!m_editingDelegate) {
3424 LOG_ERROR("No NSSpellChecker");
3428 if (grammarCheckingEnabled == !!enabled)
3431 grammarCheckingEnabled = !!enabled;
3432 COMPtr<IWebPreferences> prefs;
3433 if (SUCCEEDED(preferences(&prefs)))
3434 prefs->setGrammarCheckingEnabled(enabled);
3436 m_editingDelegate->updateGrammar();
3438 // We call _preflightSpellChecker when turning continuous spell checking on, but we don't need to do that here
3439 // because grammar checking only occurs on code paths that already preflight spell checking appropriately.
3441 BOOL grammarEnabled;
3442 if (SUCCEEDED(isGrammarCheckingEnabled(&grammarEnabled)) && !grammarEnabled)
3443 m_mainFrame->unmarkAllBadGrammar();
3448 // IWebViewUndoableEditing -----------------------------------------------------
3450 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithNode(
3451 /* [in] */ IDOMNode* /*node*/)
3453 ASSERT_NOT_REACHED();
3457 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithText(
3458 /* [in] */ BSTR text)
3460 String textString(text, ::SysStringLen(text));
3461 Position start = m_page->mainFrame()->selectionController()->selection().start();
3462 m_page->focusController()->focusedOrMainFrame()->editor()->insertText(textString, 0);
3463 m_page->mainFrame()->selectionController()->setBase(start);
3467 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithMarkupString(
3468 /* [in] */ BSTR /*markupString*/)
3470 ASSERT_NOT_REACHED();
3474 HRESULT STDMETHODCALLTYPE WebView::replaceSelectionWithArchive(
3475 /* [in] */ IWebArchive* /*archive*/)
3477 ASSERT_NOT_REACHED();
3481 HRESULT STDMETHODCALLTYPE WebView::deleteSelection( void)
3483 Editor* editor = m_page->focusController()->focusedOrMainFrame()->editor();
3484 editor->deleteSelectionWithSmartDelete(editor->canSmartCopyOrDelete());
3488 HRESULT STDMETHODCALLTYPE WebView::clearSelection( void)
3490 m_page->focusController()->focusedOrMainFrame()->selectionController()->clear();
3494 HRESULT STDMETHODCALLTYPE WebView::applyStyle(
3495 /* [in] */ IDOMCSSStyleDeclaration* /*style*/)
3497 ASSERT_NOT_REACHED();
3501 // IWebViewEditingActions ------------------------------------------------------
3503 HRESULT STDMETHODCALLTYPE WebView::copy(
3504 /* [in] */ IUnknown* /*sender*/)
3506 m_page->focusController()->focusedOrMainFrame()->editor()->command("Copy").execute();
3510 HRESULT STDMETHODCALLTYPE WebView::cut(
3511 /* [in] */ IUnknown* /*sender*/)
3513 m_page->focusController()->focusedOrMainFrame()->editor()->command("Cut").execute();
3517 HRESULT STDMETHODCALLTYPE WebView::paste(
3518 /* [in] */ IUnknown* /*sender*/)
3520 m_page->focusController()->focusedOrMainFrame()->editor()->command("Paste").execute();
3524 HRESULT STDMETHODCALLTYPE WebView::copyURL(
3525 /* [in] */ BSTR url)
3527 String temp(url, SysStringLen(url));
3528 m_page->focusController()->focusedOrMainFrame()->editor()->copyURL(KURL(temp.deprecatedString()), "");
3533 HRESULT STDMETHODCALLTYPE WebView::copyFont(
3534 /* [in] */ IUnknown* /*sender*/)
3536 ASSERT_NOT_REACHED();
3540 HRESULT STDMETHODCALLTYPE WebView::pasteFont(
3541 /* [in] */ IUnknown* /*sender*/)
3543 ASSERT_NOT_REACHED();
3547 HRESULT STDMETHODCALLTYPE WebView::delete_(
3548 /* [in] */ IUnknown* /*sender*/)
3550 m_page->focusController()->focusedOrMainFrame()->editor()->command("Delete").execute();
3554 HRESULT STDMETHODCALLTYPE WebView::pasteAsPlainText(
3555 /* [in] */ IUnknown* /*sender*/)
3557 ASSERT_NOT_REACHED();
3561 HRESULT STDMETHODCALLTYPE WebView::pasteAsRichText(
3562 /* [in] */ IUnknown* /*sender*/)
3564 ASSERT_NOT_REACHED();
3568 HRESULT STDMETHODCALLTYPE WebView::changeFont(
3569 /* [in] */ IUnknown* /*sender*/)
3571 ASSERT_NOT_REACHED();
3575 HRESULT STDMETHODCALLTYPE WebView::changeAttributes(
3576 /* [in] */ IUnknown* /*sender*/)
3578 ASSERT_NOT_REACHED();
3582 HRESULT STDMETHODCALLTYPE WebView::changeDocumentBackgroundColor(
3583 /* [in] */ IUnknown* /*sender*/)
3585 ASSERT_NOT_REACHED();
3589 HRESULT STDMETHODCALLTYPE WebView::changeColor(
3590 /* [in] */ IUnknown* /*sender*/)
3592 ASSERT_NOT_REACHED();
3596 HRESULT STDMETHODCALLTYPE WebView::alignCenter(
3597 /* [in] */ IUnknown* /*sender*/)
3599 ASSERT_NOT_REACHED();
3603 HRESULT STDMETHODCALLTYPE WebView::alignJustified(
3604 /* [in] */ IUnknown* /*sender*/)
3606 ASSERT_NOT_REACHED();
3610 HRESULT STDMETHODCALLTYPE WebView::alignLeft(
3611 /* [in] */ IUnknown* /*sender*/)
3613 ASSERT_NOT_REACHED();
3617 HRESULT STDMETHODCALLTYPE WebView::alignRight(
3618 /* [in] */ IUnknown* /*sender*/)
3620 ASSERT_NOT_REACHED();
3624 HRESULT STDMETHODCALLTYPE WebView::checkSpelling(
3625 /* [in] */ IUnknown* /*sender*/)
3627 if (!m_editingDelegate) {
3628 LOG_ERROR("No NSSpellChecker");
3632 core(m_mainFrame)->editor()->advanceToNextMisspelling();
3636 HRESULT STDMETHODCALLTYPE WebView::showGuessPanel(
3637 /* [in] */ IUnknown* /*sender*/)
3639 if (!m_editingDelegate) {
3640 LOG_ERROR("No NSSpellChecker");
3644 // Post-Tiger, this menu item is a show/hide toggle, to match AppKit. Leave Tiger behavior alone
3645 // to match rest of OS X.
3647 if (SUCCEEDED(m_editingDelegate->spellingUIIsShowing(&showing)) && showing) {
3648 m_editingDelegate->showSpellingUI(FALSE);
3651 core(m_mainFrame)->editor()->advanceToNextMisspelling(true);
3652 m_editingDelegate->showSpellingUI(TRUE);
3656 HRESULT STDMETHODCALLTYPE WebView::performFindPanelAction(
3657 /* [in] */ IUnknown* /*sender*/)
3659 ASSERT_NOT_REACHED();
3663 HRESULT STDMETHODCALLTYPE WebView::startSpeaking(
3664 /* [in] */ IUnknown* /*sender*/)
3666 ASSERT_NOT_REACHED();
3670 HRESULT STDMETHODCALLTYPE WebView::stopSpeaking(
3671 /* [in] */ IUnknown* /*sender*/)
3673 ASSERT_NOT_REACHED();
3677 // IWebNotificationObserver -----------------------------------------------------------------
3679 HRESULT STDMETHODCALLTYPE WebView::onNotify(
3680 /* [in] */ IWebNotification* notification)
3683 HRESULT hr = notification->name(&nameBSTR);
3688 name.adoptBSTR(nameBSTR);
3690 if (!wcscmp(name, WebIconDatabase::iconDatabaseDidAddIconNotification()))
3691 return notifyDidAddIcon(notification);
3693 if (!wcscmp(name, WebPreferences::webPreferencesChangedNotification()))
3694 return notifyPreferencesChanged(notification);
3699 HRESULT WebView::notifyPreferencesChanged(IWebNotification* notification)
3703 COMPtr<IUnknown> unkPrefs;
3704 hr = notification->getObject(&unkPrefs);
3708 COMPtr<IWebPreferences> preferences(Query, unkPrefs);
3710 return E_NOINTERFACE;
3712 ASSERT(preferences == m_preferences);
3718 Settings* settings = m_page->settings();
3720 hr = preferences->cursiveFontFamily(&str);
3723 settings->setCursiveFontFamily(AtomicString(str, SysStringLen(str)));
3726 hr = preferences->defaultFixedFontSize(&size);
3729 settings->setDefaultFixedFontSize(size);
3731 hr = preferences->defaultFontSize(&size);
3734 settings->setDefaultFontSize(size);
3736 hr = preferences->defaultTextEncodingName(&str);
3739 settings->setDefaultTextEncodingName(String(str, SysStringLen(str)));
3742 hr = preferences->fantasyFontFamily(&str);
3745 settings->setFantasyFontFamily(AtomicString(str, SysStringLen(str)));
3748 hr = preferences->fixedFontFamily(&str);
3751 settings->setFixedFontFamily(AtomicString(str, SysStringLen(str)));
3754 hr = preferences->isJavaEnabled(&enabled);
3757 settings->setJavaEnabled(!!enabled);
3759 hr = preferences->isJavaScriptEnabled(&enabled);
3762 settings->setJavaScriptEnabled(!!enabled);
3764 hr = preferences->javaScriptCanOpenWindowsAutomatically(&enabled);
3767 settings->setJavaScriptCanOpenWindowsAutomatically(!!enabled);
3769 hr = preferences->minimumFontSize(&size);
3772 settings->setMinimumFontSize(size);
3774 hr = preferences->minimumLogicalFontSize(&size);
3777 settings->setMinimumLogicalFontSize(size);
3779 hr = preferences->arePlugInsEnabled(&enabled);
3782 settings->setPluginsEnabled(!!enabled);
3784 hr = preferences->privateBrowsingEnabled(&enabled);
3787 settings->setPrivateBrowsingEnabled(!!enabled);
3789 hr = preferences->sansSerifFontFamily(&str);
3792 settings->setSansSerifFontFamily(AtomicString(str, SysStringLen(str)));
3795 hr = preferences->serifFontFamily(&str);
3798 settings->setSerifFontFamily(AtomicString(str, SysStringLen(str)));
3801 hr = preferences->standardFontFamily(&str);
3804 settings->setStandardFontFamily(AtomicString(str, SysStringLen(str)));
3807 hr = preferences->loadsImagesAutomatically(&enabled);
3810 settings->setLoadsImagesAutomatically(!!enabled);
3812 hr = preferences->userStyleSheetEnabled(&enabled);
3816 hr = preferences->userStyleSheetLocation(&str);
3820 RetainPtr<CFStringRef> urlString(AdoptCF, String(str, SysStringLen(str)).createCFString());
3821 RetainPtr<CFURLRef> url(AdoptCF, CFURLCreateWithString(kCFAllocatorDefault, urlString.get(), 0));
3823 // Check if the passed in string is a path and convert it to a URL.
3824 // FIXME: This is a workaround for nightly builds until we can get Safari to pass
3825 // in an URL here. See <rdar://problem/5478378>
3827 DWORD len = SysStringLen(str) + 1;
3829 int result = WideCharToMultiByte(CP_UTF8, 0, str, len, 0, 0, 0, 0);
3830 Vector<UInt8> utf8Path(result);
3831 if (!WideCharToMultiByte(CP_UTF8, 0, str, len, (LPSTR)utf8Path.data(), result, 0, 0))
3834 url.adoptCF(CFURLCreateFromFileSystemRepresentation(0, utf8Path.data(), result - 1, false));
3837 settings->setUserStyleSheetLocation(url.get());
3840 settings->setUserStyleSheetLocation(KURL(DeprecatedString("")));
3843 hr = preferences->shouldPrintBackgrounds(&enabled);
3846 settings->setShouldPrintBackgrounds(!!enabled);
3848 hr = preferences->textAreasAreResizable(&enabled);
3851 settings->setTextAreasAreResizable(!!enabled);
3853 WebKitEditableLinkBehavior behavior;
3854 hr = preferences->editableLinkBehavior(&behavior);
3857 settings->setEditableLinkBehavior((EditableLinkBehavior)behavior);
3859 hr = preferences->usesPageCache(&enabled);
3862 settings->setUsesPageCache(!!enabled);
3864 hr = preferences->isDOMPasteAllowed(&enabled);
3867 settings->setDOMPasteAllowed(!!enabled);
3869 settings->setShowsURLsInToolTips(false);
3870 settings->setForceFTPDirectoryListings(true);
3871 settings->setDeveloperExtrasEnabled(developerExtrasEnabled());
3873 FontSmoothingType smoothingType;
3874 hr = preferences->fontSmoothing(&smoothingType);
3877 settings->setFontRenderingMode(smoothingType != FontSmoothingTypeWindows ? NormalRenderingMode : AlternateRenderingMode);
3879 COMPtr<IWebPreferencesPrivate> prefsPrivate(Query, preferences);
3881 unsigned long long defaultQuota = 0;
3882 hr = prefsPrivate->defaultDatabaseQuota(&defaultQuota);
3885 settings->setDefaultDatabaseOriginQuota(defaultQuota);
3887 hr = prefsPrivate->authorAndUserStylesEnabled(&enabled);
3890 settings->setAuthorAndUserStylesEnabled(enabled);
3893 m_mainFrame->invalidate(); // FIXME
3895 hr = updateSharedSettingsFromPreferencesIfNeeded(preferences.get());
3902 HRESULT updateSharedSettingsFromPreferencesIfNeeded(IWebPreferences* preferences)
3904 if (preferences != WebPreferences::sharedStandardPreferences())
3907 WebKitCookieStorageAcceptPolicy acceptPolicy;
3908 HRESULT hr = preferences->cookieStorageAcceptPolicy(&acceptPolicy);
3912 // Set cookie storage accept policy
3913 if (CFHTTPCookieStorageRef defaultCookieStorage = wkGetDefaultHTTPCookieStorage())
3914 CFHTTPCookieStorageSetCookieAcceptPolicy(defaultCookieStorage, acceptPolicy);
3919 // IWebViewPrivate ------------------------------------------------------------
3921 HRESULT STDMETHODCALLTYPE WebView::setCustomDropTarget(
3922 /* [in] */ IDropTarget* dt)
3924 ASSERT(::IsWindow(m_viewWindow));
3927 m_hasCustomDropTarget = true;
3929 return ::RegisterDragDrop(m_viewWindow,dt);
3932 HRESULT STDMETHODCALLTYPE WebView::removeCustomDropTarget()
3934 if (!m_hasCustomDropTarget)
3936 m_hasCustomDropTarget = false;
3938 return registerDragDrop();
3941 HRESULT STDMETHODCALLTYPE WebView::setInViewSourceMode(
3942 /* [in] */ BOOL flag)
3947 return m_mainFrame->setInViewSourceMode(flag);
3950 HRESULT STDMETHODCALLTYPE WebView::inViewSourceMode(
3951 /* [retval][out] */ BOOL* flag)
3956 return m_mainFrame->inViewSourceMode(flag);
3959 HRESULT STDMETHODCALLTYPE WebView::viewWindow(
3960 /* [retval][out] */ OLE_HANDLE *window)
3962 *window = (OLE_HANDLE)(ULONG64)m_viewWindow;
3966 HRESULT STDMETHODCALLTYPE WebView::setFormDelegate(
3967 /* [in] */ IWebFormDelegate *formDelegate)
3969 m_formDelegate = formDelegate;
3973 HRESULT STDMETHODCALLTYPE WebView::formDelegate(
3974 /* [retval][out] */ IWebFormDelegate **formDelegate)
3976 if (!m_formDelegate)
3979 return m_formDelegate.copyRefTo(formDelegate);
3982 HRESULT STDMETHODCALLTYPE WebView::setFrameLoadDelegatePrivate(
3983 /* [in] */ IWebFrameLoadDelegatePrivate* d)
3985 m_frameLoadDelegatePrivate = d;
3989 HRESULT STDMETHODCALLTYPE WebView::frameLoadDelegatePrivate(
3990 /* [out][retval] */ IWebFrameLoadDelegatePrivate** d)
3992 if (!m_frameLoadDelegatePrivate)
3995 return m_frameLoadDelegatePrivate.copyRefTo(d);
3998 HRESULT STDMETHODCALLTYPE WebView::scrollOffset(
3999 /* [retval][out] */ LPPOINT offset)
4003 IntSize offsetIntSize = m_page->mainFrame()->view()->scrollOffset();
4004 offset->x = offsetIntSize.width();
4005 offset->y = offsetIntSize.height();
4009 HRESULT STDMETHODCALLTYPE WebView::scrollBy(
4010 /* [in] */ LPPOINT offset)
4014 m_page->mainFrame()->view()->scrollBy(offset->x, offset->y);
4018 HRESULT STDMETHODCALLTYPE WebView::visibleContentRect(
4019 /* [retval][out] */ LPRECT rect)
4023 FloatRect visibleContent = m_page->mainFrame()->view()->visibleContentRect();
4024 rect->left = (LONG) visibleContent.x();
4025 rect->top = (LONG) visibleContent.y();
4026 rect->right = (LONG) visibleContent.right();
4027 rect->bottom = (LONG) visibleContent.bottom();
4031 static DWORD dragOperationToDragCursor(DragOperation op) {
4032 DWORD res = DROPEFFECT_NONE;
4033 if (op & DragOperationCopy)
4034 res = DROPEFFECT_COPY;
4035 else if (op & DragOperationLink)
4036 res = DROPEFFECT_LINK;
4037 else if (op & DragOperationMove)
4038 res = DROPEFFECT_MOVE;
4039 else if (op & DragOperationGeneric)
4040 res = DROPEFFECT_MOVE; //This appears to be the Firefox behaviour
4044 static DragOperation keyStateToDragOperation(DWORD) {
4045 //FIXME: This is currently very simple, it may need to actually
4046 //work out an appropriate DragOperation in future -- however this
4047 //behaviour appears to match FireFox
4048 return (DragOperation)(DragOperationCopy | DragOperationLink);
4051 HRESULT STDMETHODCALLTYPE WebView::DragEnter(
4052 IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
4056 if (m_dropTargetHelper)
4057 m_dropTargetHelper->DragEnter(m_viewWindow, pDataObject, (POINT*)&pt, *pdwEffect);
4059 POINTL localpt = pt;
4060 ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
4061 DragData data(pDataObject, IntPoint(localpt.x, localpt.y),
4062 IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
4063 *pdwEffect = dragOperationToDragCursor(m_page->dragController()->dragEntered(&data));
4065 m_dragData = pDataObject;
4070 HRESULT STDMETHODCALLTYPE WebView::DragOver(
4071 DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
4073 if (m_dropTargetHelper)
4074 m_dropTargetHelper->DragOver((POINT*)&pt, *pdwEffect);
4077 POINTL localpt = pt;
4078 ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
4079 DragData data(m_dragData.get(), IntPoint(localpt.x, localpt.y),
4080 IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
4081 *pdwEffect = dragOperationToDragCursor(m_page->dragController()->dragUpdated(&data));
4083 *pdwEffect = DROPEFFECT_NONE;
4088 HRESULT STDMETHODCALLTYPE WebView::DragLeave()
4090 if (m_dropTargetHelper)
4091 m_dropTargetHelper->DragLeave();
4094 DragData data(m_dragData.get(), IntPoint(), IntPoint(),
4096 m_page->dragController()->dragExited(&data);
4102 HRESULT STDMETHODCALLTYPE WebView::Drop(
4103 IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
4105 if (m_dropTargetHelper)
4106 m_dropTargetHelper->Drop(pDataObject, (POINT*)&pt, *pdwEffect);
4109 *pdwEffect = DROPEFFECT_NONE;
4110 POINTL localpt = pt;
4111 ::ScreenToClient(m_viewWindow, (LPPOINT)&localpt);
4112 DragData data(pDataObject, IntPoint(localpt.x, localpt.y),
4113 IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState));
4114 m_page->dragController()->performDrag(&data);
4118 HRESULT STDMETHODCALLTYPE WebView::canHandleRequest(
4119 IWebURLRequest *request,
4122 COMPtr<WebMutableURLRequest> requestImpl;
4124 HRESULT hr = request->QueryInterface(&requestImpl);
4128 *result = !!canHandleRequest(requestImpl->resourceRequest());
4132 HRESULT STDMETHODCALLTYPE WebView::clearFocusNode()
4134 if (m_page && m_page->focusController())
4135 m_page->focusController()->setFocusedNode(0, 0);
4139 HRESULT STDMETHODCALLTYPE WebView::setInitialFocus(
4140 /* [in] */ BOOL forward)
4142 if (m_page && m_page->focusController()) {
4143 Frame* frame = m_page->focusController()->focusedOrMainFrame();
4144 frame->document()->setFocusedNode(0);
4145 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
4150 HRESULT STDMETHODCALLTYPE WebView::setTabKeyCyclesThroughElements(
4151 /* [in] */ BOOL cycles)
4154 m_page->setTabKeyCyclesThroughElements(!!cycles);
4159 HRESULT STDMETHODCALLTYPE WebView::tabKeyCyclesThroughElements(
4160 /* [retval][out] */ BOOL* result)
4163 ASSERT_NOT_REACHED();
4167 *result = m_page && m_page->tabKeyCyclesThroughElements() ? TRUE : FALSE;
4171 HRESULT STDMETHODCALLTYPE WebView::setAllowSiteSpecificHacks(
4172 /* [in] */ BOOL allow)
4174 s_allowSiteSpecificHacks = !!allow;
4178 HRESULT STDMETHODCALLTYPE WebView::addAdditionalPluginPath(
4179 /* [in] */ BSTR path)
4181 PluginDatabaseWin::installedPlugins()->addExtraPluginPath(String(path, SysStringLen(path)));
4185 HRESULT STDMETHODCALLTYPE WebView::loadBackForwardListFromOtherView(
4186 /* [in] */ IWebView* otherView)
4191 // It turns out the right combination of behavior is done with the back/forward load
4192 // type. (See behavior matrix at the top of WebFramePrivate.) So we copy all the items
4193 // in the back forward list, and go to the current one.
4194 BackForwardList* backForwardList = m_page->backForwardList();
4195 ASSERT(!backForwardList->currentItem()); // destination list should be empty
4197 COMPtr<WebView> otherWebView;
4198 if (FAILED(otherView->QueryInterface(&otherWebView)))
4200 BackForwardList* otherBackForwardList = otherWebView->m_page->backForwardList();
4201 if (!otherBackForwardList->currentItem())
4202 return S_OK; // empty back forward list, bail
4204 HistoryItem* newItemToGoTo = 0;
4206 int lastItemIndex = otherBackForwardList->forwardListCount();
4207 for (int i = -otherBackForwardList->backListCount(); i <= lastItemIndex; ++i) {
4209 // If this item is showing , save away its current scroll and form state,
4210 // since that might have changed since loading and it is normally not saved
4211 // until we leave that page.
4212 otherWebView->m_page->mainFrame()->loader()->saveDocumentAndScrollState();
4214 RefPtr<HistoryItem> newItem = otherBackForwardList->itemAtIndex(i)->copy();
4216 newItemToGoTo = newItem.get();
4217 backForwardList->addItem(newItem.release());
4220 ASSERT(newItemToGoTo);
4221 m_page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
4225 HRESULT STDMETHODCALLTYPE WebView::clearUndoRedoOperations()
4227 if (Frame* frame = m_page->focusController()->focusedOrMainFrame())
4228 frame->editor()->clearUndoRedoOperations();
4232 HRESULT STDMETHODCALLTYPE WebView::shouldClose(
4233 /* [retval][out] */ BOOL* result)
4236 ASSERT_NOT_REACHED();
4241 if (Frame* frame = m_page->focusController()->focusedOrMainFrame())
4242 *result = frame->shouldClose() ? TRUE : FALSE;
4246 HRESULT WebView::registerDragDrop()
4248 ASSERT(::IsWindow(m_viewWindow));
4249 return ::RegisterDragDrop(m_viewWindow, this);
4252 HRESULT WebView::revokeDragDrop()
4254 ASSERT(::IsWindow(m_viewWindow));
4255 return ::RevokeDragDrop(m_viewWindow);
4258 HRESULT WebView::setProhibitsMainFrameScrolling(BOOL b)
4263 m_page->mainFrame()->setProhibitsScrolling(b);
4267 HRESULT WebView::setShouldApplyMacFontAscentHack(BOOL b)
4269 SimpleFontData::setShouldApplyMacAscentHack(b);
4274 typedef HIMC (CALLBACK *getContextPtr)(HWND);
4275 typedef BOOL (CALLBACK *releaseContextPtr)(HWND, HIMC);
4276 typedef LONG (CALLBACK *getCompositionStringPtr)(HIMC, DWORD, LPVOID, DWORD);
4277 typedef BOOL (CALLBACK *setCandidateWindowPtr)(HIMC, LPCANDIDATEFORM);
4278 typedef BOOL (CALLBACK *setOpenStatusPtr)(HIMC, BOOL);
4279 typedef BOOL (CALLBACK *notifyIMEPtr)(HIMC, DWORD, DWORD, DWORD);
4280 typedef BOOL (CALLBACK *associateContextExPtr)(HWND, HIMC, DWORD);
4283 getContextPtr getContext;
4284 releaseContextPtr releaseContext;
4285 getCompositionStringPtr getCompositionString;
4286 setCandidateWindowPtr setCandidateWindow;
4287 setOpenStatusPtr setOpenStatus;
4288 notifyIMEPtr notifyIME;
4289 associateContextExPtr associateContextEx;
4291 static const IMMDict& dict();
4297 const IMMDict& IMMDict::dict()
4299 static IMMDict instance;
4305 m_instance = ::LoadLibrary(TEXT("IMM32.DLL"));
4306 getContext = reinterpret_cast<getContextPtr>(::GetProcAddress(m_instance, "ImmGetContext"));
4308 releaseContext = reinterpret_cast<releaseContextPtr>(::GetProcAddress(m_instance, "ImmReleaseContext"));
4309 ASSERT(releaseContext);
4310 getCompositionString = reinterpret_cast<getCompositionStringPtr>(::GetProcAddress(m_instance, "ImmGetCompositionStringW"));
4311 ASSERT(getCompositionString);
4312 setCandidateWindow = reinterpret_cast<setCandidateWindowPtr>(::GetProcAddress(m_instance, "ImmSetCandidateWindow"));
4313 ASSERT(setCandidateWindow);
4314 setOpenStatus = reinterpret_cast<setOpenStatusPtr>(::GetProcAddress(m_instance, "ImmSetOpenStatus"));
4315 ASSERT(setOpenStatus);
4316 notifyIME = reinterpret_cast<notifyIMEPtr>(::GetProcAddress(m_instance, "ImmNotifyIME"));
4318 associateContextEx = reinterpret_cast<associateContextExPtr>(::GetProcAddress(m_instance, "ImmAssociateContextEx"));
4319 ASSERT(associateContextEx);
4322 HIMC WebView::getIMMContext()
4324 HIMC context = IMMDict::dict().getContext(m_viewWindow);
4328 void WebView::releaseIMMContext(HIMC hIMC)
4332 IMMDict::dict().releaseContext(m_viewWindow, hIMC);
4335 void WebView::prepareCandidateWindow(Frame* targetFrame, HIMC hInputContext)
4338 if (RefPtr<Range> range = targetFrame->selectionController()->selection().toRange()) {
4339 ExceptionCode ec = 0;
4340 RefPtr<Range> tempRange = range->cloneRange(ec);
4341 caret = targetFrame->firstRectForRange(tempRange.get());
4343 caret = targetFrame->view()->contentsToWindow(caret);
4346 form.dwStyle = CFS_EXCLUDE;
4347 form.ptCurrentPos.x = caret.x();
4348 form.ptCurrentPos.y = caret.y() + caret.height();
4349 form.rcArea.top = caret.y();
4350 form.rcArea.bottom = caret.bottom();
4351 form.rcArea.left = caret.x();
4352 form.rcArea.right = caret.right();
4353 IMMDict::dict().setCandidateWindow(hInputContext, &form);
4356 void WebView::resetIME(Frame* targetFrame)
4359 targetFrame->editor()->confirmCompositionWithoutDisturbingSelection();
4361 if (HIMC hInputContext = getIMMContext()) {
4362 IMMDict::dict().notifyIME(hInputContext, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
4363 releaseIMMContext(hInputContext);
4367 void WebView::updateSelectionForIME()
4369 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
4370 if (!targetFrame || !targetFrame->editor()->hasComposition())
4373 if (targetFrame->editor()->ignoreCompositionSelectionChange())
4378 if (!targetFrame->editor()->getCompositionSelection(start, end))
4379 resetIME(targetFrame);
4382 void WebView::setInputMethodState(bool enabled)
4384 IMMDict::dict().associateContextEx(m_viewWindow, 0, enabled ? IACE_DEFAULT : 0);
4387 void WebView::selectionChanged()
4389 updateSelectionForIME();
4392 bool WebView::onIMEStartComposition()
4394 m_inIMEComposition++;
4395 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
4399 HIMC hInputContext = getIMMContext();
4400 prepareCandidateWindow(targetFrame, hInputContext);
4401 releaseIMMContext(hInputContext);
4405 static bool getCompositionString(HIMC hInputContext, DWORD type, String& result)
4407 int compositionLength = IMMDict::dict().getCompositionString(hInputContext, type, 0, 0);
4408 if (compositionLength <= 0)
4410 Vector<UChar> compositionBuffer(compositionLength / 2);
4411 compositionLength = IMMDict::dict().getCompositionString(hInputContext, type, (LPVOID)compositionBuffer.data(), compositionLength);
4412 result = String(compositionBuffer.data(), compositionLength / 2);
4413 ASSERT(!compositionLength || compositionBuffer[0]);
4414 ASSERT(!compositionLength || compositionBuffer[compositionLength / 2 - 1]);
4418 static void compositionToUnderlines(const Vector<DWORD>& clauses, const Vector<BYTE>& attributes, Vector<CompositionUnderline>& underlines)
4420 if (clauses.isEmpty()) {
4425 const size_t numBoundaries = clauses.size() - 1;
4426 underlines.resize(numBoundaries);
4427 for (unsigned i = 0; i < numBoundaries; i++) {
4428 underlines[i].startOffset = clauses[i];
4429 underlines[i].endOffset = clauses[i + 1];
4430 BYTE attribute = attributes[clauses[i]];
4431 underlines[i].thick = attribute == ATTR_TARGET_CONVERTED || attribute == ATTR_TARGET_NOTCONVERTED;
4432 underlines[i].color = Color(0,0,0);
4436 bool WebView::onIMEComposition(LPARAM lparam)
4438 HIMC hInputContext = getIMMContext();
4442 Frame* targetFrame = m_page->focusController()->focusedOrMainFrame();
4443 if (!targetFrame || !targetFrame->editor()->canEdit())
4446 prepareCandidateWindow(targetFrame, hInputContext);
4448 if (lparam & GCS_RESULTSTR || !lparam) {
4449 String compositionString;
4450 if (!getCompositionString(hInputContext, GCS_RESULTSTR, compositionString) && lparam)
4453 targetFrame->editor()->confirmComposition(compositionString);
4455 String compositionString;
4456 if (!getCompositionString(hInputContext, GCS_COMPSTR, compositionString))
4459 // Composition string attributes
4460 int numAttributes = IMMDict::dict().getCompositionString(hInputContext, GCS_COMPATTR, 0, 0);
4461 Vector<BYTE> attributes(numAttributes);
4462 IMMDict::dict().getCompositionString(hInputContext, GCS_COMPATTR, attributes.data(), numAttributes);
4465 int numClauses = IMMDict::dict().getCompositionString(hInputContext, GCS_COMPCLAUSE, 0, 0);
4466 Vector<DWORD> clauses(numClauses / sizeof(DWORD));