Merge from Chromium at DEPS revision 38.0.2125.57

This commit was generated by merge_to_master.py.

Change-Id: Id5471be56778398151383b94874a5cb54c78a5ad
diff --git a/Source/core/editing/Caret.cpp b/Source/core/editing/Caret.cpp
index 06424f2..8bdff9f 100644
--- a/Source/core/editing/Caret.cpp
+++ b/Source/core/editing/Caret.cpp
@@ -192,7 +192,7 @@
     return caretPainter->localToAbsoluteQuad(FloatRect(localRect)).enclosingBoundingBox();
 }
 
-void CaretBase::repaintCaretForLocalRect(Node* node, const LayoutRect& rect)
+void CaretBase::invalidateLocalCaretRect(Node* node, const LayoutRect& rect)
 {
     RenderBlock* caretPainter = caretRenderer(node);
     if (!caretPainter)
@@ -237,7 +237,7 @@
 
     if (RenderView* view = node->document().renderView()) {
         if (shouldRepaintCaret(view, node->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable)))
-            repaintCaretForLocalRect(node, localCaretRectWithoutUpdate());
+            invalidateLocalCaretRect(node, localCaretRectWithoutUpdate());
     }
 }
 
diff --git a/Source/core/editing/Caret.h b/Source/core/editing/Caret.h
index 674adf0..fa2b36c 100644
--- a/Source/core/editing/Caret.h
+++ b/Source/core/editing/Caret.h
@@ -68,7 +68,7 @@
 
 protected:
     static RenderBlock* caretRenderer(Node*);
-    static void repaintCaretForLocalRect(Node*, const LayoutRect&);
+    static void invalidateLocalCaretRect(Node*, const LayoutRect&);
 
 private:
     LayoutRect m_caretLocalRect; // caret rect in coords local to the renderer responsible for painting the caret
diff --git a/Source/core/editing/FrameSelection.cpp b/Source/core/editing/FrameSelection.cpp
index 7427627..e347a61 100644
--- a/Source/core/editing/FrameSelection.cpp
+++ b/Source/core/editing/FrameSelection.cpp
@@ -1252,15 +1252,6 @@
     return localCaretRectOfPosition(caretPosition, renderer);
 }
 
-static void invalidateLocalCaretRect(RenderObject* renderer, const LayoutRect& caretRect)
-{
-    // FIXME: Need to over-paint 1 pixel to workaround some rounding problems.
-    // https://bugs.webkit.org/show_bug.cgi?id=108283
-    LayoutRect inflatedRect = caretRect;
-    inflatedRect.inflate(1);
-    renderer->invalidatePaintRectangle(inflatedRect);
-}
-
 void FrameSelection::invalidateCaretRect()
 {
     if (!m_caretRectDirty)
@@ -1276,9 +1267,9 @@
 
     RenderView* view = m_frame->document()->renderView();
     if (m_previousCaretNode && shouldRepaintCaret(view, m_previousCaretNode->isContentEditable()))
-        invalidateLocalCaretRect(m_previousCaretNode->renderer(), m_previousCaretRect);
+        invalidateLocalCaretRect(m_previousCaretNode.get(), m_previousCaretRect);
     if (newNode && shouldRepaintCaret(view, newNode->isContentEditable()))
-        invalidateLocalCaretRect(newNode->renderer(), newRect);
+        invalidateLocalCaretRect(newNode, newRect);
 
     m_previousCaretNode = newNode;
     m_previousCaretRect = newRect;
@@ -1588,6 +1579,8 @@
         return;
     }
 
+    m_frame->document()->updateLayoutIgnorePendingStylesheets();
+
     // Use the rightmost candidate for the start of the selection, and the leftmost candidate for the end of the selection.
     // Example: foo <a>bar</a>.  Imagine that a line wrap occurs after 'foo', and that 'bar' is selected.   If we pass [foo, 3]
     // as the start of the selection, the selection painting code will think that content on the line containing 'foo' is selected
diff --git a/Source/core/editing/FrameSelectionTest.cpp b/Source/core/editing/FrameSelectionTest.cpp
index 826203a..0327f5a 100644
--- a/Source/core/editing/FrameSelectionTest.cpp
+++ b/Source/core/editing/FrameSelectionTest.cpp
@@ -9,6 +9,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/Text.h"
+#include "core/frame/FrameView.h"
 #include "core/html/HTMLBodyElement.h"
 #include "core/html/HTMLDocument.h"
 #include "core/testing/DummyPageHolder.h"
@@ -29,7 +30,7 @@
 
     HTMLDocument& document() const;
     void setSelection(const VisibleSelection&);
-    const FrameSelection& selection() const;
+    FrameSelection& selection() const;
     Text* textNode() { return m_textNode.get(); }
 
 private:
@@ -57,7 +58,7 @@
     m_dummyPageHolder->frame().selection().setSelection(newSelection);
 }
 
-const FrameSelection& FrameSelectionTest::selection() const
+FrameSelection& FrameSelectionTest::selection() const
 {
     return m_dummyPageHolder->frame().selection();
 }
@@ -89,4 +90,23 @@
     EXPECT_TRUE(selection().isNone());
 }
 
+TEST_F(FrameSelectionTest, InvalidateCaretRect)
+{
+    document().view()->updateLayoutAndStyleIfNeededRecursive();
+
+    VisibleSelection validSelection(Position(textNode(), 0), Position(textNode(), 0));
+    setSelection(validSelection);
+    selection().setCaretRectNeedsUpdate();
+    EXPECT_TRUE(selection().isCaretBoundsDirty());
+    selection().invalidateCaretRect();
+    EXPECT_FALSE(selection().isCaretBoundsDirty());
+
+    document().body()->removeChild(textNode());
+    document().updateLayoutIgnorePendingStylesheets();
+    selection().setCaretRectNeedsUpdate();
+    EXPECT_TRUE(selection().isCaretBoundsDirty());
+    selection().invalidateCaretRect();
+    EXPECT_FALSE(selection().isCaretBoundsDirty());
+}
+
 }
diff --git a/Source/core/events/Event.cpp b/Source/core/events/Event.cpp
index f39236e..ea99d75 100644
--- a/Source/core/events/Event.cpp
+++ b/Source/core/events/Event.cpp
@@ -255,7 +255,7 @@
         if (SVGElement* svgElement = toSVGElement(node)->correspondingElement())
             return svgElement;
     }
-    return m_currentTarget;
+    return m_currentTarget.get();
 }
 
 void Event::trace(Visitor* visitor)
diff --git a/Source/core/events/Event.h b/Source/core/events/Event.h
index 2a91721..0220d7a 100644
--- a/Source/core/events/Event.h
+++ b/Source/core/events/Event.h
@@ -204,7 +204,7 @@
     bool m_cancelBubble;
 
     unsigned short m_eventPhase;
-    RawPtrWillBeMember<EventTarget> m_currentTarget;
+    RefPtrWillBeMember<EventTarget> m_currentTarget;
     RefPtrWillBeMember<EventTarget> m_target;
     DOMTimeStamp m_createTime;
     RefPtrWillBeMember<Event> m_underlyingEvent;
diff --git a/Source/core/fileapi/FileReader.cpp b/Source/core/fileapi/FileReader.cpp
index 36361c2..9ca0c46 100644
--- a/Source/core/fileapi/FileReader.cpp
+++ b/Source/core/fileapi/FileReader.cpp
@@ -243,6 +243,10 @@
 
 void FileReader::stop()
 {
+    // The delayed abort task tidies up and advances to the DONE state.
+    if (m_loadingState == LoadingStateAborted)
+        return;
+
     if (hasPendingActivity())
         ThrottlingController::finishReader(executionContext(), this, ThrottlingController::removeReader(executionContext(), this));
     terminate();
diff --git a/Source/core/frame/FrameView.cpp b/Source/core/frame/FrameView.cpp
index 3b686e1..c97e3b1 100644
--- a/Source/core/frame/FrameView.cpp
+++ b/Source/core/frame/FrameView.cpp
@@ -121,6 +121,7 @@
     , m_inputEventsScaleFactorForEmulation(1)
     , m_layoutSizeFixedToFrameSize(true)
     , m_didScrollTimer(this, &FrameView::didScrollTimerFired)
+    , m_needsUpdateWidgetPositions(false)
 {
     ASSERT(m_frame);
     init();
@@ -2649,6 +2650,16 @@
     ScrollView::paintOverhangAreas(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect);
 }
 
+void FrameView::updateWidgetPositionsIfNeeded()
+{
+    if (!m_needsUpdateWidgetPositions)
+        return;
+
+    m_needsUpdateWidgetPositions = false;
+
+    updateWidgetPositions();
+}
+
 void FrameView::updateLayoutAndStyleForPainting()
 {
     // Updating layout can run script, which can tear down the FrameView.
@@ -2656,6 +2667,8 @@
 
     updateLayoutAndStyleIfNeededRecursive();
 
+    updateWidgetPositionsIfNeeded();
+
     if (RenderView* view = renderView()) {
         TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateLayerTree", "frame", m_frame.get());
         // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
diff --git a/Source/core/frame/FrameView.h b/Source/core/frame/FrameView.h
index f9c4758..0593976 100644
--- a/Source/core/frame/FrameView.h
+++ b/Source/core/frame/FrameView.h
@@ -102,6 +102,8 @@
     bool needsLayout() const;
     void setNeedsLayout();
 
+    void setNeedsUpdateWidgetPositions() { m_needsUpdateWidgetPositions = true; }
+
     // Methods for getting/setting the size Blink should use to layout the contents.
     IntSize layoutSize(IncludeScrollbarsInRect = ExcludeScrollbars) const;
     void setLayoutSize(const IntSize&);
@@ -369,6 +371,8 @@
     virtual IntPoint convertToContainingView(const IntPoint&) const OVERRIDE;
     virtual IntPoint convertFromContainingView(const IntPoint&) const OVERRIDE;
 
+    void updateWidgetPositionsIfNeeded();
+
     void sendResizeEventIfNeeded();
 
     void updateScrollableAreaSet();
@@ -498,6 +502,8 @@
     Timer<FrameView> m_didScrollTimer;
 
     Vector<IntRect> m_tickmarks;
+
+    bool m_needsUpdateWidgetPositions;
 };
 
 inline void FrameView::incrementVisuallyNonEmptyCharacterCount(unsigned count)
diff --git a/Source/core/html/FormAssociatedElement.cpp b/Source/core/html/FormAssociatedElement.cpp
index a90baef..ee8aec0 100644
--- a/Source/core/html/FormAssociatedElement.cpp
+++ b/Source/core/html/FormAssociatedElement.cpp
@@ -84,7 +84,7 @@
 
 void FormAssociatedElement::insertedInto(ContainerNode* insertionPoint)
 {
-    if (!m_formWasSetByParser || NodeTraversal::highestAncestorOrSelf(*insertionPoint) != NodeTraversal::highestAncestorOrSelf(*m_form.get()))
+    if (!m_formWasSetByParser || !m_form || NodeTraversal::highestAncestorOrSelf(*insertionPoint) != NodeTraversal::highestAncestorOrSelf(*m_form.get()))
         resetFormOwner();
 
     if (!insertionPoint->inDocument())
diff --git a/Source/core/html/FormAssociatedElement.h b/Source/core/html/FormAssociatedElement.h
index dc9e83c..0c278e8 100644
--- a/Source/core/html/FormAssociatedElement.h
+++ b/Source/core/html/FormAssociatedElement.h
@@ -130,6 +130,10 @@
 #endif
     OwnPtrWillBeMember<ValidityState> m_validityState;
     String m_customValidationMessage;
+    // Non-Oilpan: Even if m_formWasSetByParser is true, m_form can be null
+    // because parentNode is not a strong reference and |this| and m_form don't
+    // die together.
+    // Oilpan: If m_formWasSetByParser is true, m_form is always non-null.
     bool m_formWasSetByParser;
 };
 
diff --git a/Source/core/html/HTMLCanvasElement.cpp b/Source/core/html/HTMLCanvasElement.cpp
index 08a21cb..18c4833 100644
--- a/Source/core/html/HTMLCanvasElement.cpp
+++ b/Source/core/html/HTMLCanvasElement.cpp
@@ -236,7 +236,7 @@
         didFinalizeFrame();
     } else {
         ASSERT(hasImageBuffer());
-        m_imageBuffer->finalizeFrame();
+        m_imageBuffer->finalizeFrame(m_dirtyRect);
     }
     ASSERT(m_dirtyRect.isEmpty());
 }
