Bug 1221459 - Remove TouchCaret and SelectionCarets. r=mtseng, r=roc
authorTing-Yu Lin <tlin@mozilla.com>
Tue, 22 Dec 2015 14:14:12 +0800
changeset 277362 8c208d26dc1b1721a8685986e73c66eee5065848
parent 277361 9d9914a3e5b18834102f52801fc11d33ec737d24
child 277363 3a0eb24805cad5905912e6d2c6f1d4a7a14fa471
push id29822
push usercbook@mozilla.com
push dateWed, 23 Dec 2015 11:00:24 +0000
treeherdermozilla-central@35b211eaad1f [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmtseng, roc
bugs1221459
milestone46.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1221459 - Remove TouchCaret and SelectionCarets. r=mtseng, r=roc All the files modified are straightforward deletion except TouchManager and ZoomConstraintsClient. I add some includes and wrap TouchManager by mozilla namespace to fix build errors due to the removal of TouchCaret.
b2g/installer/package-manifest.in
browser/installer/package-manifest.in
dom/base/nsFocusManager.cpp
dom/base/nsGlobalWindow.cpp
editor/composer/moz.build
layout/base/SelectionCarets.cpp
layout/base/SelectionCarets.h
layout/base/TouchCaret.cpp
layout/base/TouchCaret.h
layout/base/TouchManager.cpp
layout/base/TouchManager.h
layout/base/ZoomConstraintsClient.cpp
layout/base/moz.build
layout/base/nsIPresShell.h
layout/base/nsPresShell.cpp
layout/base/nsPresShell.h
layout/generic/nsCanvasFrame.cpp
layout/generic/nsCanvasFrame.h
layout/generic/nsSelection.cpp
layout/style/ua.css
layout/tools/reftest/reftest-preferences.js
mobile/android/b2gdroid/installer/package-manifest.in
modules/libpref/init/all.js
testing/profiles/prefs_b2g_unittest.js
--- a/b2g/installer/package-manifest.in
+++ b/b2g/installer/package-manifest.in
@@ -808,28 +808,16 @@
 @RESPATH@/res/accessiblecaret_tilt_left.png
 @RESPATH@/res/accessiblecaret_tilt_left@1.5x.png
 @RESPATH@/res/accessiblecaret_tilt_left@2.25x.png
 @RESPATH@/res/accessiblecaret_tilt_left@2x.png
 @RESPATH@/res/accessiblecaret_tilt_right.png
 @RESPATH@/res/accessiblecaret_tilt_right@1.5x.png
 @RESPATH@/res/accessiblecaret_tilt_right@2.25x.png
 @RESPATH@/res/accessiblecaret_tilt_right@2x.png
-@RESPATH@/res/text_caret.png
-@RESPATH@/res/text_caret@1.5x.png
-@RESPATH@/res/text_caret@2.25x.png
-@RESPATH@/res/text_caret@2x.png
-@RESPATH@/res/text_caret_tilt_left.png
-@RESPATH@/res/text_caret_tilt_left@1.5x.png
-@RESPATH@/res/text_caret_tilt_left@2.25x.png
-@RESPATH@/res/text_caret_tilt_left@2x.png
-@RESPATH@/res/text_caret_tilt_right.png
-@RESPATH@/res/text_caret_tilt_right@1.5x.png
-@RESPATH@/res/text_caret_tilt_right@2.25x.png
-@RESPATH@/res/text_caret_tilt_right@2x.png
 @RESPATH@/res/grabber.gif
 #ifdef XP_MACOSX
 @RESPATH@/res/cursors/*
 #endif
 @RESPATH@/res/fonts/*
 @RESPATH@/res/dtd/*
 @RESPATH@/res/html/*
 @RESPATH@/res/language.properties
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -746,28 +746,16 @@
 @RESPATH@/res/accessiblecaret_tilt_left.png
 @RESPATH@/res/accessiblecaret_tilt_left@1.5x.png
 @RESPATH@/res/accessiblecaret_tilt_left@2.25x.png
 @RESPATH@/res/accessiblecaret_tilt_left@2x.png
 @RESPATH@/res/accessiblecaret_tilt_right.png
 @RESPATH@/res/accessiblecaret_tilt_right@1.5x.png
 @RESPATH@/res/accessiblecaret_tilt_right@2.25x.png
 @RESPATH@/res/accessiblecaret_tilt_right@2x.png
-@RESPATH@/res/text_caret.png
-@RESPATH@/res/text_caret@1.5x.png
-@RESPATH@/res/text_caret@2.25x.png
-@RESPATH@/res/text_caret@2x.png
-@RESPATH@/res/text_caret_tilt_left.png
-@RESPATH@/res/text_caret_tilt_left@1.5x.png
-@RESPATH@/res/text_caret_tilt_left@2.25x.png
-@RESPATH@/res/text_caret_tilt_left@2x.png
-@RESPATH@/res/text_caret_tilt_right.png
-@RESPATH@/res/text_caret_tilt_right@1.5x.png
-@RESPATH@/res/text_caret_tilt_right@2.25x.png
-@RESPATH@/res/text_caret_tilt_right@2x.png
 @RESPATH@/res/grabber.gif
 #ifdef XP_MACOSX
 @RESPATH@/res/cursors/*
 #endif
 @RESPATH@/res/fonts/*
 @RESPATH@/res/dtd/*
 @RESPATH@/res/html/*
 #if defined(XP_MACOSX) || defined(XP_WIN)
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -36,17 +36,16 @@
 #include "nsXULPopupManager.h"
 #include "nsMenuPopupFrame.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsIPrincipal.h"
 #include "nsIObserverService.h"
 #include "nsIObjectFrame.h"
 #include "nsBindingManager.h"
 #include "nsStyleCoord.h"
-#include "SelectionCarets.h"
 #include "TabChild.h"
 #include "nsFrameLoader.h"
 
 #include "mozilla/ContentEvents.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/EventDispatcher.h"
 #include "mozilla/EventStateManager.h"
 #include "mozilla/EventStates.h"
@@ -1687,21 +1686,16 @@ nsFocusManager::Blur(nsPIDOMWindow* aWin
   }
 
   // if we are leaving the document or the window was lowered, make the caret
   // invisible.
   if (aIsLeavingDocument || !mActiveWindow) {
     SetCaretVisible(presShell, false, nullptr);
   }
 
-  RefPtr<SelectionCarets> selectionCarets = presShell->GetSelectionCarets();
-  if (selectionCarets) {
-    selectionCarets->NotifyBlur(aIsLeavingDocument || !mActiveWindow);
-  }
-
   RefPtr<AccessibleCaretEventHub> eventHub = presShell->GetAccessibleCaretEventHub();
   if (eventHub) {
     eventHub->NotifyBlur(aIsLeavingDocument || !mActiveWindow);
   }
 
   // at this point, it is expected that this window will be still be
   // focused, but the focused content will be null, as it was cleared before
   // the event. If this isn't the case, then something else was focused during
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -202,17 +202,16 @@
 #include "mozilla/Telemetry.h"
 #include "nsLocation.h"
 #include "nsHTMLDocument.h"
 #include "nsWrapperCacheInlines.h"
 #include "mozilla/DOMEventTargetHelper.h"
 #include "prrng.h"
 #include "nsSandboxFlags.h"
 #include "TimeChangeObserver.h"
-#include "TouchCaret.h"
 #include "mozilla/dom/AudioContext.h"
 #include "mozilla/dom/BrowserElementDictionariesBinding.h"
 #include "mozilla/dom/cache/CacheStorage.h"
 #include "mozilla/dom/Console.h"
 #include "mozilla/dom/Fetch.h"
 #include "mozilla/dom/FunctionBinding.h"
 #include "mozilla/dom/HashChangeEvent.h"
 #include "mozilla/dom/MozSelfSupportBinding.h"
--- a/editor/composer/moz.build
+++ b/editor/composer/moz.build
@@ -54,21 +54,9 @@ RESOURCE_FILES += [
     'res/table-add-row-before-hover.gif',
     'res/table-add-row-before.gif',
     'res/table-remove-column-active.gif',
     'res/table-remove-column-hover.gif',
     'res/table-remove-column.gif',
     'res/table-remove-row-active.gif',
     'res/table-remove-row-hover.gif',
     'res/table-remove-row.gif',
-    'res/text_caret.png',
-    'res/text_caret@1.5x.png',
-    'res/text_caret@2.25x.png',
-    'res/text_caret@2x.png',
-    'res/text_caret_tilt_left.png',
-    'res/text_caret_tilt_left@1.5x.png',
-    'res/text_caret_tilt_left@2.25x.png',
-    'res/text_caret_tilt_left@2x.png',
-    'res/text_caret_tilt_right.png',
-    'res/text_caret_tilt_right@1.5x.png',
-    'res/text_caret_tilt_right@2.25x.png',
-    'res/text_caret_tilt_right@2x.png',
 ]
deleted file mode 100644
--- a/layout/base/SelectionCarets.cpp
+++ /dev/null
@@ -1,1340 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 sw=2 et tw=78: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "mozilla/Logging.h"
-#include "SelectionCarets.h"
-
-#include "gfxPrefs.h"
-#include "nsBidiPresUtils.h"
-#include "nsCanvasFrame.h"
-#include "nsCaret.h"
-#include "nsContentUtils.h"
-#include "nsDebug.h"
-#include "nsDocShell.h"
-#include "nsDOMTokenList.h"
-#include "nsFocusManager.h"
-#include "nsFrame.h"
-#include "nsGenericHTMLElement.h"
-#include "nsIDocument.h"
-#include "nsIDocShell.h"
-#include "nsIDOMDocument.h"
-#include "nsIDOMNodeFilter.h"
-#include "nsIPresShell.h"
-#include "nsPresContext.h"
-#include "nsRect.h"
-#include "nsView.h"
-#include "mozilla/dom/DOMRect.h"
-#include "mozilla/dom/Element.h"
-#include "mozilla/dom/ScrollViewChangeEvent.h"
-#include "mozilla/dom/Selection.h"
-#include "mozilla/dom/TreeWalker.h"
-#include "mozilla/Preferences.h"
-#include "mozilla/TouchEvents.h"
-#include "Layers.h"
-#include "TouchCaret.h"
-#include "nsFrameSelection.h"
-
-using namespace mozilla;
-using namespace mozilla::dom;
-
-static const char* kSelectionCaretsLogModuleName = "SelectionCarets";
-static mozilla::LazyLogModule gSelectionCaretsLog(kSelectionCaretsLogModuleName);
-
-// To enable all the SELECTIONCARETS_LOG print statements, set the environment
-// variable NSPR_LOG_MODULES=SelectionCarets:5
-#define SELECTIONCARETS_LOG(message, ...)                                      \
-  MOZ_LOG(gSelectionCaretsLog, LogLevel::Debug,                                    \
-         ("SelectionCarets (%p): %s:%d : " message "\n", this, __FUNCTION__,   \
-          __LINE__, ##__VA_ARGS__));
-
-#define SELECTIONCARETS_LOG_STATIC(message, ...)                               \
-  MOZ_LOG(gSelectionCaretsLog, LogLevel::Debug,                                    \
-         ("SelectionCarets: %s:%d : " message "\n", __FUNCTION__, __LINE__,    \
-          ##__VA_ARGS__));
-
-// We treat mouse/touch move as "REAL" move event once its move distance
-// exceed this value, in CSS pixel.
-static const int32_t kMoveStartTolerancePx = 5;
-
-NS_IMPL_ISUPPORTS(SelectionCarets,
-                  nsIReflowObserver,
-                  nsISelectionListener,
-                  nsIScrollObserver,
-                  nsISupportsWeakReference)
-
-/*static*/ int32_t SelectionCarets::sSelectionCaretsInflateSize = 0;
-
-SelectionCarets::SelectionCarets(nsIPresShell* aPresShell)
-  : mPresShell(aPresShell)
-  , mActiveTouchId(-1)
-  , mCaretCenterToDownPointOffsetY(0)
-  , mDragMode(NONE)
-  , mUseAsyncPanZoom(false)
-  , mInAsyncPanZoomGesture(false)
-  , mEndCaretVisible(false)
-  , mStartCaretVisible(false)
-  , mSelectionVisibleInScrollFrames(true)
-  , mVisible(false)
-{
-  MOZ_ASSERT(NS_IsMainThread());
-
-  SELECTIONCARETS_LOG("Constructor, PresShell=%p", mPresShell);
-
-  static bool addedPref = false;
-  if (!addedPref) {
-    Preferences::AddIntVarCache(&sSelectionCaretsInflateSize,
-                                "selectioncaret.inflatesize.threshold");
-    addedPref = true;
-  }
-}
-
-void
-SelectionCarets::Init()
-{
-  nsPresContext* presContext = mPresShell->GetPresContext();
-  MOZ_ASSERT(presContext, "PresContext should be given in PresShell::Init()");
-
-  nsIDocShell* docShell = presContext->GetDocShell();
-  if (!docShell) {
-    return;
-  }
-
-#if defined(MOZ_WIDGET_GONK)
-  mUseAsyncPanZoom = mPresShell->AsyncPanZoomEnabled();
-#endif
-
-  docShell->AddWeakReflowObserver(this);
-  docShell->AddWeakScrollObserver(this);
-
-  mDocShell = static_cast<nsDocShell*>(docShell);
-}
-
-SelectionCarets::~SelectionCarets()
-{
-  SELECTIONCARETS_LOG("Destructor");
-  MOZ_ASSERT(NS_IsMainThread());
-
-  mPresShell = nullptr;
-}
-
-void
-SelectionCarets::Terminate()
-{
-  RefPtr<nsDocShell> docShell(mDocShell.get());
-  if (docShell) {
-    docShell->RemoveWeakReflowObserver(this);
-    docShell->RemoveWeakScrollObserver(this);
-  }
-
-  if (mLongTapDetectorTimer) {
-    mLongTapDetectorTimer->Cancel();
-    mLongTapDetectorTimer = nullptr;
-  }
-
-  if (mScrollEndDetectorTimer) {
-    mScrollEndDetectorTimer->Cancel();
-    mScrollEndDetectorTimer = nullptr;
-  }
-
-  mPresShell = nullptr;
-}
-
-nsEventStatus
-SelectionCarets::HandleEvent(WidgetEvent* aEvent)
-{
-  WidgetMouseEvent *mouseEvent = aEvent->AsMouseEvent();
-  if (mouseEvent && mouseEvent->reason == WidgetMouseEvent::eSynthesized) {
-    return nsEventStatus_eIgnore;
-  }
-
-  WidgetTouchEvent *touchEvent = aEvent->AsTouchEvent();
-  LayoutDeviceIntPoint movePoint;
-  int32_t nowTouchId = -1;
-  if (touchEvent && !touchEvent->touches.IsEmpty()) {
-    // If touch happened, just grab event with same identifier
-    if (mActiveTouchId >= 0) {
-      for (uint32_t i = 0; i < touchEvent->touches.Length(); ++i) {
-        if (touchEvent->touches[i]->Identifier() == mActiveTouchId) {
-          movePoint = touchEvent->touches[i]->mRefPoint;
-          nowTouchId = touchEvent->touches[i]->Identifier();
-          break;
-        }
-      }
-
-      // not found, consume it
-      if (nowTouchId == -1) {
-        return nsEventStatus_eConsumeNoDefault;
-      }
-    } else {
-      movePoint = touchEvent->touches[0]->mRefPoint;
-      nowTouchId = touchEvent->touches[0]->Identifier();
-    }
-  } else if (mouseEvent) {
-    movePoint = mouseEvent->AsGUIEvent()->refPoint;
-  }
-
-  // XUL has no SelectionCarets elements.
-  if (!mPresShell->GetSelectionCaretsStartElement() ||
-      !mPresShell->GetSelectionCaretsEndElement()) {
-    return nsEventStatus_eIgnore;
-  }
-
-  // Get event coordinate relative to root frame
-  nsIFrame* rootFrame = mPresShell->GetRootFrame();
-  if (!rootFrame) {
-    return nsEventStatus_eIgnore;
-  }
-  nsPoint ptInRoot =
-    nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent, movePoint, rootFrame);
-
-  if (aEvent->mMessage == eTouchStart ||
-      (aEvent->mMessage == eMouseDown &&
-       mouseEvent->button == WidgetMouseEvent::eLeftButton)) {
-    // If having a active touch, ignore other touch down event
-    if (aEvent->mMessage == eTouchStart && mActiveTouchId >= 0) {
-      return nsEventStatus_eConsumeNoDefault;
-    }
-
-    mActiveTouchId = nowTouchId;
-    mDownPoint = ptInRoot;
-    if (IsOnStartFrameInner(ptInRoot)) {
-      mDragMode = START_FRAME;
-      mCaretCenterToDownPointOffsetY = GetCaretYCenterPosition() - ptInRoot.y;
-      SetSelectionDirection(eDirPrevious);
-      SetSelectionDragState(true);
-      return nsEventStatus_eConsumeNoDefault;
-    } else if (IsOnEndFrameInner(ptInRoot)) {
-      mDragMode = END_FRAME;
-      mCaretCenterToDownPointOffsetY = GetCaretYCenterPosition() - ptInRoot.y;
-      SetSelectionDirection(eDirNext);
-      SetSelectionDragState(true);
-      return nsEventStatus_eConsumeNoDefault;
-    } else {
-      mDragMode = NONE;
-      mActiveTouchId = -1;
-      LaunchLongTapDetector();
-    }
-  } else if (aEvent->mMessage == eTouchEnd ||
-             aEvent->mMessage == eTouchCancel ||
-             aEvent->mMessage == eMouseUp) {
-    CancelLongTapDetector();
-    if (mDragMode != NONE) {
-      // Only care about same id
-      if (mActiveTouchId == nowTouchId) {
-        SetSelectionDragState(false);
-        mDragMode = NONE;
-        mActiveTouchId = -1;
-      }
-      return nsEventStatus_eConsumeNoDefault;
-    }
-  } else if (aEvent->mMessage == eTouchMove || aEvent->mMessage == eMouseMove) {
-    if (mDragMode == START_FRAME || mDragMode == END_FRAME) {
-      if (mActiveTouchId == nowTouchId) {
-        ptInRoot.y += mCaretCenterToDownPointOffsetY;
-
-        if (mDragMode == START_FRAME) {
-          if (ptInRoot.y > mDragDownYBoundary) {
-            ptInRoot.y = mDragDownYBoundary;
-          }
-        } else if (mDragMode == END_FRAME) {
-          if (ptInRoot.y < mDragUpYBoundary) {
-            ptInRoot.y = mDragUpYBoundary;
-          }
-        }
-        return DragSelection(ptInRoot);
-      }
-
-      return nsEventStatus_eConsumeNoDefault;
-    }
-
-    nsPoint delta = mDownPoint - ptInRoot;
-    if (NS_hypot(delta.x, delta.y) >
-          nsPresContext::AppUnitsPerCSSPixel() * kMoveStartTolerancePx) {
-      CancelLongTapDetector();
-    }
-
-  } else if (aEvent->mMessage == eMouseLongTap) {
-    if (!mVisible) {
-      SELECTIONCARETS_LOG("SelectWord from eMouseLongTap");
-
-      mDownPoint = ptInRoot;
-      nsresult wordSelected = SelectWord();
-
-      if (NS_FAILED(wordSelected)) {
-        SELECTIONCARETS_LOG("SelectWord from eMouseLongTap failed!");
-        return nsEventStatus_eIgnore;
-      }
-
-      return nsEventStatus_eConsumeNoDefault;
-    }
-  }
-  return nsEventStatus_eIgnore;
-}
-
-static void
-SetElementVisibility(dom::Element* aElement, bool aVisible)
-{
-  if (!aElement) {
-    return;
-  }
-
-  ErrorResult err;
-  aElement->ClassList()->Toggle(NS_LITERAL_STRING("hidden"),
-                                   dom::Optional<bool>(!aVisible), err);
-}
-
-void
-SelectionCarets::SetVisibility(bool aVisible)
-{
-  if (!mPresShell) {
-    return;
-  }
-
-  if (mVisible == aVisible) {
-    SELECTIONCARETS_LOG("Set visibility %s, same as the old one",
-                        (aVisible ? "shown" : "hidden"));
-    return;
-  }
-
-  if (!aVisible) {
-    mSelectionVisibleInScrollFrames = false;
-  }
-
-  mVisible = aVisible;
-  SELECTIONCARETS_LOG("Set visibility %s", (mVisible ? "shown" : "hidden"));
-
-  dom::Element* startElement = mPresShell->GetSelectionCaretsStartElement();
-  SetElementVisibility(startElement, mVisible && mStartCaretVisible);
-
-  dom::Element* endElement = mPresShell->GetSelectionCaretsEndElement();
-  SetElementVisibility(endElement, mVisible && mEndCaretVisible);
-}
-
-void
-SelectionCarets::SetStartFrameVisibility(bool aVisible)
-{
-  mStartCaretVisible = aVisible;
-  SELECTIONCARETS_LOG("Set start frame visibility %s",
-                      (mStartCaretVisible ? "shown" : "hidden"));
-
-  dom::Element* element = mPresShell->GetSelectionCaretsStartElement();
-  SetElementVisibility(element, mVisible && mStartCaretVisible);
-}
-
-void
-SelectionCarets::SetEndFrameVisibility(bool aVisible)
-{
-  mEndCaretVisible = aVisible;
-  SELECTIONCARETS_LOG("Set end frame visibility %s",
-                      (mEndCaretVisible ? "shown" : "hidden"));
-
-  dom::Element* element = mPresShell->GetSelectionCaretsEndElement();
-  SetElementVisibility(element, mVisible && mEndCaretVisible);
-}
-
-void
-SelectionCarets::SetTilted(bool aIsTilt)
-{
-  dom::Element* startElement = mPresShell->GetSelectionCaretsStartElement();
-  dom::Element* endElement = mPresShell->GetSelectionCaretsEndElement();
-
-  if (!startElement || !endElement) {
-    return;
-  }
-
-  SELECTIONCARETS_LOG("Set tilted selection carets %s",
-                      (aIsTilt ? "enabled" : "disabled"));
-
-  ErrorResult err;
-  startElement->ClassList()->Toggle(NS_LITERAL_STRING("tilt"),
-                                       dom::Optional<bool>(aIsTilt), err);
-
-  endElement->ClassList()->Toggle(NS_LITERAL_STRING("tilt"),
-                                     dom::Optional<bool>(aIsTilt), err);
-}
-
-static void
-SetCaretDirection(dom::Element* aElement, bool aIsRight)
-{
-  MOZ_ASSERT(aElement);
-
-  ErrorResult err;
-  if (aIsRight) {
-    aElement->ClassList()->Add(NS_LITERAL_STRING("moz-selectioncaret-right"), err);
-    aElement->ClassList()->Remove(NS_LITERAL_STRING("moz-selectioncaret-left"), err);
-  } else {
-    aElement->ClassList()->Add(NS_LITERAL_STRING("moz-selectioncaret-left"), err);
-    aElement->ClassList()->Remove(NS_LITERAL_STRING("moz-selectioncaret-right"), err);
-  }
-}
-
-static nsIFrame*
-FindFirstNodeWithFrame(nsIDocument* aDocument,
-                       nsRange* aRange,
-                       nsFrameSelection* aFrameSelection,
-                       bool aBackward,
-                       int& aOutOffset)
-{
-  if (!aDocument || !aRange || !aFrameSelection) {
-    return nullptr;
-  }
-
-  nsCOMPtr<nsINode> startNode =
-    do_QueryInterface(aBackward ? aRange->GetEndParent() : aRange->GetStartParent());
-  nsCOMPtr<nsINode> endNode =
-    do_QueryInterface(aBackward ? aRange->GetStartParent() : aRange->GetEndParent());
-  int32_t offset = aBackward ? aRange->EndOffset() : aRange->StartOffset();
-
-  nsCOMPtr<nsIContent> startContent = do_QueryInterface(startNode);
-  CaretAssociationHint hintStart =
-    aBackward ? CARET_ASSOCIATE_BEFORE : CARET_ASSOCIATE_AFTER;
-  nsIFrame* startFrame = aFrameSelection->GetFrameForNodeOffset(startContent,
-                                                                offset,
-                                                                hintStart,
-                                                                &aOutOffset);
-
-  if (startFrame) {
-    return startFrame;
-  }
-
-  ErrorResult err;
-  RefPtr<dom::TreeWalker> walker =
-    aDocument->CreateTreeWalker(*startNode,
-                                nsIDOMNodeFilter::SHOW_ALL,
-                                nullptr,
-                                err);
-
-  if (!walker) {
-    return nullptr;
-  }
-
-  startFrame = startContent ? startContent->GetPrimaryFrame() : nullptr;
-  while (!startFrame && startNode != endNode) {
-    if (aBackward) {
-      startNode = walker->PreviousNode(err);
-    } else {
-      startNode = walker->NextNode(err);
-    }
-
-    if (!startNode) {
-      break;
-    }
-
-    startContent = do_QueryInterface(startNode);
-    startFrame = startContent ? startContent->GetPrimaryFrame() : nullptr;
-  }
-  return startFrame;
-}
-
-void
-SelectionCarets::UpdateSelectionCarets()
-{
-  if (!mPresShell) {
-    return;
-  }
-
-  RefPtr<dom::Selection> selection = GetSelection();
-  if (!selection) {
-    SELECTIONCARETS_LOG("Cannot get selection!");
-    SetVisibility(false);
-    return;
-  }
-
-  if (selection->IsCollapsed()) {
-    SELECTIONCARETS_LOG("Selection is collapsed!");
-    SetVisibility(false);
-    return;
-  }
-
-  int32_t rangeCount = selection->RangeCount();
-  RefPtr<nsRange> firstRange = selection->GetRangeAt(0);
-  RefPtr<nsRange> lastRange = selection->GetRangeAt(rangeCount - 1);
-
-  mPresShell->FlushPendingNotifications(Flush_Layout);
-
-  nsIFrame* rootFrame = mPresShell->GetRootFrame();
-
-  if (!rootFrame) {
-    SetVisibility(false);
-    return;
-  }
-
-  // Check start and end frame is rtl or ltr text
-  RefPtr<nsFrameSelection> fs = GetFrameSelection();
-  if (!fs) {
-    SetVisibility(false);
-    return;
-  }
-
-  int32_t startOffset;
-  nsIFrame* startFrame = FindFirstNodeWithFrame(mPresShell->GetDocument(),
-                                                firstRange, fs, false, startOffset);
-
-  int32_t endOffset;
-  nsIFrame* endFrame = FindFirstNodeWithFrame(mPresShell->GetDocument(),
-                                              lastRange, fs, true, endOffset);
-
-  if (!startFrame || !endFrame) {
-    SetVisibility(false);
-    return;
-  }
-
-  // Check if startFrame is after endFrame.
-  if (nsLayoutUtils::CompareTreePosition(startFrame, endFrame) > 0) {
-    SetVisibility(false);
-    return;
-  }
-
-  // If the selection is not visible, we should dispatch a event.
-  nsIFrame* commonAncestorFrame =
-    nsLayoutUtils::FindNearestCommonAncestorFrame(startFrame, endFrame);
-
-  nsRect selectionRectInRootFrame = nsLayoutUtils::GetSelectionBoundingRect(selection);
-  nsRect selectionRectInCommonAncestorFrame = selectionRectInRootFrame;
-  nsLayoutUtils::TransformRect(rootFrame, commonAncestorFrame,
-                               selectionRectInCommonAncestorFrame);
-
-  mSelectionVisibleInScrollFrames =
-    nsLayoutUtils::IsRectVisibleInScrollFrames(commonAncestorFrame,
-                                               selectionRectInCommonAncestorFrame);
-  SELECTIONCARETS_LOG("Selection visibility %s",
-                      (mSelectionVisibleInScrollFrames ? "shown" : "hidden"));
-
-
-  nsRect firstRectInStartFrame =
-    nsCaret::GetGeometryForFrame(startFrame, startOffset, nullptr);
-  nsRect lastRectInEndFrame =
-    nsCaret::GetGeometryForFrame(endFrame, endOffset, nullptr);
-
-  bool startFrameVisible =
-    nsLayoutUtils::IsRectVisibleInScrollFrames(startFrame, firstRectInStartFrame);
-  bool endFrameVisible =
-    nsLayoutUtils::IsRectVisibleInScrollFrames(endFrame, lastRectInEndFrame);
-
-  nsRect firstRectInRootFrame = firstRectInStartFrame;
-  nsRect lastRectInRootFrame = lastRectInEndFrame;
-  nsLayoutUtils::TransformRect(startFrame, rootFrame, firstRectInRootFrame);
-  nsLayoutUtils::TransformRect(endFrame, rootFrame, lastRectInRootFrame);
-
-  SetStartFrameVisibility(startFrameVisible);
-  SetEndFrameVisibility(endFrameVisible);
-
-  SetStartFramePos(firstRectInRootFrame);
-  SetEndFramePos(lastRectInRootFrame);
-  SetVisibility(true);
-
-  // Use half of the first(last) rect as the dragup(dragdown) boundary
-  mDragUpYBoundary =
-    (firstRectInRootFrame.BottomLeft().y + firstRectInRootFrame.TopLeft().y) / 2;
-  mDragDownYBoundary =
-    (lastRectInRootFrame.BottomRight().y + lastRectInRootFrame.TopRight().y) / 2;
-
-  nsRect rectStart = GetStartFrameRect();
-  nsRect rectEnd = GetEndFrameRect();
-  bool isTilt = rectStart.Intersects(rectEnd);
-  if (isTilt) {
-    SetCaretDirection(mPresShell->GetSelectionCaretsStartElement(), rectStart.x > rectEnd.x);
-    SetCaretDirection(mPresShell->GetSelectionCaretsEndElement(), rectStart.x <= rectEnd.x);
-  }
-  SetTilted(isTilt);
-}
-
-nsresult
-SelectionCarets::SelectWord()
-{
-  if (!mPresShell) {
-    return NS_ERROR_UNEXPECTED;
-  }
-
-  nsIFrame* rootFrame = mPresShell->GetRootFrame();
-  if (!rootFrame) {
-    return NS_ERROR_NOT_AVAILABLE;
-  }
-
-  // Find content offsets for mouse down point
-  nsIFrame *ptFrame = nsLayoutUtils::GetFrameForPoint(rootFrame, mDownPoint,
-    nsLayoutUtils::IGNORE_PAINT_SUPPRESSION | nsLayoutUtils::IGNORE_CROSS_DOC);
-  if (!ptFrame) {
-    return NS_ERROR_FAILURE;
-  }
-
-  bool selectable;
-  ptFrame->IsSelectable(&selectable, nullptr);
-  if (!selectable) {
-    SELECTIONCARETS_LOG(" frame %p is not selectable", ptFrame);
-    return NS_ERROR_FAILURE;
-  }
-
-  nsPoint ptInFrame = mDownPoint;
-  nsLayoutUtils::TransformPoint(rootFrame, ptFrame, ptInFrame);
-
-  nsIFrame* currFrame = ptFrame;
-  nsIContent* newFocusContent = nullptr;
-  while (currFrame) {
-    int32_t tabIndexUnused = 0;
-    if (currFrame->IsFocusable(&tabIndexUnused, true)) {
-      newFocusContent = currFrame->GetContent();
-      nsCOMPtr<nsIDOMElement> domElement(do_QueryInterface(newFocusContent));
-      if (domElement)
-        break;
-    }
-    currFrame = currFrame->GetParent();
-  }
-
-
-  // If target frame is focusable, we should move focus to it. If target frame
-  // isn't focusable, and our previous focused content is editable, we should
-  // clear focus.
-  nsFocusManager* fm = nsFocusManager::GetFocusManager();
-  nsIContent* editingHost = ptFrame->GetContent()->GetEditingHost();
-  if (newFocusContent && currFrame) {
-    nsCOMPtr<nsIDOMElement> domElement(do_QueryInterface(newFocusContent));
-    fm->SetFocus(domElement,0);
-
-    if (editingHost && !nsContentUtils::HasNonEmptyTextContent(
-          editingHost, nsContentUtils::eRecurseIntoChildren)) {
-      SELECTIONCARETS_LOG("Select a editable content %p with empty text",
-                          editingHost);
-      // Long tap on the content with empty text, no action for
-      // selectioncarets but need to dispatch the taponcaret event
-      // to support the short cut mode
-      DispatchSelectionStateChangedEvent(GetSelection(),
-                                         SelectionState::Taponcaret);
-      return NS_OK;
-    }
-  } else {
-    nsIContent* focusedContent = GetFocusedContent();
-    if (focusedContent) {
-      // Clear focus if content was editable element, or contentEditable.
-      nsGenericHTMLElement* focusedGeneric =
-        nsGenericHTMLElement::FromContent(focusedContent);
-      if (focusedContent->GetTextEditorRootContent() ||
-          (focusedGeneric && focusedGeneric->IsContentEditable())) {
-        nsIDOMWindow* win = mPresShell->GetDocument()->GetWindow();
-        if (win) {
-          fm->ClearFocus(win);
-        }
-      }
-    }
-  }
-
-  SetSelectionDragState(true);
-  nsFrame* frame = static_cast<nsFrame*>(ptFrame);
-  nsresult rs = frame->SelectByTypeAtPoint(mPresShell->GetPresContext(), ptInFrame,
-                                           eSelectWord, eSelectWord, 0);
-
-#ifdef DEBUG_FRAME_DUMP
-  nsCString frameTag;
-  frame->ListTag(frameTag);
-  SELECTIONCARETS_LOG("Frame=%s, ptInFrame=(%d, %d)", frameTag.get(),
-                      ptInFrame.x, ptInFrame.y);
-#endif
-
-  SetSelectionDragState(false);
-
-  // Clear maintain selection otherwise we cannot select less than a word
-  RefPtr<nsFrameSelection> fs = GetFrameSelection();
-  if (fs) {
-    fs->MaintainSelection();
-  }
-  return rs;
-}
-
-/*
- * If we're dragging start caret, we do not want to drag over previous
- * character of end caret. Same as end caret. So we check if content offset
- * exceed previous/next character of end/start caret base on aDragMode.
- */
-static bool
-CompareRangeWithContentOffset(nsRange* aRange,
-                              nsFrameSelection* aSelection,
-                              nsIFrame::ContentOffsets& aOffsets,
-                              SelectionCarets::DragMode aDragMode)
-{
-  MOZ_ASSERT(aDragMode != SelectionCarets::NONE);
-  nsINode* node = nullptr;
-  int32_t nodeOffset = 0;
-  CaretAssociationHint hint;
-  nsDirection dir;
-
-  if (aDragMode == SelectionCarets::START_FRAME) {
-    // Check previous character of end node offset
-    node = aRange->GetEndParent();
-    nodeOffset = aRange->EndOffset();
-    hint = CARET_ASSOCIATE_BEFORE;
-    dir = eDirPrevious;
-  } else {
-    // Check next character of start node offset
-    node = aRange->GetStartParent();
-    nodeOffset = aRange->StartOffset();
-    hint =  CARET_ASSOCIATE_AFTER;
-    dir = eDirNext;
-  }
-  nsCOMPtr<nsIContent> content = do_QueryInterface(node);
-
-  int32_t offset = 0;
-  nsIFrame* theFrame =
-    aSelection->GetFrameForNodeOffset(content, nodeOffset, hint, &offset);
-
-  if (!theFrame) {
-    return false;
-  }
-
-  // Move one character forward/backward from point and get offset
-  nsPeekOffsetStruct pos(eSelectCluster,
-                         dir,
-                         offset,
-                         nsPoint(0, 0),
-                         true,
-                         true,  //limit on scrolled views
-                         false,
-                         false,
-                         false);
-  nsresult rv = theFrame->PeekOffset(&pos);
-  if (NS_FAILED(rv)) {
-    pos.mResultContent = content;
-    pos.mContentOffset = nodeOffset;
-  }
-
-  // Compare with current point
-  int32_t result = nsContentUtils::ComparePoints(aOffsets.content,
-                                                 aOffsets.StartOffset(),
-                                                 pos.mResultContent,
-                                                 pos.mContentOffset);
-  if ((aDragMode == SelectionCarets::START_FRAME && result == 1) ||
-      (aDragMode == SelectionCarets::END_FRAME && result == -1)) {
-    aOffsets.content = pos.mResultContent;
-    aOffsets.offset = pos.mContentOffset;
-    aOffsets.secondaryOffset = pos.mContentOffset;
-  }
-
-  return true;
-}
-
-nsEventStatus
-SelectionCarets::DragSelection(const nsPoint &movePoint)
-{
-  nsIFrame* rootFrame = mPresShell->GetRootFrame();
-  if (!rootFrame) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  // Find out which content we point to
-  nsIFrame *ptFrame = nsLayoutUtils::GetFrameForPoint(rootFrame, movePoint,
-    nsLayoutUtils::IGNORE_PAINT_SUPPRESSION | nsLayoutUtils::IGNORE_CROSS_DOC);
-  if (!ptFrame) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  RefPtr<nsFrameSelection> fs = GetFrameSelection();
-  if (!fs) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  nsresult result;
-  nsIFrame *newFrame = nullptr;
-  nsPoint newPoint;
-  nsPoint ptInFrame = movePoint;
-  nsLayoutUtils::TransformPoint(rootFrame, ptFrame, ptInFrame);
-  result = fs->ConstrainFrameAndPointToAnchorSubtree(ptFrame, ptInFrame, &newFrame, newPoint);
-  if (NS_FAILED(result) || !newFrame) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  bool selectable;
-  newFrame->IsSelectable(&selectable, nullptr);
-  if (!selectable) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  nsFrame::ContentOffsets offsets =
-    newFrame->GetContentOffsetsFromPoint(newPoint);
-  if (!offsets.content) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  RefPtr<dom::Selection> selection = GetSelection();
-  if (!selection) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  int32_t rangeCount = selection->RangeCount();
-  if (rangeCount <= 0) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  // Limit the drag behavior not to cross the end of last selection range
-  // when drag the start frame and vice versa
-  RefPtr<nsRange> range = mDragMode == START_FRAME ?
-    selection->GetRangeAt(rangeCount - 1) : selection->GetRangeAt(0);
-  if (!CompareRangeWithContentOffset(range, fs, offsets, mDragMode)) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  nsIFrame* anchorFrame;
-  selection->GetPrimaryFrameForAnchorNode(&anchorFrame);
-  if (!anchorFrame) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  // Clear maintain selection so that we can drag caret freely.
-  fs->MaintainSelection(eSelectNoAmount);
-
-  // Move caret postion.
-  nsIFrame *scrollable =
-    nsLayoutUtils::GetClosestFrameOfType(anchorFrame, nsGkAtoms::scrollFrame);
-  nsWeakFrame weakScrollable = scrollable;
-  fs->HandleClick(offsets.content, offsets.StartOffset(),
-                  offsets.EndOffset(),
-                  true,
-                  false,
-                  offsets.associate);
-  if (!weakScrollable.IsAlive()) {
-    return nsEventStatus_eConsumeNoDefault;
-  }
-
-  // Scroll scrolled frame.
-  nsIScrollableFrame *saf = do_QueryFrame(scrollable);
-  nsIFrame *capturingFrame = saf->GetScrolledFrame();
-  nsPoint ptInScrolled = movePoint;
-  nsLayoutUtils::TransformPoint(rootFrame, capturingFrame, ptInScrolled);
-  fs->StartAutoScrollTimer(capturingFrame, ptInScrolled, TouchCaret::sAutoScrollTimerDelay);
-  UpdateSelectionCarets();
-  return nsEventStatus_eConsumeNoDefault;
-}
-
-nscoord
-SelectionCarets::GetCaretYCenterPosition()
-{
-  nsIFrame* rootFrame = mPresShell->GetRootFrame();
-
-  if (!rootFrame) {
-    return 0;
-  }
-
-  RefPtr<dom::Selection> selection = GetSelection();
-  if (!selection) {
-    return 0;
-  }
-
-  int32_t rangeCount = selection->RangeCount();
-  if (rangeCount <= 0) {
-    return 0;
-  }
-
-  RefPtr<nsFrameSelection> fs = GetFrameSelection();
-  if (!fs) {
-    return 0;
-  }
-
-  MOZ_ASSERT(mDragMode != NONE);
-  nsCOMPtr<nsIContent> node;
-  uint32_t nodeOffset;
-  if (mDragMode == START_FRAME) {
-    RefPtr<nsRange> range = selection->GetRangeAt(0);
-    node = do_QueryInterface(range->GetStartParent());
-    nodeOffset = range->StartOffset();
-  } else {
-    RefPtr<nsRange> range = selection->GetRangeAt(rangeCount - 1);
-    node = do_QueryInterface(range->GetEndParent());
-    nodeOffset = range->EndOffset();
-  }
-
-  int32_t offset;
-  CaretAssociationHint hint =
-    mDragMode == START_FRAME ? CARET_ASSOCIATE_AFTER : CARET_ASSOCIATE_BEFORE;
-  nsIFrame* theFrame =
-    fs->GetFrameForNodeOffset(node, nodeOffset, hint, &offset);
-
-  if (!theFrame) {
-    return 0;
-  }
-  nsRect frameRect = theFrame->GetRectRelativeToSelf();
-  nsLayoutUtils::TransformRect(theFrame, rootFrame, frameRect);
-  return frameRect.Center().y;
-}
-
-void
-SelectionCarets::SetSelectionDragState(bool aState)
-{
-  RefPtr<nsFrameSelection> fs = GetFrameSelection();
-  if (fs) {
-    fs->SetDragState(aState);
-  }
-}
-
-void
-SelectionCarets::SetSelectionDirection(nsDirection aDir)
-{
-  RefPtr<dom::Selection> selection = GetSelection();
-  if (selection) {
-    selection->AdjustAnchorFocusForMultiRange(aDir);
-  }
-}
-
-static void
-SetFramePos(dom::Element* aElement, const nsRect& aCaretRect)
-{
-  if (!aElement) {
-    return;
-  }
-
-  nsAutoString styleStr;
-  styleStr.AppendLiteral("left: ");
-  styleStr.AppendFloat(nsPresContext::AppUnitsToFloatCSSPixels(aCaretRect.Center().x));
-  styleStr.AppendLiteral("px; top: ");
-  styleStr.AppendFloat(nsPresContext::AppUnitsToFloatCSSPixels(aCaretRect.y));
-  styleStr.AppendLiteral("px; padding-top: ");
-  styleStr.AppendFloat(nsPresContext::AppUnitsToFloatCSSPixels(aCaretRect.height));
-  styleStr.AppendLiteral("px;");
-
-  SELECTIONCARETS_LOG_STATIC("Set style: %s",
-                             NS_ConvertUTF16toUTF8(styleStr).get());
-
-  aElement->SetAttr(kNameSpaceID_None, nsGkAtoms::style, styleStr, true);
-}
-
-void
-SelectionCarets::SetStartFramePos(const nsRect& aCaretRect)
-{
-  SELECTIONCARETS_LOG("x=%d, y=%d, w=%d, h=%d",
-    aCaretRect.x, aCaretRect.y, aCaretRect.width, aCaretRect.height);
-  SetFramePos(mPresShell->GetSelectionCaretsStartElement(), aCaretRect);
-}
-
-void
-SelectionCarets::SetEndFramePos(const nsRect& aCaretRect)
-{
-  SELECTIONCARETS_LOG("x=%d, y=%d, w=%d, h=%d",
-    aCaretRect.x, aCaretRect.y, aCaretRect.width, aCaretRect.height);
-  SetFramePos(mPresShell->GetSelectionCaretsEndElement(), aCaretRect);
-}
-
-bool
-SelectionCarets::IsOnStartFrameInner(const nsPoint& aPosition)
-{
-  return mVisible &&
-    nsLayoutUtils::ContainsPoint(GetStartFrameRectInner(), aPosition,
-                                 SelectionCaretsInflateSize());
-}
-
-bool
-SelectionCarets::IsOnEndFrameInner(const nsPoint& aPosition)
-{
-  return mVisible &&
-    nsLayoutUtils::ContainsPoint(GetEndFrameRectInner(), aPosition,
-                                 SelectionCaretsInflateSize());
-}
-
-nsRect
-SelectionCarets::GetStartFrameRect()
-{
-  dom::Element* element = mPresShell->GetSelectionCaretsStartElement();
-  nsIFrame* rootFrame = mPresShell->GetRootFrame();
-  return nsLayoutUtils::GetRectRelativeToFrame(element, rootFrame);
-}
-
-nsRect
-SelectionCarets::GetEndFrameRect()
-{
-  dom::Element* element = mPresShell->GetSelectionCaretsEndElement();
-  nsIFrame* rootFrame = mPresShell->GetRootFrame();
-  return nsLayoutUtils::GetRectRelativeToFrame(element, rootFrame);
-}
-
-nsRect
-SelectionCarets::GetStartFrameRectInner()
-{
-  dom::Element* element = mPresShell->GetSelectionCaretsStartElement();
-  dom::Element* childElement = element->GetFirstElementChild();
-  nsIFrame* rootFrame = mPresShell->GetRootFrame();
-  return nsLayoutUtils::GetRectRelativeToFrame(childElement, rootFrame);
-}
-
-nsRect
-SelectionCarets::GetEndFrameRectInner()
-{
-  dom::Element* element = mPresShell->GetSelectionCaretsEndElement();
-  dom::Element* childElement = element->GetFirstElementChild();
-  nsIFrame* rootFrame = mPresShell->GetRootFrame();
-  return nsLayoutUtils::GetRectRelativeToFrame(childElement, rootFrame);
-}
-
-nsIContent*
-SelectionCarets::GetFocusedContent()
-{
-  nsFocusManager* fm = nsFocusManager::GetFocusManager();
-  if (fm) {
-    return fm->GetFocusedContent();
-  }
-
-  return nullptr;
-}
-
-Selection*
-SelectionCarets::GetSelection()
-{
-  RefPtr<nsFrameSelection> fs = GetFrameSelection();
-  if (fs) {
-    return fs->GetSelection(nsISelectionController::SELECTION_NORMAL);
-  }
-  return nullptr;
-}
-
-already_AddRefed<nsFrameSelection>
-SelectionCarets::GetFrameSelection()
-{
-  nsIContent* focusNode = GetFocusedContent();
-  if (focusNode) {
-    nsIFrame* focusFrame = focusNode->GetPrimaryFrame();
-    if (!focusFrame) {
-      return nullptr;
-    }
-
-    // Prevent us from touching the nsFrameSelection associated to other
-    // PresShell.
-    RefPtr<nsFrameSelection> fs = focusFrame->GetFrameSelection();
-    if (!fs || fs->GetShell() != mPresShell) {
-      return nullptr;
-    }
-
-    return fs.forget();
-  } else {
-    return mPresShell->FrameSelection();
-  }
-}
-
-static dom::Sequence<SelectionState>
-GetSelectionStates(int16_t aReason)
-{
-  dom::Sequence<SelectionState> states;
-  if (aReason & nsISelectionListener::DRAG_REASON) {
-    states.AppendElement(SelectionState::Drag, fallible);
-  }
-  if (aReason & nsISelectionListener::MOUSEDOWN_REASON) {
-    states.AppendElement(SelectionState::Mousedown, fallible);
-  }
-  if (aReason & nsISelectionListener::MOUSEUP_REASON) {
-    states.AppendElement(SelectionState::Mouseup, fallible);
-  }
-  if (aReason & nsISelectionListener::KEYPRESS_REASON) {
-    states.AppendElement(SelectionState::Keypress, fallible);
-  }
-  if (aReason & nsISelectionListener::SELECTALL_REASON) {
-    states.AppendElement(SelectionState::Selectall, fallible);
-  }
-  if (aReason & nsISelectionListener::COLLAPSETOSTART_REASON) {
-    states.AppendElement(SelectionState::Collapsetostart, fallible);
-  }
-  if (aReason & nsISelectionListener::COLLAPSETOEND_REASON) {
-    states.AppendElement(SelectionState::Collapsetoend, fallible);
-  }
-  return states;
-}
-
-void
-SelectionCarets::DispatchCustomEvent(const nsAString& aEvent)
-{
-  SELECTIONCARETS_LOG("dispatch %s event", NS_ConvertUTF16toUTF8(aEvent).get());
-  bool defaultActionEnabled = true;
-  nsIDocument* doc = mPresShell->GetDocument();
-  MOZ_ASSERT(doc);
-  nsContentUtils::DispatchTrustedEvent(doc,
-                                       ToSupports(doc),
-                                       aEvent,
-                                       true,
-                                       false,
-                                       &defaultActionEnabled);
-}
-
-void
-SelectionCarets::DispatchSelectionStateChangedEvent(Selection* aSelection,
-                                                    SelectionState aState)
-{
-  dom::Sequence<SelectionState> state;
-  state.AppendElement(aState, fallible);
-  DispatchSelectionStateChangedEvent(aSelection, state);
-}
-
-void
-SelectionCarets::DispatchSelectionStateChangedEvent(Selection* aSelection,
-                                                    const Sequence<SelectionState>& aStates)
-{
-  nsIDocument* doc = mPresShell->GetDocument();
-
-  MOZ_ASSERT(doc);
-
-  SelectionStateChangedEventInit init;
-  init.mBubbles = true;
-
-  if (aSelection) {
-    // XXX: Do we need to flush layout?
-    mPresShell->FlushPendingNotifications(Flush_Layout);
-    nsRect rect = nsLayoutUtils::GetSelectionBoundingRect(aSelection);
-    RefPtr<DOMRect>domRect = new DOMRect(ToSupports(doc));
-
-    domRect->SetLayoutRect(rect);
-    init.mBoundingClientRect = domRect;
-    init.mVisible = mSelectionVisibleInScrollFrames;
-
-    aSelection->Stringify(init.mSelectedText);
-  }
-  init.mStates = aStates;
-
-  RefPtr<SelectionStateChangedEvent> event =
-    SelectionStateChangedEvent::Constructor(doc, NS_LITERAL_STRING("mozselectionstatechanged"), init);
-
-  event->SetTrusted(true);
-  event->GetInternalNSEvent()->mFlags.mOnlyChromeDispatch = true;
-  bool ret;
-  doc->DispatchEvent(event, &ret);
-}
-
-void
-SelectionCarets::NotifyBlur(bool aIsLeavingDocument)
-{
-  SELECTIONCARETS_LOG("Send out the blur event");
-  SetVisibility(false);
-  if (aIsLeavingDocument) {
-    CancelLongTapDetector();
-  }
-  CancelScrollEndDetector();
-  mInAsyncPanZoomGesture = false;
-  DispatchSelectionStateChangedEvent(nullptr, SelectionState::Blur);
-}
-
-nsresult
-SelectionCarets::NotifySelectionChanged(nsIDOMDocument* aDoc,
-                                        nsISelection* aSel,
-                                        int16_t aReason)
-{
-  SELECTIONCARETS_LOG("aSel (%p), Reason=%d", aSel, aReason);
-
-  if (aSel != GetSelection()) {
-    SELECTIONCARETS_LOG("Return for selection mismatch!");
-    return NS_OK;
-  }
-
-  if (!aReason || (aReason & (nsISelectionListener::DRAG_REASON |
-                              nsISelectionListener::KEYPRESS_REASON |
-                              nsISelectionListener::MOUSEDOWN_REASON))) {
-    SetVisibility(false);
-  } else {
-    UpdateSelectionCarets();
-  }
-
-  DispatchSelectionStateChangedEvent(static_cast<Selection*>(aSel),
-                                     GetSelectionStates(aReason));
-  return NS_OK;
-}
-
-static void
-DispatchScrollViewChangeEvent(nsIPresShell *aPresShell, const dom::ScrollState aState)
-{
-  nsCOMPtr<nsIDocument> doc = aPresShell->GetDocument();
-  if (doc) {
-    bool ret;
-    ScrollViewChangeEventInit detail;
-    detail.mBubbles = true;
-    detail.mCancelable = false;
-    detail.mState = aState;
-    RefPtr<ScrollViewChangeEvent> event =
-      ScrollViewChangeEvent::Constructor(doc, NS_LITERAL_STRING("scrollviewchange"), detail);
-
-    event->SetTrusted(true);
-    event->GetInternalNSEvent()->mFlags.mOnlyChromeDispatch = true;
-    doc->DispatchEvent(event, &ret);
-  }
-}
-
-void
-SelectionCarets::AsyncPanZoomStarted()
-{
-  if (mVisible) {
-    mInAsyncPanZoomGesture = true;
-    SetVisibility(false);
-    SELECTIONCARETS_LOG("Dispatch scroll started");
-    DispatchScrollViewChangeEvent(mPresShell, dom::ScrollState::Started);
-  } else {
-    RefPtr<dom::Selection> selection = GetSelection();
-    if (selection && selection->RangeCount() && selection->IsCollapsed()) {
-      mInAsyncPanZoomGesture = true;
-      DispatchScrollViewChangeEvent(mPresShell, dom::ScrollState::Started);
-    }
-  }
-}
-
-void
-SelectionCarets::AsyncPanZoomStopped()
-{
-  if (mInAsyncPanZoomGesture) {
-    mInAsyncPanZoomGesture = false;
-    SELECTIONCARETS_LOG("Update selection carets after APZ is stopped!");
-    UpdateSelectionCarets();
-
-    // SelectionStateChangedEvent should be dispatched before ScrollViewChangeEvent.
-    DispatchSelectionStateChangedEvent(GetSelection(),
-                                       SelectionState::Updateposition);
-
-    SELECTIONCARETS_LOG("Dispatch scroll stopped");
-
-    DispatchScrollViewChangeEvent(mPresShell, dom::ScrollState::Stopped);
-  }
-}
-
-void
-SelectionCarets::ScrollPositionChanged()
-{
-  if (mVisible) {
-    if (!mUseAsyncPanZoom) {
-      SetVisibility(false);
-      //TODO: handling scrolling for selection bubble when APZ is off
-      // Dispatch event to notify gaia to hide selection bubble.
-      // Positions will be updated when scroll is end, so no need to calculate
-      // and keep scroll positions here. An arbitrary (0, 0) is sent instead.
-      DispatchScrollViewChangeEvent(mPresShell, dom::ScrollState::Started);
-
-      SELECTIONCARETS_LOG("Launch scroll end detector");
-      LaunchScrollEndDetector();
-    } else {
-      if (!mInAsyncPanZoomGesture) {
-        UpdateSelectionCarets();
-        DispatchSelectionStateChangedEvent(GetSelection(),
-                                           SelectionState::Updateposition);
-      }
-    }
-  } else {
-    RefPtr<dom::Selection> selection = GetSelection();
-    if (selection && selection->RangeCount() && selection->IsCollapsed()) {
-      DispatchSelectionStateChangedEvent(selection,
-                                         SelectionState::Updateposition);
-    }
-  }
-}
-
-void
-SelectionCarets::LaunchLongTapDetector()
-{
-  if (mUseAsyncPanZoom) {
-    return;
-  }
-
-  if (!mLongTapDetectorTimer) {
-    mLongTapDetectorTimer = do_CreateInstance("@mozilla.org/timer;1");
-  }
-
-  MOZ_ASSERT(mLongTapDetectorTimer);
-  CancelLongTapDetector();
-  int32_t longTapDelay = gfxPrefs::UiClickHoldContextMenusDelay();
-
-  SELECTIONCARETS_LOG("Will fire long tap after %d ms", longTapDelay);
-  mLongTapDetectorTimer->InitWithFuncCallback(FireLongTap,
-                                              this,
-                                              longTapDelay,
-                                              nsITimer::TYPE_ONE_SHOT);
-}
-
-void
-SelectionCarets::CancelLongTapDetector()
-{
-  if (mUseAsyncPanZoom) {
-    return;
-  }
-
-  if (!mLongTapDetectorTimer) {
-    return;
-  }
-
-  SELECTIONCARETS_LOG("Cancel long tap detector!");
-  mLongTapDetectorTimer->Cancel();
-}
-
-/* static */void
-SelectionCarets::FireLongTap(nsITimer* aTimer, void* aSelectionCarets)
-{
-  RefPtr<SelectionCarets> self = static_cast<SelectionCarets*>(aSelectionCarets);
-  NS_PRECONDITION(aTimer == self->mLongTapDetectorTimer,
-                  "Unexpected timer");
-
-  SELECTIONCARETS_LOG_STATIC("SelectWord from non-APZ");
-  nsresult wordSelected = self->SelectWord();
-
-  if (NS_FAILED(wordSelected)) {
-    SELECTIONCARETS_LOG_STATIC("SelectWord from non-APZ failed!");
-  }
-}
-
-void
-SelectionCarets::LaunchScrollEndDetector()
-{
-  if (!mScrollEndDetectorTimer) {
-    mScrollEndDetectorTimer = do_CreateInstance("@mozilla.org/timer;1");
-  }
-
-  MOZ_ASSERT(mScrollEndDetectorTimer);
-
-  SELECTIONCARETS_LOG("Will fire scroll end after %d ms",
-    TouchCaret::sScrollEndTimerDelay);
-  mScrollEndDetectorTimer->InitWithFuncCallback(FireScrollEnd,
-                                                this,
-                                                TouchCaret::sScrollEndTimerDelay,
-                                                nsITimer::TYPE_ONE_SHOT);
-}
-
-void
-SelectionCarets::CancelScrollEndDetector()
-{
-  if (!mScrollEndDetectorTimer) {
-    return;
-  }
-
-  SELECTIONCARETS_LOG("Cancel scroll end detector!");
-  mScrollEndDetectorTimer->Cancel();
-}
-
-
-/* static */void
-SelectionCarets::FireScrollEnd(nsITimer* aTimer, void* aSelectionCarets)
-{
-  RefPtr<SelectionCarets> self = static_cast<SelectionCarets*>(aSelectionCarets);
-  NS_PRECONDITION(aTimer == self->mScrollEndDetectorTimer,
-                  "Unexpected timer");
-
-  SELECTIONCARETS_LOG_STATIC("Update selection carets!");
-  self->UpdateSelectionCarets();
-  self->DispatchSelectionStateChangedEvent(self->GetSelection(),
-                                           SelectionState::Updateposition);
-}
-
-NS_IMETHODIMP
-SelectionCarets::Reflow(DOMHighResTimeStamp aStart, DOMHighResTimeStamp aEnd)
-{
-  if (mVisible) {
-    SELECTIONCARETS_LOG("Update selection carets after reflow!");
-    UpdateSelectionCarets();
-
-    // We don't care selection state when we're at drag mode. We always hide
-    // bubble in drag mode. So, don't dispatch event here.
-    if (mDragMode == NONE) {
-      DispatchSelectionStateChangedEvent(GetSelection(),
-                                         SelectionState::Updateposition);
-    }
-  } else {
-    RefPtr<dom::Selection> selection = GetSelection();
-    if (selection && selection->RangeCount() && selection->IsCollapsed()) {
-      DispatchSelectionStateChangedEvent(selection,
-                                         SelectionState::Updateposition);
-    }
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SelectionCarets::ReflowInterruptible(DOMHighResTimeStamp aStart,
-                                     DOMHighResTimeStamp aEnd)
-{
-  return Reflow(aStart, aEnd);
-}
deleted file mode 100644
--- a/layout/base/SelectionCarets.h
+++ /dev/null
@@ -1,277 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 sw=2 et tw=78: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef SelectionCarets_h__
-#define SelectionCarets_h__
-
-#include "nsDirection.h"
-#include "nsIReflowObserver.h"
-#include "nsIScrollObserver.h"
-#include "nsISelectionListener.h"
-#include "nsWeakPtr.h"
-#include "nsWeakReference.h"
-#include "Units.h"
-#include "mozilla/dom/SelectionStateChangedEvent.h"
-#include "mozilla/EventForwards.h"
-#include "mozilla/WeakPtr.h"
-
-class nsDocShell;
-class nsFrameSelection;
-class nsIContent;
-class nsIPresShell;
-class nsITimer;
-
-namespace mozilla {
-
-namespace dom {
-class Selection;
-} // namespace dom
-
-/**
- * NOTE: SelectionCarets was obsoleted by AccessibleCaret, and is no longer used
- * on B2G. This file is going to be removed in bug 1221459. Please see the wiki
- * page for more information. https://wiki.mozilla.org/Copy_n_Paste
- *
- * The SelectionCarets draw a pair of carets when the selection is not
- * collapsed, one at each end of the selection.
- * SelectionCarets also handle visibility, dragging caret and selecting word
- * when long tap event fired.
- *
- * The DOM structure is 2 div elements for showing start and end caret.
- * Each div element has a child div element. That is, each caret consist of
- * outer div and inner div. Outer div takes responsibility for detecting two
- * carets are overlapping. Inner div is for actual appearance.
- *
- * Here is an explanation of the html class names:
- *   .moz-selectioncaret-left: Indicates start DIV.
- *   .moz-selectioncaret-right: Indicates end DIV.
- *   .hidden: This class name is set by SetVisibility,
- *            SetStartFrameVisibility and SetEndFrameVisibility. Element
- *            with this class name become hidden.
- *   .tilt: This class name is set by SetTilted. According to the
- *          UX spec, when selection carets are overlapping, the image of
- *          caret becomes tilt.
- */
-class SelectionCarets final : public nsIReflowObserver,
-                              public nsISelectionListener,
-                              public nsIScrollObserver,
-                              public nsSupportsWeakReference
-{
-public:
-  /**
-   * Indicate which part of caret we are dragging at.
-   */
-  enum DragMode {
-    NONE,
-    START_FRAME,
-    END_FRAME
-  };
-
-  explicit SelectionCarets(nsIPresShell *aPresShell);
-
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIREFLOWOBSERVER
-  NS_DECL_NSISELECTIONLISTENER
-
-  // Notify selection carets about the blur event to hidden itself
-  void NotifyBlur(bool aIsLeavingDocument);
-
-  // nsIScrollObserver
-  virtual void ScrollPositionChanged() override;
-
-  // AsyncPanZoom started/stopped callbacks from nsIScrollObserver
-  virtual void AsyncPanZoomStarted() override;
-  virtual void AsyncPanZoomStopped() override;
-
-  void Init();
-  void Terminate();
-
-  nsEventStatus HandleEvent(WidgetEvent* aEvent);
-
-  bool GetVisibility() const
-  {
-    return mVisible;
-  }
-
-  /**
-   * Get from pref "selectioncaret.inflatesize.threshold". This will inflate size of
-   * caret frame when we checking if user click on caret or not. In app units.
-   */
-  static int32_t SelectionCaretsInflateSize()
-  {
-    return sSelectionCaretsInflateSize;
-  }
-
-  /**
-   * Set visibility for selection caret.
-   */
-  void SetVisibility(bool aVisible);
-
-  /**
-   * Update selection caret position base on current selection range.
-   */
-  void UpdateSelectionCarets();
-
-private:
-  virtual ~SelectionCarets();
-
-  SelectionCarets() = delete;
-
-  /**
-   * Select a word base on current position, which activates only if element is
-   * selectable. Triggered by long tap event.
-   */
-  nsresult SelectWord();
-
-  /**
-   * Move selection base on current touch/mouse point
-   */
-  nsEventStatus DragSelection(const nsPoint &movePoint);
-
-  /**
-   * Get the vertical center position of selection caret relative to root
-   * frame.
-   */
-  nscoord GetCaretYCenterPosition();
-
-  /**
-   * Simulate drag state when we change the selection range.
-   * Hence, the selection change event will fire normally.
-   */
-  void SetSelectionDragState(bool aState);
-
-  void SetSelectionDirection(nsDirection aDir);
-
-  /**
-   * Move start frame of selection caret based on current caret pos.
-   * In app units.
-   */
-  void SetStartFramePos(const nsRect& aCaretRect);
-
-  /**
-   * Move end frame of selection caret based on current caret pos.
-   * In app units.
-   */
-  void SetEndFramePos(const nsRect& aCaretRect);
-
-  /**
-   * Check if aPosition is on the start or end frame of the
-   * selection caret's inner div element.
-   *
-   * @param aPosition should be relative to document's root frame
-   * in app units
-   */
-  bool IsOnStartFrameInner(const nsPoint& aPosition);
-  bool IsOnEndFrameInner(const nsPoint& aPosition);
-
-  /**
-   * Get rect of selection caret's outer div element relative
-   * to document's root frame, in app units.
-   */
-  nsRect GetStartFrameRect();
-  nsRect GetEndFrameRect();
-
-  /**
-   * Get rect of selection caret's inner div element relative
-   * to document's root frame, in app units.
-   */
-  nsRect GetStartFrameRectInner();
-  nsRect GetEndFrameRectInner();
-
-  /**
-   * Set visibility for start part of selection caret, this function
-   * only affects css property of start frame. So it doesn't change
-   * mVisible member. When caret overflows element's box we'll hide
-   * it by calling this function.
-   */
-  void SetStartFrameVisibility(bool aVisible);
-
-  /**
-   * Same as above function but for end frame of selection caret.
-   */
-  void SetEndFrameVisibility(bool aVisible);
-
-  /**
-   * Set tilt class name to start and end frame of selection caret.
-   */
-  void SetTilted(bool aIsTilt);
-
-  // Utility functions
-  dom::Selection* GetSelection();
-  already_AddRefed<nsFrameSelection> GetFrameSelection();
-  nsIContent* GetFocusedContent();
-  void DispatchSelectionStateChangedEvent(dom::Selection* aSelection,
-                                          dom::SelectionState aState);
-  void DispatchSelectionStateChangedEvent(dom::Selection* aSelection,
-                                          const dom::Sequence<dom::SelectionState>& aStates);
-  void DispatchCustomEvent(const nsAString& aEvent);
-
-  /**
-   * Detecting long tap using timer
-   */
-  void LaunchLongTapDetector();
-  void CancelLongTapDetector();
-  static void FireLongTap(nsITimer* aTimer, void* aSelectionCarets);
-
-  void LaunchScrollEndDetector();
-  void CancelScrollEndDetector();
-  static void FireScrollEnd(nsITimer* aTimer, void* aSelectionCarets);
-
-  nsIPresShell* mPresShell;
-  WeakPtr<nsDocShell> mDocShell;
-
-  // This timer is used for detecting long tap fire. If content process
-  // has APZC, we'll use APZC for long tap detecting. Otherwise, we use this
-  // timer to detect long tap.
-  nsCOMPtr<nsITimer> mLongTapDetectorTimer;
-
-  // This timer is used for detecting scroll end. We don't have
-  // scroll end event now, so we will fire this event with a
-  // const time when we scroll. So when timer triggers, we treat it
-  // as scroll end event.
-  nsCOMPtr<nsITimer> mScrollEndDetectorTimer;
-
-  // When touch or mouse down, we save the position for detecting
-  // drag distance
-  nsPoint mDownPoint;
-
-  // For filter multitouch event
-  int32_t mActiveTouchId;
-
-  nscoord mCaretCenterToDownPointOffsetY;
-
-  // The horizontal boundary is defined by the first selected frame which
-  // determines the start-caret position. When users drag the end-caret up,
-  // the touch input(pos.y) will be changed to not cross this boundary.
-  // Otherwise, the selection range changes to one character only
-  // which causes the bad user experience.
-  nscoord mDragUpYBoundary;
-  // The horizontal boundary is defined by the last selected frame which
-  // determines the end-caret position. When users drag the start-caret down,
-  // the touch input(pos.y) will be changed to not cross this boundary.
-  // Otherwise, the selection range changes to one character only
-  // which causes the bad user experience.
-  nscoord mDragDownYBoundary;
-
-  DragMode mDragMode;
-
-  // True if async-pan-zoom should be used for selection carets.
-  bool mUseAsyncPanZoom;
-  // True if AsyncPanZoom is started
-  bool mInAsyncPanZoomGesture;
-
-  bool mEndCaretVisible;
-  bool mStartCaretVisible;
-  bool mSelectionVisibleInScrollFrames;
-  bool mVisible;
-
-  // Preference
-  static int32_t sSelectionCaretsInflateSize;
-};
-
-} // namespace mozilla
-
-#endif //SelectionCarets_h__
deleted file mode 100644
--- a/layout/base/TouchCaret.cpp
+++ /dev/null
@@ -1,1110 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 sw=2 et tw=78: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "mozilla/Logging.h"
-#include "TouchCaret.h"
-
-#include <algorithm>
-
-#include "nsBlockFrame.h"
-#include "nsCanvasFrame.h"
-#include "nsCaret.h"
-#include "nsCOMPtr.h"
-#include "nsContentUtils.h"
-#include "nsDOMTokenList.h"
-#include "nsFrameSelection.h"
-#include "nsIContent.h"
-#include "nsIDOMNode.h"
-#include "nsIDOMWindow.h"
-#include "nsIFrame.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsIPresShell.h"
-#include "nsIScrollableFrame.h"
-#include "nsISelection.h"
-#include "nsISelectionController.h"
-#include "nsISelectionPrivate.h"
-#include "nsPresContext.h"
-#include "nsQueryContentEventResult.h"
-#include "nsView.h"
-#include "mozilla/dom/SelectionStateChangedEvent.h"
-#include "mozilla/dom/CustomEvent.h"
-#include "mozilla/BasicEvents.h"
-#include "mozilla/Preferences.h"
-
-using namespace mozilla;
-
-static const char* kTouchCaretLogModuleName = "TouchCaret";
-static mozilla::LazyLogModule gTouchCaretLog(kTouchCaretLogModuleName);
-
-// To enable all the TOUCHCARET_LOG print statements, set the environment
-// variable NSPR_LOG_MODULES=TouchCaret:5
-#define TOUCHCARET_LOG(message, ...)                                           \
-  MOZ_LOG(gTouchCaretLog, LogLevel::Debug,                                         \
-         ("TouchCaret (%p): %s:%d : " message "\n", this, __FUNCTION__,        \
-          __LINE__, ##__VA_ARGS__));
-
-#define TOUCHCARET_LOG_STATIC(message, ...)                                    \
-  MOZ_LOG(gTouchCaretLog, LogLevel::Debug,                                         \
-         ("TouchCaret: %s:%d : " message "\n", __FUNCTION__, __LINE__,         \
-          ##__VA_ARGS__));
-
-// Click on the boundary of input/textarea will place the caret at the
-// front/end of the content. To advoid this, we need to deflate the content
-// boundary by 61 app units (1 pixel + 1 app unit).
-static const int32_t kBoundaryAppUnits = 61;
-
-NS_IMPL_ISUPPORTS(TouchCaret,
-                  nsISelectionListener,
-                  nsIScrollObserver,
-                  nsISupportsWeakReference)
-
-/*static*/ int32_t TouchCaret::sTouchCaretInflateSize = 0;
-/*static*/ int32_t TouchCaret::sTouchCaretExpirationTime = 0;
-
-TouchCaret::TouchCaret(nsIPresShell* aPresShell)
-  : mState(TOUCHCARET_NONE),
-    mActiveTouchId(-1),
-    mCaretCenterToDownPointOffsetY(0),
-    mInAsyncPanZoomGesture(false),
-    mVisible(false)
-{
-  MOZ_ASSERT(NS_IsMainThread());
-
-  TOUCHCARET_LOG("Constructor, PresShell=%p", aPresShell);
-
-  static bool addedTouchCaretPref = false;
-  if (!addedTouchCaretPref) {
-    Preferences::AddIntVarCache(&sTouchCaretInflateSize,
-                                "touchcaret.inflatesize.threshold");
-    Preferences::AddIntVarCache(&sTouchCaretExpirationTime,
-                                "touchcaret.expiration.time");
-    addedTouchCaretPref = true;
-  }
-
-  // The presshell owns us, so no addref.
-  mPresShell = do_GetWeakReference(aPresShell);
-  MOZ_ASSERT(mPresShell, "Hey, pres shell should support weak refs");
-}
-
-void
-TouchCaret::Init()
-{
-  nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
-  if (!presShell) {
-    return;
-  }
-
-  nsPresContext* presContext = presShell->GetPresContext();
-  MOZ_ASSERT(presContext, "PresContext should be given in PresShell::Init()");
-
-  nsIDocShell* docShell = presContext->GetDocShell();
-  if (!docShell) {
-    return;
-  }
-
-  docShell->AddWeakScrollObserver(this);
-  mDocShell = static_cast<nsDocShell*>(docShell);
-}
-
-void
-TouchCaret::Terminate()
-{
-  RefPtr<nsDocShell> docShell(mDocShell.get());
-  if (docShell) {
-    docShell->RemoveWeakScrollObserver(this);
-  }
-
-  if (mScrollEndDetectorTimer) {
-    mScrollEndDetectorTimer->Cancel();
-    mScrollEndDetectorTimer = nullptr;
-  }
-
-  mDocShell = WeakPtr<nsDocShell>();
-  mPresShell = nullptr;
-}
-
-TouchCaret::~TouchCaret()
-{
-  TOUCHCARET_LOG("Destructor");
-  MOZ_ASSERT(NS_IsMainThread());
-
-  if (mTouchCaretExpirationTimer) {
-    mTouchCaretExpirationTimer->Cancel();
-    mTouchCaretExpirationTimer = nullptr;
-  }
-}
-
-nsIFrame*
-TouchCaret::GetCaretFocusFrame(nsRect* aOutRect)
-{
-  nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
-  if (!presShell) {
-    return nullptr;
-  }
-
-  RefPtr<nsCaret> caret = presShell->GetCaret();
-  if (!caret) {
-    return nullptr;
-  }
-
-  nsRect rect;
-  nsIFrame* frame = caret->GetGeometry(&rect);
-
-  if (aOutRect) {
-    *aOutRect = rect;
-  }
-
-  return frame;
-}
-
-nsCanvasFrame*
-TouchCaret::GetCanvasFrame()
-{
-  nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
-  if (!presShell) {
-    return nullptr;
-  }
-  return presShell->GetCanvasFrame();
-}
-
-nsIFrame*
-TouchCaret::GetRootFrame()
-{
-  nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
-  if (!presShell) {
-    return nullptr;
-  }
-  return presShell->GetRootFrame();
-}
-
-void
-TouchCaret::SetVisibility(bool aVisible)
-{
-  if (mVisible == aVisible) {
-    TOUCHCARET_LOG("Set visibility %s, same as the old one",
-                   (aVisible ? "shown" : "hidden"));
-    return;
-  }
-
-  nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
-  if (!presShell) {
-    return;
-  }
-
-  mozilla::dom::Element* touchCaretElement = presShell->GetTouchCaretElement();
-  if (!touchCaretElement) {
-    return;
-  }
-
-  mVisible = aVisible;
-
-  // Set touch caret visibility.
-  ErrorResult err;
-  touchCaretElement->ClassList()->Toggle(NS_LITERAL_STRING("hidden"),
-                                         dom::Optional<bool>(!mVisible),
-                                         err);
-  TOUCHCARET_LOG("Set visibility %s", (mVisible ? "shown" : "hidden"));
-
-  // Set touch caret expiration time.
-  mVisible ? LaunchExpirationTimer() : CancelExpirationTimer();
-}
-
-nsRect
-TouchCaret::GetTouchFrameRect()
-{
-  nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
-  if (!presShell) {
-    return nsRect();
-  }
-
-  dom::Element* touchCaretElement = presShell->GetTouchCaretElement();
-  nsIFrame* canvasFrame = GetCanvasFrame();
-  return nsLayoutUtils::GetRectRelativeToFrame(touchCaretElement, canvasFrame);
-}
-
-nsRect
-TouchCaret::GetContentBoundary()
-{
-  nsIFrame* focusFrame = GetCaretFocusFrame();
-  nsIFrame* canvasFrame = GetCanvasFrame();
-  if (!focusFrame || !canvasFrame) {
-    return nsRect();
-  }
-
-  // Get the editing host to determine the touch caret dragable boundary.
-  dom::Element* editingHost = focusFrame->GetContent()->GetEditingHost();
-  if (!editingHost) {
-    return nsRect();
-  }
-
-  nsRect resultRect;
-  for (nsIFrame* frame = editingHost->GetPrimaryFrame(); frame;
-       frame = frame->GetNextContinuation()) {
-    nsRect rect = frame->GetContentRectRelativeToSelf();
-    nsLayoutUtils::TransformRect(frame, canvasFrame, rect);
-    resultRect = resultRect.Union(rect);
-
-    mozilla::layout::FrameChildListIterator lists(frame);
-    for (; !lists.IsDone(); lists.Next()) {
-      // Loop over all children to take the overflow rect in to consideration.
-      nsFrameList::Enumerator childFrames(lists.CurrentList());
-      for (; !childFrames.AtEnd(); childFrames.Next()) {
-        nsIFrame* kid = childFrames.get();
-        nsRect overflowRect = kid->GetScrollableOverflowRect();
-        nsLayoutUtils::TransformRect(kid, canvasFrame, overflowRect);
-        resultRect = resultRect.Union(overflowRect);
-      }
-    }
-  }
-  // Shrink rect to make sure we never hit the boundary.
-  resultRect.Deflate(kBoundaryAppUnits);
-
-  return resultRect;
-}
-
-nscoord
-TouchCaret::GetCaretYCenterPosition()
-{
-  nsRect caretRect;
-  nsIFrame* focusFrame = GetCaretFocusFrame(&caretRect);
-  nsIFrame* canvasFrame = GetCanvasFrame();
-
-  nsLayoutUtils::TransformRect(focusFrame, canvasFrame, caretRect);
-
-  return (caretRect.y + caretRect.height / 2);
-}
-
-void
-TouchCaret::SetTouchFramePos(const nsRect& aCaretRect)
-{
-  nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
-  if (!presShell) {
-    return;
-  }
-
-  mozilla::dom::Element* touchCaretElement = presShell->GetTouchCaretElement();
-  if (!touchCaretElement) {
-    return;
-  }
-
-  // Convert aOrigin to CSS pixels.
-  RefPtr<nsPresContext> presContext = presShell->GetPresContext();
-  int32_t x = presContext->AppUnitsToIntCSSPixels(aCaretRect.Center().x);
-  int32_t y = presContext->AppUnitsToIntCSSPixels(aCaretRect.y);
-  int32_t padding = presContext->AppUnitsToIntCSSPixels(aCaretRect.height);
-
-  nsAutoString styleStr;
-  styleStr.AppendLiteral("left: ");
-  styleStr.AppendInt(x);
-  styleStr.AppendLiteral("px; top: ");
-  styleStr.AppendInt(y);
-  styleStr.AppendLiteral("px; padding-top: ");
-  styleStr.AppendInt(padding);
-  styleStr.AppendLiteral("px;");
-
-  TOUCHCARET_LOG("Set style: %s", NS_ConvertUTF16toUTF8(styleStr).get());
-
-  touchCaretElement->SetAttr(kNameSpaceID_None, nsGkAtoms::style,
-                             styleStr, true);
-}
-
-void
-TouchCaret::MoveCaret(const nsPoint& movePoint)
-{
-  nsIFrame* focusFrame = GetCaretFocusFrame();
-  nsIFrame* canvasFrame = GetCanvasFrame();
-  if (!focusFrame && !canvasFrame) {
-    return;
-  }
-  nsIFrame* scrollable =
-    nsLayoutUtils::GetClosestFrameOfType(focusFrame, nsGkAtoms::scrollFrame);
-
-  // Convert touch/mouse position to frame coordinates.
-  nsPoint offsetToCanvasFrame = nsPoint(0,0);
-  nsLayoutUtils::TransformPoint(scrollable, canvasFrame, offsetToCanvasFrame);
-  nsPoint pt = movePoint - offsetToCanvasFrame;
-
-  // Evaluate offsets.
-  nsIFrame::ContentOffsets offsets =
-    scrollable->GetContentOffsetsFromPoint(pt, nsIFrame::SKIP_HIDDEN);
-
-  // Move caret position.
-  nsWeakFrame weakScrollable = scrollable;
-  RefPtr<nsFrameSelection> fs = scrollable->GetFrameSelection();
-  fs->HandleClick(offsets.content, offsets.StartOffset(),
-                  offsets.EndOffset(),
-                  false,
-                  false,
-                  offsets.associate);
-
-  if (!weakScrollable.IsAlive()) {
-    return;
-  }
-
-  // Scroll scrolled frame.
-  nsIScrollableFrame* saf = do_QueryFrame(scrollable);
-  nsIFrame* capturingFrame = saf->GetScrolledFrame();
-  offsetToCanvasFrame = nsPoint(0,0);
-  nsLayoutUtils::TransformPoint(capturingFrame, canvasFrame, offsetToCanvasFrame);
-  pt = movePoint - offsetToCanvasFrame;
-  fs->StartAutoScrollTimer(capturingFrame, pt, sAutoScrollTimerDelay);
-}
-
-bool
-TouchCaret::IsOnTouchCaret(const nsPoint& aPoint)
-{
-  return mVisible && nsLayoutUtils::ContainsPoint(GetTouchFrameRect(), aPoint,
-                                                  TouchCaretInflateSize());
-}
-
-nsresult
-TouchCaret::NotifySelectionChanged(nsIDOMDocument* aDoc, nsISelection* aSel,
-                                   int16_t aReason)
-{
-  TOUCHCARET_LOG("aSel (%p), Reason=%d", aSel, aReason);
-
-  // Hide touch caret while no caret exists.
-  nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
-  if (!presShell) {
-    return NS_OK;
-  }
-
-  RefPtr<nsCaret> caret = presShell->GetCaret();
-  if (!caret) {
-    SetVisibility(false);
-    return NS_OK;
-  }
-
-  // The same touch caret is shared amongst the document and any text widgets it
-  // may contain. This means that the touch caret could get notifications from
-  // multiple selections.
-  // If this notification is for a selection that is not the one the
-  // the caret is currently interested in , then there is nothing to do!
-  if (aSel != caret->GetSelection()) {
-    TOUCHCARET_LOG("Return for selection mismatch!");
-    return NS_OK;
-  }
-
-  // Update touch caret position and visibility.
-  // Hide touch caret while key event causes selection change.
-  // Also hide touch caret when gecko or javascript collapse the selection.
-  if (aReason & nsISelectionListener::KEYPRESS_REASON ||
-      aReason & nsISelectionListener::COLLAPSETOSTART_REASON ||
-      aReason & nsISelectionListener::COLLAPSETOEND_REASON) {
-    TOUCHCARET_LOG("KEYPRESS_REASON");
-    SetVisibility(false);
-  } else {
-    SyncVisibilityWithCaret();
-  }
-
-  return NS_OK;
-}
-
-/**
- * Used to update caret position after PanZoom stops for
- * extended caret visibility. Never needed by MOZ_WIDGET_GONK.
- */
-void
-TouchCaret::AsyncPanZoomStarted()
-{
-}
-
-void
-TouchCaret::AsyncPanZoomStopped()
-{
-  if (mInAsyncPanZoomGesture) {
-    mInAsyncPanZoomGesture = false;
-    UpdatePosition();
-  }
-}
-
-/**
- * Used to update caret position after Scroll stops for
- * extended caret visibility. Never needed by MOZ_WIDGET_GONK.
- */
-void
-TouchCaret::ScrollPositionChanged()
-{
-}
-
-void
-TouchCaret::LaunchScrollEndDetector()
-{
-  if (!mScrollEndDetectorTimer) {
-    mScrollEndDetectorTimer = do_CreateInstance("@mozilla.org/timer;1");
-  }
-  MOZ_ASSERT(mScrollEndDetectorTimer);
-
-  mScrollEndDetectorTimer->InitWithFuncCallback(FireScrollEnd,
-                                                this,
-                                                sScrollEndTimerDelay,
-                                                nsITimer::TYPE_ONE_SHOT);
-}
-
-void
-TouchCaret::CancelScrollEndDetector()
-{
-  if (mScrollEndDetectorTimer) {
-    mScrollEndDetectorTimer->Cancel();
-  }
-}
-
-
-/* static */void
-TouchCaret::FireScrollEnd(nsITimer* aTimer, void* aTouchCaret)
-{
-  RefPtr<TouchCaret> self = static_cast<TouchCaret*>(aTouchCaret);
-  NS_PRECONDITION(aTimer == self->mScrollEndDetectorTimer,
-                  "Unexpected timer");
-  self->UpdatePosition();
-}
-
-void
-TouchCaret::SyncVisibilityWithCaret()
-{
-  TOUCHCARET_LOG("SyncVisibilityWithCaret");
-
-  if (!IsDisplayable()) {
-    SetVisibility(false);
-    return;
-  }
-
-  SetVisibility(true);
-  if (mVisible) {
-    UpdatePosition();
-  }
-}
-
-void
-TouchCaret::UpdatePositionIfNeeded()
-{
-  TOUCHCARET_LOG("UpdatePositionIfNeeded");
-
-  if (!IsDisplayable()) {
-    SetVisibility(false);
-    return;
-  }
-
-  if (mVisible) {
-    UpdatePosition();
-  }
-}
-
-bool
-TouchCaret::IsDisplayable()
-{
-  nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
-  if (!presShell) {
-    TOUCHCARET_LOG("PresShell is nullptr!");
-    return false;
-  }
-
-  RefPtr<nsCaret> caret = presShell->GetCaret();
-  if (!caret) {
-    TOUCHCARET_LOG("Caret is nullptr!");
-    return false;
-  }
-
-  nsIFrame* canvasFrame = GetCanvasFrame();
-  if (!canvasFrame) {
-    TOUCHCARET_LOG("No canvas frame!");
-    return false;
-  }
-
-  nsIFrame* rootFrame = GetRootFrame();
-  if (!rootFrame) {
-    TOUCHCARET_LOG("No root frame!");
-    return false;
-  }
-
-  dom::Element* touchCaretElement = presShell->GetTouchCaretElement();
-  if (!touchCaretElement) {
-    TOUCHCARET_LOG("No touch caret frame element!");
-    return false;
-  }
-
-  if (presShell->IsPaintingSuppressed()) {
-    TOUCHCARET_LOG("PresShell is suppressing painting!");
-    return false;
-  }
-
-  if (!caret->IsVisible()) {
-    TOUCHCARET_LOG("Caret is not visible!");
-    return false;
-  }
-
-  nsRect focusRect;
-  nsIFrame* focusFrame = caret->GetGeometry(&focusRect);
-  if (!focusFrame) {
-    TOUCHCARET_LOG("Focus frame is not valid!");
-    return false;
-  }
-
-  dom::Element* editingHost = focusFrame->GetContent()->GetEditingHost();
-  if (!editingHost) {
-    TOUCHCARET_LOG("Cannot get editing host!");
-    return false;
-  }
-
-  if (focusRect.IsEmpty()) {
-    TOUCHCARET_LOG("Focus rect is empty!");
-    return false;
-  }
-
-  if (!nsContentUtils::HasNonEmptyTextContent(
-         editingHost, nsContentUtils::eRecurseIntoChildren)) {
-    TOUCHCARET_LOG("The content is empty!");
-    return false;
-  }
-
-  if (mState != TOUCHCARET_TOUCHDRAG_ACTIVE &&
-        !nsLayoutUtils::IsRectVisibleInScrollFrames(focusFrame, focusRect)) {
-    TOUCHCARET_LOG("Caret does not show in the scrollable frame!");
-    return false;
-  }
-
-  TOUCHCARET_LOG("Touch caret is displayable!");
-  return true;
-}
-
-void
-TouchCaret::UpdatePosition()
-{
-  MOZ_ASSERT(mVisible);
-
-  nsRect rect = GetTouchCaretRect();
-  rect = ClampRectToScrollFrame(rect);
-  SetTouchFramePos(rect);
-}
-
-nsRect
-TouchCaret::GetTouchCaretRect()
-{
-  nsRect focusRect;
-  nsIFrame* focusFrame = GetCaretFocusFrame(&focusRect);
-  nsIFrame* rootFrame = GetRootFrame();
-  // Transform the position to make it relative to root frame.
-  nsLayoutUtils::TransformRect(focusFrame, rootFrame, focusRect);
-
-  return focusRect;
-}
-
-nsRect
-TouchCaret::ClampRectToScrollFrame(const nsRect& aRect)
-{
-  nsRect rect = aRect;
-  nsIFrame* focusFrame = GetCaretFocusFrame();
-  nsIFrame* rootFrame = GetRootFrame();
-
-  // Clamp the touch caret position to the scrollframe boundary.
-  nsIFrame* closestScrollFrame =
-    nsLayoutUtils::GetClosestFrameOfType(focusFrame, nsGkAtoms::scrollFrame);
-
-  while (closestScrollFrame) {
-    nsIScrollableFrame* sf = do_QueryFrame(closestScrollFrame);
-    nsRect visualRect = sf->GetScrollPortRect();
-
-    // Clamp the touch caret in the scroll port.
-    nsLayoutUtils::TransformRect(closestScrollFrame, rootFrame, visualRect);
-    rect = rect.Intersect(visualRect);
-
-    // Get next ancestor scroll frame.
-    closestScrollFrame =
-      nsLayoutUtils::GetClosestFrameOfType(closestScrollFrame->GetParent(),
-                                           nsGkAtoms::scrollFrame);
-  }
-
-  return rect;
-}
-
-/* static */void
-TouchCaret::DisableTouchCaretCallback(nsITimer* aTimer, void* aTouchCaret)
-{
-  RefPtr<TouchCaret> self = static_cast<TouchCaret*>(aTouchCaret);
-  NS_PRECONDITION(aTimer == self->mTouchCaretExpirationTimer,
-                  "Unexpected timer");
-
-  self->SetVisibility(false);
-}
-
-void
-TouchCaret::LaunchExpirationTimer()
-{
-  if (TouchCaretExpirationTime() > 0) {
-    if (!mTouchCaretExpirationTimer) {
-      mTouchCaretExpirationTimer = do_CreateInstance("@mozilla.org/timer;1");
-    }
-
-    if (mTouchCaretExpirationTimer) {
-      mTouchCaretExpirationTimer->Cancel();
-      mTouchCaretExpirationTimer->InitWithFuncCallback(DisableTouchCaretCallback,
-                                                       this,
-                                                       TouchCaretExpirationTime(),
-                                                       nsITimer::TYPE_ONE_SHOT);
-    }
-  }
-}
-
-void
-TouchCaret::CancelExpirationTimer()
-{
-  if (mTouchCaretExpirationTimer) {
-    mTouchCaretExpirationTimer->Cancel();
-  }
-}
-
-void
-TouchCaret::SetSelectionDragState(bool aState)
-{
-  nsIFrame* caretFocusFrame = GetCaretFocusFrame();
-  if (!caretFocusFrame) {
-    return;
-  }
-
-  RefPtr<nsFrameSelection> fs = caretFocusFrame->GetFrameSelection();
-  fs->SetDragState(aState);
-}
-
-nsEventStatus
-TouchCaret::HandleEvent(WidgetEvent* aEvent)
-{
-  MOZ_ASSERT(NS_IsMainThread());
-  if (!IsDisplayable()) {
-    return nsEventStatus_eIgnore;
-  }
-
-  nsEventStatus status = nsEventStatus_eIgnore;
-
-  switch (aEvent->mMessage) {
-    case eTouchStart:
-      status = HandleTouchDownEvent(aEvent->AsTouchEvent());
-      break;
-    case eMouseDown:
-      status = HandleMouseDownEvent(aEvent->AsMouseEvent());
-      break;
-    case eTouchEnd:
-      status = HandleTouchUpEvent(aEvent->AsTouchEvent());
-      break;
-    case eMouseUp:
-      status = HandleMouseUpEvent(aEvent->AsMouseEvent());
-      break;
-    case eTouchMove:
-      status = HandleTouchMoveEvent(aEvent->AsTouchEvent());
-      break;
-    case eMouseMove:
-      status = HandleMouseMoveEvent(aEvent->AsMouseEvent());
-      break;
-    case eTouchCancel:
-      mTouchesId.Clear();
-      SetState(TOUCHCARET_NONE);
-      LaunchExpirationTimer();
-      break;
-    case eKeyUp:
-    case eKeyDown:
-    case eKeyPress:
-    case eWheel:
-    case eWheelOperationStart:
-    case eWheelOperationEnd:
-      // Disable touch caret while key/wheel event is received.
-      TOUCHCARET_LOG("Receive key/wheel event %d", aEvent->mMessage);
-      SetVisibility(false);
-      break;
-    case eMouseLongTap:
-      if (mState == TOUCHCARET_TOUCHDRAG_ACTIVE) {
-        // Disable long tap event from APZ while dragging the touch caret.
-        status = nsEventStatus_eConsumeNoDefault;
-      }
-      break;
-    default:
-      break;
-  }
-
-  return status;
-}
-
-nsPoint
-TouchCaret::GetEventPosition(WidgetTouchEvent* aEvent, int32_t aIdentifier)
-{
-  for (size_t i = 0; i < aEvent->touches.Length(); i++) {
-    if (aEvent->touches[i]->mIdentifier == aIdentifier) {
-      // Get event coordinate relative to canvas frame.
-      nsIFrame* canvasFrame = GetCanvasFrame();
-      LayoutDeviceIntPoint touchIntPoint = aEvent->touches[i]->mRefPoint;
-      return nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent,
-                                                          touchIntPoint,
-                                                          canvasFrame);
-    }
-  }
-  return nsPoint(NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE);
-}
-
-nsPoint
-TouchCaret::GetEventPosition(WidgetMouseEvent* aEvent)
-{
-  // Get event coordinate relative to canvas frame.
-  nsIFrame* canvasFrame = GetCanvasFrame();
-  LayoutDeviceIntPoint mouseIntPoint = aEvent->AsGUIEvent()->refPoint;
-  return nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent,
-                                                      mouseIntPoint,
-                                                      canvasFrame);
-}
-
-nsEventStatus
-TouchCaret::HandleMouseMoveEvent(WidgetMouseEvent* aEvent)
-{
-  TOUCHCARET_LOG("Got a mouse-move in state %d", mState);
-  nsEventStatus status = nsEventStatus_eIgnore;
-
-  switch (mState) {
-    case TOUCHCARET_NONE:
-      break;
-
-    case TOUCHCARET_MOUSEDRAG_ACTIVE:
-      {
-        nsPoint movePoint = GetEventPosition(aEvent);
-        movePoint.y += mCaretCenterToDownPointOffsetY;
-        nsRect contentBoundary = GetContentBoundary();
-        movePoint = contentBoundary.ClampPoint(movePoint);
-
-        MoveCaret(movePoint);
-        mIsValidTap = false;
-        status = nsEventStatus_eConsumeNoDefault;
-      }
-      break;
-
-    case TOUCHCARET_TOUCHDRAG_ACTIVE:
-    case TOUCHCARET_TOUCHDRAG_INACTIVE:
-      // Consume mouse event in touch sequence.
-      status = nsEventStatus_eConsumeNoDefault;
-      break;
-  }
-
-  return status;
-}
-
-nsEventStatus
-TouchCaret::HandleTouchMoveEvent(WidgetTouchEvent* aEvent)
-{
-  TOUCHCARET_LOG("Got a touch-move in state %d", mState);
-  nsEventStatus status = nsEventStatus_eIgnore;
-
-  switch (mState) {
-    case TOUCHCARET_NONE:
-      break;
-
-    case TOUCHCARET_MOUSEDRAG_ACTIVE:
-      // Consume touch event in mouse sequence.
-      status = nsEventStatus_eConsumeNoDefault;
-      break;
-
-    case TOUCHCARET_TOUCHDRAG_ACTIVE:
-      {
-        nsPoint movePoint = GetEventPosition(aEvent, mActiveTouchId);
-        movePoint.y += mCaretCenterToDownPointOffsetY;
-        nsRect contentBoundary = GetContentBoundary();
-        movePoint = contentBoundary.ClampPoint(movePoint);
-
-        MoveCaret(movePoint);
-        mIsValidTap = false;
-        status = nsEventStatus_eConsumeNoDefault;
-      }
-      break;
-
-    case TOUCHCARET_TOUCHDRAG_INACTIVE:
-      // Consume eTouchMove event in TOUCHCARET_TOUCHDRAG_INACTIVE state.
-      status = nsEventStatus_eConsumeNoDefault;
-      break;
-  }
-
-  return status;
-}
-
-nsEventStatus
-TouchCaret::HandleMouseUpEvent(WidgetMouseEvent* aEvent)
-{
-  TOUCHCARET_LOG("Got a mouse-up in state %d", mState);
-  nsEventStatus status = nsEventStatus_eIgnore;
-
-  switch (mState) {
-    case TOUCHCARET_NONE:
-      break;
-
-    case TOUCHCARET_MOUSEDRAG_ACTIVE:
-      if (aEvent->button == WidgetMouseEvent::eLeftButton) {
-        SetSelectionDragState(false);
-        LaunchExpirationTimer();
-        SetState(TOUCHCARET_NONE);
-        status = nsEventStatus_eConsumeNoDefault;
-      }
-      break;
-
-    case TOUCHCARET_TOUCHDRAG_ACTIVE:
-    case TOUCHCARET_TOUCHDRAG_INACTIVE:
-      // Consume mouse event in touch sequence.
-      status = nsEventStatus_eConsumeNoDefault;
-      break;
-  }
-
-  return status;
-}
-
-nsEventStatus
-TouchCaret::HandleTouchUpEvent(WidgetTouchEvent* aEvent)
-{
-  TOUCHCARET_LOG("Got a touch-end in state %d", mState);
-  // Remove touches from cache if the stroke is gone in TOUCHDRAG states.
-  if (mState == TOUCHCARET_TOUCHDRAG_ACTIVE ||
-      mState == TOUCHCARET_TOUCHDRAG_INACTIVE) {
-    for (size_t i = 0; i < aEvent->touches.Length(); i++) {
-      nsTArray<int32_t>::index_type index =
-        mTouchesId.IndexOf(aEvent->touches[i]->mIdentifier);
-      MOZ_ASSERT(index != nsTArray<int32_t>::NoIndex);
-      mTouchesId.RemoveElementAt(index);
-    }
-  }
-
-  nsEventStatus status = nsEventStatus_eIgnore;
-
-  switch (mState) {
-    case TOUCHCARET_NONE:
-      break;
-
-    case TOUCHCARET_MOUSEDRAG_ACTIVE:
-      // Consume touch event in mouse sequence.
-      status = nsEventStatus_eConsumeNoDefault;
-      break;
-
-    case TOUCHCARET_TOUCHDRAG_ACTIVE:
-      if (mTouchesId.Length() == 0) {
-        SetSelectionDragState(false);
-        // No more finger on the screen.
-        SetState(TOUCHCARET_NONE);
-        LaunchExpirationTimer();
-      } else {
-        // Still has finger touching on the screen.
-        if (aEvent->touches[0]->mIdentifier == mActiveTouchId) {
-          // Remove finger from the touch caret.
-          SetState(TOUCHCARET_TOUCHDRAG_INACTIVE);
-          LaunchExpirationTimer();
-        } else {
-          // If the finger removed is not the finger on touch caret, remain in
-          // TOUCHCARET_DRAG_ACTIVE state.
-        }
-      }
-      status = nsEventStatus_eConsumeNoDefault;
-      break;
-
-    case TOUCHCARET_TOUCHDRAG_INACTIVE:
-      if (mTouchesId.Length() == 0) {
-        // No more finger on the screen.
-        SetState(TOUCHCARET_NONE);
-      }
-      status = nsEventStatus_eConsumeNoDefault;
-      break;
-  }
-
-  return status;
-}
-
-nsEventStatus
-TouchCaret::HandleMouseDownEvent(WidgetMouseEvent* aEvent)
-{
-  TOUCHCARET_LOG("Got a mouse-down in state %d", mState);
-  if (!GetVisibility()) {
-    // If touch caret is invisible, bypass event.
-    return nsEventStatus_eIgnore;
-  }
-
-  nsEventStatus status = nsEventStatus_eIgnore;
-
-  switch (mState) {
-    case TOUCHCARET_NONE:
-      if (aEvent->button == WidgetMouseEvent::eLeftButton) {
-        nsPoint point = GetEventPosition(aEvent);
-        if (IsOnTouchCaret(point)) {
-          SetSelectionDragState(true);
-          // Cache distence of the event point to the center of touch caret.
-          mCaretCenterToDownPointOffsetY = GetCaretYCenterPosition() - point.y;
-          // Enter TOUCHCARET_MOUSEDRAG_ACTIVE state and cancel the timer.
-          SetState(TOUCHCARET_MOUSEDRAG_ACTIVE);
-          CancelExpirationTimer();
-          status = nsEventStatus_eConsumeNoDefault;
-        } else {
-          // Set touch caret invisible if HisTest fails. Bypass event.
-          SetVisibility(false);
-          status = nsEventStatus_eIgnore;
-        }
-      } else {
-        // Set touch caret invisible if not left button down event.
-        SetVisibility(false);
-        status = nsEventStatus_eIgnore;
-      }
-      break;
-
-    case TOUCHCARET_MOUSEDRAG_ACTIVE:
-      SetVisibility(false);
-      SetState(TOUCHCARET_NONE);
-      break;
-
-    case TOUCHCARET_TOUCHDRAG_ACTIVE:
-    case TOUCHCARET_TOUCHDRAG_INACTIVE:
-      // Consume mouse event in touch sequence.
-      status = nsEventStatus_eConsumeNoDefault;
-      break;
-  }
-
-  return status;
-}
-
-nsEventStatus
-TouchCaret::HandleTouchDownEvent(WidgetTouchEvent* aEvent)
-{
-  TOUCHCARET_LOG("Got a touch-start in state %d", mState);
-
-  nsEventStatus status = nsEventStatus_eIgnore;
-
-  switch (mState) {
-    case TOUCHCARET_NONE:
-      if (!GetVisibility()) {
-        // If touch caret is invisible, bypass event.
-        status = nsEventStatus_eIgnore;
-      } else {
-        // Loop over all the touches and see if any of them is on the touch
-        // caret.
-        for (size_t i = 0; i < aEvent->touches.Length(); ++i) {
-          int32_t touchId = aEvent->touches[i]->Identifier();
-          nsPoint point = GetEventPosition(aEvent, touchId);
-          if (IsOnTouchCaret(point)) {
-            SetSelectionDragState(true);
-            // Touch start position is contained in touch caret.
-            mActiveTouchId = touchId;
-            // Cache distance of the event point to the center of touch caret.
-            mCaretCenterToDownPointOffsetY = GetCaretYCenterPosition() - point.y;
-            // Enter TOUCHCARET_TOUCHDRAG_ACTIVE state and cancel the timer.
-            SetState(TOUCHCARET_TOUCHDRAG_ACTIVE);
-            CancelExpirationTimer();
-            status = nsEventStatus_eConsumeNoDefault;
-            break;
-          }
-        }
-        // No touch is on the touch caret. Set touch caret invisible, and bypass
-        // the event.
-        if (mActiveTouchId == -1) {
-          SetVisibility(false);
-          status = nsEventStatus_eIgnore;
-        }
-      }
-      break;
-
-    case TOUCHCARET_MOUSEDRAG_ACTIVE:
-    case TOUCHCARET_TOUCHDRAG_ACTIVE:
-    case TOUCHCARET_TOUCHDRAG_INACTIVE:
-      // Consume eTouchStart event.
-      status = nsEventStatus_eConsumeNoDefault;
-      break;
-  }
-
-  // Cache active touch IDs in TOUCHDRAG states.
-  if (mState == TOUCHCARET_TOUCHDRAG_ACTIVE ||
-      mState == TOUCHCARET_TOUCHDRAG_INACTIVE) {
-    mTouchesId.Clear();
-    for (size_t i = 0; i < aEvent->touches.Length(); i++) {
-      mTouchesId.AppendElement(aEvent->touches[i]->mIdentifier);
-    }
-  }
-
-  return status;
-}
-
-void
-TouchCaret::DispatchTapEvent()
-{
-  nsCOMPtr<nsIPresShell> presShell = do_QueryReferent(mPresShell);
-  if (!presShell) {
-    return;
-  }
-
-  RefPtr<nsCaret> caret = presShell->GetCaret();
-  if (!caret) {
-    return;
-  }
-
-  dom::Selection* sel = static_cast<dom::Selection*>(caret->GetSelection());
-  if (!sel) {
-    return;
-  }
-
-  nsIDocument* doc = presShell->GetDocument();
-
-  MOZ_ASSERT(doc);
-
-  dom::SelectionStateChangedEventInit init;
-  init.mBubbles = true;
-
-  // XXX: Do we need to flush layout?
-  presShell->FlushPendingNotifications(Flush_Layout);
-  nsRect rect = nsLayoutUtils::GetSelectionBoundingRect(sel);
-  RefPtr<dom::DOMRect>domRect = new dom::DOMRect(ToSupports(doc));
-
-  domRect->SetLayoutRect(rect);
-  init.mBoundingClientRect = domRect;
-  init.mVisible = false;
-
-  sel->Stringify(init.mSelectedText);
-
-  dom::Sequence<dom::SelectionState> state;
-  state.AppendElement(dom::SelectionState::Taponcaret, fallible);
-  init.mStates = state;
-
-  RefPtr<dom::SelectionStateChangedEvent> event =
-    dom::SelectionStateChangedEvent::Constructor(doc, NS_LITERAL_STRING("mozselectionstatechanged"), init);
-
-  event->SetTrusted(true);
-  event->GetInternalNSEvent()->mFlags.mOnlyChromeDispatch = true;
-  bool ret;
-  doc->DispatchEvent(event, &ret);
-}
-
-void
-TouchCaret::SetState(TouchCaretState aState)
-{
-  TOUCHCARET_LOG("state changed from %d to %d", mState, aState);
-  if (mState == TOUCHCARET_NONE) {
-    MOZ_ASSERT(aState != TOUCHCARET_TOUCHDRAG_INACTIVE,
-               "mState: NONE => TOUCHDRAG_INACTIVE isn't allowed!");
-  }
-
-  if (mState == TOUCHCARET_TOUCHDRAG_ACTIVE) {
-    MOZ_ASSERT(aState != TOUCHCARET_MOUSEDRAG_ACTIVE,
-               "mState: TOUCHDRAG_ACTIVE => MOUSEDRAG_ACTIVE isn't allowed!");
-  }
-
-  if (mState == TOUCHCARET_MOUSEDRAG_ACTIVE) {
-    MOZ_ASSERT(aState == TOUCHCARET_MOUSEDRAG_ACTIVE ||
-               aState == TOUCHCARET_NONE,
-               "MOUSEDRAG_ACTIVE allowed next state: NONE!");
-  }
-
-  if (mState == TOUCHCARET_TOUCHDRAG_INACTIVE) {
-    MOZ_ASSERT(aState == TOUCHCARET_TOUCHDRAG_INACTIVE ||
-               aState == TOUCHCARET_NONE,
-               "TOUCHDRAG_INACTIVE allowed next state: NONE!");
-  }
-
-  mState = aState;
-
-  if (mState == TOUCHCARET_NONE) {
-    mActiveTouchId = -1;
-    mCaretCenterToDownPointOffsetY = 0;
-    if (mIsValidTap) {
-      DispatchTapEvent();
-      mIsValidTap = false;
-    }
-  } else if (mState == TOUCHCARET_TOUCHDRAG_ACTIVE ||
-             mState == TOUCHCARET_MOUSEDRAG_ACTIVE) {
-    mIsValidTap = true;
-  }
-}
deleted file mode 100644
--- a/layout/base/TouchCaret.h
+++ /dev/null
@@ -1,321 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 sw=2 et tw=78: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef mozilla_TouchCaret_h__
-#define mozilla_TouchCaret_h__
-
-#include "nsISelectionListener.h"
-#include "nsIScrollObserver.h"
-#include "nsIWeakReferenceUtils.h"
-#include "nsITimer.h"
-#include "mozilla/EventForwards.h"
-#include "mozilla/TouchEvents.h"
-#include "Units.h"
-
-class nsCanvasFrame;
-class nsIFrame;
-class nsIPresShell;
-
-namespace mozilla {
-
-/**
- * NOTE: TouchCaret was obsoleted by AccessibleCaret, and is no longer used on
- * B2G. This file is going to be removed in bug 1221459. Please see the wiki
- * page for more information. https://wiki.mozilla.org/Copy_n_Paste
- *
- * The TouchCaret places a touch caret according to caret position when the
- * caret is shown.
- * TouchCaret is also responsible for touch caret visibility. Touch caret
- * won't be shown when timer expires or while key event causes selection change.
- */
-class TouchCaret final : public nsISelectionListener,
-                         public nsIScrollObserver,
-                         public nsSupportsWeakReference
-{
-public:
-  explicit TouchCaret(nsIPresShell* aPresShell);
-
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSISELECTIONLISTENER
-
-  void Init();
-  void Terminate();
-
-  // nsIScrollObserver
-  virtual void ScrollPositionChanged() override;
-
-  // AsyncPanZoom started/stopped callbacks from nsIScrollObserver
-  virtual void AsyncPanZoomStarted() override;
-  virtual void AsyncPanZoomStopped() override;
-
-  /**
-   * Handle mouse and touch event only.
-   * Depends on visibility and position of touch caret, HandleEvent may consume
-   * that input event and return nsEventStatus_eConsumeNoDefault to the caller.
-   * In that case, caller should stop bubble up that input event.
-   */
-  nsEventStatus HandleEvent(WidgetEvent* aEvent);
-
-  void SyncVisibilityWithCaret();
-
-  void UpdatePositionIfNeeded();
-
-  /**
-   * GetVisibility will get the visibility of the touch caret.
-   */
-  bool GetVisibility() const
-  {
-    return mVisible;
-  }
-
-  /**
-   * Open or close the Android TextSelection ActionBar based on visibility.
-   */
-  static void UpdateAndroidActionBarVisibility(bool aVisibility, uint32_t& aViewID);
-
-private:
-  // Hide default constructor.
-  TouchCaret() = delete;
-
-  ~TouchCaret();
-
-  bool IsDisplayable();
-
-  void UpdatePosition();
-
-  /**
-   * SetVisibility will set the visibility of the touch caret.
-   * SetVisibility performs an attribute-changed notification which could, in
-   * theory, destroy frames.
-   */
-  void SetVisibility(bool aVisible);
-
-  /**
-   * Helper function to get caret's focus frame and caret's bounding rect.
-   */
-  nsIFrame* GetCaretFocusFrame(nsRect* aOutRect = nullptr);
-
-  /**
-   * Find the nsCanvasFrame which holds the touch caret.
-   */
-  nsCanvasFrame* GetCanvasFrame();
-
-  /**
-   * Find the root frame to update the touch caret's position.
-   */
-  nsIFrame* GetRootFrame();
-
-  /**
-   * Retrieve the bounding rectangle of the touch caret.
-   *
-   * @returns A nsRect representing the bounding rectangle of this touch caret.
-   *          The returned offset is relative to the canvas frame.
-   */
-  nsRect GetTouchFrameRect();
-
-  /**
-   * Retrieve the bounding rectangle where the caret can be positioned.
-   * If we're positioning a caret in an input field, make sure the touch caret
-   * stays within the bounds of the field.
-   *
-   * @returns A nsRect representing the bounding rectangle of this valid area.
-   *          The returned offset is relative to the canvas frame.
-   */
-  nsRect GetContentBoundary();
-
-  /**
-   * Retrieve the center y position of the caret.
-   * The returned point is relative to the canvas frame.
-   */
-  nscoord GetCaretYCenterPosition();
-
-  /**
-   * Retrieve the rect of the touch caret.
-   * The returned rect is relative to the canvas frame.
-   */
-  nsRect GetTouchCaretRect();
-
-  /**
-   * Clamp the position of the touch caret to the scroll frame boundary.
-   * The returned rect is relative to the canvas frame.
-   */
-  nsRect ClampRectToScrollFrame(const nsRect& aRect);
-
-  /**
-   * Set the position of the touch caret.
-   * Touch caret is an absolute positioned div.
-   */
-  void SetTouchFramePos(const nsRect& aRect);
-
-  void LaunchExpirationTimer();
-  void CancelExpirationTimer();
-  static void DisableTouchCaretCallback(nsITimer* aTimer, void* aPresShell);
-
-  /**
-   * Move the caret to movePoint which is relative to the canvas frame.
-   * Caret will be scrolled into view.
-   *
-   * @param movePoint tap location relative to the canvas frame.
-   */
-  void MoveCaret(const nsPoint& movePoint);
-
-  /**
-   * Check if aPoint is inside the touch caret frame.
-   *
-   * @param aPoint tap location relative to the canvas frame.
-   */
-  bool IsOnTouchCaret(const nsPoint& aPoint);
-
-  /**
-   * These Handle* functions comprise input alphabet of the TouchCaret
-   * finite-state machine triggering state transitions.
-   */
-  nsEventStatus HandleMouseMoveEvent(WidgetMouseEvent* aEvent);
-  nsEventStatus HandleMouseUpEvent(WidgetMouseEvent* aEvent);
-  nsEventStatus HandleMouseDownEvent(WidgetMouseEvent* aEvent);
-  nsEventStatus HandleTouchMoveEvent(WidgetTouchEvent* aEvent);
-  nsEventStatus HandleTouchUpEvent(WidgetTouchEvent* aEvent);
-  nsEventStatus HandleTouchDownEvent(WidgetTouchEvent* aEvent);
-
-  /**
-   * Get the coordinates of a given touch event, relative to canvas frame.
-   * @param aEvent the event
-   * @param aIdentifier the mIdentifier of the touch which is to be converted.
-   * @return the point, or (NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE) if
-   * for some reason the coordinates for the touch are not known (e.g.,
-   * the mIdentifier touch is not found).
-   */
-  nsPoint GetEventPosition(WidgetTouchEvent* aEvent, int32_t aIdentifier);
-
-  /**
-   * Set mouse down state in nsFrameSelection, we'll set state to true when
-   * user start dragging caret and set state to false when user release the
-   * caret. The reason for setting this state is it will fire drag reason
-   * when moving caret and fire mouseup reason when releasing caret. So that
-   * the display behavior of copy/paste menu becomes more reasonable.
-   */
-  void SetSelectionDragState(bool aState);
-
-  /**
-   * Get the coordinates of a given mouse event, relative to canvas frame.
-   * @param aEvent the event
-   * @return the point, or (NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE) if
-   * for some reason the coordinates for the mouse are not known.
-   */
-  nsPoint GetEventPosition(WidgetMouseEvent* aEvent);
-
-  /**
-   * States of TouchCaret finite-state machine.
-   */
-  enum TouchCaretState {
-    // In this state, either there is no touch/mouse event going on, or the
-    // first stroke does not hit the touch caret.
-    // Will enter TOUCHCARET_TOUCHDRAG_ACTIVE state if the first touch stroke
-    // hits the touch caret. Will enter TOUCHCARET_MOUSEDRAG_ACTIVE state if
-    // mouse (left button) down hits the touch caret.
-    // Allowed next state: TOUCHCARET_MOUSEDRAG_ACTIVE,
-    //                     TOUCHCARET_TOUCHDRAG_ACTIVE.
-    TOUCHCARET_NONE,
-    // The first (left button) mouse down hits on the touch caret and is
-    // alive. Will enter TOUCHCARET_NONE state if the left button is release.
-    // Allowed next states: TOUCHCARET_NONE.
-    TOUCHCARET_MOUSEDRAG_ACTIVE,
-    // The first touch start event hits on touch caret and is alive.
-    // Will enter TOUCHCARET_NONE state if the finger on touch caret is
-    // removed and there are no more fingers on the screen; will enter
-    // TOUCHCARET_TOUCHDRAG_INACTIVE state if the finger on touch caret is
-    // removed but still has fingers touching on the screen.
-    // Allowed next states: TOUCHCARET_NONE, TOUCHCARET_TOUCHDRAG_INACTIVE.
-    TOUCHCARET_TOUCHDRAG_ACTIVE,
-    // The first touch stroke, which hit on touch caret, is dead, but still has
-    // fingers touching on the screen.
-    // Will enter TOUCHCARET_NONE state if all the fingers are removed from the
-    // screen.
-    // Allowed next state: TOUCHCARET_NONE.
-    TOUCHCARET_TOUCHDRAG_INACTIVE,
-  };
-
-  /**
-   * Do actual state transition and reset substates.
-   */
-  void SetState(TouchCaretState aState);
-
-  /**
-   * Dispatch touch caret tap event to chrome.
-   */
-  void DispatchTapEvent();
-
-  /**
-   * Current state we're dealing with.
-   */
-  TouchCaretState mState;
-
-  /**
-   * Array containing all active touch IDs. When a touch happens, it gets added
-   * to this array, even if we choose not to handle it. When it ends, we remove
-   * it. We need to maintain this array in order to detect the end of the
-   * "multitouch" states because touch start events contain all current touches,
-   * but touch end events contain only those touches that have gone.
-   */
-  nsTArray<int32_t> mTouchesId;
-
-  /**
-   * The mIdentifier of the touch which is on the touch caret.
-   */
-  int32_t mActiveTouchId;
-
-  /**
-   * The offset between the tap location and the center of caret along y axis.
-   */
-  nscoord mCaretCenterToDownPointOffsetY;
-
-  /**
-   * Get from pref "touchcaret.inflatesize.threshold". This will inflate the
-   * size of the touch caret frame when checking if user clicks on the caret
-   * or not. In app units.
-   */
-  static int32_t TouchCaretInflateSize() { return sTouchCaretInflateSize; }
-
-  static int32_t TouchCaretExpirationTime()
-  {
-    return sTouchCaretExpirationTime;
-  }
-
-  void LaunchScrollEndDetector();
-  void CancelScrollEndDetector();
-  static void FireScrollEnd(nsITimer* aTimer, void* aSelectionCarets);
-
-  // This timer is used for detecting scroll end. We don't have
-  // scroll end event now, so we will fire this event with a
-  // const time when we scroll. So when timer triggers, we treat it
-  // as scroll end event.
-  nsCOMPtr<nsITimer> mScrollEndDetectorTimer;
-
-  nsWeakPtr mPresShell;
-  WeakPtr<nsDocShell> mDocShell;
-
-  // True if AsyncPanZoom is started
-  bool mInAsyncPanZoomGesture;
-
-  // Touch caret visibility
-  bool mVisible;
-  // Use for detecting single tap on touch caret.
-  bool mIsValidTap;
-  // Touch caret timer
-  nsCOMPtr<nsITimer> mTouchCaretExpirationTimer;
-
-  // Preference
-  static int32_t sTouchCaretInflateSize;
-  static int32_t sTouchCaretExpirationTime;
-
-  // The auto scroll timer's interval in miliseconds.
-  friend class SelectionCarets;
-  static const int32_t sAutoScrollTimerDelay = 30;
-  // Time for trigger scroll end event, in miliseconds.
-  static const int32_t sScrollEndTimerDelay = 300;
-};
-} //namespace mozilla
-#endif //mozilla_TouchCaret_h__
--- a/layout/base/TouchManager.cpp
+++ b/layout/base/TouchManager.cpp
@@ -1,17 +1,26 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=2 sw=2 et tw=78:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  */
 
 #include "TouchManager.h"
+
+#include "mozilla/TouchEvents.h"
+#include "mozilla/dom/EventTarget.h"
+#include "nsIFrame.h"
 #include "nsPresShell.h"
+#include "nsView.h"
+
+namespace mozilla {
+
+using EventTarget = ::mozilla::dom::EventTarget;
 
 nsRefPtrHashtable<nsUint32HashKey, dom::Touch>* TouchManager::gCaptureTouchList;
 
 /*static*/ void
 TouchManager::InitializeStatics()
 {
   NS_ASSERTION(!gCaptureTouchList, "InitializeStatics called multiple times!");
   gCaptureTouchList = new nsRefPtrHashtable<nsUint32HashKey, dom::Touch>;
@@ -217,8 +226,10 @@ TouchManager::PreHandleEvent(WidgetEvent
       gCaptureTouchList->Enumerate(&AppendToTouchList, (void *)&touches);
       break;
     }
     default:
       break;
   }
   return true;
 }
+
+} // namespace mozilla
--- a/layout/base/TouchManager.h
+++ b/layout/base/TouchManager.h
@@ -10,16 +10,18 @@
  */
 
 #ifndef TouchManager_h_
 #define TouchManager_h_
 
 class PresShell;
 class nsIDocument;
 
+namespace mozilla {
+
 class TouchManager {
 public:
   // Initialize and release static variables
   static void InitializeStatics();
   static void ReleaseStatics();
 
   void Init(PresShell* aPresShell, nsIDocument* aDocument);
   void Destroy();
@@ -34,9 +36,11 @@ public:
 
 private:
   void EvictTouches();
 
   RefPtr<PresShell>   mPresShell;
   nsCOMPtr<nsIDocument> mDocument;
 };
 
+} // namespace mozilla
+
 #endif /* !defined(TouchManager_h_) */
--- a/layout/base/ZoomConstraintsClient.cpp
+++ b/layout/base/ZoomConstraintsClient.cpp
@@ -2,18 +2,20 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ZoomConstraintsClient.h"
 
 #include <inttypes.h>
 #include "FrameMetrics.h"
+#include "gfxPrefs.h"
 #include "LayersLogging.h"
 #include "mozilla/layers/APZCCallbackHelper.h"
+#include "mozilla/Preferences.h"
 #include "nsDocument.h"
 #include "nsIFrame.h"
 #include "nsLayoutUtils.h"
 #include "nsPoint.h"
 #include "nsPresShell.h"
 #include "nsView.h"
 #include "nsViewportInfo.h"
 #include "Units.h"
--- a/layout/base/moz.build
+++ b/layout/base/moz.build
@@ -35,19 +35,18 @@ with Files('nsStyle*'):
     BUG_COMPONENT = ('Core', 'CSS Parsing and Computation')
 
 with Files('nsChangeHint.h'):
     BUG_COMPONENT = ('Core', 'CSS Parsing and Computation')
 
 with Files('nsBidi*'):
     BUG_COMPONENT = ('Core', 'Layout: Text')
 
-for caret_file in ('AccessibleCaret*', 'TouchCaret*', 'SelectionCarets*'):
-    with Files(caret_file):
-        BUG_COMPONENT = ('Core', 'Selection')
+with Files('AccessibleCaret*'):
+    BUG_COMPONENT = ('Core', 'Selection')
 
 XPIDL_SOURCES += [
     'nsIStyleSheetService.idl',
 ]
 
 if CONFIG['MOZ_DEBUG']:
     UNIFIED_SOURCES += [
         'nsAutoLayoutPhase.cpp',
@@ -142,19 +141,17 @@ UNIFIED_SOURCES += [
     'nsQuoteList.cpp',
     'nsStyleChangeList.cpp',
     'nsStyleSheetService.cpp',
     'PaintTracker.cpp',
     'PositionedEventTargeting.cpp',
     'RestyleManager.cpp',
     'RestyleTracker.cpp',
     'ScrollbarStyles.cpp',
-    'SelectionCarets.cpp',
     'StackArena.cpp',
-    'TouchCaret.cpp',
     'TouchManager.cpp',
     'ZoomConstraintsClient.cpp',
 ]
 
 # nsPresArena.cpp needs to be built separately because it uses plarena.h.
 # nsRefreshDriver.cpp needs to be built separately because of name clashes in the OS X headers
 SOURCES += [
     'nsPresArena.cpp',
--- a/layout/base/nsIPresShell.h
+++ b/layout/base/nsIPresShell.h
@@ -58,18 +58,16 @@ class nsView;
 class nsRenderingContext;
 class nsIPageSequenceFrame;
 class nsCanvasFrame;
 class nsAString;
 class nsCaret;
 namespace mozilla {
 class AccessibleCaretEventHub;
 class CSSStyleSheet;
-class TouchCaret;
-class SelectionCarets;
 } // namespace mozilla
 class nsFrameSelection;
 class nsFrameManager;
 class nsILayoutHistoryState;
 class nsIReflowCallback;
 class nsIDOMNode;
 class nsCSSFrameConstructor;
 class nsISelection;
@@ -803,41 +801,16 @@ public:
   /**
    * Notification sent by a frame informing the pres shell that it is about to
    * be destroyed.
    * This allows any outstanding references to the frame to be cleaned up
    */
   virtual void NotifyDestroyingFrame(nsIFrame* aFrame) = 0;
 
   /**
-   * Get the touch caret, if it exists. AddRefs it.
-   */
-  virtual already_AddRefed<mozilla::TouchCaret> GetTouchCaret() const = 0;
-
-  /**
-   * Returns the touch caret element of the presshell.
-   */
-  virtual mozilla::dom::Element* GetTouchCaretElement() const = 0;
-
-  /**
-   * Get the selection caret, if it exists. AddRefs it.
-   */
-  virtual already_AddRefed<mozilla::SelectionCarets> GetSelectionCarets() const = 0;
-
-  /**
-   * Returns the start part of selection caret element of the presshell.
-   */
-  virtual mozilla::dom::Element* GetSelectionCaretsStartElement() const = 0;
-
-  /**
-   * Returns the end part of selection caret element of the presshell.
-   */
-  virtual mozilla::dom::Element* GetSelectionCaretsEndElement() const = 0;
-
-  /**
    * Get the AccessibleCaretEventHub, if it exists. AddRefs it.
    */
   virtual already_AddRefed<mozilla::AccessibleCaretEventHub> GetAccessibleCaretEventHub() const = 0;
 
   /**
    * Get the caret, if it exists. AddRefs it.
    */
   virtual already_AddRefed<nsCaret> GetCaret() const = 0;
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -73,18 +73,16 @@
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsReadableUtils.h"
 #include "nsIPageSequenceFrame.h"
 #include "nsIPermissionManager.h"
 #include "nsIMozBrowserFrame.h"
 #include "nsCaret.h"
 #include "AccessibleCaretEventHub.h"
-#include "TouchCaret.h"
-#include "SelectionCarets.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsFrameManager.h"
 #include "nsXPCOM.h"
 #include "nsILayoutHistoryState.h"
 #include "nsILineIterator.h" // for ScrollContentIntoView
 #include "PLDHashTable.h"
 #include "mozilla/dom/BeforeAfterKeyboardEventBinding.h"
 #include "mozilla/dom/Touch.h"
@@ -700,44 +698,20 @@ nsIPresShell::FrameSelection()
   return ret.forget();
 }
 
 //----------------------------------------------------------------------
 
 static bool sSynthMouseMove = true;
 static uint32_t sNextPresShellId;
 static bool sPointerEventEnabled = true;
-static bool sTouchCaretEnabled = false;
-static bool sSelectionCaretEnabled = false;
 static bool sAccessibleCaretEnabled = false;
 static bool sBeforeAfterKeyboardEventEnabled = false;
 
 /* static */ bool
-PresShell::TouchCaretPrefEnabled()
-{
-  static bool initialized = false;
-  if (!initialized) {
-    Preferences::AddBoolVarCache(&sTouchCaretEnabled, "touchcaret.enabled");
-    initialized = true;
-  }
-  return sTouchCaretEnabled;
-}
-
-/* static */ bool
-PresShell::SelectionCaretPrefEnabled()
-{
-  static bool initialized = false;
-  if (!initialized) {
-    Preferences::AddBoolVarCache(&sSelectionCaretEnabled, "selectioncaret.enabled");
-    initialized = true;
-  }
-  return sSelectionCaretEnabled;
-}
-
-/* static */ bool
 PresShell::AccessibleCaretEnabled()
 {
   static bool initialized = false;
   if (!initialized) {
     Preferences::AddBoolVarCache(&sAccessibleCaretEnabled, "layout.accessiblecaret.enabled");
     initialized = true;
   }
   return sAccessibleCaretEnabled;
@@ -877,28 +851,16 @@ PresShell::Init(nsIDocument* aDocument,
   // Notify our prescontext that it now has a compatibility mode.  Note that
   // this MUST happen after we set up our style set but before we create any
   // frames.
   mPresContext->CompatibilityModeChanged();
 
   // Add the preference style sheet.
   UpdatePreferenceStyles();
 
-  if (TouchCaretPrefEnabled() && !AccessibleCaretEnabled()) {
-    // Create touch caret handle
-    mTouchCaret = new TouchCaret(this);
-    mTouchCaret->Init();
-  }
-
-  if (SelectionCaretPrefEnabled() && !AccessibleCaretEnabled()) {
-    // Create selection caret handle
-    mSelectionCarets = new SelectionCarets(this);
-    mSelectionCarets->Init();
-  }
-
   if (AccessibleCaretEnabled()) {
     // Need to happen before nsFrameSelection has been set up.
     mAccessibleCaretEventHub = new AccessibleCaretEventHub(this);
   }
 
   mSelection = new nsFrameSelection();
 
   mSelection->Init(this, nullptr);
@@ -1190,26 +1152,16 @@ PresShell::Destroy()
     mCaret->Terminate();
     mCaret = nullptr;
   }
 
   if (mSelection) {
     mSelection->DisconnectFromPresShell();
   }
 
-  if (mTouchCaret) {
-    mTouchCaret->Terminate();
-    mTouchCaret = nullptr;
-  }
-
-  if (mSelectionCarets) {
-    mSelectionCarets->Terminate();
-    mSelectionCarets = nullptr;
-  }
-
   if (mAccessibleCaretEventHub) {
     mAccessibleCaretEventHub->Terminate();
     mAccessibleCaretEventHub = nullptr;
   }
 
   // release our pref style sheet, if we have one still
   RemovePreferenceStyles();
 
@@ -1986,29 +1938,16 @@ PresShell::NotifyDestroyingFrame(nsIFram
 }
 
 already_AddRefed<nsCaret> PresShell::GetCaret() const
 {
   RefPtr<nsCaret> caret = mCaret;
   return caret.forget();
 }
 
-// TouchCaret
-already_AddRefed<TouchCaret> PresShell::GetTouchCaret() const
-{
-  RefPtr<TouchCaret> touchCaret = mTouchCaret;
-  return touchCaret.forget();
-}
-
-already_AddRefed<SelectionCarets> PresShell::GetSelectionCarets() const
-{
-  RefPtr<SelectionCarets> selectionCaret = mSelectionCarets;
-  return selectionCaret.forget();
-}
-
 already_AddRefed<AccessibleCaretEventHub> PresShell::GetAccessibleCaretEventHub() const
 {
   RefPtr<AccessibleCaretEventHub> eventHub = mAccessibleCaretEventHub;
   return eventHub.forget();
 }
 
 void PresShell::SetCaret(nsCaret *aNewCaret)
 {
@@ -2029,22 +1968,16 @@ NS_IMETHODIMP PresShell::SetCaretEnabled
   if (mCaretEnabled != oldEnabled)
   {
     MOZ_ASSERT(mCaret);
     if (mCaret) {
       mCaret->SetVisible(mCaretEnabled);
     }
   }
 
-  // We should sync touch caret's visibility with caret every time since touch
-  // caret might be hidden due to timeout while caret is enabled.
-  if (mTouchCaret) {
-    mTouchCaret->SyncVisibilityWithCaret();
-  }
-
   return NS_OK;
 }
 
 NS_IMETHODIMP PresShell::SetCaretReadOnly(bool aReadOnly)
 {
   if (mCaret)
     mCaret->SetCaretReadOnly(aReadOnly);
   return NS_OK;
@@ -2365,34 +2298,16 @@ PresShell::GetPageSequenceFrame() const
 
 nsCanvasFrame*
 PresShell::GetCanvasFrame() const
 {
   nsIFrame* frame = mFrameConstructor->GetDocElementContainingBlock();
   return do_QueryFrame(frame);
 }
 
-Element*
-PresShell::GetTouchCaretElement() const
-{
-  return GetCanvasFrame() ? GetCanvasFrame()->GetTouchCaretElement() : nullptr;
-}
-
-Element*
-PresShell::GetSelectionCaretsStartElement() const
-{
-  return GetCanvasFrame() ? GetCanvasFrame()->GetSelectionCaretsStartElement() : nullptr;
-}
-
-Element*
-PresShell::GetSelectionCaretsEndElement() const
-{
-  return GetCanvasFrame() ? GetCanvasFrame()->GetSelectionCaretsEndElement() : nullptr;
-}
-
 void
 PresShell::BeginUpdate(nsIDocument *aDocument, nsUpdateType aUpdateType)
 {
 #ifdef DEBUG
   mUpdateCount++;
 #endif
   mFrameConstructor->BeginUpdate();
 
@@ -3781,20 +3696,16 @@ PresShell::UnsuppressAndInvalidate()
 
   ScheduleBeforeFirstPaint();
 
   mPaintingSuppressed = false;
   nsIFrame* rootFrame = mFrameConstructor->GetRootFrame();
   if (rootFrame) {
     // let's assume that outline on a root frame is not supported
     rootFrame->InvalidateFrame();
-
-    if (mTouchCaret) {
-      mTouchCaret->SyncVisibilityWithCaret();
-    }
   }
 
   // now that painting is unsuppressed, focus may be set on the document
   nsPIDOMWindow *win = mDocument->GetWindow();
   if (win)
     win->SetReadyForFocus();
 
   if (!mHaveShutDown) {
@@ -6975,57 +6886,16 @@ PresShell::HandleEvent(nsIFrame* aFrame,
   if (mIsDestroying ||
       (sDisableNonTestMouseEvents && !aEvent->mFlags.mIsSynthesizedForTests &&
        aEvent->HasMouseEventMessage())) {
     return NS_OK;
   }
 
   RecordMouseLocation(aEvent);
 
-  // Determine whether event need to be consumed by touch caret or not.
-  if (TouchCaretPrefEnabled() || SelectionCaretPrefEnabled()) {
-    // We have to target the focus window because regardless of where the
-    // touch goes, we want to access the touch caret when user is typing on an
-    // editable element.
-    nsCOMPtr<nsPIDOMWindow> window = GetFocusedDOMWindowInOurWindow();
-    nsCOMPtr<nsIDocument> retargetEventDoc = window ? window->GetExtantDoc() : nullptr;
-    nsCOMPtr<nsIPresShell> presShell = retargetEventDoc ?
-                                       retargetEventDoc->GetShell() :
-                                       nullptr;
-
-    // Bug 1057256: Touch caret should handle the event before selection carets.
-    // Otherwise, a long tap on touch caret will be incorrectly handled by
-    // selection carets which makes moving touch caret failed.
-    RefPtr<TouchCaret> touchCaret = presShell ?
-                                      presShell->GetTouchCaret() :
-                                      nullptr;
-    if (touchCaret) {
-      *aEventStatus = touchCaret->HandleEvent(aEvent);
-      if (*aEventStatus == nsEventStatus_eConsumeNoDefault) {
-        // If the event is consumed by the touch caret, cancel APZC panning by
-        // setting mMultipleActionsPrevented.
-        aEvent->mFlags.mMultipleActionsPrevented = true;
-        return NS_OK;
-      }
-    }
-
-    RefPtr<SelectionCarets> selectionCaret = presShell ?
-                                               presShell->GetSelectionCarets() :
-                                               nullptr;
-    if (selectionCaret) {
-      *aEventStatus = selectionCaret->HandleEvent(aEvent);
-      if (*aEventStatus == nsEventStatus_eConsumeNoDefault) {
-        // If the event is consumed by the selection carets, cancel APZC panning by
-        // setting mMultipleActionsPrevented.
-        aEvent->mFlags.mMultipleActionsPrevented = true;
-        return NS_OK;
-      }
-    }
-  }
-
   if (AccessibleCaretEnabled()) {
     // We have to target the focus window because regardless of where the
     // touch goes, we want to access the copy paste manager.
     nsCOMPtr<nsPIDOMWindow> window = GetFocusedDOMWindowInOurWindow();
     nsCOMPtr<nsIDocument> retargetEventDoc =
       window ? window->GetExtantDoc() : nullptr;
     nsCOMPtr<nsIPresShell> presShell =
       retargetEventDoc ? retargetEventDoc->GetShell() : nullptr;
@@ -8836,20 +8706,16 @@ PresShell::DidDoReflow(bool aInterruptib
     DOMHighResTimeStamp now = GetPerformanceNow();
     docShell->NotifyReflowObservers(aInterruptible, mLastReflowStart, now);
   }
 
   if (sSynthMouseMove) {
     SynthesizeMouseMove(false);
   }
 
-  if (mTouchCaret) {
-    mTouchCaret->UpdatePositionIfNeeded();
-  }
-
   mPresContext->NotifyMissingFonts();
 }
 
 DOMHighResTimeStamp
 PresShell::GetPerformanceNow()
 {
   DOMHighResTimeStamp now = 0;
   nsPIDOMWindow* window = mDocument->GetInnerWindow();
--- a/layout/base/nsPresShell.h
+++ b/layout/base/nsPresShell.h
@@ -68,22 +68,16 @@ class PresShell final : public nsIPresSh
 public:
   PresShell();
 
   NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
 
   // nsISupports
   NS_DECL_ISUPPORTS
 
-  // Touch caret preference
-  static bool TouchCaretPrefEnabled();
-
-  // Selection caret preference
-  static bool SelectionCaretPrefEnabled();
-
   static bool AccessibleCaretEnabled();
 
   // BeforeAfterKeyboardEvent preference
   static bool BeforeAfterKeyboardEventEnabled();
 
   void Init(nsIDocument* aDocument, nsPresContext* aPresContext,
             nsViewManager* aViewManager, nsStyleSet* aStyleSet,
             nsCompatibility aCompatMode);
@@ -241,24 +235,16 @@ public:
   virtual void WillPaintWindow() override;
   virtual void DidPaintWindow() override;
   virtual void ScheduleViewManagerFlush(PaintType aType = PAINT_DEFAULT) override;
   virtual void DispatchSynthMouseMove(mozilla::WidgetGUIEvent* aEvent,
                                       bool aFlushOnHoverChange) override;
   virtual void ClearMouseCaptureOnView(nsView* aView) override;
   virtual bool IsVisible() override;
 
-  // touch caret
-  virtual already_AddRefed<mozilla::TouchCaret> GetTouchCaret() const override;
-  virtual mozilla::dom::Element* GetTouchCaretElement() const override;
-  // selection caret
-  virtual already_AddRefed<mozilla::SelectionCarets> GetSelectionCarets() const override;
-  virtual mozilla::dom::Element* GetSelectionCaretsStartElement() const override;
-  virtual mozilla::dom::Element* GetSelectionCaretsEndElement() const override;
-
   virtual already_AddRefed<mozilla::AccessibleCaretEventHub> GetAccessibleCaretEventHub() const override;
 
   // caret handling
   virtual already_AddRefed<nsCaret> GetCaret() const override;
   NS_IMETHOD SetCaretEnabled(bool aInEnable) override;
   NS_IMETHOD SetCaretReadOnly(bool aReadOnly) override;
   NS_IMETHOD GetCaretEnabled(bool *aOutEnabled) override;
   NS_IMETHOD SetCaretVisibilityDuringSelection(bool aVisibility) override;
@@ -811,25 +797,21 @@ private:
 protected:
   nsRevocableEventPtr<nsSynthMouseMoveEvent> mSynthMouseMoveEvent;
   nsCOMPtr<nsIContent>      mLastAnchorScrolledTo;
   RefPtr<nsCaret>         mCaret;
   RefPtr<nsCaret>         mOriginalCaret;
   nsCallbackEventRequest*   mFirstCallbackEventRequest;
   nsCallbackEventRequest*   mLastCallbackEventRequest;
 
-  // TouchManager
-  TouchManager              mTouchManager;
+  mozilla::TouchManager     mTouchManager;
 
   RefPtr<ZoomConstraintsClient> mZoomConstraintsClient;
   RefPtr<MobileViewportManager> mMobileViewportManager;
 
-  // TouchCaret
-  RefPtr<mozilla::TouchCaret> mTouchCaret;
-  RefPtr<mozilla::SelectionCarets> mSelectionCarets;
   RefPtr<mozilla::AccessibleCaretEventHub> mAccessibleCaretEventHub;
 
   // This timer controls painting suppression.  Until it fires
   // or all frames are constructed, we won't paint anything but
   // our <body> background and scrollbars.
   nsCOMPtr<nsITimer>        mPaintSuppressionTimer;
 
   nsCOMPtr<nsITimer>        mDelayedPaintTimer;
--- a/layout/generic/nsCanvasFrame.cpp
+++ b/layout/generic/nsCanvasFrame.cpp
@@ -18,21 +18,16 @@
 #include "nsPresShell.h"
 #include "nsIPresShell.h"
 #include "nsDisplayList.h"
 #include "nsCSSFrameConstructor.h"
 #include "nsFrameManager.h"
 #include "gfxPlatform.h"
 #include "nsPrintfCString.h"
 #include "mozilla/dom/AnonymousContent.h"
-// for touchcaret
-#include "nsContentList.h"
-#include "nsContentCreatorFunctions.h"
-#include "nsContentUtils.h"
-#include "nsStyleSet.h"
 // for focus
 #include "nsIScrollableFrame.h"
 #ifdef DEBUG_CANVAS_FOCUS
 #include "nsIDocShell.h"
 #endif
 
 //#define DEBUG_CANVAS_FOCUS
 
@@ -49,18 +44,16 @@ NS_NewCanvasFrame(nsIPresShell* aPresShe
 
 NS_IMPL_FRAMEARENA_HELPERS(nsCanvasFrame)
 
 NS_QUERYFRAME_HEAD(nsCanvasFrame)
   NS_QUERYFRAME_ENTRY(nsCanvasFrame)
   NS_QUERYFRAME_ENTRY(nsIAnonymousContentCreator)
 NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame)
 
-NS_IMPL_ISUPPORTS(nsCanvasFrame::DummyTouchListener, nsIDOMEventListener)
-
 void
 nsCanvasFrame::ShowCustomContentContainer()
 {
   if (mCustomContentContainer) {
     mCustomContentContainer->UnsetAttr(kNameSpaceID_None, nsGkAtoms::hidden, true);
   }
 }
 
@@ -78,76 +71,16 @@ nsresult
 nsCanvasFrame::CreateAnonymousContent(nsTArray<ContentInfo>& aElements)
 {
   if (!mContent) {
     return NS_OK;
   }
 
   nsCOMPtr<nsIDocument> doc = mContent->OwnerDoc();
   nsresult rv = NS_OK;
-  ErrorResult er;
-  // We won't create touch caret element if preference is not enabled.
-  if (PresShell::TouchCaretPrefEnabled()) {
-    RefPtr<NodeInfo> nodeInfo;
-
-    // Create and append touch caret frame.
-    nodeInfo = doc->NodeInfoManager()->GetNodeInfo(nsGkAtoms::div, nullptr,
-                                                   kNameSpaceID_XHTML,
-                                                   nsIDOMNode::ELEMENT_NODE);
-    NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);
-
-    rv = NS_NewHTMLElement(getter_AddRefs(mTouchCaretElement), nodeInfo.forget(),
-                           NOT_FROM_PARSER);
-    NS_ENSURE_SUCCESS(rv, rv);
-    aElements.AppendElement(mTouchCaretElement);
-
-    // Set touch caret to visibility: hidden by default.
-    nsAutoString classValue;
-    classValue.AppendLiteral("moz-touchcaret hidden");
-    rv = mTouchCaretElement->SetAttr(kNameSpaceID_None, nsGkAtoms::_class,
-                                     classValue, true);
-
-    if (!mDummyTouchListener) {
-      mDummyTouchListener = new DummyTouchListener();
-    }
-    mTouchCaretElement->AddEventListener(NS_LITERAL_STRING("touchstart"),
-                                         mDummyTouchListener, false);
-    NS_ENSURE_SUCCESS(rv, rv);
-  }
-
-  if (PresShell::SelectionCaretPrefEnabled()) {
-    // Selection caret
-    mSelectionCaretsStartElement = doc->CreateHTMLElement(nsGkAtoms::div);
-    aElements.AppendElement(mSelectionCaretsStartElement);
-    nsCOMPtr<mozilla::dom::Element> selectionCaretsStartElementInner = doc->CreateHTMLElement(nsGkAtoms::div);
-    mSelectionCaretsStartElement->AppendChildTo(selectionCaretsStartElementInner, false);
-
-    mSelectionCaretsEndElement = doc->CreateHTMLElement(nsGkAtoms::div);
-    aElements.AppendElement(mSelectionCaretsEndElement);
-    nsCOMPtr<mozilla::dom::Element> selectionCaretsEndElementInner = doc->CreateHTMLElement(nsGkAtoms::div);
-    mSelectionCaretsEndElement->AppendChildTo(selectionCaretsEndElementInner, false);
-
-    rv = mSelectionCaretsStartElement->SetAttr(kNameSpaceID_None, nsGkAtoms::_class,
-                                               NS_LITERAL_STRING("moz-selectioncaret-left hidden"),
-                                               true);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    rv = mSelectionCaretsEndElement->SetAttr(kNameSpaceID_None, nsGkAtoms::_class,
-                                             NS_LITERAL_STRING("moz-selectioncaret-right hidden"),
-                                             true);
-
-    if (!mDummyTouchListener) {
-      mDummyTouchListener = new DummyTouchListener();
-    }
-    mSelectionCaretsStartElement->AddEventListener(NS_LITERAL_STRING("touchstart"),
-                                                   mDummyTouchListener, false);
-    mSelectionCaretsEndElement->AddEventListener(NS_LITERAL_STRING("touchstart"),
-                                                 mDummyTouchListener, false);
-    NS_ENSURE_SUCCESS(rv, rv);
-  }
 
   // Create the custom content container.
   mCustomContentContainer = doc->CreateHTMLElement(nsGkAtoms::div);
 #ifdef DEBUG
   // We restyle our mCustomContentContainer, even though it's root anonymous
   // content.  Normally that's not OK because the frame constructor doesn't know
   // how to order the frame tree in such cases, but we make this work for this
   // particular case, so it's OK.
@@ -183,59 +116,28 @@ nsCanvasFrame::CreateAnonymousContent(ns
   }
 
   return NS_OK;
 }
 
 void
 nsCanvasFrame::AppendAnonymousContentTo(nsTArray<nsIContent*>& aElements, uint32_t aFilter)
 {
-  if (mTouchCaretElement) {
-    aElements.AppendElement(mTouchCaretElement);
-  }
-
-  if (mSelectionCaretsStartElement) {
-    aElements.AppendElement(mSelectionCaretsStartElement);
-  }
-
-  if (mSelectionCaretsEndElement) {
-    aElements.AppendElement(mSelectionCaretsEndElement);
-  }
-
   aElements.AppendElement(mCustomContentContainer);
 }
 
 void
 nsCanvasFrame::DestroyFrom(nsIFrame* aDestructRoot)
 {
   nsIScrollableFrame* sf =
     PresContext()->GetPresShell()->GetRootScrollFrameAsScrollable();
   if (sf) {
     sf->RemoveScrollPositionListener(this);
   }
 
-  if (mTouchCaretElement) {
-    mTouchCaretElement->RemoveEventListener(NS_LITERAL_STRING("touchstart"),
-                                            mDummyTouchListener, false);
-  }
-
-  if (mSelectionCaretsStartElement) {
-    mSelectionCaretsStartElement->RemoveEventListener(NS_LITERAL_STRING("touchstart"),
-                                                      mDummyTouchListener, false);
-  }
-
-  if (mSelectionCaretsEndElement) {
-    mSelectionCaretsEndElement->RemoveEventListener(NS_LITERAL_STRING("touchstart"),
-                                                    mDummyTouchListener, false);
-  }
-
-  nsContentUtils::DestroyAnonymousContent(&mTouchCaretElement);
-  nsContentUtils::DestroyAnonymousContent(&mSelectionCaretsStartElement);
-  nsContentUtils::DestroyAnonymousContent(&mSelectionCaretsEndElement);
-
   // Elements inserted in the custom content container have the same lifetime as
   // the document, so before destroying the container, make sure to keep a clone
   // of each of them at document level so they can be re-appended on reframe.
   if (mCustomContentContainer) {
     nsCOMPtr<nsIDocument> doc = mContent->OwnerDoc();
     ErrorResult rv;
 
     nsTArray<RefPtr<mozilla::dom::AnonymousContent>>& docAnonContents =
@@ -292,18 +194,18 @@ nsCanvasFrame::SetInitialChildList(Child
 
 void
 nsCanvasFrame::AppendFrames(ChildListID     aListID,
                             nsFrameList&    aFrameList)
 {
   MOZ_ASSERT(aListID == kPrincipalList, "unexpected child list");
   if (!mFrames.IsEmpty()) {
     for (nsFrameList::Enumerator e(aFrameList); !e.AtEnd(); e.Next()) {
-      // We only allow native anonymous child frame for touch caret,
-      // which its placeholder is added to the Principal child lists.
+      // We only allow native anonymous child frames to be in principal child
+      // list in canvas frame.
       MOZ_ASSERT(e.get()->GetContent()->IsInNativeAnonymousSubtree(),
                  "invalid child list");
     }
   }
   nsFrame::VerifyDirtyBitSet(aFrameList);
   nsContainerFrame::AppendFrames(aListID, aFrameList);
 }
 
@@ -522,25 +424,16 @@ nsCanvasFrame::BuildDisplayList(nsDispla
     if (needBlendContainer) {
       aLists.BorderBackground()->AppendNewToTop(
         new (aBuilder) nsDisplayBlendContainer(aBuilder, this, aLists.BorderBackground()));
     }
   }
 
   nsIFrame* kid;
   for (kid = GetFirstPrincipalChild(); kid; kid = kid->GetNextSibling()) {
-    // Skip touch/selection caret frame if we do not build caret.
-    if (!aBuilder->IsBuildingCaret()) {
-      if(kid->GetContent() == mTouchCaretElement ||
-         kid->GetContent() == mSelectionCaretsStartElement||
-         kid->GetContent() == mSelectionCaretsEndElement) {
-        continue;
-      }
-    }
-
     // Put our child into its own pseudo-stack.
     BuildDisplayListForChild(aBuilder, kid, aDirtyRect, aLists);
   }
 
 #ifdef DEBUG_CANVAS_FOCUS
   nsCOMPtr<nsIContent> focusContent;
   aPresContext->EventStateManager()->
     GetFocusedContent(getter_AddRefs(focusContent));
--- a/layout/generic/nsCanvasFrame.h
+++ b/layout/generic/nsCanvasFrame.h
@@ -9,17 +9,16 @@
 #define nsCanvasFrame_h___
 
 #include "mozilla/Attributes.h"
 #include "mozilla/EventForwards.h"
 #include "nsContainerFrame.h"
 #include "nsIScrollPositionListener.h"
 #include "nsDisplayList.h"
 #include "nsIAnonymousContentCreator.h"
-#include "nsIDOMEventListener.h"
 
 class nsPresContext;
 class nsRenderingContext;
 
 /**
  * Root frame class.
  *
  * The root frame is the parent frame for the document element's frame.
@@ -78,33 +77,16 @@ public:
     return nsContainerFrame::IsFrameOfType(aFlags &
              ~(nsIFrame::eCanContainOverflowContainers));
   }
 
   // nsIAnonymousContentCreator
   virtual nsresult CreateAnonymousContent(nsTArray<ContentInfo>& aElements) override;
   virtual void AppendAnonymousContentTo(nsTArray<nsIContent*>& aElements, uint32_t aFilter) override;
 
-  // Touch caret handle function
-  mozilla::dom::Element* GetTouchCaretElement() const
-  {
-     return mTouchCaretElement;
-  }
-
-  // Selection Caret Handle function
-  mozilla::dom::Element* GetSelectionCaretsStartElement() const
-  {
-    return mSelectionCaretsStartElement;
-  }
-
-  mozilla::dom::Element* GetSelectionCaretsEndElement() const
-  {
-    return mSelectionCaretsEndElement;
-  }
-
   mozilla::dom::Element* GetCustomContentContainer() const
   {
     return mCustomContentContainer;
   }
 
   /**
    * Unhide the CustomContentContainer. This call only has an effect if
    * mCustomContentContainer is non-null.
@@ -160,38 +142,17 @@ public:
 
   nsRect CanvasArea() const;
 
 protected:
   // Data members
   bool                      mDoPaintFocus;
   bool                      mAddedScrollPositionListener;
 
-  nsCOMPtr<mozilla::dom::Element> mTouchCaretElement;
-  nsCOMPtr<mozilla::dom::Element> mSelectionCaretsStartElement;
-  nsCOMPtr<mozilla::dom::Element> mSelectionCaretsEndElement;
   nsCOMPtr<mozilla::dom::Element> mCustomContentContainer;
-
-  class DummyTouchListener final : public nsIDOMEventListener
-  {
-  public:
-    NS_DECL_ISUPPORTS
-
-    NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent) override
-    {
-      return NS_OK;
-    }
-  private:
-    ~DummyTouchListener() {}
-  };
-
-  /**
-   * A no-op touch-listener used for APZ purposes.
-   */
-  RefPtr<DummyTouchListener> mDummyTouchListener;
 };
 
 /**
  * Override nsDisplayBackground methods so that we pass aBGClipRect to
  * PaintBackground, covering the whole overflow area.
  * We can also paint an "extra background color" behind the normal
  * background.
  */
--- a/layout/generic/nsSelection.cpp
+++ b/layout/generic/nsSelection.cpp
@@ -46,19 +46,16 @@ static NS_DEFINE_CID(kFrameTraversalCID,
 #include "nsContentUtils.h"
 #include "nsThreadUtils.h"
 #include "mozilla/Preferences.h"
 #include "nsDOMClassInfoID.h"
 
 #include "nsPresContext.h"
 #include "nsIPresShell.h"
 #include "nsCaret.h"
-#include "TouchCaret.h"
-#include "SelectionCarets.h"
-
 #include "AccessibleCaretEventHub.h"
 
 #include "mozilla/MouseEvents.h"
 #include "mozilla/TextEvents.h"
 
 #include "nsITimer.h"
 #include "nsFrameManager.h"
 // notifications
@@ -818,34 +815,16 @@ nsFrameSelection::Init(nsIPresShell *aSh
   static bool prefCachesInitialized = false;
   if (!prefCachesInitialized) {
     prefCachesInitialized = true;
 
     Preferences::AddBoolVarCache(&sSelectionEventsEnabled,
                                  "dom.select_events.enabled", false);
   }
 
-  // Set touch caret as selection listener
-  RefPtr<TouchCaret> touchCaret = mShell->GetTouchCaret();
-  if (touchCaret) {
-    int8_t index = GetIndexFromSelectionType(nsISelectionController::SELECTION_NORMAL);
-    if (mDomSelections[index]) {
-      mDomSelections[index]->AddSelectionListener(touchCaret);
-    }
-  }
-
-  // Set selection caret as selection listener
-  RefPtr<SelectionCarets> selectionCarets = mShell->GetSelectionCarets();
-  if (selectionCarets) {
-    int8_t index = GetIndexFromSelectionType(nsISelectionController::SELECTION_NORMAL);
-    if (mDomSelections[index]) {
-      mDomSelections[index]->AddSelectionListener(selectionCarets);
-    }
-  }
-
   RefPtr<AccessibleCaretEventHub> eventHub = mShell->GetAccessibleCaretEventHub();
   if (eventHub) {
     int8_t index = GetIndexFromSelectionType(nsISelectionController::SELECTION_NORMAL);
     if (mDomSelections[index]) {
       mDomSelections[index]->AddSelectionListener(eventHub);
     }
   }
 
@@ -3285,29 +3264,16 @@ nsFrameSelection::SetDelayedCaretData(Wi
   } else {
     mDelayedMouseEventValid = false;
   }
 }
 
 void
 nsFrameSelection::DisconnectFromPresShell()
 {
-  // Remove touch caret as selection listener
-  RefPtr<TouchCaret> touchCaret = mShell->GetTouchCaret();
-  if (touchCaret) {
-    int8_t index = GetIndexFromSelectionType(nsISelectionController::SELECTION_NORMAL);
-    mDomSelections[index]->RemoveSelectionListener(touchCaret);
-  }
-
-  RefPtr<SelectionCarets> selectionCarets = mShell->GetSelectionCarets();
-  if (selectionCarets) {
-    int8_t index = GetIndexFromSelectionType(nsISelectionController::SELECTION_NORMAL);
-    mDomSelections[index]->RemoveSelectionListener(selectionCarets);
-  }
-
   RefPtr<AccessibleCaretEventHub> eventHub = mShell->GetAccessibleCaretEventHub();
   if (eventHub) {
     int8_t index = GetIndexFromSelectionType(nsISelectionController::SELECTION_NORMAL);
     mDomSelections[index]->RemoveSelectionListener(eventHub);
   }
 
   StopAutoScrollTimer();
   for (int32_t i = 0; i < nsISelectionController::NUM_SELECTIONTYPES; i++) {
--- a/layout/style/ua.css
+++ b/layout/style/ua.css
@@ -412,124 +412,16 @@ div:-moz-native-anonymous.moz-accessible
     background-image: url("resource://gre/res/accessiblecaret_tilt_left@2.25x.png");
   }
 
   div:-moz-native-anonymous.moz-accessiblecaret.right > div.image {
     background-image: url("resource://gre/res/accessiblecaret_tilt_right@2.25x.png");
   }
 }
 
-div:-moz-native-anonymous.moz-touchcaret,
-div:-moz-native-anonymous.moz-selectioncaret-left,
-div:-moz-native-anonymous.moz-selectioncaret-right {
-  position: fixed;
-  width: 44px;
-  height: 47px;
-}
-
-div:-moz-native-anonymous.moz-selectioncaret-left > div,
-div:-moz-native-anonymous.moz-selectioncaret-right > div {
-  position: absolute;
-  width: 100%;
-  height: 100%;
-  bottom: 0;
-}
-
-div:-moz-native-anonymous.moz-touchcaret,
-div:-moz-native-anonymous.moz-selectioncaret-left,
-div:-moz-native-anonymous.moz-selectioncaret-right,
-div:-moz-native-anonymous.moz-selectioncaret-left > div,
-div:-moz-native-anonymous.moz-selectioncaret-right > div {
-  background-position: center bottom;
-  background-size: 100%;
-  background-repeat: no-repeat;
-  z-index: 2147483647;
-}
-
-div:-moz-native-anonymous.moz-touchcaret,
-div:-moz-native-anonymous.moz-selectioncaret-left > div,
-div:-moz-native-anonymous.moz-selectioncaret-right > div {
-  background-image: url("resource://gre/res/text_caret.png");
-}
-
-div:-moz-native-anonymous.moz-touchcaret,
-div:-moz-native-anonymous.moz-selectioncaret-left,
-div:-moz-native-anonymous.moz-selectioncaret-right {
-  margin-left: -23px;
-}
-
-div:-moz-native-anonymous.moz-selectioncaret-left.tilt > div {
-  background-image: url("resource://gre/res/text_caret_tilt_left.png");
-  margin-left: -17px;
-}
-
-div:-moz-native-anonymous.moz-selectioncaret-right.tilt > div {
-  background-image: url("resource://gre/res/text_caret_tilt_right.png");
-  margin-left: 18px;
-}
-
-@media (min-resolution: 1.5dppx) {
-  div:-moz-native-anonymous.moz-touchcaret,
-  div:-moz-native-anonymous.moz-selectioncaret-left > div,
-  div:-moz-native-anonymous.moz-selectioncaret-right > div {
-    background-image: url("resource://gre/res/text_caret@1.5x.png");
-  }
-
-  div:-moz-native-anonymous.moz-selectioncaret-left.tilt > div {
-    background-image: url("resource://gre/res/text_caret_tilt_left@1.5x.png");
-  }
-
-  div:-moz-native-anonymous.moz-selectioncaret-right.tilt > div {
-    background-image: url("resource://gre/res/text_caret_tilt_right@1.5x.png");
-  }
-}
-
-@media (min-resolution: 2dppx) {
-  div:-moz-native-anonymous.moz-touchcaret,
-  div:-moz-native-anonymous.moz-selectioncaret-left > div,
-  div:-moz-native-anonymous.moz-selectioncaret-right > div {
-    background-image: url("resource://gre/res/text_caret@2x.png");
-  }
-
-  div:-moz-native-anonymous.moz-selectioncaret-left.tilt > div {
-    background-image: url("resource://gre/res/text_caret_tilt_left@2x.png");
-  }
-
-  div:-moz-native-anonymous.moz-selectioncaret-right.tilt > div {
-    background-image: url("resource://gre/res/text_caret_tilt_right@2x.png");
-  }
-}
-
-@media (min-resolution: 2.25dppx) {
-  div:-moz-native-anonymous.moz-touchcaret,
-  div:-moz-native-anonymous.moz-selectioncaret-left > div,
-  div:-moz-native-anonymous.moz-selectioncaret-right > div {
-    background-image: url("resource://gre/res/text_caret@2.25x.png");
-  }
-
-  div:-moz-native-anonymous.moz-selectioncaret-left.tilt > div {
-    background-image: url("resource://gre/res/text_caret_tilt_left@2.25x.png");
-  }
-
-  div:-moz-native-anonymous.moz-selectioncaret-right.tilt > div {
-    background-image: url("resource://gre/res/text_caret_tilt_right@2.25x.png");
-  }
-}
-
-div:-moz-native-anonymous.moz-touchcaret.hidden,
-div:-moz-native-anonymous.moz-selectioncaret-left.hidden,
-div:-moz-native-anonymous.moz-selectioncaret-right.hidden,
-div:-moz-native-anonymous.moz-selectioncaret-left.hidden > div,
-div:-moz-native-anonymous.moz-selectioncaret-right.hidden > div {
-  width: 0px;
-  height: 0px;
-  margin: 0px;
-  visibility: hidden;
-}
-
 /* Custom content container in the CanvasFrame, fixed positioned on top of
    everything else, not reacting to pointer events. */
 div:-moz-native-anonymous.moz-custom-content-container {
   pointer-events: none;
   -moz-top-layer: top;
   position: fixed;
   top: 0;
   left: 0;
--- a/layout/tools/reftest/reftest-preferences.js
+++ b/layout/tools/reftest/reftest-preferences.js
@@ -46,19 +46,16 @@
     // Disable interruptible reflow since (1) it's normally not going to
     // happen, but (2) it might happen if we somehow end up with both
     // pending user events and clock skew.  So to avoid having to change
     // MakeProgress to deal with waiting for interruptible reflows to
     // complete for a rare edge case, we just disable interruptible
     // reflow so that that rare edge case doesn't lead to reftest
     // failures.
     branch.setBoolPref("layout.interruptible-reflow.enabled", false);
-    // Disable the auto-hide feature of touch caret to avoid potential
-    // intermittent issues.
-    branch.setIntPref("touchcaret.expiration.time", 0);
 
     // Tell the search service we are running in the US.  This also has the
     // desired side-effect of preventing our geoip lookup.
     branch.setBoolPref("browser.search.isUS", true);
     branch.setCharPref("browser.search.countryCode", "US");
     // Prevent the geoSpecificDefaults XHR by emptying the URL.
     branch.setCharPref("browser.search.geoSpecificDefaults.url", "");
 
--- a/mobile/android/b2gdroid/installer/package-manifest.in
+++ b/mobile/android/b2gdroid/installer/package-manifest.in
@@ -538,28 +538,28 @@
 @BINPATH@/res/table-remove-row-hover.gif
 @BINPATH@/res/table-remove-row.gif
 @BINPATH@/res/grabber.gif
 @BINPATH@/res/dtd/*
 @BINPATH@/res/html/*
 @BINPATH@/res/language.properties
 @BINPATH@/res/entityTables/*
 #ifdef NIGHTLY_BUILD
-@BINPATH@/res/text_caret.png
-@BINPATH@/res/text_caret@1.5x.png
-@BINPATH@/res/text_caret@2.25x.png
-@BINPATH@/res/text_caret@2x.png
-@BINPATH@/res/text_caret_tilt_left.png
-@BINPATH@/res/text_caret_tilt_left@1.5x.png
-@BINPATH@/res/text_caret_tilt_left@2.25x.png
-@BINPATH@/res/text_caret_tilt_left@2x.png
-@BINPATH@/res/text_caret_tilt_right.png
-@BINPATH@/res/text_caret_tilt_right@1.5x.png
-@BINPATH@/res/text_caret_tilt_right@2.25x.png
-@BINPATH@/res/text_caret_tilt_right@2x.png
+@BINPATH@/res/accessiblecaret.png
+@BINPATH@/res/accessiblecaret@1.5x.png
+@BINPATH@/res/accessiblecaret@2.25x.png
+@BINPATH@/res/accessiblecaret@2x.png
+@BINPATH@/res/accessiblecaret_tilt_left.png
+@BINPATH@/res/accessiblecaret_tilt_left@1.5x.png
+@BINPATH@/res/accessiblecaret_tilt_left@2.25x.png
+@BINPATH@/res/accessiblecaret_tilt_left@2x.png
+@BINPATH@/res/accessiblecaret_tilt_right.png
+@BINPATH@/res/accessiblecaret_tilt_right@1.5x.png
+@BINPATH@/res/accessiblecaret_tilt_right@2.25x.png
+@BINPATH@/res/accessiblecaret_tilt_right@2x.png
 #endif
 
 #ifndef MOZ_ANDROID_EXCLUDE_FONTS
 @BINPATH@/res/fonts/*
 #else
 @BINPATH@/res/fonts/*.properties
 #endif
 
--- a/modules/libpref/init/all.js
+++ b/modules/libpref/init/all.js
@@ -4851,35 +4851,16 @@ pref("browser.safebrowsing.provider.mozi
 pref("browser.safebrowsing.provider.mozilla.lists.mozfull.description", "mozfullDesc");
 
 // Allow users to ignore Safe Browsing warnings.
 pref("browser.safebrowsing.allowOverride", true);
 
 // Turn off Spatial navigation by default.
 pref("snav.enabled", false);
 
-// Original caret implementation on collapsed selection.
-pref("touchcaret.enabled", false);
-
-// This will inflate the size of the touch caret frame when checking if user
-// clicks on the caret or not. In app units.
-pref("touchcaret.inflatesize.threshold", 40);
-
-// We'll start to increment time when user release the control of touch caret.
-// When time exceed this expiration time, we'll hide touch caret.
-// In milliseconds. (0 means disable this feature)
-pref("touchcaret.expiration.time", 3000);
-
-// Original caret implementation on non-collapsed selection.
-pref("selectioncaret.enabled", false);
-
-// This will inflate size of selection caret frame when we checking if
-// user click on selection caret or not. In app units.
-pref("selectioncaret.inflatesize.threshold", 40);
-
 // New implementation to unify touch-caret and selection-carets.
 pref("layout.accessiblecaret.enabled", false);
 
 // CSS attributes of the AccessibleCaret in CSS pixels.
 pref("layout.accessiblecaret.width", "34.0");
 pref("layout.accessiblecaret.height", "36.0");
 pref("layout.accessiblecaret.margin-left", "-18.5");
 pref("layout.accessiblecaret.bar.width", "2.0");
--- a/testing/profiles/prefs_b2g_unittest.js
+++ b/testing/profiles/prefs_b2g_unittest.js
@@ -4,9 +4,8 @@ user_pref("b2g.system_manifest_url","app
 user_pref("b2g.system_startup_url","app://test-container.gaiamobile.org/index.html");
 user_pref("dom.ipc.browser_frames.oop_by_default", false);
 user_pref("dom.ipc.tabs.disabled", false);
 user_pref("dom.ipc.tabs.shutdownTimeoutSecs", 0);
 user_pref("dom.mozBrowserFramesEnabled", "%(OOP)s");
 user_pref("dom.mozBrowserFramesWhitelist","app://test-container.gaiamobile.org,http://mochi.test:8888");
 user_pref("dom.testing.datastore_enabled_for_hosted_apps", true);
 user_pref("marionette.force-local", true);
-user_pref("touchcaret.expiration.time", 0);