WebViewImpl.cpp 91.9 KB
Newer Older
1
/*
2
 * Copyright (C) 2010 Google Inc. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WebViewImpl.h"

34
#include "AutofillPopupMenuClient.h"
35
#include "AXObjectCache.h"
36
#include "BackForwardListChromium.h"
37
#include "CCThreadImpl.h"
38 39
#include "CSSStyleSelector.h"
#include "CSSValueKeywords.h"
aroben@apple.com's avatar
aroben@apple.com committed
40
#include "Chrome.h"
41
#include "ColorSpace.h"
42
#include "CompositionUnderlineVectorBuilder.h"
43 44 45
#include "ContextMenu.h"
#include "ContextMenuController.h"
#include "ContextMenuItem.h"
46
#include "Cursor.h"
47
#include "DOMUtilitiesPrivate.h"
48
#include "DeviceOrientationClientProxy.h"
49 50 51
#include "Document.h"
#include "DocumentLoader.h"
#include "DragController.h"
52
#include "DragData.h"
53
#include "DragScrollTimer.h"
54 55
#include "Editor.h"
#include "EventHandler.h"
56
#include "Extensions3D.h"
57 58 59
#include "FocusController.h"
#include "FontDescription.h"
#include "FrameLoader.h"
60
#include "FrameSelection.h"
61 62
#include "FrameTree.h"
#include "FrameView.h"
63
#include "GeolocationClientProxy.h"
64
#include "GraphicsContext.h"
65
#include "GraphicsContext3D.h"
66
#include "GraphicsContext3DPrivate.h"
67 68
#include "HTMLInputElement.h"
#include "HTMLMediaElement.h"
69
#include "HTMLNames.h"
70
#include "HTMLTextAreaElement.h"
71
#include "HitTestResult.h"
72
#include "Image.h"
73
#include "ImageBuffer.h"
74 75 76
#include "InspectorController.h"
#include "KeyboardCodes.h"
#include "KeyboardEvent.h"
77
#include "LayerChromium.h"
78
#include "LayerPainterChromium.h"
79 80
#include "MIMETypeRegistry.h"
#include "NodeRenderStyle.h"
81
#include "NonCompositedContentHost.h"
82 83
#include "Page.h"
#include "PageGroup.h"
84
#include "PageGroupLoadDeferrer.h"
85 86 87 88
#include "Pasteboard.h"
#include "PlatformContextSkia.h"
#include "PlatformKeyboardEvent.h"
#include "PlatformMouseEvent.h"
89
#include "PlatformThemeChromiumGtk.h"
90
#include "PlatformWheelEvent.h"
91
#include "PopupContainer.h"
92
#include "PopupMenuClient.h"
93
#include "ProgressTracker.h"
94 95 96 97
#include "RenderView.h"
#include "ResourceHandle.h"
#include "SecurityOrigin.h"
#include "Settings.h"
98
#include "SpeechInputClientImpl.h"
99
#include "TextIterator.h"
100
#include "Timer.h"
101
#include "TraceEvent.h"
102
#include "TypingCommand.h"
103
#include "UserGestureIndicator.h"
104
#include "Vector.h"
105
#include "WebAccessibilityObject.h"
106
#include "WebAutofillClient.h"
107
#include "WebDevToolsAgentImpl.h"
108
#include "WebDevToolsAgentPrivate.h"
109 110
#include "WebDragData.h"
#include "WebFrameImpl.h"
111
#include "WebGraphicsContext3D.h"
112
#include "WebImage.h"
113
#include "WebInputElement.h"
114 115
#include "WebInputEvent.h"
#include "WebInputEventConversion.h"
116
#include "WebKit.h"
117
#include "WebKitPlatformSupport.h"
118 119
#include "WebMediaPlayerAction.h"
#include "WebNode.h"
120 121
#include "WebPlugin.h"
#include "WebPluginContainerImpl.h"
122 123
#include "WebPoint.h"
#include "WebPopupMenuImpl.h"
124
#include "WebRange.h"
125
#include "WebRect.h"
126
#include "WebRuntimeFeatures.h"
127 128 129 130
#include "WebSettingsImpl.h"
#include "WebString.h"
#include "WebVector.h"
#include "WebViewClient.h"
131
#include "cc/CCHeadsUpDisplay.h"
132
#include <wtf/ByteArray.h>
133
#include <wtf/CurrentTime.h>
134
#include <wtf/MainThread.h>
135 136
#include <wtf/RefPtr.h>

137 138 139 140 141 142 143 144
#if ENABLE(GESTURE_EVENTS)
#include "PlatformGestureEvent.h"
#endif

#if ENABLE(GESTURE_RECOGNIZER)
#include "PlatformGestureRecognizer.h"
#endif

145
#if USE(CG)
146
#include <CoreGraphics/CGBitmapContext.h>
147 148
#include <CoreGraphics/CGContext.h>
#endif
149

150
#if OS(WINDOWS)
151 152
#include "RenderThemeChromiumWin.h"
#else
153
#if OS(UNIX) && !OS(DARWIN)
154 155
#include "RenderThemeChromiumLinux.h"
#endif
156 157 158 159 160 161 162 163
#include "RenderTheme.h"
#endif

// Get rid of WTF's pow define so we can use std::pow.
#undef pow
#include <cmath> // for std::pow

using namespace WebCore;
164
using namespace std;
165

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
namespace {

GraphicsContext3D::Attributes getCompositorContextAttributes()
{
    // Explicitly disable antialiasing for the compositor. As of the time of
    // this writing, the only platform that supported antialiasing for the
    // compositor was Mac OS X, because the on-screen OpenGL context creation
    // code paths on Windows and Linux didn't yet have multisampling support.
    // Mac OS X essentially always behaves as though it's rendering offscreen.
    // Multisampling has a heavy cost especially on devices with relatively low
    // fill rate like most notebooks, and the Mac implementation would need to
    // be optimized to resolve directly into the IOSurface shared between the
    // GPU and browser processes. For these reasons and to avoid platform
    // disparities we explicitly disable antialiasing.
    GraphicsContext3D::Attributes attributes;
    attributes.antialias = false;
182
    attributes.shareResources = true;
183 184 185 186 187
    return attributes;
}

} // anonymous namespace

188 189 190 191 192 193
namespace WebKit {

// Change the text zoom level by kTextSizeMultiplierRatio each time the user
// zooms text in or out (ie., change by 20%).  The min and max values limit
// text zoom to half and 3x the original text size.  These three values match
// those in Apple's port in WebKit/WebKit/WebView/WebView.mm
194 195 196 197
const double WebView::textSizeMultiplierRatio = 1.2;
const double WebView::minTextSizeMultiplier = 0.5;
const double WebView::maxTextSizeMultiplier = 3.0;

198 199 200 201 202 203 204

// The group name identifies a namespace of pages.  Page group is used on OSX
// for some programs that use HTML views to display things that don't seem like
// web pages to the user (so shouldn't have visited link coloring).  We only use
// one page group.
const char* pageGroupName = "default";

205
// Used to defer all page activity in cases where the embedder wishes to run
206 207
// a nested event loop. Using a stack enables nesting of message loop invocations.
static Vector<PageGroupLoadDeferrer*> pageGroupLoadDeferrerStack;
208

209 210 211 212 213 214 215 216 217 218 219 220 221
// Ensure that the WebDragOperation enum values stay in sync with the original
// DragOperation constants.
#define COMPILE_ASSERT_MATCHING_ENUM(coreName) \
    COMPILE_ASSERT(int(coreName) == int(Web##coreName), dummy##coreName)
COMPILE_ASSERT_MATCHING_ENUM(DragOperationNone);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationCopy);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationLink);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationGeneric);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationPrivate);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationMove);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationDelete);
COMPILE_ASSERT_MATCHING_ENUM(DragOperationEvery);

222
static const PopupContainerSettings autofillPopupSettings = {
223 224
    false, // setTextOnIndexChange
    false, // acceptOnAbandon
225 226 227
    true, // loopSelectionNavigation
    false // restrictWidthOfListBox (For security reasons show the entire entry
          // so the user doesn't enter information he did not intend to.)
228 229
};

230 231
static bool shouldUseExternalPopupMenus = false;

232 233
// WebView ----------------------------------------------------------------

234
WebView* WebView::create(WebViewClient* client)
235
{
236
    // Keep runtime flag for device motion turned off until it's implemented.
237
    WebRuntimeFeatures::enableDeviceMotion(false);
238

239
    // Pass the WebViewImpl's self-reference to the caller.
240
    return adoptRef(new WebViewImpl(client)).leakRef();
241 242
}

243 244 245 246 247
void WebView::setUseExternalPopupMenus(bool useExternalPopupMenus)
{
    shouldUseExternalPopupMenus = useExternalPopupMenus;
}

248 249 250 251 252 253 254 255 256 257
void WebView::updateVisitedLinkState(unsigned long long linkHash)
{
    Page::visitedStateChanged(PageGroup::pageGroup(pageGroupName), linkHash);
}

void WebView::resetVisitedLinkState()
{
    Page::allVisitedStateChanged(PageGroup::pageGroup(pageGroupName));
}

258 259 260 261
void WebView::willEnterModalLoop()
{
    PageGroup* pageGroup = PageGroup::pageGroup(pageGroupName);
    ASSERT(pageGroup);
262 263

    if (pageGroup->pages().isEmpty())
264 265 266 267 268
        pageGroupLoadDeferrerStack.append(static_cast<PageGroupLoadDeferrer*>(0));
    else {
        // Pick any page in the page group since we are deferring all pages.
        pageGroupLoadDeferrerStack.append(new PageGroupLoadDeferrer(*pageGroup->pages().begin(), true));
    }
269 270 271 272
}

void WebView::didExitModalLoop()
{
273
    ASSERT(pageGroupLoadDeferrerStack.size());
274

275 276
    delete pageGroupLoadDeferrerStack.last();
    pageGroupLoadDeferrerStack.removeLast();
277 278
}

279 280 281 282 283 284 285 286 287 288 289 290 291
void WebViewImpl::initializeMainFrame(WebFrameClient* frameClient)
{
    // NOTE: The WebFrameImpl takes a reference to itself within InitMainFrame
    // and releases that reference once the corresponding Frame is destroyed.
    RefPtr<WebFrameImpl> frame = WebFrameImpl::create(frameClient);

    frame->initializeAsMainFrame(this);

    // Restrict the access to the local file system
    // (see WebView.mm WebView::_commonInitializationWithFrameName).
    SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForLocalOnly);
}

292
void WebViewImpl::setAutofillClient(WebAutofillClient* autofillClient)
293
{
294
    m_autofillClient = autofillClient;
295 296
}

297 298 299
void WebViewImpl::setDevToolsAgentClient(WebDevToolsAgentClient* devToolsClient) 
{
    if (devToolsClient)
300
        m_devToolsAgent = adoptPtr(new WebDevToolsAgentImpl(this, devToolsClient));
301 302 303 304
    else
        m_devToolsAgent.clear();
}

305
void WebViewImpl::setPermissionClient(WebPermissionClient* permissionClient)
306
{
307
    m_permissionClient = permissionClient;
308 309 310 311 312 313 314
}

void WebViewImpl::setSpellCheckClient(WebSpellCheckClient* spellCheckClient)
{
    m_spellCheckClient = spellCheckClient;
}

315
WebViewImpl::WebViewImpl(WebViewClient* client)
316
    : m_client(client)
317
    , m_autofillClient(0)
318
    , m_permissionClient(0)
319
    , m_spellCheckClient(0)
320 321 322 323
    , m_chromeClientImpl(this)
    , m_contextMenuClientImpl(this)
    , m_dragClientImpl(this)
    , m_editorClientImpl(this)
324
    , m_inspectorClientImpl(this)
325 326 327 328 329
    , m_observedNewNavigation(false)
#ifndef NDEBUG
    , m_newNavigationLoader(0)
#endif
    , m_zoomLevel(0)
330 331
    , m_minimumZoomLevel(zoomFactorToZoomLevel(minTextSizeMultiplier))
    , m_maximumZoomLevel(zoomFactorToZoomLevel(maxTextSizeMultiplier))
332 333 334 335 336 337 338 339
    , m_contextMenuAllowed(false)
    , m_doingDragAndDrop(false)
    , m_ignoreInputEvents(false)
    , m_suppressNextKeypressEvent(false)
    , m_initialNavigationPolicy(WebNavigationPolicyIgnore)
    , m_imeAcceptEvents(true)
    , m_operationsAllowed(WebDragOperationNone)
    , m_dragOperation(WebDragOperationNone)
340 341
    , m_autofillPopupShowing(false)
    , m_autofillPopup(0)
342 343
    , m_isTransparent(false)
    , m_tabsToLinks(false)
344
    , m_dragScrollTimer(adoptPtr(new DragScrollTimer))
345
#if USE(ACCELERATED_COMPOSITING)
346
    , m_rootGraphicsLayer(0)
347
    , m_isAcceleratedCompositingActive(false)
348
    , m_compositorCreationFailed(false)
349
    , m_recreatingGraphicsContext(false)
350 351
#endif
#if ENABLE(INPUT_SPEECH)
352
    , m_speechInputClient(SpeechInputClientImpl::create(client))
353
#endif
354 355
    , m_deviceOrientationClientProxy(adoptPtr(new DeviceOrientationClientProxy(client ? client->deviceOrientationClient() : 0)))
    , m_geolocationClientProxy(adoptPtr(new GeolocationClientProxy(client ? client->geolocationClient() : 0)))
356 357 358
#if ENABLE(GESTURE_RECOGNIZER)
    , m_gestureRecognizer(WebCore::PlatformGestureRecognizer::create())
#endif
359 360 361 362 363
{
    // WebKit/win/WebView.cpp does the same thing, except they call the
    // KJS specific wrapper around this method. We need to have threading
    // initialized because CollatorICU requires it.
    WTF::initializeThreading();
364
    WTF::initializeMainThread();
365 366 367 368

    // set to impossible point so we always get the first mouse pos
    m_lastMousePosition = WebPoint(-1, -1);

369 370 371 372 373 374 375
    Page::PageClients pageClients;
    pageClients.chromeClient = &m_chromeClientImpl;
    pageClients.contextMenuClient = &m_contextMenuClientImpl;
    pageClients.editorClient = &m_editorClientImpl;
    pageClients.dragClient = &m_dragClientImpl;
    pageClients.inspectorClient = &m_inspectorClientImpl;
#if ENABLE(INPUT_SPEECH)
376
    pageClients.speechInputClient = m_speechInputClient.get();
377
#endif
378
    pageClients.deviceOrientationClient = m_deviceOrientationClientProxy.get();
379
    pageClients.geolocationClient = m_geolocationClientProxy.get();
380
    pageClients.backForwardClient = BackForwardListChromium::create(this);
381

382
    m_page = adoptPtr(new Page(pageClients));
383

384 385
    m_geolocationClientProxy->setController(m_page->geolocationController());

386
    m_page->setGroupName(pageGroupName);
387

388
#if ENABLE(PAGE_VISIBILITY_API)
389 390
    if (m_client)
        setVisibilityState(m_client->visibilityState(), true);
391 392
#endif

393
    m_inspectorSettingsMap = adoptPtr(new SettingsMap);
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
}

WebViewImpl::~WebViewImpl()
{
    ASSERT(!m_page);
}

RenderTheme* WebViewImpl::theme() const
{
    return m_page.get() ? m_page->theme() : RenderTheme::defaultTheme().get();
}

WebFrameImpl* WebViewImpl::mainFrameImpl()
{
    return m_page.get() ? WebFrameImpl::fromFrame(m_page->mainFrame()) : 0;
}

bool WebViewImpl::tabKeyCyclesThroughElements() const
{
    ASSERT(m_page.get());
    return m_page->tabKeyCyclesThroughElements();
}

void WebViewImpl::setTabKeyCyclesThroughElements(bool value)
{
    if (m_page)
        m_page->setTabKeyCyclesThroughElements(value);
}

void WebViewImpl::mouseMove(const WebMouseEvent& event)
{
    if (!mainFrameImpl() || !mainFrameImpl()->frameView())
        return;

    m_lastMousePosition = WebPoint(event.x, event.y);

    // We call mouseMoved here instead of handleMouseMovedEvent because we need
    // our ChromeClientImpl to receive changes to the mouse position and
    // tooltip text, and mouseMoved handles all of that.
    mainFrameImpl()->frame()->eventHandler()->mouseMoved(
        PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
}

void WebViewImpl::mouseLeave(const WebMouseEvent& event)
{
    // This event gets sent as the main frame is closing.  In that case, just
    // ignore it.
    if (!mainFrameImpl() || !mainFrameImpl()->frameView())
        return;

    m_client->setMouseOverURL(WebURL());

    mainFrameImpl()->frame()->eventHandler()->handleMouseMoveEvent(
        PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));
}

void WebViewImpl::mouseDown(const WebMouseEvent& event)
{
    if (!mainFrameImpl() || !mainFrameImpl()->frameView())
        return;

455 456 457
    // If there is a select popup open, close it as the user is clicking on
    // the page (outside of the popup).  We also save it so we can prevent a
    // click on the select element from immediately reopening the popup.
458 459 460 461 462 463
    RefPtr<WebCore::PopupContainer> selectPopup;
    if (event.button == WebMouseEvent::ButtonLeft) {
        selectPopup = m_selectPopup;
        hideSelectPopup();
        ASSERT(!m_selectPopup);
    }
464

465 466 467
    m_lastMouseDownPoint = WebPoint(event.x, event.y);

    if (event.button == WebMouseEvent::ButtonLeft) {
468 469 470 471 472 473 474 475
        IntPoint point(event.x, event.y);
        point = m_page->mainFrame()->view()->windowToContents(point);
        HitTestResult result(m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false));
        Node* hitNode = result.innerNonSharedNode();

        // Take capture on a mouse down on a plugin so we can send it mouse events.
        if (hitNode && hitNode->renderer() && hitNode->renderer()->isEmbeddedObject())
            m_mouseCaptureNode = hitNode;
476 477 478 479 480
    }

    mainFrameImpl()->frame()->eventHandler()->handleMousePressEvent(
        PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));

481 482 483 484 485 486 487
    if (m_selectPopup && m_selectPopup == selectPopup) {
        // That click triggered a select popup which is the same as the one that
        // was showing before the click.  It means the user clicked the select
        // while the popup was showing, and as a result we first closed then
        // immediately reopened the select popup.  It needs to be closed.
        hideSelectPopup();
    }
488 489 490

    // Dispatch the contextmenu event regardless of if the click was swallowed.
    // On Windows, we handle it on mouse up, not down.
491
#if OS(DARWIN)
492 493 494 495
    if (event.button == WebMouseEvent::ButtonRight
        || (event.button == WebMouseEvent::ButtonLeft
            && event.modifiers & WebMouseEvent::ControlKey))
        mouseContextMenu(event);
496
#elif OS(UNIX)
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    if (event.button == WebMouseEvent::ButtonRight)
        mouseContextMenu(event);
#endif
}

void WebViewImpl::mouseContextMenu(const WebMouseEvent& event)
{
    if (!mainFrameImpl() || !mainFrameImpl()->frameView())
        return;

    m_page->contextMenuController()->clearContextMenu();

    PlatformMouseEventBuilder pme(mainFrameImpl()->frameView(), event);

    // Find the right target frame. See issue 1186900.
    HitTestResult result = hitTestResultForWindowPos(pme.pos());
    Frame* targetFrame;
    if (result.innerNonSharedNode())
        targetFrame = result.innerNonSharedNode()->document()->frame();
    else
        targetFrame = m_page->focusController()->focusedOrMainFrame();

519
#if OS(WINDOWS)
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    targetFrame->view()->setCursor(pointerCursor());
#endif

    m_contextMenuAllowed = true;
    targetFrame->eventHandler()->sendContextMenuEvent(pme);
    m_contextMenuAllowed = false;
    // Actually showing the context menu is handled by the ContextMenuClient
    // implementation...
}

void WebViewImpl::mouseUp(const WebMouseEvent& event)
{
    if (!mainFrameImpl() || !mainFrameImpl()->frameView())
        return;

535
#if OS(UNIX) && !OS(DARWIN)
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    // If the event was a middle click, attempt to copy text into the focused
    // frame. We execute this before we let the page have a go at the event
    // because the page may change what is focused during in its event handler.
    //
    // This code is in the mouse up handler. There is some debate about putting
    // this here, as opposed to the mouse down handler.
    //   xterm: pastes on up.
    //   GTK: pastes on down.
    //   Firefox: pastes on up.
    //   Midori: couldn't paste at all with 0.1.2
    //
    // There is something of a webcompat angle to this well, as highlighted by
    // crbug.com/14608. Pages can clear text boxes 'onclick' and, if we paste on
    // down then the text is pasted just before the onclick handler runs and
    // clears the text box. So it's important this happens after the
    // handleMouseReleaseEvent() earlier in this function
    if (event.button == WebMouseEvent::ButtonMiddle) {
        Frame* focused = focusedWebCoreFrame();
554
        FrameView* view = m_page->mainFrame()->view();
555
        IntPoint clickPoint(m_lastMouseDownPoint.x, m_lastMouseDownPoint.y);
556 557
        IntPoint contentPoint = view->windowToContents(clickPoint);
        HitTestResult hitTestResult = focused->eventHandler()->hitTestResultAtPoint(contentPoint, false, false, ShouldHitTestScrollbars);
558
        // We don't want to send a paste when middle clicking a scroll bar or a
559
        // link (which will navigate later in the code).  The main scrollbars
560 561
        // have to be handled separately.
        if (!hitTestResult.scrollbar() && !hitTestResult.isLiveLink() && focused && !view->scrollbarAtPoint(clickPoint)) {
562 563 564 565 566 567 568 569 570 571 572 573 574
            Editor* editor = focused->editor();
            Pasteboard* pasteboard = Pasteboard::generalPasteboard();
            bool oldSelectionMode = pasteboard->isSelectionMode();
            pasteboard->setSelectionMode(true);
            editor->command(AtomicString("Paste")).execute();
            pasteboard->setSelectionMode(oldSelectionMode);
        }
    }
#endif

    mainFrameImpl()->frame()->eventHandler()->handleMouseReleaseEvent(
        PlatformMouseEventBuilder(mainFrameImpl()->frameView(), event));

575
#if OS(WINDOWS)
576 577 578 579 580 581 582
    // Dispatch the contextmenu event regardless of if the click was swallowed.
    // On Mac/Linux, we handle it on mouse down, not up.
    if (event.button == WebMouseEvent::ButtonRight)
        mouseContextMenu(event);
#endif
}

583
bool WebViewImpl::mouseWheel(const WebMouseWheelEvent& event)
584 585
{
    PlatformWheelEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
586
    return mainFrameImpl()->frame()->eventHandler()->handleWheelEvent(platformEvent);
587 588
}

589 590 591 592
#if ENABLE(GESTURE_EVENTS)
bool WebViewImpl::gestureEvent(const WebGestureEvent& event)
{
    PlatformGestureEventBuilder platformEvent(mainFrameImpl()->frameView(), event);
593 594 595 596 597 598 599 600
    bool handled = mainFrameImpl()->frame()->eventHandler()->handleGestureEvent(platformEvent);

    Frame* frame = mainFrameImpl()->frame();
    WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
    if (pluginContainer)
        handled |= pluginContainer->handleGestureEvent(platformEvent);

    return handled;
601 602 603
}
#endif

604 605 606 607 608 609 610 611 612 613 614 615 616 617
bool WebViewImpl::keyEvent(const WebKeyboardEvent& event)
{
    ASSERT((event.type == WebInputEvent::RawKeyDown)
        || (event.type == WebInputEvent::KeyDown)
        || (event.type == WebInputEvent::KeyUp));

    // Please refer to the comments explaining the m_suppressNextKeypressEvent
    // member.
    // The m_suppressNextKeypressEvent is set if the KeyDown is handled by
    // Webkit. A keyDown event is typically associated with a keyPress(char)
    // event and a keyUp event. We reset this flag here as this is a new keyDown
    // event.
    m_suppressNextKeypressEvent = false;

618 619 620 621
    // If there is a select popup, it should be the one processing the event,
    // not the page.
    if (m_selectPopup)
        return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));
622

623
    // Give Autocomplete a chance to consume the key events it is interested in.
624 625 626 627 628 629 630 631 632 633 634
    if (autocompleteHandleKeyEvent(event))
        return true;

    Frame* frame = focusedWebCoreFrame();
    if (!frame)
        return false;

    EventHandler* handler = frame->eventHandler();
    if (!handler)
        return keyEventDefault(event);

635
#if !OS(DARWIN)
636
    const WebInputEvent::Type contextMenuTriggeringEventType =
637
#if OS(WINDOWS)
638
        WebInputEvent::KeyUp;
639
#elif OS(UNIX)
640 641 642
        WebInputEvent::RawKeyDown;
#endif

643 644 645
    bool isUnmodifiedMenuKey = !(event.modifiers & WebInputEvent::InputModifiers) && event.windowsKeyCode == VKEY_APPS;
    bool isShiftF10 = event.modifiers == WebInputEvent::ShiftKey && event.windowsKeyCode == VKEY_F10;
    if ((isUnmodifiedMenuKey || isShiftF10) && event.type == contextMenuTriggeringEventType) {
646 647 648
        sendContextMenuEvent(event);
        return true;
    }
649
#endif // !OS(DARWIN)
650 651 652 653

    PlatformKeyboardEventBuilder evt(event);

    if (handler->keyEvent(evt)) {
654 655 656
        if (WebInputEvent::RawKeyDown == event.type) {
            // Suppress the next keypress event unless the focused node is a plug-in node.
            // (Flash needs these keypress events to handle non-US keyboards.)
657
            Node* node = focusedWebCoreNode();
658 659 660
            if (!node || !node->renderer() || !node->renderer()->isEmbeddedObject())
                m_suppressNextKeypressEvent = true;
        }
661 662 663 664 665 666 667 668
        return true;
    }

    return keyEventDefault(event);
}

bool WebViewImpl::autocompleteHandleKeyEvent(const WebKeyboardEvent& event)
{
669
    if (!m_autofillPopupShowing
670 671 672 673 674 675 676
        // Home and End should be left to the text field to process.
        || event.windowsKeyCode == VKEY_HOME
        || event.windowsKeyCode == VKEY_END)
      return false;

    // Pressing delete triggers the removal of the selected suggestion from the DB.
    if (event.windowsKeyCode == VKEY_DELETE
677
        && m_autofillPopup->selectedIndex() != -1) {
678 679 680 681 682 683 684 685 686 687 688
        Node* node = focusedWebCoreNode();
        if (!node || (node->nodeType() != Node::ELEMENT_NODE)) {
            ASSERT_NOT_REACHED();
            return false;
        }
        Element* element = static_cast<Element*>(node);
        if (!element->hasLocalName(HTMLNames::inputTag)) {
            ASSERT_NOT_REACHED();
            return false;
        }

689
        int selectedIndex = m_autofillPopup->selectedIndex();
690

691
        if (!m_autofillPopupClient->canRemoveSuggestionAtIndex(selectedIndex))
692 693
            return false;

694
        WebString name = WebInputElement(static_cast<HTMLInputElement*>(element)).nameForAutofill();
695 696
        WebString value = m_autofillPopupClient->itemText(selectedIndex);
        m_autofillClient->removeAutocompleteSuggestion(name, value);
697 698
        // Update the entries in the currently showing popup to reflect the
        // deletion.
699 700
        m_autofillPopupClient->removeSuggestionAtIndex(selectedIndex);
        refreshAutofillPopup();
701 702 703
        return false;
    }

704
    if (!m_autofillPopup->isInterestedInEventForKey(event.windowsKeyCode))
705 706
        return false;

707
    if (m_autofillPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event))) {
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
        // We need to ignore the next Char event after this otherwise pressing
        // enter when selecting an item in the menu will go to the page.
        if (WebInputEvent::RawKeyDown == event.type)
            m_suppressNextKeypressEvent = true;
        return true;
    }

    return false;
}

bool WebViewImpl::charEvent(const WebKeyboardEvent& event)
{
    ASSERT(event.type == WebInputEvent::Char);

    // Please refer to the comments explaining the m_suppressNextKeypressEvent
    // member.  The m_suppressNextKeypressEvent is set if the KeyDown is
    // handled by Webkit. A keyDown event is typically associated with a
    // keyPress(char) event and a keyUp event. We reset this flag here as it
    // only applies to the current keyPress event.
727 728
    bool suppress = m_suppressNextKeypressEvent;
    m_suppressNextKeypressEvent = false;
729

730 731 732 733 734
    // If there is a select popup, it should be the one processing the event,
    // not the page.
    if (m_selectPopup)
        return m_selectPopup->handleKeyEvent(PlatformKeyboardEventBuilder(event));

735 736
    Frame* frame = focusedWebCoreFrame();
    if (!frame)
737
        return suppress;
738 739 740

    EventHandler* handler = frame->eventHandler();
    if (!handler)
741
        return suppress || keyEventDefault(event);
742 743 744 745 746

    PlatformKeyboardEventBuilder evt(event);
    if (!evt.isCharacterKey())
        return true;

747 748 749 750
    // Accesskeys are triggered by char events and can't be suppressed.
    if (handler->handleAccessKey(evt))
        return true;

751 752 753 754 755
    // Safari 3.1 does not pass off windows system key messages (WM_SYSCHAR) to
    // the eventHandler::keyEvent. We mimic this behavior on all platforms since
    // for now we are converting other platform's key events to windows key
    // events.
    if (evt.isSystemKey())
756
        return false;
757

758
    if (!suppress && !handler->keyEvent(evt))
759 760 761 762 763
        return keyEventDefault(event);

    return true;
}

764 765 766 767 768 769 770
#if ENABLE(TOUCH_EVENTS)
bool WebViewImpl::touchEvent(const WebTouchEvent& event)
{
    if (!mainFrameImpl() || !mainFrameImpl()->frameView())
        return false;

    PlatformTouchEventBuilder touchEventBuilder(mainFrameImpl()->frameView(), event);
771 772 773 774 775 776 777 778 779
    bool defaultPrevented = mainFrameImpl()->frame()->eventHandler()->handleTouchEvent(touchEventBuilder);

#if ENABLE(GESTURE_RECOGNIZER)
    OwnPtr<Vector<WebCore::PlatformGestureEvent> > gestureEvents(m_gestureRecognizer->processTouchEventForGestures(touchEventBuilder, defaultPrevented));
    for (unsigned int  i = 0; i < gestureEvents->size(); i++)
        mainFrameImpl()->frame()->eventHandler()->handleGestureEvent(gestureEvents->at(i));
#endif

    return defaultPrevented;
780 781 782
}
#endif

783
#if !OS(DARWIN)
784
// Mac has no way to open a context menu based on a keyboard event.
785 786 787 788 789 790 791 792 793 794 795
bool WebViewImpl::sendContextMenuEvent(const WebKeyboardEvent& event)
{
    // The contextMenuController() holds onto the last context menu that was
    // popped up on the page until a new one is created. We need to clear
    // this menu before propagating the event through the DOM so that we can
    // detect if we create a new menu for this event, since we won't create
    // a new menu if the DOM swallows the event and the defaultEventHandler does
    // not run.
    page()->contextMenuController()->clearContextMenu();

    m_contextMenuAllowed = true;
796 797
    Frame* focusedFrame = page()->focusController()->focusedOrMainFrame();
    bool handled = focusedFrame->eventHandler()->sendContextMenuEventForKey();
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
    m_contextMenuAllowed = false;
    return handled;
}
#endif

bool WebViewImpl::keyEventDefault(const WebKeyboardEvent& event)
{
    Frame* frame = focusedWebCoreFrame();
    if (!frame)
        return false;

    switch (event.type) {
    case WebInputEvent::Char:
        if (event.windowsKeyCode == VKEY_SPACE) {
            int keyCode = ((event.modifiers & WebInputEvent::ShiftKey) ? VKEY_PRIOR : VKEY_NEXT);
            return scrollViewWithKeyboard(keyCode, event.modifiers);
        }
        break;
    case WebInputEvent::RawKeyDown:
        if (event.modifiers == WebInputEvent::ControlKey) {
            switch (event.windowsKeyCode) {
819
#if !OS(DARWIN)
820 821 822 823 824 825 826
            case 'A':
                focusedFrame()->executeCommand(WebString::fromUTF8("SelectAll"));
                return true;
            case VKEY_INSERT:
            case 'C':
                focusedFrame()->executeCommand(WebString::fromUTF8("Copy"));
                return true;
827
#endif
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
            // Match FF behavior in the sense that Ctrl+home/end are the only Ctrl
            // key combinations which affect scrolling. Safari is buggy in the
            // sense that it scrolls the page for all Ctrl+scrolling key
            // combinations. For e.g. Ctrl+pgup/pgdn/up/down, etc.
            case VKEY_HOME:
            case VKEY_END:
                break;
            default:
                return false;
            }
        }
        if (!event.isSystemKey && !(event.modifiers & WebInputEvent::ShiftKey))
            return scrollViewWithKeyboard(event.windowsKeyCode, event.modifiers);
        break;
    default:
        break;
    }
    return false;
}

bool WebViewImpl::scrollViewWithKeyboard(int keyCode, int modifiers)
{
    ScrollDirection scrollDirection;
    ScrollGranularity scrollGranularity;
852 853 854 855 856 857 858 859 860
#if OS(DARWIN)
    // Control-Up/Down should be PageUp/Down on Mac.
    if (modifiers & WebMouseEvent::ControlKey) {
      if (keyCode == VKEY_UP)
        keyCode = VKEY_PRIOR;
      else if (keyCode == VKEY_DOWN)
        keyCode = VKEY_NEXT;
    }
#endif
861 862 863 864
    if (!mapKeyCodeForScroll(keyCode, &scrollDirection, &scrollGranularity))
        return false;
    return propagateScroll(scrollDirection, scrollGranularity);
}
865

866 867 868 869
bool WebViewImpl::mapKeyCodeForScroll(int keyCode,
                                      WebCore::ScrollDirection* scrollDirection,
                                      WebCore::ScrollGranularity* scrollGranularity)
{
870 871
    switch (keyCode) {
    case VKEY_LEFT:
872 873
        *scrollDirection = ScrollLeft;
        *scrollGranularity = ScrollByLine;
874 875
        break;
    case VKEY_RIGHT:
876 877
        *scrollDirection = ScrollRight;
        *scrollGranularity = ScrollByLine;
878 879
        break;
    case VKEY_UP:
880 881
        *scrollDirection = ScrollUp;
        *scrollGranularity = ScrollByLine;
882 883
        break;
    case VKEY_DOWN:
884 885
        *scrollDirection = ScrollDown;
        *scrollGranularity = ScrollByLine;
886 887
        break;
    case VKEY_HOME:
888 889
        *scrollDirection = ScrollUp;
        *scrollGranularity = ScrollByDocument;
890 891
        break;
    case VKEY_END:
892 893
        *scrollDirection = ScrollDown;
        *scrollGranularity = ScrollByDocument;
894 895
        break;
    case VKEY_PRIOR:  // page up
896 897
        *scrollDirection = ScrollUp;
        *scrollGranularity = ScrollByPage;
898 899
        break;
    case VKEY_NEXT:  // page down
900 901
        *scrollDirection = ScrollDown;
        *scrollGranularity = ScrollByPage;
902 903 904 905 906
        break;
    default:
        return false;
    }

907
    return true;
908 909
}

910 911 912 913 914 915
void WebViewImpl::hideSelectPopup()
{
    if (m_selectPopup.get())
        m_selectPopup->hidePopup();
}

916 917 918 919 920 921 922
bool WebViewImpl::propagateScroll(ScrollDirection scrollDirection,
                                  ScrollGranularity scrollGranularity)
{
    Frame* frame = focusedWebCoreFrame();
    if (!frame)
        return false;

923
    bool scrollHandled = frame->eventHandler()->scrollOverflow(scrollDirection, scrollGranularity);
924 925
    Frame* currentFrame = frame;
    while (!scrollHandled && currentFrame) {
926
        scrollHandled = currentFrame->view()->scroll(scrollDirection, scrollGranularity);
927 928 929 930 931
        currentFrame = currentFrame->tree()->parent();
    }
    return scrollHandled;
}

932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
void  WebViewImpl::popupOpened(WebCore::PopupContainer* popupContainer)
{
    if (popupContainer->popupType() == WebCore::PopupContainer::Select) {
        ASSERT(!m_selectPopup);
        m_selectPopup = popupContainer;
    }
}

void  WebViewImpl::popupClosed(WebCore::PopupContainer* popupContainer)
{
    if (popupContainer->popupType() == WebCore::PopupContainer::Select) {
        ASSERT(m_selectPopup.get());
        m_selectPopup = 0;
    }
}

948
void WebViewImpl::hideAutofillPopup()
949
{
950 951 952
    if (m_autofillPopupShowing) {
        m_autofillPopup->hidePopup();
        m_autofillPopupShowing = false;
953 954 955
    }
}

956
Frame* WebViewImpl::focusedWebCoreFrame() const
957 958 959 960 961 962 963 964 965
{
    return m_page.get() ? m_page->focusController()->focusedOrMainFrame() : 0;
}

WebViewImpl* WebViewImpl::fromPage(Page* page)
{
    if (!page)
        return 0;

966 967
    ChromeClientImpl* chromeClient = static_cast<ChromeClientImpl*>(page->chrome()->client());
    return static_cast<WebViewImpl*>(chromeClient->webView());
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
}

// WebWidget ------------------------------------------------------------------

void WebViewImpl::close()
{
    RefPtr<WebFrameImpl> mainFrameImpl;

    if (m_page.get()) {
        // Initiate shutdown for the entire frameset.  This will cause a lot of
        // notifications to be sent.
        if (m_page->mainFrame()) {
            mainFrameImpl = WebFrameImpl::fromFrame(m_page->mainFrame());
            m_page->mainFrame()->loader()->frameDetached();
        }
        m_page.clear();
    }

    // Should happen after m_page.clear().
    if (m_devToolsAgent.get())
        m_devToolsAgent.clear();

    // Reset the delegate to prevent notifications being sent as we're being
    // deleted.
    m_client = 0;

    deref();  // Balances ref() acquired in WebView::create
}

997 998 999 1000
void WebViewImpl::willStartLiveResize()
{
    if (mainFrameImpl() && mainFrameImpl()->frameView())
        mainFrameImpl()->frameView()->willStartLiveResize();
1001 1002 1003 1004 1005

    Frame* frame = mainFrameImpl()->frame();
    WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
    if (pluginContainer)
        pluginContainer->willStartLiveResize();
1006 1007
}

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
void WebViewImpl::resize(const WebSize& newSize)
{
    if (m_size == newSize)
        return;
    m_size = newSize;

    if (mainFrameImpl()->frameView()) {
        mainFrameImpl()->frameView()->resize(m_size.width, m_size.height);
        mainFrameImpl()->frame()->eventHandler()->sendResizeEvent();
    }

    if (m_client) {
1020 1021
        if (isAcceleratedCompositingActive()) {
#if USE(ACCELERATED_COMPOSITING)
1022
            updateLayerTreeViewport();
1023
#endif
1024 1025
        } else {
            WebRect damagedRect(0, 0, m_size.width, m_size.height);
1026
            m_client->didInvalidateRect(damagedRect);
1027
        }
1028 1029 1030
    }
}

1031 1032 1033 1034
void WebViewImpl::willEndLiveResize()
{
    if (mainFrameImpl() && mainFrameImpl()->frameView())
        mainFrameImpl()->frameView()->willEndLiveResize();
1035 1036 1037 1038 1039

    Frame* frame = mainFrameImpl()->frame();
    WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(frame);
    if (pluginContainer)
        pluginContainer->willEndLiveResize();
1040 1041
}

1042
void WebViewImpl::animate(double frameBeginTime)
1043
{
1044
#if ENABLE(REQUEST_ANIMATION_FRAME)
1045 1046 1047 1048 1049
    TRACE_EVENT("WebViewImpl::animate", this, 0);
    // FIXME: remove this zero-check once render_widget has been modified to
    // pass in a frameBeginTime.
    if (!frameBeginTime)
        frameBeginTime = currentTime();
1050 1051 1052
    WebFrameImpl* webframe = mainFrameImpl();
    if (webframe) {
        FrameView* view = webframe->frameView();
1053
        if (view) {
1054 1055 1056 1057
#if !USE(THREADED_COMPOSITING)
            if (m_layerTreeHost)
                m_layerTreeHost->setAnimating(true);
#endif
1058
            view->serviceScriptedAnimations(convertSecondsToDOMTimeStamp(frameBeginTime));
1059 1060 1061 1062
#if !USE(THREADED_COMPOSITING)
            if (m_layerTreeHost)
                m_layerTreeHost->setAnimating(false);
#endif
1063
        }
1064 1065 1066 1067
    }
#endif
}

1068 1069
void WebViewImpl::layout()
{
1070
    TRACE_EVENT("WebViewImpl::layout", this, 0);
1071

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    WebFrameImpl* webframe = mainFrameImpl();
    if (webframe) {
        // In order for our child HWNDs (NativeWindowWidgets) to update properly,
        // they need to be told that we are updating the screen.  The problem is
        // that the native widgets need to recalculate their clip region and not
        // overlap any of our non-native widgets.  To force the resizing, call
        // setFrameRect().  This will be a quick operation for most frames, but
        // the NativeWindowWidgets will update a proper clipping region.
        FrameView* view = webframe->frameView();
        if (view)
            view->setFrameRect(view->frameRect());

        // setFrameRect may have the side-effect of causing existing page
        // layout to be invalidated, so layout needs to be called last.

        webframe->layout();
    }
}

1091 1092 1093
#if USE(ACCELERATED_COMPOSITING)
void WebViewImpl::doPixelReadbackToCanvas(WebCanvas* canvas, const IntRect& rect)
{
1094
#if USE(SKIA)
1095 1096 1097 1098 1099
    PlatformContextSkia context(canvas);

    // PlatformGraphicsContext is actually a pointer to PlatformContextSkia
    GraphicsContext gc(reinterpret_cast<PlatformGraphicsContext*>(&context));
    int bitmapHeight = canvas->getDevice()->accessBitmap(false).height();
1100
#elif USE(CG)