diff --git a/Source/core/html/HTMLSelectElement.cpp b/Source/core/html/HTMLSelectElement.cpp
index 2a353bb..371c143 100644
--- a/Source/core/html/HTMLSelectElement.cpp
+++ b/Source/core/html/HTMLSelectElement.cpp
@@ -1407,8 +1407,10 @@
         GestureEvent& gestureEvent = toGestureEvent(*event);
         int listIndex = listIndexForEventTargetOption(gestureEvent);
         if (listIndex >= 0) {
-            if (!isDisabledFormControl())
+            if (!isDisabledFormControl()) {
                 updateSelectedState(listIndex, true, gestureEvent.shiftKey());
+                listBoxOnChange();
+            }
             event->setDefaultHandled();
         }
     } else if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
diff --git a/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp b/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
index 86c46e4..d8fdc11 100644
--- a/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
+++ b/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
@@ -40,6 +40,7 @@
 
 BaseChooserOnlyDateAndTimeInputType::~BaseChooserOnlyDateAndTimeInputType()
 {
+    closeDateTimeChooser();
 }
 
 void BaseChooserOnlyDateAndTimeInputType::handleDOMActivateEvent(Event*)
@@ -142,12 +143,5 @@
     BaseClickableWithKeyInputType::accessKeyAction(element(), sendMouseEvents);
 }
 
-void BaseChooserOnlyDateAndTimeInputType::trace(Visitor* visitor)
-{
-    visitor->trace(m_dateTimeChooser);
-    BaseDateAndTimeInputType::trace(visitor);
-    DateTimeChooserClient::trace(visitor);
-}
-
 }
 #endif
diff --git a/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h b/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h
index dba4e38..d641fa1 100644
--- a/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h
+++ b/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h
@@ -36,11 +36,8 @@
 
 class BaseChooserOnlyDateAndTimeInputType : public BaseDateAndTimeInputType, public DateTimeChooserClient {
     WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(BaseChooserOnlyDateAndTimeInputType);
-public:
-    virtual void trace(Visitor*) OVERRIDE;
-
 protected:
-    explicit BaseChooserOnlyDateAndTimeInputType(HTMLInputElement& element) : BaseDateAndTimeInputType(element) { }
+    BaseChooserOnlyDateAndTimeInputType(HTMLInputElement& element) : BaseDateAndTimeInputType(element) { }
     virtual ~BaseChooserOnlyDateAndTimeInputType();
 
 private:
@@ -62,7 +59,7 @@
     virtual void didChooseValue(double) OVERRIDE;
     virtual void didEndChooser() OVERRIDE;
 
-    RefPtrWillBeMember<DateTimeChooser> m_dateTimeChooser;
+    RefPtr<DateTimeChooser> m_dateTimeChooser;
 };
 
 }
diff --git a/Source/core/html/shadow/MediaControls.cpp b/Source/core/html/shadow/MediaControls.cpp
index 4b5c0f0..7960cac 100644
--- a/Source/core/html/shadow/MediaControls.cpp
+++ b/Source/core/html/shadow/MediaControls.cpp
@@ -45,6 +45,11 @@
     return !document.settings() || document.settings()->fullscreenSupported();
 }
 
+static bool deviceSupportsMouse(const Document& document)
+{
+    return !document.settings() || document.settings()->deviceSupportsMouse();
+}
+
 MediaControls::MediaControls(HTMLMediaElement& mediaElement)
     : HTMLDivElement(mediaElement.document())
     , m_mediaElement(&mediaElement)
@@ -229,9 +234,13 @@
     // Never hide for a media element without visual representation.
     if (!mediaElement().hasVideo())
         return false;
-    // Don't hide if the controls are hovered or the mouse is over the video area.
+    // Don't hide if the mouse is over the controls.
+    const bool ignoreControlsHover = behaviorFlags & IgnoreControlsHover;
+    if (!ignoreControlsHover && m_panel->hovered())
+        return false;
+    // Don't hide if the mouse is over the video area.
     const bool ignoreVideoHover = behaviorFlags & IgnoreVideoHover;
-    if (m_panel->hovered() || (!ignoreVideoHover && m_isMouseOverControls))
+    if (!ignoreVideoHover && m_isMouseOverControls)
         return false;
     // Don't hide if focus is on the HTMLMediaElement or within the
     // controls/shadow tree. (Perform the checks separately to avoid going
@@ -399,7 +408,12 @@
     if (mediaElement().togglePlayStateWillPlay())
         return;
 
-    if (!shouldHideMediaControls(IgnoreFocus | IgnoreVideoHover))
+    unsigned behaviorFlags = IgnoreFocus | IgnoreVideoHover;
+    // FIXME: improve this check, see http://www.crbug.com/401177.
+    if (!deviceSupportsMouse(document())) {
+        behaviorFlags |= IgnoreControlsHover;
+    }
+    if (!shouldHideMediaControls(behaviorFlags))
         return;
 
     makeTransparent();
diff --git a/Source/core/html/shadow/MediaControls.h b/Source/core/html/shadow/MediaControls.h
index 21c767a..a08c21b 100644
--- a/Source/core/html/shadow/MediaControls.h
+++ b/Source/core/html/shadow/MediaControls.h
@@ -82,7 +82,8 @@
 
     enum HideBehaviorFlags {
         IgnoreVideoHover = 1 << 0,
-        IgnoreFocus = 1 << 1
+        IgnoreFocus = 1 << 1,
+        IgnoreControlsHover = 1 << 2
     };
 
     bool shouldHideMediaControls(unsigned behaviorFlags = 0) const;
diff --git a/Source/core/html/shadow/PickerIndicatorElement.cpp b/Source/core/html/shadow/PickerIndicatorElement.cpp
index 13ffe01..b704634 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.cpp
+++ b/Source/core/html/shadow/PickerIndicatorElement.cpp
@@ -62,6 +62,8 @@
 
 PickerIndicatorElement::~PickerIndicatorElement()
 {
+    closePopup();
+    ASSERT(!m_chooser);
 }
 
 RenderObject* PickerIndicatorElement::createRenderer(RenderStyle*)
@@ -152,9 +154,7 @@
 void PickerIndicatorElement::trace(Visitor* visitor)
 {
     visitor->trace(m_pickerIndicatorOwner);
-    visitor->trace(m_chooser);
     HTMLDivElement::trace(visitor);
-    DateTimeChooserClient::trace(visitor);
 }
 
 }
diff --git a/Source/core/html/shadow/PickerIndicatorElement.h b/Source/core/html/shadow/PickerIndicatorElement.h
index 5d16338..de93905 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.h
+++ b/Source/core/html/shadow/PickerIndicatorElement.h
@@ -42,7 +42,6 @@
 class PagePopup;
 
 class PickerIndicatorElement FINAL : public HTMLDivElement, public DateTimeChooserClient {
-    WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(PickerIndicatorElement);
 public:
     // PickerIndicatorOwner implementer must call removePickerIndicatorOwner when
     // it doesn't handle event, e.g. at destruction.
@@ -80,7 +79,7 @@
     HTMLInputElement* hostInput();
 
     RawPtrWillBeMember<PickerIndicatorOwner> m_pickerIndicatorOwner;
-    RefPtrWillBeMember<DateTimeChooser> m_chooser;
+    RefPtr<DateTimeChooser> m_chooser;
     bool m_isInOpenPopup;
 };
 
diff --git a/Source/core/loader/EmptyClients.cpp b/Source/core/loader/EmptyClients.cpp
index 3d788dc..26cb664 100644
--- a/Source/core/loader/EmptyClients.cpp
+++ b/Source/core/loader/EmptyClients.cpp
@@ -86,9 +86,9 @@
     return nullptr;
 }
 
-PassRefPtrWillBeRawPtr<DateTimeChooser> EmptyChromeClient::openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&)
+PassRefPtr<DateTimeChooser> EmptyChromeClient::openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&)
 {
-    return nullptr;
+    return PassRefPtr<DateTimeChooser>();
 }
 
 void EmptyChromeClient::openTextDataListChooser(HTMLInputElement&)
diff --git a/Source/core/loader/EmptyClients.h b/Source/core/loader/EmptyClients.h
index 8b8d49b..b37b7a5 100644
--- a/Source/core/loader/EmptyClients.h
+++ b/Source/core/loader/EmptyClients.h
@@ -144,7 +144,7 @@
     virtual void enumerateChosenDirectory(FileChooser*) OVERRIDE { }
 
     virtual PassOwnPtr<ColorChooser> createColorChooser(LocalFrame*, ColorChooserClient*, const Color&) OVERRIDE;
-    virtual PassRefPtrWillBeRawPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) OVERRIDE;
+    virtual PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) OVERRIDE;
     virtual void openTextDataListChooser(HTMLInputElement&) OVERRIDE;
 
     virtual void runOpenPanel(LocalFrame*, PassRefPtr<FileChooser>) OVERRIDE;
diff --git a/Source/core/loader/FrameFetchContext.cpp b/Source/core/loader/FrameFetchContext.cpp
index 608a18b..da7a4df 100644
--- a/Source/core/loader/FrameFetchContext.cpp
+++ b/Source/core/loader/FrameFetchContext.cpp
@@ -60,20 +60,23 @@
     bool isMainResource = type == FetchMainResource;
     if (!isMainResource) {
         String outgoingReferrer;
+        ReferrerPolicy referrerPolicy;
         String outgoingOrigin;
         if (request.httpReferrer().isNull()) {
             outgoingReferrer = document->outgoingReferrer();
+            referrerPolicy = document->referrerPolicy();
             outgoingOrigin = document->outgoingOrigin();
         } else {
             outgoingReferrer = request.httpReferrer();
+            referrerPolicy = request.referrerPolicy();
             outgoingOrigin = SecurityOrigin::createFromString(outgoingReferrer)->toString();
         }
 
-        outgoingReferrer = SecurityPolicy::generateReferrerHeader(document->referrerPolicy(), request.url(), outgoingReferrer);
+        outgoingReferrer = SecurityPolicy::generateReferrerHeader(referrerPolicy, request.url(), outgoingReferrer);
         if (outgoingReferrer.isEmpty())
             request.clearHTTPReferrer();
-        else if (!request.httpReferrer())
-            request.setHTTPReferrer(Referrer(outgoingReferrer, document->referrerPolicy()));
+        else
+            request.setHTTPReferrer(Referrer(outgoingReferrer, referrerPolicy));
 
         request.addHTTPOriginIfNeeded(AtomicString(outgoingOrigin));
     }
diff --git a/Source/core/page/Chrome.cpp b/Source/core/page/Chrome.cpp
index 412fcbf..e2fffaa 100644
--- a/Source/core/page/Chrome.cpp
+++ b/Source/core/page/Chrome.cpp
@@ -341,7 +341,7 @@
     return m_client->createColorChooser(frame, client, initialColor);
 }
 
-PassRefPtrWillBeRawPtr<DateTimeChooser> Chrome::openDateTimeChooser(DateTimeChooserClient* client, const DateTimeChooserParameters& parameters)
+PassRefPtr<DateTimeChooser> Chrome::openDateTimeChooser(DateTimeChooserClient* client, const DateTimeChooserParameters& parameters)
 {
     notifyPopupOpeningObservers();
     return m_client->openDateTimeChooser(client, parameters);
diff --git a/Source/core/page/Chrome.h b/Source/core/page/Chrome.h
index 42dcc6d..d7683e8 100644
--- a/Source/core/page/Chrome.h
+++ b/Source/core/page/Chrome.h
@@ -26,7 +26,6 @@
 #include "core/page/FocusType.h"
 #include "platform/Cursor.h"
 #include "platform/HostWindow.h"
-#include "platform/heap/Handle.h"
 #include "wtf/Forward.h"
 
 namespace blink {
@@ -118,7 +117,7 @@
     void print(LocalFrame*);
 
     PassOwnPtr<ColorChooser> createColorChooser(LocalFrame*, ColorChooserClient*, const Color& initialColor);
-    PassRefPtrWillBeRawPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&);
+    PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&);
     void openTextDataListChooser(HTMLInputElement&);
 
     void runOpenPanel(LocalFrame*, PassRefPtr<FileChooser>);
diff --git a/Source/core/page/ChromeClient.h b/Source/core/page/ChromeClient.h
index 48d4940..ec61965 100644
--- a/Source/core/page/ChromeClient.h
+++ b/Source/core/page/ChromeClient.h
@@ -168,7 +168,7 @@
     //    returns true, if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
     //  - <datalist> UI for date/time input types regardless of
     //    ENABLE(INPUT_MULTIPLE_FIELDS_UI)
-    virtual PassRefPtrWillBeRawPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) = 0;
+    virtual PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) = 0;
 
     virtual void openTextDataListChooser(HTMLInputElement&) = 0;
 
diff --git a/Source/core/page/EventHandler.cpp b/Source/core/page/EventHandler.cpp
index 66c7a6b..f0166a1 100644
--- a/Source/core/page/EventHandler.cpp
+++ b/Source/core/page/EventHandler.cpp
@@ -2097,11 +2097,6 @@
     RefPtr<Scrollbar> scrollbar = targetedEvent.hitTestResult().scrollbar();
     const PlatformGestureEvent& gestureEvent = targetedEvent.event();
 
-    if (!scrollbar) {
-        FrameView* view = m_frame->view();
-        scrollbar = view ? view->scrollbarAtPoint(gestureEvent.position()) : 0;
-    }
-
     if (scrollbar) {
         bool eventSwallowed = scrollbar->gestureEvent(gestureEvent);
         if (gestureEvent.type() == PlatformEvent::GestureTapDown && eventSwallowed)
@@ -2226,55 +2221,56 @@
         modifierFlags |= PlatformEvent::ShiftKey;
     PlatformEvent::Modifiers modifiers = static_cast<PlatformEvent::Modifiers>(modifierFlags);
 
+    HitTestResult currentHitTest = targetedEvent.hitTestResult();
+
     // We use the adjusted position so the application isn't surprised to see a event with
     // co-ordinates outside the target's bounds.
     IntPoint adjustedPoint = m_frame->view()->windowToContents(gestureEvent.position());
 
-    // Do a new hit-test at the (adjusted) gesture co-ordinates. This is necessary because
-    // touch adjustment sometimes returns a different node than what hit testing would return
-    // for the same point.
-    // FIXME: Fix touch adjustment to avoid the need for a redundant hit test. http://crbug.com/398914
-    HitTestResult newHitTest = hitTestResultInFrame(m_frame, adjustedPoint, HitTestRequest::ReadOnly);
-
     PlatformMouseEvent fakeMouseMove(adjustedPoint, gestureEvent.globalPosition(),
         NoButton, PlatformEvent::MouseMoved, /* clickCount */ 0,
         modifiers, PlatformMouseEvent::FromTouch, gestureEvent.timestamp());
-    dispatchMouseEvent(EventTypeNames::mousemove, newHitTest.targetNode(), 0, fakeMouseMove, true);
+    dispatchMouseEvent(EventTypeNames::mousemove, currentHitTest.innerNode(), 0, fakeMouseMove, true);
 
     // Do a new hit-test in case the mousemove event changed the DOM.
+    // Note that if the original hit test wasn't over an element (eg. was over a scrollbar) we
+    // don't want to re-hit-test because it may be in the wrong frame (and there's no way the page
+    // could have seen the event anyway).
     // FIXME: Use a hit-test cache to avoid unnecessary hit tests. http://crbug.com/398920
-    newHitTest = hitTestResultInFrame(m_frame, adjustedPoint, HitTestRequest::ReadOnly);
-    m_clickNode = newHitTest.targetNode();
+    if (currentHitTest.innerNode())
+        currentHitTest = hitTestResultInFrame(m_frame, adjustedPoint, HitTestRequest::ReadOnly);
+    m_clickNode = currentHitTest.innerNode();
     if (m_clickNode && m_clickNode->isTextNode())
         m_clickNode = NodeRenderingTraversal::parent(m_clickNode.get());
 
     PlatformMouseEvent fakeMouseDown(adjustedPoint, gestureEvent.globalPosition(),
         LeftButton, PlatformEvent::MousePressed, gestureEvent.tapCount(),
         modifiers, PlatformMouseEvent::FromTouch,  gestureEvent.timestamp());
-    bool swallowMouseDownEvent = !dispatchMouseEvent(EventTypeNames::mousedown, newHitTest.targetNode(), gestureEvent.tapCount(), fakeMouseDown, true);
+    bool swallowMouseDownEvent = !dispatchMouseEvent(EventTypeNames::mousedown, currentHitTest.innerNode(), gestureEvent.tapCount(), fakeMouseDown, true);
     if (!swallowMouseDownEvent)
         swallowMouseDownEvent = handleMouseFocus(fakeMouseDown);
     if (!swallowMouseDownEvent)
-        swallowMouseDownEvent = handleMousePressEvent(MouseEventWithHitTestResults(fakeMouseDown, newHitTest));
+        swallowMouseDownEvent = handleMousePressEvent(MouseEventWithHitTestResults(fakeMouseDown, currentHitTest));
 
     // FIXME: Use a hit-test cache to avoid unnecessary hit tests. http://crbug.com/398920
-    newHitTest = hitTestResultInFrame(m_frame, adjustedPoint, HitTestRequest::ReadOnly);
+    if (currentHitTest.innerNode())
+        currentHitTest = hitTestResultInFrame(m_frame, adjustedPoint, HitTestRequest::ReadOnly);
     PlatformMouseEvent fakeMouseUp(adjustedPoint, gestureEvent.globalPosition(),
         LeftButton, PlatformEvent::MouseReleased, gestureEvent.tapCount(),
         modifiers, PlatformMouseEvent::FromTouch,  gestureEvent.timestamp());
-    bool swallowMouseUpEvent = !dispatchMouseEvent(EventTypeNames::mouseup, newHitTest.targetNode(), gestureEvent.tapCount(), fakeMouseUp, false);
+    bool swallowMouseUpEvent = !dispatchMouseEvent(EventTypeNames::mouseup, currentHitTest.innerNode(), gestureEvent.tapCount(), fakeMouseUp, false);
 
     bool swallowClickEvent = false;
     if (m_clickNode) {
-        if (newHitTest.targetNode()) {
-            Node* clickTargetNode = newHitTest.targetNode()->commonAncestor(*m_clickNode, parentForClickEvent);
+        if (currentHitTest.innerNode()) {
+            Node* clickTargetNode = currentHitTest.innerNode()->commonAncestor(*m_clickNode, parentForClickEvent);
             swallowClickEvent = !dispatchMouseEvent(EventTypeNames::click, clickTargetNode, gestureEvent.tapCount(), fakeMouseUp, true);
         }
         m_clickNode = nullptr;
     }
 
     if (!swallowMouseUpEvent)
-        swallowMouseUpEvent = handleMouseReleaseEvent(MouseEventWithHitTestResults(fakeMouseUp, newHitTest));
+        swallowMouseUpEvent = handleMouseReleaseEvent(MouseEventWithHitTestResults(fakeMouseUp, currentHitTest));
 
     return swallowMouseDownEvent | swallowMouseUpEvent | swallowClickEvent;
 }
@@ -2588,11 +2584,36 @@
     // FIXME: We should not do a rect-based hit-test if touch adjustment is disabled.
     HitTestResult hitTestResult = hitTestResultAtPoint(hitTestPoint, hitType | HitTestRequest::ReadOnly, touchRadius);
 
+    // Hit-test the main frame scrollbars (in addition to the child-frame and RenderLayer
+    // scroll bars checked by the hit-test code.
+    if (!hitTestResult.scrollbar()) {
+        if (FrameView* view = m_frame->view()) {
+            hitTestResult.setScrollbar(view->scrollbarAtPoint(gestureEvent.position()));
+        }
+    }
+
     // Adjust the location of the gesture to the most likely nearby node, as appropriate for the
     // type of event.
     PlatformGestureEvent adjustedEvent = gestureEvent;
     applyTouchAdjustment(&adjustedEvent, &hitTestResult);
 
+    // Do a new hit-test at the (adjusted) gesture co-ordinates. This is necessary because
+    // rect-based hit testing and touch adjustment sometimes return a different node than
+    // what a point-based hit test would return for the same point.
+    // FIXME: Fix touch adjustment to avoid the need for a redundant hit test. http://crbug.com/398914
+    if (shouldApplyTouchAdjustment(gestureEvent)) {
+        LocalFrame* hitFrame = hitTestResult.innerNodeFrame();
+        if (!hitFrame)
+            hitFrame = m_frame;
+        hitTestResult = hitTestResultInFrame(hitFrame, hitFrame->view()->windowToContents(adjustedEvent.position()), hitType | HitTestRequest::ReadOnly);
+        // FIXME: HitTest entry points should really check for main frame scrollbars themselves.
+        if (!hitTestResult.scrollbar()) {
+            if (FrameView* view = m_frame->view()) {
+                hitTestResult.setScrollbar(view->scrollbarAtPoint(gestureEvent.position()));
+            }
+        }
+    }
+
     // Now apply hover/active state to the final target.
     // FIXME: This is supposed to send mouseenter/mouseleave events, but doesn't because we
     // aren't passing a PlatformMouseEvent.
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index 56d2f40..f111de6 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -1766,7 +1766,9 @@
 
     // FIXME: For now just support fixed heights.  Eventually should support percentage heights as well.
     if (!logicalHeightLength.isFixed()) {
-        LayoutUnit fillFallbackExtent = containingBlockStyle->isHorizontalWritingMode() ? view()->frameView()->visibleHeight() : view()->frameView()->visibleWidth();
+        LayoutUnit fillFallbackExtent = containingBlockStyle->isHorizontalWritingMode()
+            ? view()->frameView()->unscaledVisibleContentSize().height()
+            : view()->frameView()->unscaledVisibleContentSize().width();
         LayoutUnit fillAvailableExtent = containingBlock()->availableLogicalHeight(ExcludeMarginBorderPadding);
         return std::min(fillAvailableExtent, fillFallbackExtent);
     }
@@ -2853,7 +2855,7 @@
 LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h, AvailableLogicalHeightType heightType) const
 {
     if (isRenderView())
-        return isHorizontalWritingMode() ? toRenderView(this)->frameView()->visibleHeight() : toRenderView(this)->frameView()->visibleWidth();
+        return isHorizontalWritingMode() ? toRenderView(this)->frameView()->unscaledVisibleContentSize().height() : toRenderView(this)->frameView()->unscaledVisibleContentSize().width();
 
     // We need to stop here, since we don't want to increase the height of the table
     // artificially.  We're going to rely on this cell getting expanded to some new
diff --git a/Source/core/rendering/RenderLayer.cpp b/Source/core/rendering/RenderLayer.cpp
index 6ec78b9..08a6368 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -907,7 +907,7 @@
 RenderLayer* RenderLayer::enclosingTransformedAncestor() const
 {
     RenderLayer* curr = parent();
-    while (curr && !curr->isRootLayer() && !curr->transform())
+    while (curr && !curr->isRootLayer() && !curr->renderer()->hasTransform())
         curr = curr->parent();
 
     return curr;
diff --git a/Source/core/rendering/RenderLayerScrollableArea.cpp b/Source/core/rendering/RenderLayerScrollableArea.cpp
index 9b304aa..633c4c6 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.cpp
+++ b/Source/core/rendering/RenderLayerScrollableArea.cpp
@@ -365,10 +365,7 @@
         box().setPreviousPaintInvalidationRect(box().boundsRectForPaintInvalidation(repaintContainer));
         // Update regions, scrolling may change the clip of a particular region.
         frameView->updateAnnotatedRegions();
-        // FIXME: We shouldn't call updateWidgetPositions() here since it might tear down the render tree,
-        // for now we just crash to avoid allowing an attacker to use after free.
-        frameView->updateWidgetPositions();
-        RELEASE_ASSERT(frameView->renderView());
+        frameView->setNeedsUpdateWidgetPositions();
         updateCompositingLayersAfterScroll();
     }
 
diff --git a/Source/core/rendering/RenderObject.cpp b/Source/core/rendering/RenderObject.cpp
index 88dae63..5964f5c 100644
--- a/Source/core/rendering/RenderObject.cpp
+++ b/Source/core/rendering/RenderObject.cpp
@@ -1327,11 +1327,16 @@
                 box->addFocusRingRects(layerFocusRingRects, LayoutPoint(), box);
                 for (size_t i = 0; i < layerFocusRingRects.size(); ++i) {
                     FloatQuad quadInBox = box->localToContainerQuad(FloatRect(layerFocusRingRects[i]), paintContainer);
-                    rects.append(pixelSnappedIntRect(LayoutRect(quadInBox.boundingBox())));
+                    FloatRect rect = quadInBox.boundingBox();
+                    // Floor the location instead of using pixelSnappedIntRect to match the !hasLayer() path.
+                    // FIXME: roundedIntSize matches pixelSnappedIntRect in other places of addFocusRingRects
+                    // because we always floor the offset.
+                    // This assumption is fragile and should be replaced by better solution.
+                    rects.append(IntRect(flooredIntPoint(rect.location()), roundedIntSize(rect.size())));
                 }
             } else {
                 FloatPoint pos(additionalOffset);
-                pos.move(box->locationOffset()); // FIXME: Snap offsets? crbug.com/350474
+                pos.move(box->locationOffset());
                 box->addFocusRingRects(rects, flooredIntPoint(pos), paintContainer);
             }
         } else {
diff --git a/Source/core/rendering/RenderSelectionInfo.h b/Source/core/rendering/RenderSelectionInfo.h
index cdcc7df..f0deb6b 100644
--- a/Source/core/rendering/RenderSelectionInfo.h
+++ b/Source/core/rendering/RenderSelectionInfo.h
@@ -81,7 +81,7 @@
 
     void repaint()
     {
-        m_object->invalidatePaintUsingContainer(m_repaintContainer, m_rect, InvalidationSelection);
+        m_object->invalidatePaintUsingContainer(m_repaintContainer, enclosingIntRect(m_rect), InvalidationSelection);
     }
 
     LayoutRect rect() const { return m_rect; }
@@ -111,7 +111,7 @@
         // repaintContainer as the render object. Find out why it does that and fix.
         if (m_repaintContainer && m_repaintContainer->layer()->groupedMapping())
             RenderLayer::mapRectToPaintInvalidationBacking(m_repaintContainer, m_repaintContainer, repaintRect);
-        m_object->invalidatePaintUsingContainer(m_repaintContainer, repaintRect, InvalidationSelection);
+        m_object->invalidatePaintUsingContainer(m_repaintContainer, enclosingIntRect(repaintRect), InvalidationSelection);
     }
 
     RenderBlock* block() const { return toRenderBlock(m_object); }
diff --git a/Source/core/rendering/compositing/CompositedLayerMapping.cpp b/Source/core/rendering/compositing/CompositedLayerMapping.cpp
index a65bbdd..cfd9b13 100644
--- a/Source/core/rendering/compositing/CompositedLayerMapping.cpp
+++ b/Source/core/rendering/compositing/CompositedLayerMapping.cpp
@@ -54,6 +54,7 @@
 #include "platform/LengthFunctions.h"
 #include "platform/RuntimeEnabledFeatures.h"
 #include "platform/fonts/FontCache.h"
+#include "platform/geometry/TransformState.h"
 #include "platform/graphics/GraphicsContext.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/text/StringBuilder.h"
@@ -761,11 +762,12 @@
 
             m_overflowControlsHostLayer->setPosition(IntPoint(-m_overflowControlsClippingLayer->offsetFromRenderer()));
         } else {
-            ASSERT(m_owningLayer.transformAncestor() == compositingStackingContext->transformAncestor());
-            LayoutPoint localOffsetToTransformedAncestor = m_owningLayer.computeOffsetFromTransformedAncestor();
-            LayoutPoint compositingStackingContextOffsetToTransformedAncestor = compositingStackingContext->computeOffsetFromTransformedAncestor();
-
-            m_overflowControlsHostLayer->setPosition(FloatPoint(localOffsetToTransformedAncestor - compositingStackingContextOffsetToTransformedAncestor));
+            // The controls are in the same 2D space as the compositing container, so we can map them into the space of the container.
+            TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
+            m_owningLayer.renderer()->mapLocalToContainer(compositingStackingContext->renderer(), transformState, ApplyContainerFlip);
+            transformState.flatten();
+            LayoutPoint offsetFromStackingContainer = LayoutPoint(transformState.lastPlanarPoint());
+            m_overflowControlsHostLayer->setPosition(FloatPoint(offsetFromStackingContainer));
         }
     } else {
         m_overflowControlsHostLayer->setPosition(FloatPoint());
@@ -1885,11 +1887,13 @@
         && (compositingAncestorLayer->compositedLayerMapping()->mainGraphicsLayer()->drawsContent()
             || compositingAncestorLayer->compositedLayerMapping()->paintsIntoCompositedAncestor());
 
-    if (paintsIntoCompositedAncestor() != previousPaintsIntoCompositedAncestor)
-        compositor()->paintInvalidationOnCompositingChange(&m_owningLayer);
-
-    // FIXME: this is bogus. We need to make this assignment before the check above.
     m_requiresOwnBackingStoreForAncestorReasons = !canPaintIntoAncestor;
+    if (paintsIntoCompositedAncestor() != previousPaintsIntoCompositedAncestor) {
+        // Back out the change temporarily while invalidating with respect to the old container.
+        m_requiresOwnBackingStoreForAncestorReasons = !m_requiresOwnBackingStoreForAncestorReasons;
+        compositor()->paintInvalidationOnCompositingChange(&m_owningLayer);
+        m_requiresOwnBackingStoreForAncestorReasons = !m_requiresOwnBackingStoreForAncestorReasons;
+    }
 
     return m_requiresOwnBackingStoreForAncestorReasons != previousRequiresOwnBackingStoreForAncestorReasons;
 }
@@ -1908,8 +1912,12 @@
         || renderer->hasReflection()
         || renderer->hasFilter();
 
-    if (paintsIntoCompositedAncestor() != previousPaintsIntoCompositedAncestor)
+    if (paintsIntoCompositedAncestor() != previousPaintsIntoCompositedAncestor) {
+        // Back out the change temporarily while invalidating with respect to the old container.
+        m_requiresOwnBackingStoreForIntrinsicReasons = !m_requiresOwnBackingStoreForIntrinsicReasons;
         compositor()->paintInvalidationOnCompositingChange(&m_owningLayer);
+        m_requiresOwnBackingStoreForIntrinsicReasons = !m_requiresOwnBackingStoreForIntrinsicReasons;
+    }
 
     return m_requiresOwnBackingStoreForIntrinsicReasons != previousRequiresOwnBackingStoreForIntrinsicReasons;
 }
diff --git a/Source/core/rendering/compositing/CompositingInputsUpdater.cpp b/Source/core/rendering/compositing/CompositingInputsUpdater.cpp
index 5355a6c..1bf13b1 100644
--- a/Source/core/rendering/compositing/CompositingInputsUpdater.cpp
+++ b/Source/core/rendering/compositing/CompositingInputsUpdater.cpp
@@ -114,7 +114,7 @@
 
             const RenderLayer* parent = layer->parent();
             properties.opacityAncestor = parent->isTransparent() ? parent : parent->opacityAncestor();
-            properties.transformAncestor = parent->transform() ? parent : parent->transformAncestor();
+            properties.transformAncestor = parent->hasTransform() ? parent : parent->transformAncestor();
             properties.filterAncestor = parent->hasFilter() ? parent : parent->filterAncestor();
 
             if (info.hasAncestorWithClipOrOverflowClip) {
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
index bd59c28..2df4523 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
@@ -165,7 +165,7 @@
     ASSERT(sourceGraphic);
     builder.setSourceGraphic(sourceGraphic);
     RefPtr<ImageFilter> imageFilter = builder.build(filterData->builder->lastEffect(), ColorSpaceDeviceRGB);
-    FloatRect boundaries = enclosingIntRect(filterData->boundaries);
+    FloatRect boundaries = filterData->boundaries;
     context->save();
 
     FloatSize deviceSize = context->getCTM().mapSize(boundaries.size());
@@ -181,8 +181,9 @@
         float scale = sqrtf(FilterEffect::maxFilterArea() / scaledArea);
         context->scale(scale, scale);
     }
-    // Clip drawing of filtered image to primitive boundaries.
-    context->clipRect(boundaries);
+    // Clip drawing of filtered image to the minimum required paint rect.
+    FilterEffect* lastEffect = filterData->builder->lastEffect();
+    context->clipRect(lastEffect->determineAbsolutePaintRect(lastEffect->maxEffectRect()));
     if (filterElement->hasAttribute(SVGNames::filterResAttr)) {
         // Get boundaries in device coords.
         // FIXME: See crbug.com/382491. Is the use of getCTM OK here, given it does not include device
diff --git a/Source/devtools/front_end/elements/ElementsPanel.js b/Source/devtools/front_end/elements/ElementsPanel.js
index f92bae6..f43abb3 100644
--- a/Source/devtools/front_end/elements/ElementsPanel.js
+++ b/Source/devtools/front_end/elements/ElementsPanel.js
@@ -107,7 +107,7 @@
     WebInspector.targetManager.observeTargets(this);
     WebInspector.settings.showUAShadowDOM.addChangeListener(this._showUAShadowDOMChanged.bind(this));
     WebInspector.targetManager.addModelListener(WebInspector.DOMModel, WebInspector.DOMModel.Events.DocumentUpdated, this._documentUpdatedEvent, this);
-    WebInspector.targetManager.addModelListener(WebInspector.DOMModel, WebInspector.CSSStyleModel.Events.ModelWasEnabled, this._updateSidebars, this);
+    WebInspector.targetManager.addModelListener(WebInspector.CSSStyleModel, WebInspector.CSSStyleModel.Events.ModelWasEnabled, this._updateSidebars, this);
 }
 
 WebInspector.ElementsPanel.prototype = {
@@ -1162,12 +1162,9 @@
             }
         }
 
-        var element = event.target.enclosingNodeOrSelfWithClass("elements-tree-outline");
-        if (!element)
-            return;
         var treeOutline = null;
         for (var i = 0; i < this._treeOutlines.length; ++i) {
-            if (this._treeOutlines[i].element === element)
+            if (this._treeOutlines[i].selectedDOMNode() === this._lastValidSelectedNode)
                 treeOutline = this._treeOutlines[i];
         }
         if (!treeOutline)
diff --git a/Source/devtools/front_end/elements/Spectrum.js b/Source/devtools/front_end/elements/Spectrum.js
index 492424f..67d0454 100644
--- a/Source/devtools/front_end/elements/Spectrum.js
+++ b/Source/devtools/front_end/elements/Spectrum.js
@@ -365,6 +365,7 @@
             this.hide(true);
         }
 
+        delete this._isHidden;
         this._anchorElement = element;
 
         this._spectrum.setColor(color);
@@ -373,6 +374,7 @@
 
         document.addEventListener("mousedown", this._hideProxy, false);
         window.addEventListener("blur", this._hideProxy, false);
+        window.addEventListener("resize", this._hideProxy, false);
         return true;
     },
 
@@ -389,12 +391,14 @@
      */
     hide: function(commitEdit)
     {
-        if (!this._popover.isShowing())
+        if (this._isHidden)
             return;
+        this._isHidden = true;
         this._popover.hide();
 
         document.removeEventListener("mousedown", this._hideProxy, false);
         window.removeEventListener("blur", this._hideProxy, false);
+        window.removeEventListener("resize", this._hideProxy, false);
 
         this.dispatchEventToListeners(WebInspector.SpectrumPopupHelper.Events.Hidden, !!commitEdit);
 
diff --git a/Source/devtools/front_end/main/Main.js b/Source/devtools/front_end/main/Main.js
index 040c995..9177e28 100644
--- a/Source/devtools/front_end/main/Main.js
+++ b/Source/devtools/front_end/main/Main.js
@@ -159,10 +159,8 @@
         console.timeStamp("Main._loaded");
 
         // FIXME: Make toolbox a real app.
-        if (WebInspector.queryParam("toolbox")) {
-            new WebInspector.Toolbox();
+        if (WebInspector.queryParam("toolbox"))
             return;
-        }
 
         this._createSettings();
         this._createModuleManager();
diff --git a/Source/devtools/front_end/main/Toolbox.js b/Source/devtools/front_end/main/Toolbox.js
index 4eb9e3d..291b19e 100644
--- a/Source/devtools/front_end/main/Toolbox.js
+++ b/Source/devtools/front_end/main/Toolbox.js
@@ -14,7 +14,7 @@
  */
 WebInspector.Toolbox = function()
 {
-    if (!window.opener)
+    if (!window.opener || !WebInspector.queryParam("toolbox"))
         return;
 
     WebInspector.zoomManager = new WebInspector.ZoomManager(window.opener.InspectorFrontendHost);
diff --git a/Source/platform/DateTimeChooser.h b/Source/platform/DateTimeChooser.h
index bec4c6c..d85c331 100644
--- a/Source/platform/DateTimeChooser.h
+++ b/Source/platform/DateTimeChooser.h
@@ -33,7 +33,6 @@
 
 #include "platform/PlatformExport.h"
 #include "platform/geometry/IntRect.h"
-#include "platform/heap/Handle.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
 
@@ -64,12 +63,12 @@
     bool isAnchorElementRTL;
 };
 
-class PLATFORM_EXPORT DateTimeChooser : public RefCountedWillBeGarbageCollectedFinalized<DateTimeChooser> {
+// For pickers like color pickers and date pickers.
+class PLATFORM_EXPORT DateTimeChooser : public RefCounted<DateTimeChooser> {
 public:
     virtual ~DateTimeChooser();
 
     virtual void endChooser() = 0;
-    virtual void trace(Visitor*) { }
 };
 
 } // namespace blink
diff --git a/Source/platform/DateTimeChooserClient.cpp b/Source/platform/DateTimeChooserClient.cpp
index 7b36bc5..73c6a3a 100644
--- a/Source/platform/DateTimeChooserClient.cpp
+++ b/Source/platform/DateTimeChooserClient.cpp
@@ -33,6 +33,8 @@
 
 namespace blink {
 
-DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(DateTimeChooserClient)
+DateTimeChooserClient::~DateTimeChooserClient()
+{
+}
 
 } // namespace blink
diff --git a/Source/platform/DateTimeChooserClient.h b/Source/platform/DateTimeChooserClient.h
index 24c1de6..302ca2f 100644
--- a/Source/platform/DateTimeChooserClient.h
+++ b/Source/platform/DateTimeChooserClient.h
@@ -32,22 +32,20 @@
 #define DateTimeChooserClient_h
 
 #include "platform/PlatformExport.h"
-#include "platform/heap/Handle.h"
 #include "wtf/text/WTFString.h"
 
 namespace blink {
 
-class PLATFORM_EXPORT DateTimeChooserClient : public WillBeGarbageCollectedMixin {
-    DECLARE_EMPTY_VIRTUAL_DESTRUCTOR_WILL_BE_REMOVED(DateTimeChooserClient);
+class PLATFORM_EXPORT DateTimeChooserClient {
 public:
+    virtual ~DateTimeChooserClient();
+
     // Called when user picked a value.
     virtual void didChooseValue(const String&) = 0;
     // Called when user picked a value.
     virtual void didChooseValue(double) = 0;
     // Called when chooser has ended.
     virtual void didEndChooser() = 0;
-
-    virtual void trace(Visitor*) { }
 };
 
 } // namespace blink
diff --git a/Source/platform/graphics/BitmapImage.cpp b/Source/platform/graphics/BitmapImage.cpp
index a090db0..4ba74c8 100644
--- a/Source/platform/graphics/BitmapImage.cpp
+++ b/Source/platform/graphics/BitmapImage.cpp
@@ -368,7 +368,7 @@
 
 PassRefPtr<Image> BitmapImage::imageForDefaultFrame()
 {
-    if (isBitmapImage() && maybeAnimated())
+    if (isAnimated())
         return BitmapImage::create(frameAtIndex(0));
 
     return Image::imageForDefaultFrame();
@@ -553,11 +553,17 @@
 {
     if (m_animationFinished)
         return false;
-    if (frameCount() > 1)
+    if (isAnimated())
         return true;
+
     return m_source.repetitionCount() != cAnimationNone;
 }
 
+bool BitmapImage::isAnimated()
+{
+    return frameCount() > 1;
+}
+
 void BitmapImage::advanceAnimation(Timer<BitmapImage>*)
 {
     internalAdvanceAnimation(false);
diff --git a/Source/platform/graphics/BitmapImage.h b/Source/platform/graphics/BitmapImage.h
index 05dede7..d085182 100644
--- a/Source/platform/graphics/BitmapImage.h
+++ b/Source/platform/graphics/BitmapImage.h
@@ -106,6 +106,8 @@
     virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator, WebBlendMode) OVERRIDE;
     virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator, WebBlendMode, RespectImageOrientationEnum) OVERRIDE;
 
+    // True if the image is animated (contains multiple frames)
+    bool isAnimated();
     size_t currentFrame() const { return m_currentFrame; }
     size_t frameCount();
     PassRefPtr<NativeImageSkia> frameAtIndex(size_t);
diff --git a/Source/platform/graphics/Canvas2DImageBufferSurface.h b/Source/platform/graphics/Canvas2DImageBufferSurface.h
index cd00958..fc18234 100644
--- a/Source/platform/graphics/Canvas2DImageBufferSurface.h
+++ b/Source/platform/graphics/Canvas2DImageBufferSurface.h
@@ -53,7 +53,7 @@
     }
 
     // ImageBufferSurface implementation
-    virtual void finalizeFrame() OVERRIDE { m_layerBridge->finalizeFrame(); }
+    virtual void finalizeFrame(const FloatRect &dirtyRect) OVERRIDE { m_layerBridge->finalizeFrame(dirtyRect); }
     virtual void willAccessPixels() OVERRIDE { m_layerBridge->willAccessPixels(); }
     virtual SkCanvas* canvas() const OVERRIDE { return m_layerBridge->canvas(); }
     virtual bool isValid() const OVERRIDE { return m_layerBridge && m_layerBridge->checkSurfaceValid(); }
diff --git a/Source/platform/graphics/Canvas2DLayerBridge.cpp b/Source/platform/graphics/Canvas2DLayerBridge.cpp
index f88c278..ac1f0c8 100644
--- a/Source/platform/graphics/Canvas2DLayerBridge.cpp
+++ b/Source/platform/graphics/Canvas2DLayerBridge.cpp
@@ -175,6 +175,8 @@
 void Canvas2DLayerBridge::freeTransientResources()
 {
     ASSERT(!m_destructionInProgress);
+    if (!m_isSurfaceValid)
+        return;
     freeReleasedMailbox();
     flush();
     freeMemoryIfPossible(bytesAllocated());
@@ -543,10 +545,11 @@
     return m_layer->layer();
 }
 
-void Canvas2DLayerBridge::finalizeFrame()
+void Canvas2DLayerBridge::finalizeFrame(const FloatRect &dirtyRect)
 {
     ASSERT(!m_destructionInProgress);
     Canvas2DLayerManager::get().layerDidDraw(this);
+    m_layer->layer()->invalidateRect(dirtyRect);
     m_didRecordDrawCommand = true;
 }
 
diff --git a/Source/platform/graphics/Canvas2DLayerBridge.h b/Source/platform/graphics/Canvas2DLayerBridge.h
index a1efa63..3b93e43 100644
--- a/Source/platform/graphics/Canvas2DLayerBridge.h
+++ b/Source/platform/graphics/Canvas2DLayerBridge.h
@@ -66,7 +66,7 @@
     virtual void skippedPendingDrawCommands() OVERRIDE;
 
     // ImageBufferSurface implementation
-    void finalizeFrame();
+    void finalizeFrame(const FloatRect &dirtyRect);
     void willAccessPixels();
     SkCanvas* canvas() const { return m_canvas.get(); }
     bool checkSurfaceValid();
diff --git a/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp b/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp
index ef0fcfe..e710614 100644
--- a/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp
+++ b/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp
@@ -135,6 +135,39 @@
         ::testing::Mock::VerifyAndClearExpectations(&mainMock);
     }
 
+    void noDrawOnContextLostTest()
+    {
+        MockCanvasContext mainMock;
+        OwnPtr<MockWebGraphicsContext3DProvider> mainMockProvider = adoptPtr(new MockWebGraphicsContext3DProvider(&mainMock));
+        RefPtr<SkSurface> surface = adoptRef(SkSurface::NewRasterPMColor(300, 150));
+        OwnPtr<SkDeferredCanvas> canvas = adoptPtr(SkDeferredCanvas::Create(surface.get()));
+
+        ::testing::Mock::VerifyAndClearExpectations(&mainMock);
+
+        {
+            Canvas2DLayerBridgePtr bridge(adoptRef(new Canvas2DLayerBridge(mainMockProvider.release(), canvas.release(), surface, 0, NonOpaque)));
+            ::testing::Mock::VerifyAndClearExpectations(&mainMock);
+            EXPECT_TRUE(bridge->checkSurfaceValid());
+            SkPaint paint;
+            uint32_t genID = surface->generationID();
+            bridge->canvas()->drawRect(SkRect::MakeXYWH(0, 0, 1, 1), paint);
+            EXPECT_EQ(genID, surface->generationID());
+            mainMock.fakeContextLost();
+            EXPECT_EQ(genID, surface->generationID());
+            bridge->canvas()->drawRect(SkRect::MakeXYWH(0, 0, 1, 1), paint);
+            EXPECT_EQ(genID, surface->generationID());
+            EXPECT_FALSE(bridge->checkSurfaceValid());
+            EXPECT_EQ(genID, surface->generationID());
+            bridge->canvas()->drawRect(SkRect::MakeXYWH(0, 0, 1, 1), paint);
+            EXPECT_EQ(genID, surface->generationID());
+            bridge->freeTransientResources();
+            EXPECT_EQ(genID, surface->generationID());
+            ::testing::Mock::VerifyAndClearExpectations(&mainMock);
+        }
+
+        ::testing::Mock::VerifyAndClearExpectations(&mainMock);
+    }
+
     void prepareMailboxWithBitmapTest()
     {
         MockCanvasContext mainMock;
@@ -157,6 +190,11 @@
     fullLifecycleTest();
 }
 
+TEST_F(Canvas2DLayerBridgeTest, testNoDrawOnContextLost)
+{
+    noDrawOnContextLostTest();
+}
+
 TEST_F(Canvas2DLayerBridgeTest, prepareMailboxWithBitmapTest)
 {
     prepareMailboxWithBitmapTest();
diff --git a/Source/platform/graphics/Canvas2DLayerManagerTest.cpp b/Source/platform/graphics/Canvas2DLayerManagerTest.cpp
index 47e5767..93e99f9 100644
--- a/Source/platform/graphics/Canvas2DLayerManagerTest.cpp
+++ b/Source/platform/graphics/Canvas2DLayerManagerTest.cpp
@@ -236,12 +236,13 @@
 
     void doDeferredFrameTestTask(FakeCanvas2DLayerBridge* layer, bool skipCommands)
     {
+        FloatRect invalidationRect(0, 0, 1, 1);
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
-        layer->finalizeFrame();
+        layer->finalizeFrame(invalidationRect);
         layer->storageAllocatedForRecordingChanged(1);
         EXPECT_TRUE(Canvas2DLayerManager::get().m_taskObserverActive);
         if (skipCommands) {
-            layer->finalizeFrame();
+            layer->finalizeFrame(invalidationRect);
             layer->skippedPendingDrawCommands();
         }
         Platform::current()->currentThread()->exitRunLoop();
diff --git a/Source/platform/graphics/GraphicsLayer.cpp b/Source/platform/graphics/GraphicsLayer.cpp
index eb89f25..5b36b9d 100644
--- a/Source/platform/graphics/GraphicsLayer.cpp
+++ b/Source/platform/graphics/GraphicsLayer.cpp
@@ -815,6 +815,7 @@
     m_contentsOpaque = opaque;
     m_layer->layer()->setOpaque(m_contentsOpaque);
     m_opaqueRectTrackingContentLayerDelegate->setOpaque(m_contentsOpaque);
+    clearContentsLayerIfUnregistered();
     if (m_contentsLayer)
         m_contentsLayer->setOpaque(opaque);
 }
diff --git a/Source/platform/graphics/ImageBuffer.cpp b/Source/platform/graphics/ImageBuffer.cpp
index 0defbb0..4ea1880 100644
--- a/Source/platform/graphics/ImageBuffer.cpp
+++ b/Source/platform/graphics/ImageBuffer.cpp
@@ -123,9 +123,9 @@
         m_client->didFinalizeFrame();
 }
 
-void ImageBuffer::finalizeFrame()
+void ImageBuffer::finalizeFrame(const FloatRect &dirtyRect)
 {
-    m_surface->finalizeFrame();
+    m_surface->finalizeFrame(dirtyRect);
     didFinalizeFrame();
 }
 
diff --git a/Source/platform/graphics/ImageBuffer.h b/Source/platform/graphics/ImageBuffer.h
index f52516a..d4ae356 100644
--- a/Source/platform/graphics/ImageBuffer.h
+++ b/Source/platform/graphics/ImageBuffer.h
@@ -90,7 +90,7 @@
     GraphicsContext* context() const;
 
     // Called at the end of a task that rendered a whole frame
-    void finalizeFrame();
+    void finalizeFrame(const FloatRect &dirtyRect);
     void didFinalizeFrame();
 
     bool isDirty();
diff --git a/Source/platform/graphics/ImageBufferSurface.h b/Source/platform/graphics/ImageBufferSurface.h
index d81ab9b..242a89d 100644
--- a/Source/platform/graphics/ImageBufferSurface.h
+++ b/Source/platform/graphics/ImageBufferSurface.h
@@ -46,6 +46,7 @@
 
 class ImageBuffer;
 class WebLayer;
+class FloatRect;
 
 enum OpacityMode {
     NonOpaque,
@@ -73,7 +74,7 @@
     virtual void setImageBuffer(ImageBuffer*) { }
     virtual PassRefPtr<SkPicture> getPicture();
     virtual void didClearCanvas() { }
-    virtual void finalizeFrame() { }
+    virtual void finalizeFrame(const FloatRect &dirtyRect) { }
 
     OpacityMode opacityMode() const { return m_opacityMode; }
     const IntSize& size() const { return m_size; }
diff --git a/Source/platform/graphics/RecordingImageBufferSurface.cpp b/Source/platform/graphics/RecordingImageBufferSurface.cpp
index 252d436..0c73332 100644
--- a/Source/platform/graphics/RecordingImageBufferSurface.cpp
+++ b/Source/platform/graphics/RecordingImageBufferSurface.cpp
@@ -102,7 +102,7 @@
     return nullptr;
 }
 
-void RecordingImageBufferSurface::finalizeFrame()
+void RecordingImageBufferSurface::finalizeFrame(const FloatRect &)
 {
     if (!finalizeFrameInternal() && !m_rasterCanvas) {
         fallBackToRasterCanvas();
diff --git a/Source/platform/graphics/RecordingImageBufferSurface.h b/Source/platform/graphics/RecordingImageBufferSurface.h
index c8af6a0..e011f07 100644
--- a/Source/platform/graphics/RecordingImageBufferSurface.h
+++ b/Source/platform/graphics/RecordingImageBufferSurface.h
@@ -29,7 +29,7 @@
     virtual PassRefPtr<SkPicture> getPicture() OVERRIDE;
     virtual bool isValid() const OVERRIDE { return true; }
     virtual void willAccessPixels() OVERRIDE;
-    virtual void finalizeFrame() OVERRIDE;
+    virtual void finalizeFrame(const FloatRect&) OVERRIDE;
     virtual void didClearCanvas() OVERRIDE;
     virtual void setImageBuffer(ImageBuffer*) OVERRIDE;
 
diff --git a/Source/platform/graphics/RecordingImageBufferSurfaceTest.cpp b/Source/platform/graphics/RecordingImageBufferSurfaceTest.cpp
index a2aedc9..e08b765 100644
--- a/Source/platform/graphics/RecordingImageBufferSurfaceTest.cpp
+++ b/Source/platform/graphics/RecordingImageBufferSurfaceTest.cpp
@@ -52,7 +52,8 @@
     virtual void didProcessTask() OVERRIDE
     {
         ASSERT_TRUE(m_isDirty);
-        m_imageBuffer->finalizeFrame();
+        FloatRect dirtyRect(0, 0, 1, 1);
+        m_imageBuffer->finalizeFrame(dirtyRect);
         ASSERT_FALSE(m_isDirty);
     }
 
diff --git a/Source/platform/graphics/test/MockWebGraphicsContext3D.h b/Source/platform/graphics/test/MockWebGraphicsContext3D.h
index cd42b39..6e93a24 100644
--- a/Source/platform/graphics/test/MockWebGraphicsContext3D.h
+++ b/Source/platform/graphics/test/MockWebGraphicsContext3D.h
@@ -37,6 +37,7 @@
 public:
     MockWebGraphicsContext3D()
         : m_nextTextureId(1)
+        , m_contextLost(false)
     {
     }
 
@@ -48,7 +49,7 @@
 
     virtual void synthesizeGLError(WGC3Denum) { }
 
-    virtual bool isContextLost() { return false; }
+    virtual bool isContextLost() { return m_contextLost; }
 
     virtual void* mapBufferSubDataCHROMIUM(WGC3Denum target, WGC3Dintptr offset, WGC3Dsizeiptr size, WGC3Denum access) { return 0; }
     virtual void unmapBufferSubDataCHROMIUM(const void*) { }
@@ -286,8 +287,10 @@
 
     virtual WebString getTranslatedShaderSourceANGLE(WebGLId) { return WebString(); }
 
+    void fakeContextLost() { m_contextLost = true; }
 protected:
     unsigned m_nextTextureId;
+    bool m_contextLost;
     Attributes m_attrs;
 };
 
diff --git a/Source/platform/heap/Handle.h b/Source/platform/heap/Handle.h
index 217af5d..9b4252e 100644
--- a/Source/platform/heap/Handle.h
+++ b/Source/platform/heap/Handle.h
@@ -929,10 +929,6 @@
     ~DummyBase() { }
 };
 
-// Export this instance to support WillBeGarbageCollectedMixin
-// uses by code residing in non-webcore components.
-template class PLATFORM_EXPORT DummyBase<void>;
-
 #define PassRefPtrWillBeRawPtr WTF::PassRefPtr
 #define RefCountedWillBeGarbageCollected WTF::RefCounted
 #define RefCountedWillBeGarbageCollectedFinalized WTF::RefCounted
diff --git a/Source/web/ChromeClientImpl.cpp b/Source/web/ChromeClientImpl.cpp
index 6f845f5..a4c7410 100644
--- a/Source/web/ChromeClientImpl.cpp
+++ b/Source/web/ChromeClientImpl.cpp
@@ -582,7 +582,7 @@
     return controller.release();
 }
 
-PassRefPtrWillBeRawPtr<DateTimeChooser> ChromeClientImpl::openDateTimeChooser(DateTimeChooserClient* pickerClient, const DateTimeChooserParameters& parameters)
+PassRefPtr<DateTimeChooser> ChromeClientImpl::openDateTimeChooser(DateTimeChooserClient* pickerClient, const DateTimeChooserParameters& parameters)
 {
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
     return DateTimeChooserImpl::create(this, pickerClient, parameters);
diff --git a/Source/web/ChromeClientImpl.h b/Source/web/ChromeClientImpl.h
index e5047e1..455cd6d 100644
--- a/Source/web/ChromeClientImpl.h
+++ b/Source/web/ChromeClientImpl.h
@@ -129,7 +129,7 @@
     virtual void annotatedRegionsChanged() OVERRIDE;
     virtual bool paintCustomOverhangArea(GraphicsContext*, const IntRect&, const IntRect&, const IntRect&) OVERRIDE;
     virtual PassOwnPtr<ColorChooser> createColorChooser(LocalFrame*, ColorChooserClient*, const Color&) OVERRIDE;
-    virtual PassRefPtrWillBeRawPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) OVERRIDE;
+    virtual PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) OVERRIDE;
     virtual void openTextDataListChooser(HTMLInputElement&) OVERRIDE;
     virtual void runOpenPanel(LocalFrame*, PassRefPtr<FileChooser>) OVERRIDE;
     virtual void enumerateChosenDirectory(FileChooser*) OVERRIDE;
diff --git a/Source/web/DateTimeChooserImpl.cpp b/Source/web/DateTimeChooserImpl.cpp
index de6ec61..5219ead 100644
--- a/Source/web/DateTimeChooserImpl.cpp
+++ b/Source/web/DateTimeChooserImpl.cpp
@@ -57,9 +57,9 @@
     m_popup = m_chromeClient->openPagePopup(this, m_parameters.anchorRectInRootView);
 }
 
-PassRefPtrWillBeRawPtr<DateTimeChooserImpl> DateTimeChooserImpl::create(ChromeClientImpl* chromeClient, DateTimeChooserClient* client, const DateTimeChooserParameters& parameters)
+PassRefPtr<DateTimeChooserImpl> DateTimeChooserImpl::create(ChromeClientImpl* chromeClient, DateTimeChooserClient* client, const DateTimeChooserParameters& parameters)
 {
-    return adoptRefWillBeNoop(new DateTimeChooserImpl(chromeClient, client, parameters));
+    return adoptRef(new DateTimeChooserImpl(chromeClient, client, parameters));
 }
 
 DateTimeChooserImpl::~DateTimeChooserImpl()
@@ -171,7 +171,7 @@
 
 void DateTimeChooserImpl::setValueAndClosePopup(int numValue, const String& stringValue)
 {
-    RefPtrWillBeRawPtr<DateTimeChooserImpl> protector(this);
+    RefPtr<DateTimeChooserImpl> protector(this);
     if (numValue >= 0)
         setValue(stringValue);
     endChooser();
@@ -194,12 +194,6 @@
     m_client->didEndChooser();
 }
 
-void DateTimeChooserImpl::trace(Visitor* visitor)
-{
-    visitor->trace(m_client);
-    DateTimeChooser::trace(visitor);
-}
-
 } // namespace blink
 
 #endif // ENABLE(INPUT_MULTIPLE_FIELDS_UI)
diff --git a/Source/web/DateTimeChooserImpl.h b/Source/web/DateTimeChooserImpl.h
index 56bfcd5..e1ef5a8 100644
--- a/Source/web/DateTimeChooserImpl.h
+++ b/Source/web/DateTimeChooserImpl.h
@@ -43,9 +43,8 @@
 
 class DateTimeChooserImpl FINAL : public DateTimeChooser, public PagePopupClient {
 public:
-    static PassRefPtrWillBeRawPtr<DateTimeChooserImpl> create(ChromeClientImpl*, DateTimeChooserClient*, const DateTimeChooserParameters&);
+    static PassRefPtr<DateTimeChooserImpl> create(ChromeClientImpl*, DateTimeChooserClient*, const DateTimeChooserParameters&);
     virtual ~DateTimeChooserImpl();
-    virtual void trace(Visitor*) OVERRIDE;
 
     // DateTimeChooser functions:
     virtual void endChooser() OVERRIDE;
@@ -62,7 +61,7 @@
     virtual void didClosePopup() OVERRIDE;
 
     ChromeClientImpl* m_chromeClient;
-    RawPtrWillBeMember<DateTimeChooserClient> m_client;
+    DateTimeChooserClient* m_client;
     PagePopup* m_popup;
     DateTimeChooserParameters m_parameters;
     OwnPtr<Locale> m_locale;
diff --git a/Source/web/ExternalDateTimeChooser.cpp b/Source/web/ExternalDateTimeChooser.cpp
index ca0f5af..ea5f8dc 100644
--- a/Source/web/ExternalDateTimeChooser.cpp
+++ b/Source/web/ExternalDateTimeChooser.cpp
@@ -76,10 +76,10 @@
     ASSERT(client);
 }
 
-PassRefPtrWillBeRawPtr<ExternalDateTimeChooser> ExternalDateTimeChooser::create(ChromeClientImpl* chromeClient, WebViewClient* webViewClient, DateTimeChooserClient* client, const DateTimeChooserParameters& parameters)
+PassRefPtr<ExternalDateTimeChooser> ExternalDateTimeChooser::create(ChromeClientImpl* chromeClient, WebViewClient* webViewClient, DateTimeChooserClient* client, const DateTimeChooserParameters& parameters)
 {
     ASSERT(chromeClient);
-    RefPtrWillBeRawPtr<ExternalDateTimeChooser> chooser = adoptRefWillBeNoop(new ExternalDateTimeChooser(client));
+    RefPtr<ExternalDateTimeChooser> chooser = adoptRef(new ExternalDateTimeChooser(client));
     if (!chooser->openDateTimeChooser(chromeClient, webViewClient, parameters))
         chooser.clear();
     return chooser.release();
diff --git a/Source/web/ExternalDateTimeChooser.h b/Source/web/ExternalDateTimeChooser.h
index 6e9dabf..ccd9b6a 100644
--- a/Source/web/ExternalDateTimeChooser.h
+++ b/Source/web/ExternalDateTimeChooser.h
@@ -41,7 +41,7 @@
 
 class ExternalDateTimeChooser FINAL : public blink::DateTimeChooser {
 public:
-    static PassRefPtrWillBeRawPtr<ExternalDateTimeChooser> create(ChromeClientImpl*, WebViewClient*, blink::DateTimeChooserClient*, const blink::DateTimeChooserParameters&);
+    static PassRefPtr<ExternalDateTimeChooser> create(ChromeClientImpl*, WebViewClient*, blink::DateTimeChooserClient*, const blink::DateTimeChooserParameters&);
     virtual ~ExternalDateTimeChooser();
 
     // The following functions are for DateTimeChooserCompletion.
diff --git a/Source/web/ExternalPopupMenu.cpp b/Source/web/ExternalPopupMenu.cpp
index 52d6052..067830e 100644
--- a/Source/web/ExternalPopupMenu.cpp
+++ b/Source/web/ExternalPopupMenu.cpp
@@ -70,7 +70,7 @@
     }
 
     WebPopupMenuInfo info;
-    getPopupMenuInfo(&info);
+    getPopupMenuInfo(info, *m_popupMenuClient);
     if (info.items.isEmpty())
         return;
     m_webExternalPopupMenu = m_webView.client()->createExternalPopupMenu(info, this);
@@ -124,7 +124,7 @@
 void ExternalPopupMenu::didChangeSelection(int index)
 {
     if (m_popupMenuClient)
-        m_popupMenuClient->selectionChanged(toPopupMenuItemIndex(index));
+        m_popupMenuClient->selectionChanged(toPopupMenuItemIndex(index, *m_popupMenuClient));
 }
 
 void ExternalPopupMenu::didAcceptIndex(int index)
@@ -132,7 +132,7 @@
     // Calling methods on the PopupMenuClient might lead to this object being
     // derefed. This ensures it does not get deleted while we are running this
     // method.
-    int popupMenuItemIndex = toPopupMenuItemIndex(index);
+    int popupMenuItemIndex = toPopupMenuItemIndex(index, *m_popupMenuClient);
     RefPtr<ExternalPopupMenu> guard(this);
 
     if (m_popupMenuClient) {
@@ -158,7 +158,7 @@
         m_popupMenuClient->valueChanged(static_cast<unsigned>(-1), true);
     else {
         for (size_t i = 0; i < indices.size(); ++i)
-            m_popupMenuClient->listBoxSelectItem(toPopupMenuItemIndex(indices[i]), (i > 0), false, (i == indices.size() - 1));
+            m_popupMenuClient->listBoxSelectItem(toPopupMenuItemIndex(indices[i], *m_popupMenuClient), (i > 0), false, (i == indices.size() - 1));
     }
 
     // The call to valueChanged above might have lead to a call to
@@ -179,49 +179,51 @@
     m_webExternalPopupMenu = 0;
 }
 
-void ExternalPopupMenu::getPopupMenuInfo(WebPopupMenuInfo* info)
+void ExternalPopupMenu::getPopupMenuInfo(WebPopupMenuInfo& info, PopupMenuClient& popupMenuClient)
 {
-    int itemCount = m_popupMenuClient->listSize();
+    int itemCount = popupMenuClient.listSize();
     int count = 0;
     Vector<WebMenuItemInfo> items(static_cast<size_t>(itemCount));
     for (int i = 0; i < itemCount; ++i) {
-        PopupMenuStyle style = m_popupMenuClient->itemStyle(i);
+        PopupMenuStyle style = popupMenuClient.itemStyle(i);
         if (style.isDisplayNone())
             continue;
 
         WebMenuItemInfo& popupItem = items[count++];
-        popupItem.label = m_popupMenuClient->itemText(i);
-        popupItem.toolTip = m_popupMenuClient->itemToolTip(i);
-        if (m_popupMenuClient->itemIsSeparator(i))
+        popupItem.label = popupMenuClient.itemText(i);
+        popupItem.toolTip = popupMenuClient.itemToolTip(i);
+        if (popupMenuClient.itemIsSeparator(i))
             popupItem.type = WebMenuItemInfo::Separator;
-        else if (m_popupMenuClient->itemIsLabel(i))
+        else if (popupMenuClient.itemIsLabel(i))
             popupItem.type = WebMenuItemInfo::Group;
         else
             popupItem.type = WebMenuItemInfo::Option;
-        popupItem.enabled = m_popupMenuClient->itemIsEnabled(i);
-        popupItem.checked = m_popupMenuClient->itemIsSelected(i);
+        popupItem.enabled = popupMenuClient.itemIsEnabled(i);
+        popupItem.checked = popupMenuClient.itemIsSelected(i);
         popupItem.textDirection = toWebTextDirection(style.textDirection());
         popupItem.hasTextDirectionOverride = style.hasTextDirectionOverride();
     }
 
-    info->itemHeight = m_popupMenuClient->menuStyle().font().fontMetrics().height();
-    info->itemFontSize = static_cast<int>(m_popupMenuClient->menuStyle().font().fontDescription().computedSize());
-    info->selectedIndex = toExternalPopupMenuItemIndex(m_popupMenuClient->selectedIndex());
-    info->rightAligned = m_popupMenuClient->menuStyle().textDirection() == RTL;
-    info->allowMultipleSelection = m_popupMenuClient->multiple();
-    info->items = items;
+    info.itemHeight = popupMenuClient.menuStyle().font().fontMetrics().height();
+    info.itemFontSize = static_cast<int>(popupMenuClient.menuStyle().font().fontDescription().computedSize());
+    info.selectedIndex = toExternalPopupMenuItemIndex(popupMenuClient.selectedIndex(), popupMenuClient);
+    info.rightAligned = popupMenuClient.menuStyle().textDirection() == RTL;
+    info.allowMultipleSelection = popupMenuClient.multiple();
+    if (count < itemCount)
+        items.shrink(count);
+    info.items = items;
+
 }
 
-int ExternalPopupMenu::toPopupMenuItemIndex(int externalPopupMenuItemIndex)
+int ExternalPopupMenu::toPopupMenuItemIndex(int externalPopupMenuItemIndex, PopupMenuClient& popupMenuClient)
 {
-    ASSERT(m_popupMenuClient);
     if (externalPopupMenuItemIndex < 0)
         return externalPopupMenuItemIndex;
 
-    int itemCount = m_popupMenuClient->listSize();
+    int itemCount = popupMenuClient.listSize();
     int indexTracker = 0;
     for (int i = 0; i < itemCount ; ++i) {
-        if (m_popupMenuClient->itemStyle(i).isDisplayNone())
+        if (popupMenuClient.itemStyle(i).isDisplayNone())
             continue;
         if (indexTracker++ == externalPopupMenuItemIndex)
             return i;
@@ -229,16 +231,15 @@
     return -1;
 }
 
-int ExternalPopupMenu::toExternalPopupMenuItemIndex(int popupMenuItemIndex)
+int ExternalPopupMenu::toExternalPopupMenuItemIndex(int popupMenuItemIndex, PopupMenuClient& popupMenuClient)
 {
-    ASSERT(m_popupMenuClient);
     if (popupMenuItemIndex < 0)
         return popupMenuItemIndex;
 
-    int itemCount = m_popupMenuClient->listSize();
+    int itemCount = popupMenuClient.listSize();
     int indexTracker = 0;
     for (int i = 0; i < itemCount; ++i) {
-        if (m_popupMenuClient->itemStyle(i).isDisplayNone())
+        if (popupMenuClient.itemStyle(i).isDisplayNone())
             continue;
         if (popupMenuItemIndex == i)
             return indexTracker;
diff --git a/Source/web/ExternalPopupMenu.h b/Source/web/ExternalPopupMenu.h
index 893cf0b..b629f4c 100644
--- a/Source/web/ExternalPopupMenu.h
+++ b/Source/web/ExternalPopupMenu.h
@@ -57,6 +57,15 @@
     ExternalPopupMenu(LocalFrame&, PopupMenuClient*, WebViewImpl&);
     virtual ~ExternalPopupMenu();
 
+
+    // Fills |info| with the popup menu information contained in the
+    // PopupMenuClient associated with this ExternalPopupMenu.
+    // FIXME: public only for test access. Need to revert once gtest
+    // helpers from chromium are available for blink.
+    static void getPopupMenuInfo(WebPopupMenuInfo&, PopupMenuClient&);
+    static int toPopupMenuItemIndex(int index, PopupMenuClient&);
+    static int toExternalPopupMenuItemIndex(int index, PopupMenuClient&);
+
 private:
     // PopupMenu methods:
     virtual void show(const FloatQuad& controlPosition, const IntSize&, int index) OVERRIDE;
@@ -71,11 +80,6 @@
     virtual void didCancel() OVERRIDE;
 
     void dispatchEvent(Timer<ExternalPopupMenu>*);
-    // Fills |info| with the popup menu information contained in the
-    // PopupMenuClient associated with this ExternalPopupMenu.
-    void getPopupMenuInfo(WebPopupMenuInfo* info);
-    int toPopupMenuItemIndex(int index);
-    int toExternalPopupMenuItemIndex(int index);
 
     PopupMenuClient* m_popupMenuClient;
     RefPtr<FrameView> m_frameView;
diff --git a/Source/web/ExternalPopupMenuTest.cpp b/Source/web/ExternalPopupMenuTest.cpp
new file mode 100644
index 0000000..33a9a0a
--- /dev/null
+++ b/Source/web/ExternalPopupMenuTest.cpp
@@ -0,0 +1,96 @@
+// Copyright (c) 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "web/ExternalPopupMenu.h"
+
+#include "platform/PopupMenu.h"
+#include "platform/PopupMenuClient.h"
+#include "public/web/WebPopupMenuInfo.h"
+#include <gtest/gtest.h>
+
+using namespace blink;
+
+namespace {
+
+const size_t kListSize = 7;
+
+class TestPopupMenuClient : public PopupMenuClient {
+public:
+    TestPopupMenuClient() : m_listSize(0) { }
+    virtual ~TestPopupMenuClient() { }
+
+    virtual void valueChanged(unsigned listIndex, bool fireEvents = true) OVERRIDE { }
+    virtual void selectionChanged(unsigned listIndex, bool fireEvents = true) OVERRIDE { }
+    virtual void selectionCleared() OVERRIDE { }
+
+    virtual String itemText(unsigned listIndex) const OVERRIDE { return emptyString(); }
+    virtual String itemToolTip(unsigned listIndex) const OVERRIDE { return emptyString(); }
+    virtual String itemAccessibilityText(unsigned listIndex) const OVERRIDE { return emptyString(); }
+    virtual bool itemIsEnabled(unsigned listIndex) const OVERRIDE { return true; }
+    virtual PopupMenuStyle itemStyle(unsigned listIndex) const OVERRIDE
+    {
+        FontDescription fontDescription;
+        fontDescription.setComputedSize(12.0);
+        Font font(fontDescription);
+        font.update(nullptr);
+        bool displayNone = m_displayNoneIndexSet.find(listIndex) != m_displayNoneIndexSet.end();
+        return PopupMenuStyle(Color::black, Color::white, font, true, displayNone, Length(), TextDirection(), false);
+    }
+    virtual PopupMenuStyle menuStyle() const OVERRIDE { return itemStyle(0); }
+    virtual LayoutUnit clientPaddingLeft() const OVERRIDE { return 0; }
+    virtual LayoutUnit clientPaddingRight() const OVERRIDE { return 0; }
+    virtual int listSize() const OVERRIDE { return m_listSize; }
+    virtual int selectedIndex() const OVERRIDE { return 0; }
+    virtual void popupDidHide() OVERRIDE { }
+    virtual bool itemIsSeparator(unsigned listIndex) const OVERRIDE { return false;}
+    virtual bool itemIsLabel(unsigned listIndex) const OVERRIDE { return false; }
+    virtual bool itemIsSelected(unsigned listIndex) const OVERRIDE { return listIndex == 0;}
+    virtual void setTextFromItem(unsigned listIndex) OVERRIDE { }
+    virtual bool multiple() const OVERRIDE { return false; }
+
+    void setListSize(size_t size) { m_listSize = size; }
+    void setDisplayNoneIndex(unsigned index) { m_displayNoneIndexSet.insert(index); }
+private:
+    size_t m_listSize;
+    std::set<unsigned> m_displayNoneIndexSet;
+};
+
+class ExternalPopupMenuDisplayNoneItemsTest : public testing::Test {
+public:
+    ExternalPopupMenuDisplayNoneItemsTest() { }
+
+protected:
+    virtual void SetUp() OVERRIDE
+    {
+        m_popupMenuClient.setListSize(kListSize);
+
+        // Set the 4th an 5th items to have "display: none" property
+        m_popupMenuClient.setDisplayNoneIndex(3);
+        m_popupMenuClient.setDisplayNoneIndex(4);
+    }
+
+    TestPopupMenuClient m_popupMenuClient;
+};
+
+TEST_F(ExternalPopupMenuDisplayNoneItemsTest, PopupMenuInfoSizeTest)
+{
+    WebPopupMenuInfo info;
+    ExternalPopupMenu::getPopupMenuInfo(info, m_popupMenuClient);
+    EXPECT_EQ(5U, info.items.size());
+}
+
+TEST_F(ExternalPopupMenuDisplayNoneItemsTest, IndexMappingTest)
+{
+    // 6th indexed item in popupmenu would be the 4th item in ExternalPopupMenu,
+    // and vice-versa.
+    EXPECT_EQ(4, ExternalPopupMenu::toExternalPopupMenuItemIndex(6, m_popupMenuClient));
+    EXPECT_EQ(6, ExternalPopupMenu::toPopupMenuItemIndex(4, m_popupMenuClient));
+
+    // Invalid index, methods should return -1.
+    EXPECT_EQ(-1, ExternalPopupMenu::toExternalPopupMenuItemIndex(8, m_popupMenuClient));
+    EXPECT_EQ(-1, ExternalPopupMenu::toPopupMenuItemIndex(8, m_popupMenuClient));
+}
+
+} // namespace
diff --git a/Source/web/WebViewImpl.cpp b/Source/web/WebViewImpl.cpp
index 6096aec..0638063 100644
--- a/Source/web/WebViewImpl.cpp
+++ b/Source/web/WebViewImpl.cpp
@@ -3588,6 +3588,10 @@
     Position startPosition = startVisiblePosition.deepEquivalent();
     Position endPosition = endVisiblePosition.deepEquivalent();
 
+    // document() will return null if -webkit-user-select is set to none.
+    if (!startPosition.document() || !endPosition.document())
+        return;
+
     RefPtrWillBeRawPtr<Range> range = Range::create(*startPosition.document(), startPosition, endPosition);
     if (!range)
         return;
diff --git a/Source/web/tests/WebViewTest.cpp b/Source/web/tests/WebViewTest.cpp
index 35feefd..817e82b 100644
--- a/Source/web/tests/WebViewTest.cpp
+++ b/Source/web/tests/WebViewTest.cpp
@@ -1624,6 +1624,23 @@
     EXPECT_STREQ(kExpectedClipHtml, clipHtml.utf8().c_str());
 }
 
+TEST_F(WebViewTest, SmartClipReturnsEmptyStringsWhenUserSelectIsNone)
+{
+    WebString clipText;
+    WebString clipHtml;
+    WebRect clipRect;
+    URLTestHelpers::registerMockedURLFromBaseURL(WebString::fromUTF8(m_baseURL.c_str()), WebString::fromUTF8("Ahem.ttf"));
+    URLTestHelpers::registerMockedURLFromBaseURL(WebString::fromUTF8(m_baseURL.c_str()), WebString::fromUTF8("smartclip_user_select_none.html"));
+    WebView* webView = m_webViewHelper.initializeAndLoad(m_baseURL + "smartclip_user_select_none.html");
+    webView->setPageScaleFactorLimits(1, 1);
+    webView->resize(WebSize(500, 500));
+    webView->layout();
+    WebRect cropRect(0, 0, 100, 100);
+    webView->extractSmartClipData(cropRect, clipText, clipHtml, clipRect);
+    EXPECT_STREQ("", clipText.utf8().c_str());
+    EXPECT_STREQ("", clipHtml.utf8().c_str());
+}
+
 class CreateChildCounterFrameClient : public FrameTestHelpers::TestWebFrameClient {
 public:
     CreateChildCounterFrameClient() : m_count(0) { }
diff --git a/Source/web/tests/data/smartclip_user_select_none.html b/Source/web/tests/data/smartclip_user_select_none.html
new file mode 100644
index 0000000..3c576bb
--- /dev/null
+++ b/Source/web/tests/data/smartclip_user_select_none.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html>
+
+<head>
+  <style>
+    body {
+        -webkit-user-select:none;
+    }
+  </style>
+</head>
+
+<body>
+abcdefghijklmnopqrstuvwxyz<br>
+abcdefghijklmnopqrstuvwxyz<br>
+abcdefghijklmnopqrstuvwxyz<br>
+abcdefghijklmnopqrstuvwxyz<br>
+abcdefghijklmnopqrstuvwxyz<br>
+abcdefghijklmnopqrstuvwxyz<br>
+</body>
+
+</html>
diff --git a/Source/web/web.gypi b/Source/web/web.gypi
index 4787ff8..df6879c 100644
--- a/Source/web/web.gypi
+++ b/Source/web/web.gypi
@@ -261,6 +261,7 @@
       'win/WebFontRendering.cpp',
     ],
     'web_unittest_files': [
+      'ExternalPopupMenuTest.cpp',
       'WebNodeTest.cpp',
       # FIXME: Move the tests from web/tests/ to appropriate places.
       # crbug.com/353585